from selenium import webdriver
from selenium.webdriver.chrome.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement

browser: WebDriver = webdriver.Chrome('./chromedriver')
browser.get('https://scraping-for-beginner.herokuapp.com/ranking/')

elemRankingBox: WebElement = browser.find_element_by_class_name('u_areaListRankingBox')
elemTitle: WebElement = elemRankingBox\
    .find_element_by_class_name('u_title')\
    .find_element_by_tag_name('h2')
titles: str = elemTitle.text
_, title = titles.split('\n')
print(title)

# 総合評価
elemRankBox: WebElement = browser.find_element_by_class_name('u_rankBox')
elemSumRank: WebElement = elemRankBox.find_element_by_class_name('evaluateNumber')
print('総合ランク ', elemSumRank.text)

# 他の評価
elemAnotherRankBox: WebElement = browser.find_element_by_class_name('u_categoryTipsItem')
elemRankHobby: WebElement = elemAnotherRankBox.find_elements_by_class_name('is_rank')[0]
elemHbyRank: WebElement = elemRankHobby.find_element_by_class_name('evaluateNumber')
print('楽しさ : ', elemHbyRank.text)

elemPeople: WebElement = elemAnotherRankBox.find_elements_by_class_name('is_rank')[1]
elemPle: WebElement = elemPeople.find_element_by_class_name('evaluateNumber')
print('人混みの多さ : ', elemPle.text)

elemRankView: WebElement = elemAnotherRankBox.find_elements_by_class_name('is_rank')[2]
elemView: WebElement = elemRankView.find_element_by_class_name('evaluateNumber')
print('景色 : ', elemView.text)

elemRankAcc: WebElement = elemAnotherRankBox.find_elements_by_class_name('is_rank')[3]
elemAcc: WebElement = elemRankAcc.find_element_by_class_name('evaluateNumber')
print('アクセス : ', elemAcc.text)

# 全ての情報取得(タイトル)
elemRankingBs: list = browser.find_elements_by_class_name('u_areaListRankingBox')

titleList: list = []
for elemRankB in elemRankingBs:
    elemTitle: WebElement = elemRankB.find_element_by_class_name('u_title')
    titleSplit = elemTitle.text.split('\n')[1]

    titleList.append(titleSplit)

print(titleList)

# 全ての情報取得(総合評価)
elemRankingBs: list = browser.find_elements_by_class_name('u_areaListRankingBox')

sumRankingList: list = []
for elemRankB in elemRankingBs:
    elemRanking: WebElement = elemRankB.find_element_by_class_name('u_rankBox')
    elemSumRank: WebElement = elemRanking.find_element_by_class_name('evaluateNumber')
    rank: float = float(elemSumRank.text)
    sumRankingList.append(rank)

print(sumRankingList)

# 全ての情報取得(各評価)
elemRankingBs: list = browser.find_elements_by_class_name('u_areaListRankingBox')

rankingList: list = []
for elemRankB in elemRankingBs:
    elemAnotherRankBox: WebElement = elemRankB.find_element_by_class_name('u_categoryTipsItem')
    elemAnotherRanks: list = elemAnotherRankBox.find_elements_by_class_name('is_rank')
    tempRankingList: list = [float(elemAnotherRb.find_element_by_class_name('evaluateNumber').text) for elemAnotherRb in elemAnotherRanks]
    rankingList.append(tempRankingList)

print(rankingList)

# Pandasに変換
import pandas

dataFrame1: pandas.DataFrame = pandas.DataFrame()
dataFrame1['観光地名'] = titleList
dataFrame1['総合評価'] = sumRankingList
print(dataFrame1)

dataFrame2: pandas.DataFrame = pandas.DataFrame(rankingList)
dataFrame2.columns = ['楽しさ', '人混みの多さ', '景色', 'アクセス']
print(dataFrame2)

concatDataFrame: pandas.DataFrame = pandas.concat([dataFrame1, dataFrame2], axis=1)
print(concatDataFrame)
concatDataFrame.to_csv('観光地情報.csv', index=False)

# 全ページの情報取得

ts: list = []
srs: list = []
rs: list = []
for page in range(1, 4):
    browser.get('https://scraping-for-beginner.herokuapp.com/ranking/?page={}'.format(page))

    elemRankingBs: list = browser.find_elements_by_class_name('u_areaListRankingBox')
    for elemRankB in elemRankingBs:
        elemTitle: WebElement = elemRankB.find_element_by_class_name('u_title')
        titleSplit = elemTitle.text.split('\n')[1]
        ts.append(titleSplit)

    for elemRankB in elemRankingBs:
        elemRanking: WebElement = elemRankB.find_element_by_class_name('u_rankBox')
        elemSumRank: WebElement = elemRanking.find_element_by_class_name('evaluateNumber')
        rank: float = float(elemSumRank.text)
        srs.append(rank)

    for elemRankB in elemRankingBs:
        elemAnotherRankBox: WebElement = elemRankB.find_element_by_class_name('u_categoryTipsItem')
        elemAnotherRanks: list = elemAnotherRankBox.find_elements_by_class_name('is_rank')
        tempRankingList: list = [float(elemAnotherRb.find_element_by_class_name('evaluateNumber').text) for elemAnotherRb in elemAnotherRanks]
        rs.append(tempRankingList)

print('タイトル ', ts)
print('総合ランキング ', srs)
print('項目別ランキング ', rs)

# Pandasに変換
import pandas

dataFrame3: pandas.DataFrame = pandas.DataFrame()
dataFrame3['観光地名'] = ts
dataFrame3['総合評価'] = srs
print(dataFrame3)

dataFrame4: pandas.DataFrame = pandas.DataFrame(rs)
dataFrame4.columns = ['楽しさ', '人混みの多さ', '景色', 'アクセス']
print(dataFrame4)

concatDataFrame: pandas.DataFrame = pandas.concat([dataFrame3, dataFrame4], axis=1)
print(concatDataFrame)
concatDataFrame.to_csv('観光地総合情報.csv', index=False)

browser.quit()


user_string = input('Введите строку: ')
freq = {}  # частота букв в слове

for letter in user_string:
    keys = freq.keys()  # сохраню ключи из словаря
    if letter in keys:
        freq[letter] += 1
    else:
        freq[letter] = 1
print(freq)


#!/usr/bin/python3
# -*- coding: utf-8 -*-

import datetime
import math
import os
import sys
import time

import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras

try:
    current_path = os.path.split(os.path.realpath(__file__))[0]
except:
    current_path = os.path.split(os.path.realpath("__file__"))[0]

flags = tf.app.flags
# [1] System
flags.DEFINE_integer("buffer_size", 10, "buffer_size")
flags.DEFINE_string("current_path", current_path, "")

# [2] Dataset
flags.DEFINE_string("train_file_path", os.path.join(
    current_path, "raw_data", "train.csv"), "train_file_path")
flags.DEFINE_list("input_shape", [28, 28, 1], "input_shape")

# [3] Build model
flags.DEFINE_integer("hidden_units", 1, "hidden_units")
flags.DEFINE_string("build_model_type", "Build", "[Load Build]")
flags.DEFINE_string("load_model_path", os.path.join(
    current_path, "model", "default_model.h5"), "if load")

# [4] Train
flags.DEFINE_integer("batch_size", 128, "")
flags.DEFINE_integer("num_parallel_calls", 8, "")
flags.DEFINE_float("learning_rate", 0.0001, "")
flags.DEFINE_float("beta_1", 0.9, "")
flags.DEFINE_float("beta_2", 0.991, "")
flags.DEFINE_float("epsilon", 1e-8, "")
flags.DEFINE_bool("decay", False, "")
flags.DEFINE_integer("epochs", 100, "")
flags.DEFINE_integer("steps_per_epoch", 100, "default is 100")

# [5] Output
flags.DEFINE_string("record_type", "record_parameters", "")
flags.DEFINE_string("predict_x_path", os.path.join(
    current_path, "raw_data", "test.csv"), "")
flags.DEFINE_string("log_file", os.path.join(
    current_path, "log"), "")
flags.DEFINE_string("model_save_path", os.path.join(
    current_path, "model", "default_model.h5"), "")
flags.DEFINE_string("history_output_path", os.path.join(
    current_path, "train_process", "default_train_process.csv"), "")
flags.DEFINE_string("predict_label_output_path", os.path.join(
    current_path, "submit", "default_submit.csv"), "")

# [6]定义分布式参数
# 参数服务器parameter server节点
flags.DEFINE_string('ps_hosts', '127.0.0.1:22221',
                    'Comma-separated list of hostname:port pairs')
# 两个worker节点
flags.DEFINE_string('worker_hosts', '127.0.0.1:22221',
                    'Comma-separated list of hostname:port pairs')
# 设置job name参数
flags.DEFINE_string('job_name', "worker", 'job name: worker or ps')
# 设置任务的索引
flags.DEFINE_integer('task_index', 0, 'Index of task within the job')
# 选择异步并行，同步并行
flags.DEFINE_integer("issync", None, "是否采用分布式的同步模式，1表示同步模式，0表示异步模式")
flags.DEFINE_string('server_target', "None", ' ')

FLAGS = flags.FLAGS
IMAGE_PIXELS = 28

server = tf.train.Server.create_local_server()

def Timer(func):
    def newFunc(*args, **args2):
        t1 = datetime.datetime.now()
        back = func(*args, **args2)
        print(" This function【{}】cost time:{} \n".format(
            func.__name__, datetime.datetime.now()-t1))
        return back
    return newFunc

def main(__):

    print(f"Tensorflow Version is {tf.__version__}")

    # mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

    if FLAGS.job_name is None or FLAGS.job_name == '':
        raise ValueError('Must specify an explicit job_name !')
    else:
        print('job_name : %s' % FLAGS.job_name)
    if FLAGS.task_index is None or FLAGS.task_index == '':
        raise ValueError('Must specify an explicit task_index!')
    else:
        print('task_index : %d' % FLAGS.task_index)

    ps_spec = FLAGS.ps_hosts.split(',')
    worker_spec = FLAGS.worker_hosts.split(',')

    # 创建集群
    num_worker = len(worker_spec)
    print("Cluster num is {}".format(num_worker))
    cluster = tf.train.ClusterSpec({'ps': ps_spec, 'worker': worker_spec})
    server = tf.train.Server(
        cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index)
    if FLAGS.job_name == 'ps':
        server.join()

    is_chief = (FLAGS.task_index == 0)
    worker_device = '/job:worker/task:%d/cpu:0' % FLAGS.task_index
    with tf.device(tf.train.replica_device_setter(cluster=cluster, worker_device=worker_device)):
        # with tf.device("/cpu:0"):
        # --------[PART 01] build model --------------
        # ----[0] init  (1 V 2 placehold)
        # 0.1 Variable
        # 0.2 placeholder
        global_step = tf.Variable(
            0, name='global_step', trainable=False)  # 创建纪录全局训练步数变量
        hid_w = tf.Variable(tf.truncated_normal([IMAGE_PIXELS * IMAGE_PIXELS, FLAGS.hidden_units],
                                                stddev=1.0 / IMAGE_PIXELS), name='hid_w')
        hid_b = tf.Variable(tf.zeros([FLAGS.hidden_units]), name='hid_b')

        sm_w = tf.Variable(tf.truncated_normal([FLAGS.hidden_units, 10],
                                               stddev=1.0 / math.sqrt(FLAGS.hidden_units)), name='sm_w')
        sm_b = tf.Variable(tf.zeros([10]), name='sm_b')

        x = tf.placeholder(tf.float32, [None, IMAGE_PIXELS * IMAGE_PIXELS])
        y_ = tf.placeholder(tf.float32, [None, 10])  # real_y

        # ----[1]  Forward

        hid_lin = tf.nn.xw_plus_b(x, hid_w, hid_b)
        hid = tf.nn.relu(hid_lin)
        y = tf.nn.softmax(tf.nn.xw_plus_b(hid, sm_w, sm_b))

        #----[2].BackProp (loss ,opt )

        cross_entropy = - \
            tf.reduce_sum(y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0)))
        opt = tf.train.AdamOptimizer(FLAGS.learning_rate)
        train_step = opt.minimize(cross_entropy, global_step=global_step)

        # 生成本地的参数初始化操作init_op
        init_op = tf.global_variables_initializer()
        #train_dir = tempfile.mkdtemp()
        sv = tf.train.Supervisor(is_chief=is_chief, logdir=FLAGS.log_file, init_op=init_op, recovery_wait_secs=1,
                                 global_step=global_step)

        if is_chief:
            print('Worker %d: Initailizing session...' % FLAGS.task_index)
        else:
            print('Worker %d: Waiting for session to be initaialized...' %
                  FLAGS.task_index)
        # --------[PART 02 ] Train  model --------------
        run_metadata = tf.RunMetadata()
        run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
        config = tf.ConfigProto(graph_options=tf.GraphOptions(
            optimizer_options=tf.OptimizerOptions(opt_level=tf.OptimizerOptions.L0)))

        sess = sv.prepare_or_wait_for_session(server.target)

        print('Worker %d: Session initialization  complete.' % FLAGS.task_index)
        time_begin = time.time()
        print('Traing begins @ %f' % time_begin)
        local_step = 0

        while True:
            batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batch_size)
            train_feed = {x: batch_xs, y_: batch_ys}
            """
            feed_dict 输入数据是最慢的
            _, step = sess.run([train_step, global_step], feed_dict=train_feed)
            """

            local_step += 1

            now = time.time()
            print('%f: Worker %d: traing step %d dome (global step:%d)' %
                  (now, FLAGS.task_index, local_step, step))

            if step >= FLAGS.train_steps:
                break

        time_end = time.time()
        print('Training ends @ %f' % time_end)
        train_time = time_end - time_begin
        print('Training elapsed time:%f s' % train_time)

        val_feed = {x: mnist.validation.images, y_: mnist.validation.labels}
        val_xent = sess.run(cross_entropy, feed_dict=val_feed)
        print('After %d training step(s), validation cross entropy = %g' %
              (FLAGS.train_steps, val_xent))
        sess.close()

    # ------------[Part 4] Output   ----------------
    if FLAGS.record_type == "record_parameters":
        par_str = "lr_%g_b1_%g_b2_%g_bsize_%g" % (
            FLAGS.learning_rate, FLAGS.beta_1, FLAGS.beta_2, FLAGS.batch_size)
        FLAGS.model_save_path = os.path.join(
            FLAGS.current_path, "model", par_str + ".h5")
        FLAGS.history_output_path = os.path.join(
            FLAGS.current_path, "train_process", par_str + ".csv")
        FLAGS.predict_label_output_path = os.path.join(
            FLAGS.current_path, "submit", par_str+".csv")

    # 1 . model save
    model.save(FLAGS.model_save_path)
    history_df = pd.DataFrame(history.history)
    history_df.to_csv(FLAGS.history_output_path)

    # 2. predict
    predict_data = pd.read_csv(FLAGS.predict_x_path)

    predict_x = predict_data.values.reshape([len(predict_data)] + [28, 28, 1])
    predict_y = model.predict(predict_x)
    # label
    predict_label = np.argmax(predict_y, axis=1)
    df_predict_label = pd.DataFrame(
        {"ImageId": range(1, len(predict_label)+1), "Label": predict_label})
    # export
    df_predict_label.to_csv(FLAGS.predict_label_output_path, index=False)

if __name__ == "__main__":

    tf.app.run()


def find_unassigned_table_cell(table):
    """
    Search through a table and return the first [row, column] pair
    who's value is None.

    Parameters
    ----------
    table : list of lists of str

    Returns
    -------
    list of int
        The row column pair of the None type cell
    """
    for row in range(len(table)):
        for column in range(len(table[row])):
            if table[row][column] is None:
                return row, column
    return row, column


import configuration
import requests
import data

def post_products_kits(product_ids):
    return requests.post(configuration.URL_SERVICE + configuration.PRODUCTS_KITS_PATH,  # подставляем полный url
                         headers=data.headers,
                         json=data.product_ids)  # а здесь заголовки

response = post_products_kits(data.product_ids);
print(response.status_code),
print(response.json())


from django.contrib import admin
from django.db.models.base import Model
from django.utils import timezone
from .models import MultipleQuestion, MultipleQuestionOption, MultipleVoting, QuestionOption, BinaryQuestionOption, ScoreQuestionOption
from .models import Question, BinaryQuestion, ScoreQuestion
from .models import Voting, BinaryVoting, ScoreVoting
from .filters import StartedFilter
from visualizer.telegramBot import auto_notifications

def start(modeladmin, request, queryset):
    for v in queryset.all():
        v.create_pubkey()
        v.start_date = timezone.now()
        v.save()
        send_notifications(v)

def stop(ModelAdmin, request, queryset):
    for v in queryset.all():
        v.end_date = timezone.now()
        v.save()
        send_notifications(v)

def tally(ModelAdmin, request, queryset):
    for v in queryset.filter(end_date__lt=timezone.now()):
        token = request.session.get('auth-token', '')
        v.tally_votes(token)

#for users who have auto notifications enabled
def send_notifications(v):
    auto_notifications(v)

class QuestionOptionInline(admin.TabularInline):
    model = QuestionOption

class QuestionAdmin(admin.ModelAdmin):
    inlines = [QuestionOptionInline]

class VotingAdmin(admin.ModelAdmin):
    list_display = ('name', 'start_date', 'end_date')
    readonly_fields = ('start_date', 'end_date', 'pub_key',
                       'tally', 'postproc')
    #date_hierarchy = 'start_date'
    list_filter = (StartedFilter,)
    search_fields = ('name', )

    actions = [ start, stop, tally ]

class BinaryQuestionOptionInline(admin.TabularInline):
    model = BinaryQuestionOption

class BinaryQuestionAdmin(admin.ModelAdmin):
    inlines = [BinaryQuestionOptionInline]

class BinaryVotingAdmin(admin.ModelAdmin):
    list_display = ('name', 'start_date', 'end_date')
    readonly_fields = ('start_date', 'end_date', 'pub_key',
                       'tally', 'postproc')
    #date_hierarchy = 'start_date'
    list_filter = (StartedFilter,)
    search_fields = ('name', )

    actions = [ start, stop, tally ]

class ScoreQuestionOptionInline(admin.TabularInline):
    model = ScoreQuestionOption

class ScoreQuestionAdmin(admin.ModelAdmin):
    inlines = [ScoreQuestionOptionInline]

class ScoreVotingAdmin(admin.ModelAdmin):
    list_display = ('name', 'start_date', 'end_date')
    readonly_fields = ('start_date', 'end_date', 'pub_key',
                       'tally', 'postproc')
    #date_hierarchy = 'start_date'
    list_filter = (StartedFilter,)
    search_fields = ('name', )

    actions = [ start, stop, tally ]

class MultipleQuestionOptionInline(admin.TabularInline):
    model = MultipleQuestionOption

class MultipleQuestionAdmin(admin.ModelAdmin):
    inlines = [MultipleQuestionOptionInline]

class MultipleVotingAdmin(admin.ModelAdmin):
    list_display = ('name', 'start_date', 'end_date')
    readonly_fields = ('start_date', 'end_date', 'pub_key',
                       'tally', 'postproc')
    #date_hierarchy = 'start_date'
    list_filter = (StartedFilter,)
    search_fields = ('name', )

    actions = [ start, stop, tally ]

admin.site.register(Voting, VotingAdmin)
admin.site.register(Question, QuestionAdmin)
admin.site.register(BinaryVoting, BinaryVotingAdmin)
admin.site.register(BinaryQuestion, BinaryQuestionAdmin)
admin.site.register(ScoreVoting, ScoreVotingAdmin)
admin.site.register(ScoreQuestion, ScoreQuestionAdmin)
admin.site.register(MultipleVoting, MultipleVotingAdmin)
admin.site.register(MultipleQuestion, MultipleQuestionAdmin)


import json

#LOCATIONS = {'L0': 0, 'L1': 1} #{ L0: 0, L1: 1, L2: 2, LM1: 3, LM2: 4, LM3: 5}
TRACK1 = (0, 1, 0, 2, 0, 3)
TRACK2 = (0, 1, 2, 0, 2, 3)

class Worker:

    def __init__(self, id, track):
        self.id = id
        self.track = track
        self.track_step = 0
        self.location = self.track[self.track_step]

    def __repr__(self):
        return '{id:'+str(self.id)+', location:'+str(self.location)+ '}'

    def step(self, point):
        self.track_step = self.track_step + 1 if self.track_step < len(self.track) - 1  else 0
        self.location = self.track[self.track_step]

class Simulator:

    def __init__(self, n, period):
        # n - количество рабочих
        # period - время в условных единицах

        self.Workers = []
        for i in range(n):
            track = TRACK1 if i % 2 == 0 else TRACK2
            self.Workers.append(Worker(i, track))
        self.period = period
        self.timer = 0
        self.log = []

    def run(self):
        for point in range(self.period):
            for w in self.Workers:
                self.contacts(point)
                print(repr(w))
                w.step(point)

        with open('logs.json', 'w', encoding='utf-8') as logs:
            print(json.dumps(self.log), file=logs)

    def contacts(self, point):
        for w1 in self.Workers:
            for w2 in self.Workers:
                if w1 != w2:
                    if w1.location == w2.location:
                        self.log.append({'time': point,'id1': w1.id, 'id2': w2.id, 'rssi': 1 })

s = Simulator(2, 10)
s.run()


# plink utility

import pandas as pd
import numpy as np
import sqlite3 as sql
import os

from file_db_define import *

def write_plink_ref_freq(plink_ref_freq_file, plink_ref_freq_db):

   # separation char is one more space, so sep='\s+', and grep expression need 'python' engine
   plink_ref_freq = \
        pd.read_csv(plink_ref_freq_file, encoding="UTF-8", sep='\s+', engine='python')
   #ref_freq = pd.read_csv(plink_ref_freq_file, encoding="UTF-8", sep='\t')
   print(plink_ref_freq.shape)
   print(plink_ref_freq.head())

   # to have database in ram, use below ":memory:"
   # con = sql.connect(":memory:")

   # remove database if exist
   if os.path.isfile(plink_ref_freq_db):
      os.remove(plink_ref_freq_db)

   con = sql.connect(plink_ref_freq_db)
   cur = con.cursor()

   # below line is not needed because database was removed already
   # if database is not removed in advance, use below line
   # cur.execute("DROP TABLE IF EXISTS freq")

   print("#### write plink_ref_freq into freq table\n")

   # data type: [ref] https://docs.python.org/ko/3/library/sqlite3.html
   cur.execute("CREATE TABLE freq(CHR INTEGER, SNP TEXT, A1 TEXT, A2 TEXT, MAF REAL, NCHROBS INTEGER)")
   # cur.execute("CREATE TABLE freq(CHR tinyint, SNP text, A1 text, A2 text, MAF real, NCHROBS smallint)")

   # "executemany" need "list of tuple" input, so convert dataframe to list of tuple":
   # [ref] https://www.kite.com/python/answers/how-to-convert-a-pandas-dataframe-into-a-list-of-tuples-in-python
   cur.executemany("INSERT INTO freq VALUES (?, ?, ?, ?, ?, ?)", \
      list(plink_ref_freq.to_records(index=False)))

   cur.execute("CREATE INDEX idx_freq_SNP_A1_A2 ON freq(SNP, A1, A2)")

   con.commit()
   con.close()

'''
  mutate(snp_freq = foreach(row = 1:n(), .combine = c, .multicombine = TRUE) %do% {
    con <- dbConnect(SQLite(), 'reference/Plink/ref.frq.sqlite')
    on.exit(dbDisconnect(con), add = TRUE)
    res <- dbGetQuery(con,
              sprintf('select * from freq where SNP="%s" and ((A1="%s" and A2="%s") or (A1="%s" and A2="%s"))',
              snpname[row], ref_allele[row], eff_allele[row], eff_allele[row], ref_allele[row]))
    if (nrow(res) == 0)
      return(NA)
    else {
      res <- res[1,]
      return(ifelse(res$A1 == eff_allele[row], res$MAF, 1 - res$MAF))
    }
  }) %>%
'''

def query_plink_ref_freq(plink_ref_freq_db, snpname, ref_allele, eff_allele):

   con = sql.connect(plink_ref_freq_db)
   cur = con.cursor()
   query_string = \
        'SELECT * FROM freq WHERE SNP="{}" and ((A1="{}" and A2="{}") or (A1="{}" and A2="{}"))'.\
        format(snpname, ref_allele, eff_allele, eff_allele, ref_allele)
   cur.execute(query_string)
   rows = cur.fetchall()
   # "rows" type = list of tuple
   # "rows" example:
   # CHR                                   SNP               A1   A2  MAF         NCHROBS
   # [(b'\x01\x00\x00\x00\x00\x00\x00\x00', 'rs9645429:G:A', 'A', 'G', 0.001823, b'\xb8\x19\x00\x00\x00\x00\x00\x00')]
   con.close()

   if len(rows) == 0:
      return np.NaN
   else:
      rows = rows[0]
      return np.where(rows[2] == eff_allele, rows[4], 1 - rows[4])

def test_query_plink_ref_freq(plink_ref_freq_db):

   print("### query plink_ref_freq_db\n")

   con = sql.connect(plink_ref_freq_db)
   cur = con.cursor()
   query_string = \
        'SELECT * FROM freq WHERE SNP="{}" and ((A1="{}" and A2="{}") or (A1="{}" and A2="{}"))'.\
        format("rs9645429:G:A", "A", "G", "A", "G")
   cur.execute(query_string)
   rows = cur.fetchall()
   con.close()
   for row in rows:
        print(row)
        # print example:
        # "CHR", "NCHROBS" column(integer type) show byte
        # CHR                                   SNP               A1   A2  MAF         NCHROBS
        # (b'\x01\x00\x00\x00\x00\x00\x00\x00', 'rs9645429:G:A', 'A', 'G', 0.001823, b'\xb8\x19\x00\x00\x00\x00\x00\x00')

   return rows

if __name__ == "__main__":

   test_write_plink_ref_freq = False

   if test_write_plink_ref_freq:
      write_plink_ref_freq(plink_ref_freq_file, plink_ref_freq_db)

   rows = test_query_plink_ref_freq(plink_ref_freq_db)


from django.contrib import admin
from django.urls import path

from pages.views import home_view, contact_view, about_view
from products.views import (
    render_initial_data,
    dynamic_delete_view,
    product_list_view,
    dynamic_lookup_view,
)

app_name = 'products'
urlpatterns = [
    # path('admin/', admin.site.urls),
    # path('initial/', render_initial_data),
    path('', product_list_view, name='product-list'),
    path('<int:my_id>/', dynamic_lookup_view, name='product-lookup'),
    path('<int:my_id>/delete/', dynamic_delete_view, name='product-delete'),
]


SHOPIFY_TEMPLATE = {
    "Handle": "",
    "Title": "",
    "Body(HTML)": "",
    "Vendor": "",
    "Type": "",
    "Tags": "",
    "Published": "",
    "Option1 Name": "",
    "Option1 Value": "",
    "Option2 Name": "",
    "Option2 Value": "",
    "Option3 Name": "",
    "Option3 Value": "",
    "Variant SKU": "",
    "Variant Grams": "",
    "Variant Inventory Tracker": "",
    "Variant Inventory Qty": "",
    "Variant Inventory Policy": "",
    "Variant Fulfillment Service": "",
    "Variant Price": "",
    "Variant Compare At Price": "",
    "Variant Requires Shipping": "",
    "Variant Taxable": "",
    "Variant Barcode": "",
    "Image Src": "",
    "Image Alt Text": "",
    "Gift Card": "",
    "Google Shopping / MPN": "",
    "Google Shopping / Age Group": "",
    "Google Shopping / Gender": "",
    "Google Shopping / Google Product Category": "",
    "SEO Title": "",
    "SEO Description": "",
    "Google Shopping / AdWords Grouping": "",
    "Google Shopping / AdWords Labels": "",
    "Google Shopping / Condition": "",
    "Google Shopping / Custom Product": "",
    "Google Shopping / Custom Label 0": "",
    "Google Shopping / Custom Label 1": "",
    "Google Shopping / Custom Label 2": "",
    "Google Shopping / Custom Label 3": "",
    "Google Shopping / Custom Label 4": "",
    "Variant Image": "",
    "Variant Weight Unit": "",
}

APS_TEMPLATE = {
    "sku":"",
    "skus": [],
    "part_number":"",
    "oem":"",
    "title":"",
    "description":"",
    "type":"",
    "category":"",
    "subcategory":"",
    "product_type": "",
    "pool_type": "",
    "pool_or_spa": "",
    "product_handle": "",
    "manufacturer":"",
    "cost":"",
    "costs": [],
    "list_price":"",
    "available":"",
    "obsolete":"",
    "discontinued": "",
    "weight":"",
    "weight_uom":"",
    "height":"",
    "height_uom":"",
    "length":"",
    "length_uom":"",
    "width":"",
    "width_uom":"",
    "uom":"",
    "upc": "",
    "parent":"",
    "parent_id": "",
    "parent_sku":"",
    "image_url":"",
    "images":[],
    "fulfillment":"",
    "asins":[],
    "original_manufacturer":"",
    "instructuctions":"",
    "warranty":"",
    "categories":[],
    "tags":set(),
    "quantity":0,
    "fba_fee":0,
}

CATEGORIES = {
    "name":"",
    "category":""
}
ASINS = {
    "asin":"",
    "sales_rank":"",
    "url":"",
    "fulfillment":""
}

COSTS = {
    "name":"",
    "cost":""
}

SKUS = {
    "name":"",
    "sku":""
}

IMAGES = {
    "source":"",
    "description":"",
    "url":""
}

VALPAK_TEMPLATE = {
    "sku":"",
    "category":"",
    "og_manufacturer":"",
    "title":"",
    "country":"",
    "upc":"",
    "oem":"",
    "part_number":"",
    "image_urls":"",
    "part_number":"",
}


import random
import re
import copy
import traceback
from collections import Counter, defaultdict
from cvmonitor.aug_clean import MonitorValues
from .utils import is_int

def get_fields_info(device_types=['respirator', 'ivac', 'monitor']):

    ivac = {
        'Medication Name': {'max_len': 10, 'dtype': str},
        'Volume Left to Infuse':  {'max_len': 3, 'min': 10, 'max': None, 'dtype': int},
        'Volume to Insert':  {'max_len': 3, 'min': 10, 'max': None, 'dtype': int},
        'Infusion Rate':  {'max_len': 4, 'min': 0, 'max': None, 'dtype': float, 'num_digits_after_point': 1},
    }
    respirator = {
        'Ventilation Mode': {'max_len': 10, 'dtype': str},
        'Tidal Volume': {'max_len': 3, 'min': 350, 'max': 600, 'dtype': int, "min_range": 200, "max_range": 1000},
        'Expiratory Tidal Volume': {'max_len': 3, 'min': None, 'max': None, 'dtype': int},
        'Rate': {'max_len': 2, 'min': 10, 'max': 40, 'dtype': int, "min_range": 0, "max_range": 99},
        'Total Rate': {'max_len': 2, 'min': 10, 'max': 40, 'dtype': int, "min_range": 0, "max_range": 99},
        'Peep': {'max_len': 2, 'min': None, 'max': None, 'dtype': int, "min_range": 0, "max_range": 99},
        'Ppeak': {'max_len': 2, 'min': None, 'max': 40, 'dtype': int},
        'MV': {'max_len': 3, 'min': None, 'max': 999, 'dtype': int, "min_range": 0, "max_range": 1000},
        'FIO2': {'max_len': 3, 'min': None, 'max': None, 'dtype': int},
        # FIXME: assume that operator selects only X.X part, without the digit 1
        'I:E Ratio': {'max_len': 2, 'min': None, 'max': None, 'dtype': float, 'num_digits_after_point': 1},
        'Inspiratory time': {'max_len': 2, 'min': None, 'max': None, 'dtype': float, 'num_digits_after_point': 1},
    }
    monitor = {
        'HR': {'max_len': 3, 'min': 45, 'max': 120, 'dtype': int, "max_range": 200, "min_range": 10},
        'SpO2': {'max_len': 3, 'min': 90, 'max': None, 'dtype': int, "min_range": 20, "max_range": 100},
        'RR': {'max_len': 2, 'min': 8, 'max': 26, 'dtype': int, "min_range": 0, "max_range": 99},
        'IBP': {'max_len': 7, 'regex': '.*?([1-2]{0,1}[0-9]{1,2}) *([/17]) *([1-2]{0,1}[0-9]{1,2}).*', 'sub': '\\1/\\3'},
        'NIBP': {'max_len': 7, 'regex': '.*?([1-2]{0,1}[0-9]{1,2}) *([/17]) *([1-2]{0,1}[0-9]{1,2}).*', 'sub': '\\1/\\3'},
        'IBP-Mean': {'max_len': 3, 'dtype': int, "min_range": 10, "max_range": 500},
        'NIBP-Mean': {'max_len': 3, 'dtype': int, "min_range": 10, "max_range": 500},
        'IBP-Systole': {'max_len': 3, 'min': 80, 'max': 180, 'dtype': int, "min_range": 40, "max_range": 299},  # left blood pressure
        'IBP-Diastole': {'max_len': 3, 'min': 40, 'max': 100, 'dtype': int, "min_range": 40, "max_range": 299},  # right blood pressure
        'NIBP-Systole': {'max_len': 3, 'min': 80, 'max': 180, 'dtype': int, "min_range": 40, "max_range": 299},  # left blood pressure
        'NIBP-Diastole': {'max_len': 3, 'min': 40, 'max': 100, 'dtype': int, "min_range": 40, "max_range": 299},  # right blood pressure
        'Temp': {'min_len': 2, 'max_len': 3, 'min': 35.0, 'max': 38.0, 'dtype': float, 'num_digits_after_point': 1, "min_range": 33, "max_range": 45},
        'etCO2': {'max_len': 2, 'min': 24, 'max': 44, 'dtype': int, "min_range": 0, "max_range": 999},
    }
    # for annotations only, currently not found in android app
    # 'hr_saturation': {'max_len': 3, 'min': 45, 'max': 120, 'dtype': int},
    devices = {}

    if 'respirator' in device_types:
        devices.update(respirator)
    if 'monitor' in device_types:
        devices.update(monitor)
    if 'ivac' in device_types:
        devices.update(ivac)
    return devices

def get_field_rand_value(field_info, current=None):
    if field_info.get('dtype') in [float, int]:
        max_val = field_info.get('max') or int(0.99999 * (10**(field_info['max_len'])))
        min_val = field_info.get('min') or 0
        if current is None:
            base = random.randint(min_val,  max_val)
            if 'num_digits_after_point' in field_info:
                divisor = 10**field_info['num_digits_after_point']
                base = float(base) + random.randint(0, divisor) * (1/divisor)
        else:
            base = field_info['dtype'](current) + random.randint(-3, 3)
            if random.randint(0, 1) == 0:
                base += 0.1
            base = max(min_val, min(base, max_val))
            base = field_info['dtype'](base)
    if field_info.get('dtype') in [str]:
        base = random.choice(['wine', 'beer', 'coffee', 'soda', 'water'])
    if 'dtype' not in field_info:
        base = '100/100'  # rstr.xeger(field_info['regex'])
    max_len = field_info.get('max_len', 20)
    base = str(base)
    if '.' in base:
        max_len += 1
    if len(base) > max_len:
        base = base[:max_len]
    return base

def cleanup_field(field_info, field_value):
    res = ''
    if field_info.get('regex'):
        regex_res = re.match(field_info.get('regex'), field_value or '')
        if not regex_res:
            return ''
        if field_info.get('sub'):
            return re.sub(field_info.get('regex'), field_info.get('sub'), field_value or '')
        return ''.join(regex_res.groups())
    if field_info.get('dtype') == str:
        res = field_value
    if field_info.get('dtype') == int:
        for c in field_value:
            if is_int(c):
                res += c
                if len(res) >= field_info.get('max_len', 10):
                    break
    if field_info.get('dtype') == float:
        for c in field_value:
            if is_int(c) or c == '.':
                res += c
                if len(res) >= field_info.get('max_len', 10)+1:
                    break
    return res

# Currently unused, replaced with Cleaner
class PostProcessor():

    """
    Cleaning ocr data
    """

    def __init__(self, devices, average_length=3):
        self.monitors = {}
        self.devices = devices
        self.average_length = average_length

    def clean(self, segments):
        cleaned_segments = {}
        for s in segments:
            if s.get('name') and s.get('name') in self.devices and s.get('value') and s.get('level') != 'crop':
                cleaned = copy.deepcopy(s)
                cleaned['value'] = cleanup_field(self.devices[s['name']], s['value'])
                cleaned_segments[s['name']] = cleaned
        for s in segments:
            if s.get('name') and s.get('name') in self.devices and s.get('value'):
                if s.get('name') in cleaned_segments and not cleaned_segments[s.get('name')].get('value'):
                    cleaned = copy.deepcopy(s)
                    cleaned['value'] = cleanup_field(self.devices[s['name']], s['value'])
                    cleaned_segments[s['name']] = cleaned

        for s in segments:
            if s.get('name') == 'tracker':
                cleaned_segments['tracker'] = s
        cleaned_segments = [s for s in cleaned_segments.values()]
        return cleaned_segments

    def average(self, segments, monitorId, imageId):
        if monitorId not in self.monitors:
            self.monitors[monitorId] = [(imageId, segments)]
            return segments
        if len(self.monitors[monitorId]) <= self.average_length:
            self.monitors[monitorId].append((imageId, segments))

        if len(self.monitors[monitorId]) > self.average_length:
            self.monitors[monitorId].pop(0)

        if len(self.monitors[monitorId]) < self.average_length:
            return segments

        values = {}
        segments_dict = {}
        for pId, pSegments in self.monitors[monitorId]:
            for s in pSegments:
                if s.get('name'):
                    segments_dict[s.get('name')] = s
                    if s.get('name') not in values:
                        values[s['name']] = []
                    values[s['name']].append(s.get('value'))

        for k, v in values.items():
            if v:
                segments_dict[k]['value'] = Counter(v).most_common(1)[0][0]
            else:
                segments_dict[k]['value'] = None
        return [s for s in segments_dict.values()]

    def __call__(self, segments, monitorId, imageId):
        tracker = None
        for s in segments:
            if s.get('name') == 'tracker':
                tracker = copy.deepcopy(s)
        resseg = self.clean(segments)  # self.average(self.clean(segments),monitorId,imageId)
        for s in segments:
            if s.get('name') == 'tracker':
                s.update(tracker)
        return resseg

class Cleaner:

    def __init__(self, sensors):
        self.sensors = sensors
        self.monitors = defaultdict(lambda: MonitorValues(sensors))

    def sysdis(self, segments_dict):
        if "IBP" in segments_dict and "IBP-Systole" not in segments_dict and "IBP-Diastole" not in segments_dict:
            values = segments_dict["IBP"]["value"]
            if values and isinstance(values, list):
                values = [v for v in values if v and isinstance(v, str)]
                if all(['/' in v for v in values]):
                    systole = copy.deepcopy(segments_dict["IBP"])
                    systole["value"] = [x.split("/")[0] for x in values]
                    diastole = copy.deepcopy(segments_dict["IBP"])
                    diastole["value"] = [x.split("/")[-1] for x in values]
                    systole["name"] = "IBP-Systole"
                    diastole["name"] = "IBP-Diastole"
                    segments_dict["IBP-Systole"] = systole
                    segments_dict["IBP-Diastole"] = diastole
                    del segments_dict["IBP"]

        if "NIBP" in segments_dict and "NIBP-Systole" not in segments_dict and "NIBP-Diastole" not in segments_dict:
            values = segments_dict["NIBP"]["value"]
            if values and isinstance(values, list):
                values = [v for v in values if v and isinstance(v, str)]
                if all(['/' in v for v in values]):
                    systole = copy.deepcopy(segments_dict["NIBP"])
                    systole["value"] = [x.split("/")[0] for x in values]
                    diastole = copy.deepcopy(segments_dict["NIBP"])
                    diastole["value"] = [x.split("/")[-1] for x in values]
                    systole["name"] = "NIBP-Systole"
                    diastole["name"] = "NIBP-Diastole"
                    segments_dict["NIBP-Systole"] = systole
                    segments_dict["NIBP-Diastole"] = diastole
                    del segments_dict["NIBP"]

    def basic_cleanup(self, segments):
        segments_dict = {}
        for segment in segments:
            try:
                name = segment.get("name")
                if name is None or not name:
                    continue
                if name not in segments_dict:
                    segments_dict[name] = copy.deepcopy(segment)
                    segments_dict[name]["value"] = list()
                cleaned_field = segment.get("value")
                if name in self.sensors and segment.get("value"):
                    cleaned_field = cleanup_field(self.sensors[name], segment.get("value"))
                segments_dict[name]["value"].append(cleaned_field)

                # Get the location of the merged segment from the crop
                if segment.get("level") == "crop":
                    segments_dict[name].update(dict(top=segment["top"], left=segment["left"], bottom=segment["bottom"], right=segment["right"]))
            except Exception:
                traceback.print_exc()
                continue
        return segments_dict

    def clean_segments(self, segments, monitorId, imageId):
        try:
            segments_dict = self.basic_cleanup(segments)

            # Split systole-diastole
            self.sysdis(segments_dict)

            if monitorId is None:
                monitorId = "unkown monitor"
            mv: MonitorValues = self.monitors[monitorId]

            for name, aug_dict in segments_dict.items():
                try:
                    if name in self.sensors and self.sensors[name].get("dtype") in [float, int]:
                        res = mv.get_latest_valid_value(aug_dict)
                        if res:
                            segments_dict[name]["value"] = res
                    if isinstance(segments_dict[name]["value"], list):
                        if not segments_dict[name]["value"]:
                            segments_dict[name]["value"] = None
                        else:
                            try:
                                segments_dict[name]["value"] = Counter(segments_dict[name]["value"]).most_common(1)[0][0]
                            except Exception:
                                segments_dict[name]["value"] = segments_dict[name]["value"][0] if len(segments_dict[name]["value"]) > 0 else None
                    if "clean_value" in segments_dict[name]:
                        segments_dict[name].pop("clean_value")
                except Exception:
                    traceback.print_exc()
                    continue
            return [v for k, v in segments_dict.items()]
        except Exception:
            traceback.print_exc()
            return segments


import bpy
import sys
import importlib
import inspect
from pathlib import Path

bl_info = {
    'name': 'Taremin Mesh Combiner',
    'category': '3D View',
    'author': 'Taremin',
    'location': 'View 3D > UI > Taremin',
    'description': "mesh combine tool",
    'version': (0, 1, 2),
    'blender': (2, 80, 0),
    'wiki_url': '',
    'tracker_url': '',
    'warning': '',
}

# モジュール読み込み
module_names = [
    "util",
    "group_settings",
    "props",
    "combine_mesh",
    "panel",
]
namespace = globals()
for name in module_names:
    fullname = '{}.{}.{}'.format(__package__, "lib", name)
    if fullname in sys.modules:
        namespace[name] = importlib.reload(sys.modules[fullname])
    else:
        namespace[name] = importlib.import_module(fullname)

# クラスの登録
classes = [
    # このファイル内のBlenderクラス
]
for module in module_names:
    for module_class in [obj for name, obj in inspect.getmembers(namespace[module], inspect.isclass) if hasattr(obj, "bl_rna")]:
        classes.append(module_class)

def register():
    for value in classes:
        retry = 0
        while True:
            try:
                bpy.utils.register_class(value)
                break
            except ValueError:
                bpy.utils.unregister_class(value)
                retry += 1
                if retry > 1:
                    break
    props = namespace["props"]
    bpy.types.Scene.taremin_mc = bpy.props.PointerProperty(
        type=props.TareminMeshCombinerProps)

def unregister():
    for value in classes:
        print("Unregister:", value)
        try:
            bpy.utils.unregister_class(value)
        except RuntimeError:
            pass

    del bpy.types.Scene.taremin_mc
    Path(__file__).touch()

if __name__ == '__main__':
    register()


import os
import random
from typing import Any, Dict, List

from django.utils import timezone

import yaml
from faker import Faker
from requests_mock import Mocker

fake = Faker()
MOCK_FILES_DIR = os.path.join(
    os.path.abspath(os.path.dirname(__file__)),
    "schemas",
)

_cache = {}

def read_schema(service: str):
    if service not in _cache:
        file_name = f"{service}.yaml"
        file = os.path.join(MOCK_FILES_DIR, file_name)
        with open(file, "rb") as api_spec:
            _cache[service] = api_spec.read()

    return _cache[service]

def mock_service_oas_get(m: Mocker, url: str, service: str, oas_url: str = "") -> None:
    if not oas_url:
        oas_url = f"{url}schema/openapi.yaml?v=3"
    content = read_schema(service)
    m.get(oas_url, content=content)

def generate_oas_component(
    service: str,
    component: str,
    **properties,
) -> Dict[str, Any]:
    """
    Generate an object conforming to the OAS schema definition.

    Any extra kwargs passed in are used as explicit values for properties.
    """
    schema = yaml.safe_load(read_schema(service))

    definition = schema["components"]
    for bit in component.split("/"):
        definition = definition[bit]

    assert (
        definition["type"] == "object"
    ), "Types other than object are not supported (yet)"

    return generate_object(schema, definition, **properties)

def generate_object(schema: dict, definition: dict, **properties):
    obj = properties.copy()

    if "discriminator" in definition:
        # Not implemented yet...
        return {}

    for prop, prop_def in definition["properties"].items():
        if prop in obj:
            continue
        obj[prop] = generate_prop(schema, prop_def)
    return obj

def generate_prop(schema: dict, prop_definition: dict) -> Any:
    if "$ref" in prop_definition:
        ref_bits = prop_definition["$ref"].replace("#/", "", 1).split("/")
        prop_definition = schema
        for bit in ref_bits:
            prop_definition = prop_definition[bit]

    prop_type = prop_definition["type"]

    if prop_definition.get("nullable"):
        return None

    enum = prop_definition.get("enum")
    if enum:
        return random.choice(enum)

    if prop_type == "string":
        fmt = prop_definition.get("format")
        if fmt == "uri":
            return fake.url(schemes=["https"])

        elif fmt == "duration":
            return "P3W"

        elif fmt == "date":
            return fake.date()

        elif fmt == "date-time":
            return fake.date_time(tzinfo=timezone.utc).isoformat()

        elif fmt is None:
            return fake.pystr(
                min_chars=prop_definition.get("minLength"),
                max_chars=prop_definition.get("maxLength", 20),
            )

    elif prop_type == "boolean":
        return fake.pybool()

    elif prop_type == "array":
        item = generate_prop(schema, prop_definition["items"])
        return [item]

    elif prop_type == "object":
        return generate_object(schema, prop_definition)

def paginated_response(results: List[dict]) -> Dict[str, Any]:
    body = {
        "count": len(results),
        "previous": None,
        "next": None,
        "results": results,
    }
    return body


from base import *
import sys
import os
import csv
import qi

class face(base):

    def __init__(self, ip, port):

        base.__init__(self)
        self.ip = ip
        self.port = port

    def initface(self, demo, nao):
        try:
            app = qi.Application([str(demo) , "--qi-url=" + "tcp://" + str(self.ip) + ":" + str(self.port)])
        except RuntimeError:
            print ("Connection Failed for Face api")
            sys.exit(1)

        self.myC = demo(app, nao)
        app.run()


from contextlib import contextmanager
import logging
import time

def add_async_graph(module, r: float = None, log_flops: bool = False, log_runtime: bool = False):
    module.asy_graph = None
    module.asy_flops_log = [] if log_flops else None
    module.asy_runtime_log = [] if log_runtime else None
    if r is not None:
        module.asy_radius = r
    return module

def make_asynchronous(module, initialization_func, processing_func):
    def async_forward(*args, **kwargs):
        with async_context(module, initialization_func, processing_func) as func:
            output = func(module, *args, **kwargs)
        return output

    module.forward = async_forward
    return module

@contextmanager
def async_context(module, initialization_func, processing_func):
    do_log_runtime = getattr(module, "asy_runtime_log", None) is not None
    start_time = time.time() if do_log_runtime else None

    if module.asy_graph is None:
        logging.debug(f"Graph initialization of module {module}")
        yield initialization_func
    else:
        logging.debug(f"Calling processing of module {module}")
        yield processing_func

    if do_log_runtime:
        dt = time.time() - start_time
        module.asy_runtime_log.append(dt)


# -*- coding: utf-8 -*-
from setuptools import setup

__author__ = 'viruzzz-kun'
__version__ = '0.1'

if __name__ == '__main__':
    setup(
        name="bouser",
        version=__version__,
        description="Bouser application server for Twisted",
        long_description='',
        author=__author__,
        author_email="viruzzz.soft@gmail.com",
        license='ISC',
        url="http://github.com/hitsl/bouser",
        packages=[
            "bouser",
            "bouser.helpers",
            "bouser.ext",
            "bouser.castiel",
            "bouser.castiel.auth",
            "bouser.web",
            "twisted.plugins",
        ],
        zip_safe=False,
        package_data={
            'bouser.web': [
                'static/bootstrap/css/*',
                'static/bootstrap/fonts/*',
                'static/bootstrap/img/*',
                'static/bootstrap/js/*',
                'static/css/*',
                'static/js/*',
                'templates/*'
            ],
            'twisted': ['plugins/bouser_plugin.py'],
        },
        install_requires=[
            'twisted',  # Core
            'blinker',  # For signals
            'msgpack-python',  # Serialization
            'jinja2',  # Web
            'six',  # Compatibility
        ],
        extras_require={
            'Auth.SVN': [],
            'Auth.SASLDB': [],
        },
        classifiers=[
            "Development Status :: 4 - Beta",
            "Environment :: No Input/Output (Daemon)",
            "Programming Language :: Python",
        ])

    try:
        from twisted.plugin import IPlugin, getPlugins
        list(getPlugins(IPlugin))
    except ImportError:
        raise SystemExit("twisted not found.  Make sure you have installed the Twisted core package.")


import requests

def get_access_token(client, secret):
    access_url = 'https://api.moltin.com/oauth/access_token'
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
    }
    payload = {
        'client_id': client,
        'client_secret': secret,
        'grant_type': 'client_credentials',
    }
    response = requests.post(access_url, headers=headers, data=payload)
    response.raise_for_status()
    return response.json()['access_token']

def get_all_products(token):
    products_url = 'https://api.moltin.com/pcm/products'
    headers = {
        'Authorization': f'Bearer {token}',
    }
    response = requests.get(products_url, headers=headers)
    response.raise_for_status()
    items = []
    for item in response.json()['data']:
        item['attributes']['id'] = item['id']
        items.append(item['attributes'])
    return items

def get_product(token, product_id):
    product_url = f'https://api.moltin.com/catalog/products/{product_id}'
    headers = {
        'Authorization': f'Bearer {token}',
    }
    response = requests.get(product_url, headers=headers)
    response.raise_for_status()
    return response.json()['data']

def add_product_to_cart(token, cart_id, product_id, quantity):
    cart_url = f'https://api.moltin.com/v2/carts/{cart_id}/items'
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json',
    }
    payload = {
        'data': {
            'id': product_id,
            'type': 'cart_item',
            'quantity': quantity,
        }
    }
    response = requests.post(cart_url, headers=headers, json=payload)
    response.raise_for_status()
    return response.json()

def get_cart_items(token, cart_id):
    cart_url = f'https://api.moltin.com/v2/carts/{cart_id}/items'
    headers = {
        'Authorization': f'Bearer {token}',
    }
    response = requests.get(cart_url, headers=headers)
    response.raise_for_status()
    return response.json()

def remove_cart_item(token, cart_id, product_id):
    item_url = f'https://api.moltin.com/v2/carts/{cart_id}/items/{product_id}'
    headers = {
        'Authorization': f'Bearer {token}',
    }
    response = requests.delete(item_url, headers=headers)
    response.raise_for_status()
    return response.json()

def get_product_available_stock(token, product_id):
    stock_url = f'https://api.moltin.com/v2/inventories/{product_id}'
    headers = {
        'Authorization': f'Bearer {token}',
    }
    response = requests.get(stock_url, headers=headers)
    response.raise_for_status()
    return response.json()['data']['available']

def get_file_url_by_id(token, file_id):
    file_url = f'https://api.moltin.com/v2/files/{file_id}'
    headers = {
        'Authorization': f'Bearer {token}',
    }
    response = requests.get(file_url, headers=headers)
    response.raise_for_status()
    return response.json()['data']['link']['href']

def create_customer(token, name, email):
    customer_url = 'https://api.moltin.com/v2/customers'
    headers = {
        'Authorization': f'Bearer {token}',
        'Content-Type': 'application/json',
    }
    payload = {
        'data': {
            'type': 'customer',
            'name': name,
            'email': email,
        }
    }
    response = requests.post(customer_url, headers=headers, json=payload)
    response.raise_for_status()
    return response.json()


#!/bin/python3

import os
import math

def theLoveLetterMystery(s):
    # Check if the string is already palindrome
    h = math.ceil(len(s)/2)
    l = len(s) // 2
    if s[:l] == s[h:][::-1]:
        return 0

    # Check what letters doesn't make it one
    operations = 0
    for i in range(l):
        # Compare i to its corresponding inverse
        inv = len(s)-1-i
        if s[i] != s[inv]:
            # Calculate the number of operations needed
            operations += abs(ord(s[i]) - ord(s[inv]))
    return operations

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    q = int(input())

    for q_itr in range(q):
        s = input()

        result = theLoveLetterMystery(s)

        fptr.write(str(result) + '\n')

    fptr.close()


""" This program runs a series of numbers from a user chosen start number and end number """

#get the start+end numbers
start = int(input("Choose a starting number"))

end = int(input("Choose a end number"))

if start < end:
    increment = 1
else:
    increment = -1

#forloop
for i in range (start, end+increment, increment):
    print(i)


from decimal import Decimal

from typing import List

from models import User
from models import StatementLevel, Statement
from models.transaction import Transaction

import datetime
import mongoengine
import pytest
from models.account import Account
from models.category import TransactionCategory
from models.income_transaction import IncomeTransaction
from models.expense_transaction import ExpenseTransaction

def not_repeated(items) -> bool:
    return len(set(items)) == len(items)

def is_consistent(month_statement: Statement):
    accounts_total_change = sum([acc.income + acc.expense for acc in month_statement.accounts])
    funds_total_change = sum([fnd.income + fnd.expense for fnd in month_statement.funds])
    categories_total_change = sum([cat.change for cat in month_statement.categories])

    accounts_not_repeated = not_repeated(
        [str(account_change.account.id) for account_change in month_statement.accounts]) is True
    categories_not_repeated = not_repeated(
        [str(category_change.category.id) for category_change in month_statement.categories]) is True
    funds_not_repeated = not_repeated([str(fund_change.fund.id) for fund_change in month_statement.funds]) is True

    return accounts_total_change == funds_total_change == categories_total_change and accounts_not_repeated and funds_not_repeated and categories_not_repeated

@pytest.fixture(params=[
    ([Decimal("1000.00"), Decimal("300"), Decimal("500")]),
    ([Decimal("-222.00"), Decimal("400"), Decimal("-500")]),
    ([Decimal("-211.12"), Decimal("12.1"), Decimal("500.00"), Decimal("-451.00"), Decimal("723.99")]),
])
def one_month_transactions(request, db, mongodb, user):
    account = Account.objects(owner=user)[0]

    income_category = TransactionCategory.objects(kind="income")[0]
    expense_category = TransactionCategory.objects(kind="expense")[0]

    transaction_date = datetime.date(2021, 2, 1)

    transactions = []

    for change in request.param:
        if change > 0:
            transaction = IncomeTransaction(owner=user, account_id=account.id, change=change,
                                            category=income_category,
                                            date_accomplished=transaction_date)
        else:
            transaction = ExpenseTransaction(owner=user, account_id=account.id, change=change,
                                             category=expense_category,
                                             date_accomplished=transaction_date)

        transaction.save()
        transactions.append(transaction)

    return transactions

def test_all_levels_query(user: User, one_month_transactions: List[Statement]):
    # TODO load several month, test all levels belongs to request years a months
    statements = Statement.objects.all_levels(month=2, year=2021, owner=user)

    assert len(statements) == 3
    result_levels = [statement.level for statement in statements]
    for level in [StatementLevel.GENERAL, StatementLevel.YEAR, StatementLevel.MONTH]:
        assert level in result_levels

@pytest.mark.parametrize(('change',),
                         [(Decimal("-300.00"),), (Decimal("300.00"),), (Decimal("2000.21"),), (Decimal("-1.23"),)])
def test_new_transaction_generates_new_statements(db, mongodb, user, change):
    # TODO Move this part to fixture
    account = Account.objects(owner=user)[0]

    income_category = TransactionCategory.objects(kind="income")[0]
    expense_category = TransactionCategory.objects(kind="expense")[0]

    transaction_date = datetime.date(2021, 2, 12)

    if change > 0:
        transaction = IncomeTransaction(owner=user, account_id=account.id, change=change,
                                        category=income_category.id,
                                        date_accomplished=transaction_date)
    else:
        transaction = ExpenseTransaction(owner=user, account_id=account.id, change=change,
                                         category=expense_category.id,
                                         date_accomplished=transaction_date)

    transaction.save()

    statements = Statement.objects.all_levels(month=transaction_date.month,
                                              year=transaction_date.year,
                                              owner=user)

    for statement in statements:
        assert statement is not None
        assert len(statement.categories) == 1
        assert len(statement.accounts) == 1
        assert len(statement.funds) > 0
        assert is_consistent(statement) is True

        assert statement.categories[0].change == change

        if change > 0:
            assert statement.categories[0].category.id == income_category.id
        else:
            assert statement.categories[0].category.id == expense_category.id

        assert statement.accounts[0].income + statement.accounts[0].expense == change
        assert statement.accounts[0].account.id == account.id

        assert sum([fund_change.income + fund_change.expense for fund_change in statement.funds]) == change

        if change > 0:
            assert statement.accounts[0].expense == 0
            assert sum([fund_change.expense for fund_change in statement.funds]) == 0
        else:
            assert statement.accounts[0].income == 0
            assert sum([fund_change.income for fund_change in statement.funds]) == 0

@pytest.mark.parametrize(('changes'), [
    ([Decimal("-100.00"), Decimal("300"), Decimal("500")]),
    ([Decimal("-222.00"), Decimal("400"), Decimal("-500")]),
    ([Decimal("-211.12"), Decimal("12.1"), Decimal("500.00"), Decimal("451.00"), Decimal("723.99")]),
])
def test_new_transaction_updates_existing_statements(db, mongodb, user, changes):
    account = Account.objects(owner=user)[0]

    income_category = TransactionCategory.objects(kind="income")[0]
    expense_category = TransactionCategory.objects(kind="expense")[0]

    transaction_date = datetime.date(2021, 2, 12)

    for change in changes:

        if change > 0:
            transaction = IncomeTransaction(owner=user, account_id=account.id, change=change,
                                            category=income_category,
                                            date_accomplished=transaction_date)
        else:
            transaction = ExpenseTransaction(owner=user, account_id=account.id, change=change,
                                             category=expense_category,
                                             date_accomplished=transaction_date)

        transaction.save()

    statements = Statement.objects.all_levels(month=transaction_date.month,
                                              year=transaction_date.year,
                                              owner=user)

    for statement in statements:
        total_income = sum([change for change in changes if change > 0])
        total_expense = sum(changes) - total_income
        total_balance = total_income + total_expense

        assert len(statement.categories) == 2
        for category_change in statement.categories:
            if category_change.category.id == expense_category.id:
                assert category_change.change == total_expense

            if category_change.category.id == income_category.id:
                assert category_change.change == total_income

        assert len(statement.accounts) == 1
        assert statement.accounts[0].income == total_income
        assert statement.accounts[0].expense == total_expense
        assert len(statement.funds) > 0
        assert sum([fund_change.income + fund_change.expense for fund_change in statement.funds]) == total_balance

    # TODO: Collect every fund transacion and validate against fund changes.

def test_statements_consistency(user, one_month_transactions):
    transaction_date = one_month_transactions[0].date_accomplished
    expected_total_change = sum([t.total_change for t in one_month_transactions])
    statements = Statement.objects.all_levels(month=transaction_date.month,
                                              year=transaction_date.year,
                                              owner=user)

    for statement in statements:
        assert is_consistent(statement) is True
        assert expected_total_change == statement.total_change

def test_removed_transaction_changes_statements(user, one_month_transactions: List[Statement]):
    transaction_date = one_month_transactions[0].date_accomplished

    expected_total_change = sum([t.total_change for t in one_month_transactions])

    for transaction in one_month_transactions:
        statements_initial_state: List[Statement] = list(Statement.objects.all_levels(month=transaction_date.month,
                                                                                year=transaction_date.year,
                                                                                owner=user))

        tr: Transaction = Transaction.objects(
            id=transaction.id).get()  # Getting a transaction instance instead of a specialization
        total_change = tr.total_change
        tr.delete()

        statements_current_state: List[Statement] = list(Statement.objects.all_levels(month=transaction_date.month,
                                                                                year=transaction_date.year,
                                                                                owner=user))

        expected_total_change -= total_change

        tr_account_id = tr.account_transactions[0].account.id

        for statement_initial_state, statement_current_state in [
            (statements_initial_state[index], statements_current_state[index]) for index, _ in
            enumerate(statements_initial_state)]:

            assert is_consistent(statement_current_state)
            if tr.is_income():
                assert statement_current_state.get_account_change(
                    tr_account_id).income == statement_initial_state.get_account_change(tr_account_id).income - \
                       tr.account_transactions[0].change

            if tr.is_expense():
                assert statement_current_state.accounts[0].expense == statement_initial_state.get_account_change(
                    tr_account_id).expense - \
                       tr.account_transactions[0].change

            assert statement_current_state.total_change == expected_total_change


def shiftedTAS(N, L, F, n_left):
    """
    IMPLEMENTING THE SHIFTED CYCLIC TAS
    :param N: Number of machines
    :param L: Coding parameter
    :param F: Number of tasks
    :param n_left: index of machine that left
    :return: an array shiftedT[n] representing a pair (start, end) indices of the task assignment to machine n
             shiftedT[n_left] = (-1,-1)
    """
    # only use this function when one machine left
    assert n_left != -1, "ERROR: n_left = -1"

    # formula slightly different from the paper due to labelling n_left from 0->N-1 instead
    delta = ((N - n_left - 1) - int((N + L - 2) / 2)) * (F / (N * (N - 1)))
    shiftedT = []
    num_allocated_tasks = (L * F) / (N - 1)
    for n in range(N):
        if n == n_left:
            start = None
            end = None
        elif n < n_left:
            start = int(delta + n * F / (N - 1)) % F
            end = int(start + num_allocated_tasks - 1) % F
        else:
            start = int(delta + (n - 1) * F / (N - 1)) % F
            end = int(start + num_allocated_tasks - 1) % F
        shiftedT.append((start, end))

    return shiftedT

def main():
    N = 5
    L = 3
    F = 20
    for n_left in range(N):
        T = shiftedTAS(N, L, F, n_left)
        print("n_left = ", n_left, "\n")
        for n in range(N):
            print("     n = ", n, ": [", T[n][0],", ", T[n][1],"]")
        print("-------------------------\n")

if __name__ == '__main__':
    main()


#!/usr/bin/python3
import transformations
import numpy
from matplotlib import pyplot as plt

def plot_vec(d, starti, name, ax, maxy=50):
  t = data[:, 0]
  x = data[:, starti+0]
  y = data[:, starti+1]
  z = data[:, starti+2]
  plt.figure()
  plt.subplot(111, sharex=ax)
  plt.plot(t, x, label=name+" x")
  plt.plot(t, y, label=name+" y")
  plt.plot(t, z, label=name+" z")
#  plt.ylim(-maxy, maxy)
  plt.legend()

data = numpy.genfromtxt("basic_sim_data.csv", delimiter=',')[1:]
x = []
y = []
vx = []
vy = []
t = []
yaw = []
heel = []
pitch = []
heading = []
sail = []
rudder = []
yaw_true = []
alphaw = []
alphasail = []
goalr = []
goalh = []
for row in data:
  for i in range(len(row)):
    if abs(row[i]) > 1e5:
      row[i] = float("nan")
  t.append(row[0])
  sail.append(row[1])
  rudder.append(row[2])
  x.append(row[3])
  y.append(row[4])
  vx.append(row[5])
  vy.append(row[6])
  heading.append(numpy.arctan2(vy[-1], vx[-1]));
  q = row[7:11]
  e = transformations.euler_from_quaternion(q, axes='rzxy')
  yaw.append(e[0])
  heel.append(e[1])
  pitch.append(e[2])

  rotmat = transformations.quaternion_matrix(q)
  yaw_true.append(numpy.arctan2(rotmat[1, 0], rotmat[0, 0]))
  windx = row[11]
  windy = row[12]
  alphaw.append(numpy.arctan2(vy[-1] - windy, vx[-1] - windx) - yaw_true[-1])
  alphasail.append(alphaw[-1] - sail[-1])
  goalr.append(numpy.clip(yaw_true[-1] - .1, -.4, .4))
  goalh.append(row[46])

plt.plot(x, y, 'o')
plt.title("Boat Position (Wind is blowing left-to-right on screen)")
plt.xlabel("X position (m)")
plt.ylabel("Y position (m)")
plt.figure()
ax = plt.subplot(111)
ax.plot(t, x, label='x')
ax.plot(t, y, label='y')
ax2 = ax.twinx()
ax2.plot(t, vx, 'c*', label='vx')
ax2.plot(t, vy, 'r*', label='vy')
ax.legend(loc='upper left')
ax2.legend(loc='upper right')
plt.figure()
plt.subplot(111, sharex=ax)
plt.plot(t, yaw, label='Heading')
plt.plot(t, heel, label='Heel')
plt.plot(t, pitch, label='Pitch')
plt.legend()
plt.figure()
plt.subplot(111, sharex=ax)
plt.plot(t, sail, label="Sail")
plt.plot(t, rudder, label="Rudder")
plt.plot(t, yaw_true, label="yaw")
plt.plot(t, alphaw, label="Apparent Wind")
plt.plot(t, alphasail, label="Sail AoA")
plt.plot(t, goalh, label="Goal Heading")
plt.plot(t, heading, label="true heading")
plt.legend()
plt.figure()
plt.plot(t, data[:, 33], label="Rudder Yaw Torque")
plt.plot(t, data[:, 30], label="Sail Yaw Torque")
plt.plot(t, data[:, 45], label="Net Yaw Torque")
plt.legend()
plt.title("All Yaw Torques");
plot_vec(data, 13, "Sail Force", ax)
plot_vec(data, 16, "Rudder Force", ax)
plot_vec(data, 19, "Keel Force", ax)
plot_vec(data, 22, "Hull Force", ax)
plot_vec(data, 25, "Net Force", ax)
plot_vec(data, 28, "Sail Torque", ax)
plot_vec(data, 31, "Rudder Torque", ax)
plot_vec(data, 34, "Keel Torque", ax)
plot_vec(data, 37, "Hull Torque", ax)
plot_vec(data, 40, "Righting Torque", ax)
plot_vec(data, 43, "Net Torque", ax)
plt.show()


from tkinter import *
from random import *
from tkinter import messagebox

def gameStart():
    global gameStarted, numBomb, gameOver, gameVictory, bombRemaining, realBombRemaining, numRevealed
    setting.destroy()
    main = Tk()
    main.title("Minesweeper Game")
    main.resizable(FALSE, FALSE)
    #print(mapWidth)
    #print(mapHeight)
    gameStarted = False
    gameOver = False
    gameVictory = False
    realBombRemaining = numBomb
    bombRemaining = numBomb
    numRevealed = 0

    def checkVictory():
        global gameOver, gameVictory, mapWidth, mapHeight
        if ((numRevealed + numBomb == mapHeight * mapWidth) or (bombRemaining == realBombRemaining == 0)) and not gameOver:
            gameOver = True
            gameVictory = True
            gameWon()

    def genBomb(pressedx, pressedy): # Generate bombs on the map, excluding the first grid and those nearby
        global mapHeight, mapWidth, numBomb, bomb
        safe = [i for i in range(mapWidth * mapHeight)]
        bomb = []

        # Exclude first grid and those nearby
        numRemoved = 1
        safe.remove(pressedx * mapWidth + pressedy)
        for i in range(-1, 2):
            for j in range(-1, 2):
                if 0 <= pressedx + i and pressedx + i <= mapHeight - 1 and 0 <= pressedy + j and pressedy + j <= mapWidth - 1 and (i != 0 or j != 0):
                    #print((pressedx + i), (pressedy + j))
                    if len(safe) > numBomb:
                        #print((pressedx + i), (pressedy + j),len(safe),  mapHeight * mapWidth - numBomb)
                        safe.remove((pressedx + i) * mapWidth + (pressedy + j))
                        numRemoved += 1

        # Generate bombs randomly from the safe list, removing them from the safe list while doing so
        for i in range(numBomb):
            selected = int(random() * (mapWidth * mapHeight - i - numRemoved))
            #print(i, safe[selected] // mapWidth, safe[selected] % mapWidth)
            gameGrid[safe[selected] // mapWidth][safe[selected] % mapWidth].isBomb = True
            #gameGrid[safe[selected] // mapWidth][safe[selected] % mapWidth].interact.config(bg="red")
            bomb.append(safe[selected])
            safe.remove(safe[selected])

    # Popup message for winning, reveal all grids
    def gameWon():
        for i in range(mapHeight):
            for j in range(mapWidth):
                gameGrid[i][j].revealGrid()
        response = messagebox.askyesno("CONGRATULATIONS!", "You win! Play again?")
        main.destroy()
        if response == 1:
            gameSetting()

    def showBomb(): # Show all bombs in about 1.25 sec one by one
        global bomb, mapWidth, realBombRemaining
        bombShow = bomb.pop()
        delay = int(random() * 2500 / realBombRemaining)
        gameGrid[bombShow // mapWidth][bombShow % mapWidth].interact.config(text="ðŸ’¥", fg="red")
        gameGrid[bombShow // mapWidth][bombShow % mapWidth].isRevealed = True
        if len(bomb) > 0:
            main.after(delay, showBomb)
        else:
            for i in range(mapHeight):
                for j in range(mapWidth):
                    gameGrid[i][j].revealGrid()
            response = messagebox.askyesno("GAME OVER!", "You lose! Play again?")
            main.destroy()
            if response == 1:
                gameSetting()

    def gameLost():
        global gameOver, mapWidth
        gameOver = True
        showBomb()

    def calBomb(): # Calculate the number of nearby bombs for all grids
        global mapHeight, mapWidth
        for i in range(mapHeight):
            for j in range(mapWidth):
                for k in range(-1, 2):
                    for l in range(-1, 2):
                        if i + k >= 0 and i + k <= mapHeight - 1 and j + l >= 0 and j + l <= mapWidth - 1 and (k != 0 or l != 0) and gameGrid[i + k][j + l].isBomb:
                            gameGrid[i][j].nearbyBomb += 1

                #print(gameGrid[i][j].nearbyBomb)
                #gameGrid[i][j].interact.config(text=gameGrid[i][j].nearbyBomb)

    def drawMap():
        global mapHeight, mapWidth, numBomb, lbl6
        for i in range(mapHeight):
            for j in range(mapWidth):
                gameGrid[i][j].interact.grid(row=i, column=j)

        lbl6 = Label(main, text="Bombs Remaining: " + str(bombRemaining), anchor=E, font=("Courier New", 11))
        lbl6.grid(row=mapHeight+1, column=0, columnspan=mapWidth, sticky=E)
        #lbl6.bind("<Button-3>", lambda event: print("!"))

    class gridStat():
        row = 0
        column = 0
        isFlagged = False
        isBomb = False
        isRevealed = False
        nearbyBomb = 0
        interact = Button()

        def pressed(self):
            global gameStarted, gameOver
            #print(self.row, self.column)
            if not gameOver:
                if not gameStarted:
                    genBomb(self.row, self.column)
                    calBomb()
                    gameStarted = True
                self.revealGrid()
            if self.isRevealed:
                #print(self.nearFlag())
                if self.nearbyBomb == self.nearFlag():
                    self.revealNear()

            elif self.nearFlag() == self.nearbyBomb and not self.isFlagged:
                self.revealNear()

        def revealNear(self):
            for i in range(-1, 2):
                for j in range(-1, 2):
                    if (self.row + i >= 0 and
                        self.row + i <= mapHeight - 1 and
                        self.column + j >= 0 and
                        self.column + j <= mapWidth - 1 and
                        (i != 0 or j != 0)):
                            gameGrid[self.row + i][self.column + j].revealGrid()

        def nearFlag(self):
            temp = 0
            for i in range(-1, 2):
                for j in range(-1, 2):
                    if (self.row + i >= 0 and
                        self.row + i <= mapHeight - 1 and
                        self.column + j >= 0 and
                        self.column + j <= mapWidth - 1 and
                        gameGrid[self.row + i][self.column + j].isFlagged):
                            temp += 1
            return temp

        def flag(self):
            global bombRemaining, lbl6, realBombRemaining, mapWidth, gameVictory
            if (gameVictory or not self.isRevealed) and gameStarted:
                self.isFlagged = not self.isFlagged
                if self.isFlagged:
                    self.interact.config(text="ðŸš©",fg="red")
                    bombRemaining -= 1
                    if self.isBomb:
                        realBombRemaining -= 1
                        bomb.remove(self.row * mapWidth + self.column)
                else:
                    self.interact.config(text="", fg="black")
                    bombRemaining += 1
                    if self.isBomb:
                        realBombRemaining += 1
                        bomb.insert(int(random()*len(bomb)), self.row * mapWidth + self.column)
            lbl6.config(text="Bombs Remaining: " + str(bombRemaining))
            checkVictory()

        def bombColor(self):
            color = [None, "#0000AA", "#00AA00", "#CC0000", "#000088", "#008800", "#000088", "#004400", "#440000"]
            self.interact.config(fg=color[self.nearbyBomb])

        def revealGrid(self):
            global gameOver, gameVictory, bomb, numRevealed
            if (gameOver and not self.isRevealed) or (not self.isFlagged and not self.isRevealed):
                self.isRevealed = True
                numRevealed += 1
                if self.isBomb and not self.isFlagged and not gameOver:
                    self.interact.config(text="ðŸ’¥", fg="black", bg="red")
                    #print(bomb)
                    #print(self.row * mapWidth + self.column)
                    bomb.remove(self.row * mapWidth + self.column)
                    gameLost()
                elif gameVictory and not self.isFlagged and self.isBomb:
                    self.flag()
                elif not self.isFlagged and self.nearbyBomb == 0 and (gameVictory or not gameOver):
                    self.interact.config(bg="#bbbbbb")
                    self.revealNear()
                elif gameOver and self.isFlagged and not self.isBomb:
                    self.interact.config(fg="#888888")
                elif not self.isFlagged and (gameVictory or not gameOver) and not self.isBomb:
                    self.interact.config(text=self.nearbyBomb, bg="#bbbbbb")
                    self.bombColor()
                checkVictory()

        def __init__(self, r, c):
            self.row = r
            self.column = c
            self.interact = Button(main, width=2, height=1, font=("Courier New Bold",  11), command=self.pressed)
            self.interact.bind("<Button-3>", lambda event: self.flag())

    gameGrid = [[gridStat(i, j) for j in range(mapWidth)] for i in range(mapHeight)]

    drawMap()

    main.mainloop()

# Game Setting Window
def gameSetting():
    global mapHeightSlider, mapWidthSlider, bombDensitySlider, setting, btn2, mapWidth
    setting = Tk()
    setting.title("Game Settings")
    setting.resizable(FALSE, FALSE)
    lbl1 = Label(setting, width=36, font=("Courier New",20), text="Minesweeper", anchor=CENTER)
    lbl1.grid(row=0, column=0, columnspan=4, sticky=N+E)
    lbl2 = Label(setting, text="Map Width: ", anchor=E, width=4)
    lbl2.grid(row=1, column=0, sticky=E+W)
    lbl3 = Label(setting, text="Map Height: ", anchor=E, width=4)
    lbl3.grid(row=2, column=0, sticky=E+W)
    lbl5 = Label(setting, text="Bomb Desnity (%): ", anchor=E, width=4)
    lbl5.grid(row=3, column=0, sticky=E+W)
    mapWidthSlider = Scale(setting, from_=8, to=50, orient=HORIZONTAL) # Slider for choosing the map width (8 - 50)
    mapHeightSlider = Scale(setting, from_=8, to=24, orient=HORIZONTAL) # Slider for choosing the map height (8 - 24)
    bombDensitySlider = Scale(setting, from_=15, to=30, orient=HORIZONTAL) # Slider for choosing the bomb density (15% - 30%)
    mapWidthSlider.grid(row=1, column=1, columnspan=3, sticky=E+W, padx=10)
    mapHeightSlider.grid(row=2, column=1, columnspan=3, sticky=E+W, padx=10)
    bombDensitySlider.grid(row=3, column=1, columnspan=3, sticky=E+W, padx=10)
    mapWidthSlider.set(mapWidth)
    mapHeightSlider.set(mapHeight)
    bombDensitySlider.set(bombDensity)
    btn1 = Button(setting, text="Confirm Map Settings", command=mapSize) # Confirm Map Settings button
    btn1.grid(row=4, column=1, columnspan=2, sticky=E+W, pady=20)
    btn2 = Button(setting, text="< Start Game! >", command=lambda: gameStart()) # Game Start button, destroys the setting screen
    setting.mainloop()

def mapSize(): # Confirm the map size, and determine the number of bombs
    global mapHeight, mapWidth, numBomb, bombDensity
    mapHeight = mapHeightSlider.get()
    mapWidth = mapWidthSlider.get()
    bombDensity = bombDensitySlider.get()
    numBomb = int(mapHeight * mapWidth * bombDensity / 500) * 5 # No. of bombs must be multiples of 5
    lbl4 = Label(setting, text= "No. of Bombs: ", anchor=E, width=4)
    lbl5 = Label(setting, text=numBomb, anchor=W)
    lbl4.grid(row=5, column=0, sticky=E+W, pady=10)
    lbl5.grid(row=5, column=1, columnspan=3, sticky=E+W, padx=10, pady=10)
    btn2.grid(row=6, column=1, columnspan=2, sticky=E+W, pady=20)

mapWidth = 8
mapHeight = 8
bombDensity = 15
gameSetting()


# Exercício 41 - Faça um programa que receba o valor de uma dívida e mostre uma tabela com os seguintes dados: valor da dívida, valor dos juros,
# quantidade de parcelas e valor da parcela.

divida_inicial = 1000 #float(input('Informe o valor da dívida: R$ '))
parcelas = 1
valor_juros = 0
porcentagem = 0
valor_parcela = valor_juros + divida
cifrao = 'R$'
divida = divida_inicial

print('Valor da Dívida     Valor dos Juros     Quantidade de Parcelas    Valor da Parcela')
print(f' {cifrao:2} {divida:.2f} {valor_juros:16.2f} {parcelas:23.0f} {valor_parcela:25.2f}')

porcentagem = 5

for i in range(3, 13, 3):
  parcelas = i * 1
  porcentagem += 5
  valor_juros = divida_inicial * (porcentagem / 100)
  divida = divida_inicial + valor_juros
  valor_parcela = divida / parcelas

  print(f' {cifrao:2} {divida:.2f} {valor_juros:16.2f} {parcelas:23.0f} {valor_parcela:25.2f}')


"""Common utilities"""
from typing import Optional

import requests

from gdrive_sync.models import DriveFile
from websites.models import WebsiteContent

def fetch_content_file_size(
    content: WebsiteContent, bucket: "s3.Bucket"  # noqa: F821
) -> Optional[int]:
    """Return the size (in bytes) of the file associated with `content`."""
    size = None

    # Our data has different fields used for file location throughout the years.
    # We check them in order of "recently adopted."
    file_key = (
        content.file.name
        or content.metadata.get("file")
        or content.metadata.get("file_location")
    )

    if file_key:
        file_key = file_key.strip("/")
        size = bucket.Object(file_key).content_length
    elif content.metadata.get("video_files", {}).get("archive_url"):
        # Some of our video resources are directly linked to YT videos, and their
        # downloadable content is in an archive url.
        file_url = content.metadata["video_files"]["archive_url"]
        response = requests.request("HEAD", file_url, headers={}, data={}, timeout=30)
        size = response.headers.get("Content-Length")

    return size

def fetch_drive_file_size(
    drive_file: DriveFile, bucket: "s3.Bucket"  # noqa: F821
) -> Optional[int]:  # noqa: F821, RUF100
    """Return the size (in bytes) of the file associated with `drive_file.s3_key`."""
    size = None
    file_key = drive_file.s3_key

    if file_key:
        size = bucket.Object(file_key).content_length

    return size