from collections import deque

N, M, V = map(int,input().split())
DFSvisited = [False for _ in range(N+1)]
BFSvisited = [False for _ in range(N+1)]
# print(DFSvisited)
# print(BFSvisited)

# 인접 행렬 입력
# 두 개의 인덱스, 기준 노드 번호/ 연결된 노드 번호
# 두 개의 인덱스에 있는 값 (정수), 노드 간의 거리
INF = 999999999 # 연결 안된 경우
graph2 =[[INF]*(N+1) for _ in range(N+1)]
for i in range(M):
  node, node2 = map(int,input().split())
  # 무비용, 무방향
  # 연결됨 & 무비용 -> 0
  # 연결안됨 -> INF
  graph2[node][node2] = 0
  graph2[node2][node] = 0

# 각 노드의 자리가 인덱스로 정해져 있으므로,
# 노드 번호 순으로 정렬 안해도 됨
print(graph2)

# DFS 인접 행렬
def DFS(g, v):
  DFSvisited[v] = True
  print(v, end=' ')
  for i in range(1, N+1):
    # INF (의미 없는 값)으로 채워졌을 수도 있으니 확인
    if g[v][i] != INF and not DFSvisited[i]:
      DFS(g, i)

# BFS 인접 행렬
def BFS(g, v):
  queue = deque([v])
  BFSvisited[v] = True
  while queue:
    now = queue.popleft()
    print(now, end=' ')
    for i in range(1, N+1):
        # INF (의미 없는 값)으로 채워졌을 수도 있으니 확인
      if g[now][i] != INF and not BFSvisited[i]:
          queue.append(i)
          BFSvisited[i] = True

DFS(graph, V)
print()
BFS(graph, V)


import sys
import os

class RedirectStd(object):
    def __init__(self, log_file="log/angr_graph/std_out_err.log", mode='a'):
        log_dir, log_name = os.path.split(log_file)
        os.makedirs(log_dir, exist_ok=True)

        # files
        self.log_file_path = log_file
        self._log_file = open(self.log_file_path, mode)
        self.stdout = sys.stdout
        self.stderr = sys.stderr

        # state
        self.have_redirect = False
        self._closed = False
        self.mode = mode

    def redirect(self):
        assert not self._closed, "the redirector have been closed, try reopen it by redirectStd.reopen()"
        sys.stdout = self._log_file
        sys.stderr = self._log_file
        self.have_redirect = True
        return self

    def redirect_back(self):
        assert not self._closed, "the redirector have been closed, try reopen it by redirectStd.reopen()"
        sys.stdout = self.stdout
        sys.stderr = self.stderr
        self.have_redirect = False
        return self

    def close(self):
        assert not self._closed, "the redirector is already closed"
        self.redirect_back()
        self._log_file.close()
        self._closed = True
        return self

    def reopen(self, mode=None):
        if mode is not None:
            self.mode = mode
        self._log_file = open(self.log_file_path, self.mode)
        self._closed = False


"""
Train convolutional network for sentiment analysis on IMDB corpus. Based on
"Convolutional Neural Networks for Sentence Classification" by Yoon Kim
http://arxiv.org/pdf/1408.5882v2.pdf

For "CNN-rand" and "CNN-non-static" gets to 88-90%, and "CNN-static" - 85% after 2-5 epochs with following settings:
embedding_dim = 50
filter_sizes = (3, 8)
num_filters = 10
dropout_prob = (0.5, 0.8)
hidden_dims = 50

Differences from original article:
- larger IMDB corpus, longer sentences; sentence length is very important, just like data size
- smaller embedding dimension, 50 instead of 300
- 2 filter sizes instead of original 3
- fewer filters; original work uses 100, experiments show that 3-10 is enough;
- random initialization is no worse than word2vec init on IMDB corpus
- sliding Max Pooling instead of original Global Pooling
"""

import numpy as np
import data_helpers
import data_helpers_elmo
import tensorflow as tf
from keras.layers import Dense, Dropout, Flatten, Input, MaxPooling1D, Convolution1D, Embedding
from keras.layers.merge import Concatenate

from keras import backend as K
import keras.layers as layers
from keras.models import Model, load_model
from keras.engine import Layer
from attention import Attention,Attention_weight
import tensorflow_hub as hub
from keras import regularizers
from Capsule import Capsule
from keras.callbacks import EarlyStopping
from keras.callbacks import ModelCheckpoint
from sklearn.metrics import accuracy_score
import keras
# ---------------------- Parameters section -------------------
#

# Model Hyperparameters
embedding_dim = 1024
filter_sizes = (3,4)
num_filters = 128
dropout_prob = (0.5, 0.8)
hidden_dims = 100

# Training parameters
batch_size = 8
num_epochs = 6

#
# ---------------------- Parameters end -----------------------
def Precision(y_true, y_pred):
    """精确率"""
    tp= K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))  # true positives
    pp= K.sum(K.round(K.clip(y_pred, 0, 1))) # predicted positives
    precision = tp/ (pp+ K.epsilon())
    return precision

def Recall(y_true, y_pred):
    """召回率"""
    tp = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) # true positives
    pp = K.sum(K.round(K.clip(y_true, 0, 1))) # possible positives
    recall = tp / (pp + K.epsilon())
    return recall

def F1(y_true, y_pred):
    """F1-score"""
    precision = Precision(y_true, y_pred)
    recall = Recall(y_true, y_pred)
    f1 = 2 * ((precision * recall) / (precision + recall + K.epsilon()))
    return f1
class ELMoEmbedding(Layer):

    def __init__(self, idx2word, output_mode="elmo", trainable=True, **kwargs):
        assert output_mode in ["default", "word_emb", "lstm_outputs1", "lstm_outputs2", "elmo"]
        assert trainable in [True, False]
        self.idx2word = idx2word
        self.output_mode = output_mode
        self.trainable = trainable
        self.max_length = None
        self.word_mapping = None
        self.lookup_table = None
        self.elmo_model = None
        self.embedding = None
        super(ELMoEmbedding, self).__init__(**kwargs)

    def build(self, input_shape):
        self.max_length = input_shape[1]
        self.word_mapping = [x[1] for x in sorted(self.idx2word.items(), key=lambda x: x[0])]
        self.lookup_table = tf.contrib.lookup.index_to_string_table_from_tensor(self.word_mapping, default_value="<PAD/>")
        sess = tf.Session()
        K.set_session(sess)
        tf.logging.set_verbosity(tf.logging.ERROR)
        sess.run(tf.global_variables_initializer())
        sess.run(tf.tables_initializer())
        #self.lookup_table.init.run(session=K.get_session())
        self.elmo_model = hub.Module("https://tfhub.dev/google/elmo/2", trainable=self.trainable)
        super(ELMoEmbedding, self).build(input_shape)

    def call(self, x):
        x = tf.cast(x, dtype=tf.int64)
        sequence_lengths = tf.cast(tf.count_nonzero(x, axis=1), dtype=tf.int32)
        strings = self.lookup_table.lookup(x)
        sess=tf.Session()
        sess.run(tf.tables_initializer())
        inputs = {
            "tokens": strings,
            "sequence_len": sequence_lengths
        }
        return self.elmo_model(inputs, signature="tokens", as_dict=True)[self.output_mode]

    def compute_output_shape(self, input_shape):
        if self.output_mode == "default":
            return (input_shape[0], 1024)
        if self.output_mode == "word_emb":
            return (input_shape[0], self.max_length, 512)
        if self.output_mode == "lstm_outputs1":
            return (input_shape[0], self.max_length, 1024)
        if self.output_mode == "lstm_outputs2":
            return (input_shape[0], self.max_length, 1024)
        if self.output_mode == "elmo":
            return (input_shape[0], self.max_length, 1024)

    def get_config(self):
        config = {
            'idx2word': self.idx2word,
            'output_mode': self.output_mode
        }
        base_config = super(ELMoEmbedding, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))
"""
def ElmoEmbedding(x):

    return elmo_model(inputs={
                            "tokens": tf.squeeze(tf.cast(x[0], tf.string)),
                            "sequence_len":tf.squeeze(tf.cast(x[1], tf.int32))
                      },
                      signature="tokens",
                      as_dict=True)["elmo"]

    return elmo_model(x,
                  signature="default",
                  as_dict=True)["elmo"]
"""
def load_data():
    #x, y,sequence_length= data_helpers_elmo.load_data()
    x, y, vocabulary, vocabulary_inv_list,sequence_length,x_t,y_t = data_helpers.load_data()
    #print(x[0])
    vocabulary_inv = {key: value for key, value in enumerate(vocabulary_inv_list)}
    y = y.argmax(axis=1)
    y_t = y_t.argmax(axis=1)
    #print(y[0])
    # Shuffle data
    np.random.seed(9)
    shuffle_indices = np.random.permutation(np.arange(len(y)))
    x = np.array(x)[shuffle_indices]
    #x = x[shuffle_indices]
    y = y[shuffle_indices]

    train_len = int(len(x) * 0.9)
    x_train = x[:train_len]
    y_train = y[:train_len]
    x_test = x[train_len:]
    y_test = y[train_len:]
    return x_train, y_train, x_test, y_test, vocabulary_inv,sequence_length,x_t,y_t
def load_data_test():
    x, y, vocabulary, vocabulary_inv_list,sequence_length= data_helpers.load_data_test()
    y = y.argmax(axis=1)

    return x, y
# Data Preparation
print("Load data...")
#x_train, y_train, x_test, y_test,sequence_length,x_t,y_t = load_data()
x_train, y_train, x_test, y_test, vocabulary_inv,sequence_length,x_t,y_t= load_data()
#x_t,y_t=load_data_test()

print("load data finished")

# Build model

class Babysiter(keras.callbacks.Callback):
    def __init__(self):
        super(Babysiter, self).__init__()

    def on_epoch_end(self, batch, logs={}):
        y_pre = model.predict(x_t,batch_size=batch_size)
        y_predict=[]

        for i in range(y_pre.shape[0]):
            if(y_pre[i][0]>0.5):
                y_predict.append(1)
            else:
                y_predict.append(0)
        y_predict = np.array(y_predict)
        precision=precision_score(y_t, y_predict)
        recall=recall_score(y_t, y_predict)
        f1=f1_score(y_t, y_predict)
        print("precision：%0.3f"%precision)
        print("recall: %0.3f"%recall)
        print("f1: %0.3f"%f1)
        print("                            ")
"""
sess = tf.Session()
K.set_session(sess)

tf.logging.set_verbosity(tf.logging.ERROR)

#elmo_model = hub.Module("https://tfhub.dev/google/elmo/2", trainable=True)
sess.run(tf.global_variables_initializer())
sess.run(tf.tables_initializer())
#print("elmo_model initialized finished")
"""
#sess=tf.Session()
#sess.run(tf.tables_initializer())
input_text = Input(shape=(sequence_length,), dtype='int32')
#input_text = Input(shape=(sequence_length,), dtype="string")
input_length = layers.Input(shape=(1,), dtype=tf.int32)
#embeddings = layers.Lambda(ElmoEmbedding, output_shape=(sequence_length,embedding_dim))([input_text,input_length])
#embeddings = layers.Lambda(ElmoEmbedding, output_shape=(sequence_length,embedding_dim))(input_text)
embeddings = ELMoEmbedding(idx2word=vocabulary_inv,output_mode="elmo")(input_text)

z,weight=Attention_weight(8,64)([embeddings, embeddings, embeddings])
#z=embeddings
conv_blocks = []
for sz in filter_sizes:
    conv = Convolution1D(filters=num_filters,
                         kernel_size=sz,
                         padding="valid",
                         #padding="same",
                         activation="relu",
                         kernel_regularizer=regularizers.l2(0.01),
                         #activity_regularizer=regularizers.l1(0.01),
                         strides=1)(z)
    #conv = Capsule(2, 64, 3, True)(conv)
    conv = MaxPooling1D(pool_size=3)(conv)
    conv = Flatten()(conv)
    conv_blocks.append(conv)
z = Concatenate()(conv_blocks) if len(conv_blocks) > 1 else conv_blocks[0]

z = Dropout(dropout_prob[1])(z)

z = Dense(hidden_dims, activation="relu")(z)
model_output = Dense(1, activation="sigmoid")(z)

model = Model(inputs=input_text, outputs=model_output)
#model = Model(inputs=[input_text,input_length], outputs=model_output)
adam=keras.optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
model.compile(
              loss="binary_crossentropy",
              optimizer="adam",
              #optimizer=adam,
              #metrics=[Precision,Recall,F1]
              metrics=[Precision,Recall,F1]
              )
model.summary()

#print(x_train_word_length[0:10])
#print(x_test_word_length[0:10])
filepath="./model_elmo/model_{epoch:02d}.hdf5"
early_stopping = EarlyStopping(monitor='val_acc', patience=10, verbose=1)
checkpoint = ModelCheckpoint(filepath, monitor='val_acc',verbose=1,
                            save_best_only=False,save_weights_only=False,mode='auto', period=1)

model.fit(
          #[x_train,x_train_word_length],
          x_train,
          y_train, batch_size=batch_size, epochs=num_epochs,
          #validation_data=([x_test,x_test_word_length], y_test),
          validation_data=(x_test, y_test),
          verbose=1,
          callbacks=[Babysiter(),checkpoint]
          )

#model.save('ElmoModel.h5')


import cv2
import numpy as np

def abs_sobel_thresh(img, orient='x', sobel_kernel=3, thresh = (0, 255)):
    # Apply the following steps to img
    # 1) Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    # 2) Take the derivative in x or y given orient = 'x' or 'y'
    sobel = cv2.Sobel(gray, cv2.CV_64F, 1*(orient == "x"), 1*(orient == "y"), ksize=sobel_kernel)
    # 3) Take the absolute value of the derivative or gradient
    abs_sobel = np.abs(sobel)
    # 4) Scale to 8-bit (0 - 255) then convert to type = np.uint8
    scaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))
    # 5) Create a mask of 1's where the scaled gradient magnitude
    # is > thresh_min and < thresh_max
    binary_output = np.zeros_like(scaled_sobel)
    binary_output[(scaled_sobel>=thresh[0]) & (scaled_sobel<=thresh[1])] = 1
    # 6) Return this mask as your binary_output image
    return binary_output

def mag_thresh(img, sobel_kernel=3, mag_thresh=(0, 255)):
    # Apply the following steps to img
    # 1) Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    # 2) Take the gradient in x and y separately
    sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
    sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
    # 3) Calculate the magnitude
    magnitude = np.sqrt(sobel_x**2+sobel_y**2)
    # 4) Scale to 8-bit (0 - 255) and convert to type = np.uint8
    scaled = np.uint8(255*magnitude/np.max(magnitude))
    # 5) Create a binary mask where mag thresholds are met
    binary_output = np.zeros_like(scaled)
    binary_output[(scaled >= mag_thresh[0]) & (scaled <= mag_thresh[1])] = 1
    # 6) Return this mask as your binary_output image
    return binary_output

def dir_thresh(img, sobel_kernel=3, thresh=(0, np.pi / 2)):
    # Apply the following steps to img
    # 1) Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    # 2) Take the gradient in x and y separately
    sobel_x = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
    sobel_y = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
    # 3) Take the absolute value of the x and y gradients
    sobel_x_abs = np.abs(sobel_x)
    sobel_y_abs = np.abs(sobel_y)
    # 4) Use np.arctan2(abs_sobely, abs_sobelx) to calculate the direction of the gradient
    grad_dir = np.arctan2(sobel_y_abs, sobel_x_abs)
    # 5) Create a binary mask where direction thresholds are met
    binary_output = np.zeros_like(grad_dir)
    binary_output[(grad_dir>=thresh[0]) & (grad_dir<=thresh[1])] = 1
    # 6) Return this mask as your binary_output image
    return binary_output

def hls_extract(img, channel):
    # 1) Convert to HLS color space
    hls_image = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
    return hls_image[:, :, channel]

def hsv_extract(img, channel):
    # 1) Convert to HSV color space
    hsv_image = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
    return hsv_image[:, :, channel]

def hls_threshold(img, channel=2, thresh=(0, 255)):
    # 1) Convert to HLS color space
    hls_image = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)
    # 2) Apply a threshold to the S channel
    binary_output = np.zeros(hls_image[:, :, 2].shape)
    binary_output[(hls_image[:, :, channel]>thresh[0]) & (hls_image[:, :, channel] <= thresh[1])] = 1
    # 3) Return a binary image of threshold result
    return binary_output

def hsv_threshold(img, channel=2, thresh=(0, 255)):
    # 1) Convert to HLS color space
    hls_image = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
    # 2) Apply a threshold to the S channel
    binary_output = np.zeros(hls_image[:, :, 2].shape)
    binary_output[(hls_image[:, :, channel]>thresh[0]) & (hls_image[:, :, channel] <= thresh[1])] = 1
    # 3) Return a binary image of threshold result
    return binary_output

def apply_single_threshold(img, thresh=(0,255)):
    binary_output = np.zeros(img.shape)
    binary_output[(img[:, :] > thresh[0]) & (img[:, :] <= thresh[1])] = 1
    return binary_output

# Edit this function to create your own pipeline.
def apply_thresholds(image):
    sobel_kernel = 15
    mag_kernel = 9
    dir_kernel = 15
    abs_threshold = (10, 70)
    mag_threshold = (10, 70)
    dir_threshold = (0.7, 1.3)
    s_threshold = (170, 255)
    h_threshold = (0, 20)

    img = np.copy(image)

    # Gradient thresholding
    sobelx_binary = abs_sobel_thresh(img, orient='x', sobel_kernel=sobel_kernel, thresh=abs_threshold)
    sobely_binary = abs_sobel_thresh(img, orient='y', sobel_kernel=sobel_kernel, thresh=abs_threshold)
    mag_binary = mag_thresh(img, sobel_kernel=mag_kernel, mag_thresh=mag_threshold)
    dir_binary = dir_thresh(img, sobel_kernel=dir_kernel, thresh=dir_threshold)
    gradient_binary = np.zeros_like(dir_binary)
    # gradient_binary[((sobelx_binary == 1) & (sobely_binary == 1)) & ((mag_binary == 1) & (dir_binary == 1))] = 1  # Example
    # gradient_binary[(sobelx_binary == 1) & (sobely_binary == 1)] = 1  # Example
    gradient_binary[((mag_binary == 1) & (dir_binary == 1))] = 1  # Example
    # combined_gradient_bin[(sobelx_binary==1)] = 1  # Example

    # Threshold color channel
    hsv_image = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
    v_binary = apply_single_threshold(hsv_image[:,:,2], thresh=(220, 255))
    s_binary = hls_threshold(img, 2, s_threshold)
    h_binary = hls_threshold(img, 0, h_threshold)
    color_binary =np.zeros_like(s_binary)
    # color_binary = np.copy(s_binary)
    color_binary[(v_binary==1) | (s_binary==1)] = 1

    # Stack each channel
    # binary_img = np.uint8(np.dstack((np.zeros_like(combined_gradient_bin), combined_gradient_bin, color_binary)) * 255)

    # binary_img = np.copy(gradient_binary)
    binary_img = np.zeros_like(gradient_binary)
    # binary_img[(gradient_binary == 1) & (color_binary == 1)] = 1
    binary_img[(color_binary==1) & (gradient_binary==1)] = 1

    return binary_img


from django.db.models.signals import post_save, pre_save

from macalicious.utils import unique_slug_generator

from .models import Cart, CartItem

def cart_item_pre_save_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        prefix = "item_"
        instance.slug = unique_slug_generator(instance, prefix, instance.content_object.get_name())

pre_save.connect(cart_item_pre_save_receiver, sender=CartItem)

def cart_item_post_save_receiver(sender, instance, *args, **kwargs):
    cart = instance.cart
    total_items = 0  # Keep track of all items in the cart
    total_amount = 0  # Keep track of cart item line total for cart total
    # update cart items and total after each item gets added to the cart
    for item in cart.cart_items.all():
        total_items += 1
        total_amount += item.get_total()
    # update the cart with number of items and cart total
    cart.number_of_items = total_items
    cart.total = total_amount
    cart.save()

post_save.connect(cart_item_post_save_receiver, sender=CartItem)


from fastapi import FastAPI, APIRouter

from app import routes
from app.database.session import Database

from settings import DATABASE_URL

async def on_startup() -> None:
    app.state.db = Database(DATABASE_URL)
    await app.state.db.connect()

async def on_shutdown() -> None:
    await app.state.db.disconnect()

app = FastAPI(title="FSP Service")
app.add_event_handler('startup', on_startup)
app.add_event_handler('shutdown', on_shutdown)
main_api_router = APIRouter(prefix='/api')
main_api_router.include_router(routes.cities.router, tags=['Города'])
main_api_router.include_router(routes.edges.router, tags=['Пути'])
app.include_router(main_api_router)


import os

myDict = {
            "hungry" : "Due to fast metabolism",# Key can be Lower case or Upper case
            "Flash": "Fastest Man Alive",
            "Age": 24,
            "Other Members": ["Superman", "WonderWoman", "Batman"], # Lists can also be defined inside dict

            "Teen Titans" : ("Cyborg", "Star fire, raven, Beastboy, Robin"),     #Dictionaries Can Contain Tuples too

            "Co-op Team" : {"Nightwing":"All Rounder Leader",
                            "Aquaman":"Vice Leader",
                            "Superboy":"Heavy Hitter",
                            "Miss Martian": "Psychic Force"}, #We can also Define a Dict under Another Dict meaning Nesting of Dict is possible
            1:(1.0) #This is a Tuple containing a floating point no.
}#Remember to use, after each entry

print("\n\n", myDict.keys())         #Prints all the keys in List Fashion
print("\n\n", type(myDict.keys()))   #prints the Type of dict
print("\n\n", list(myDict.keys()))   #Typecasting Dict to List
print("\n\n", myDict.values(), "\n")       #Prints all the values in Dict in List Fashion
print("\n\n", myDict.items())        #Prints dict Contents as a tuple(key, values) for all values

print("\n\n",myDict, "\n")
updatedDict={
    "New Members": ["Martian Manhunter", "Atom", "Shazam"],
    1:2 #This is a Tuple containing a integer no.
    }# Dictionaries can be updated and we can add new keys and values pairs in our previous dict
    #Predifined Key and Values can also be Overwritten in this manner

myDict.update(updatedDict) # Updating dictionaries

print("\n\n",myDict) #Printing new Dictionary

print(myDict.get("Flash")) # Prints value associated with key "Flash"
print(myDict["Flash"]) # Prints value associated with key "Flash"

# The difference between .get and [] sytax in Dictionaries?
print(myDict.get("Flashs2")) # Returns None as Flash2 is not present in the dictionary
#print(myDict["Flashs2"]) # throws an error as Flash2 is not present in the dictionary

#NOTE: More methods can be found on Python Docs: https://docs.python.org/3/library/stdtypes.html#dict


from django.shortcuts import render,get_object_or_404,redirect
from django.http import HttpResponse
from django.http import Http404
from django.template import loader
from .models import Driver
from .forms import DriverForm
# Create your views here.

def index(request):
    if request.user.is_authenticated:
        form=DriverForm()
        return render(request,'driver/index.html',{'form':form})
    else:
        return redirect("http://localhost:8000/home/404")

def driver(request):
    if request.POST:
        form=DriverForm(request.POST)
        if form.is_valid():
            form.save()
            success_message='Driver registered'
            form=DriverForm()
            return render(request,'driver/index.html',{'form':form,'success' : success_message})
    else:
        if request.user.is_authenticated:
            form=DriverForm()
            error_message='Something went wrong error'
            return render(request,'driver/index.html',{ 'form' : form ,'error':error_message})
        else:
            return redirect("http://localhost:8000/home/404")

def drivers(request):
    if request.POST:
        form=DriverForm(request.POST)
        return render(request,'driver/index.html',{'form':form})
    else:
        if request.user.is_authenticated:
            drivers = Driver.objects.all()
            return render(request,'driver/driverlist.html',{ 'drivers' : drivers ,'user':request.user})
        else:
            return redirect("http://localhost:8000/home/404")

def delete(request,id):
    if request.POST:
        return render(request,'driver/index.html',{'form':form})
    else:
        if request.user.is_authenticated:
            drivers = Driver.objects.get(id=id)
            drivers.delete()
            return redirect('http://localhost:8000/driver/drivers')
        else:
            return redirect("http://localhost:8000/home/404")

def edit(request,id):
    if request.method == "POST":
        driver=Driver.objects.get(id=id)
        form=DriverForm(request.POST,instance=driver)
        if form.is_valid():
            form.save()
            return redirect('http://localhost:8000/driver/drivers')
    elif request.user.is_authenticated:
        driver=Driver.objects.get(id=id)
        form=DriverForm(instance=driver)
        return render(request,'driver/driverEdit.html',{ 'form' : form ,'id':id})


import tkinter as tk
from tkinter import messagebox
import serial
from PIL import ImageTk, Image

# Constants
COM_PORT = 'COM3'
BAUD_RATE = 9600

# Create a serial connection to Arduino
ser = serial.Serial(COM_PORT, BAUD_RATE)

# Define the function to send the selected shelf to Arduino
def send_shelf(shelf):
    ser.write(shelf.encode())
    status_label.config(text=f"Retrieving medication from Shelf {shelf}...")
    log_text.insert('end', f"Retrieving medication from Shelf {shelf}...\n")

# Define the function to handle the button click event
def on_click(shelf):
    send_shelf(shelf)
        # Add code to control the robot arm to pick up the item from the selected shelf and place it on the counter
        # For example:
        # ser.write('P'.encode()) # send command to Arduino to activate the robot arm's picking action
        # ser.write('D'.encode()) # send command to Arduino to activate the robot arm's delivery action

# Define the function to reset the robot arm to its initial position
def move_to_home_position():
    ser.write('H'.encode())
    status_label.config(text="Robot arm moved to Home Position")
    log_text.insert('end', "Robot arm moved to Home Position\n")

# Create a window and add buttons for each shelf
root = tk.Tk()
root.geometry('900x600')
root.title('Medication Storage Control System')
root.configure(bg='#34495A') # Use a consistent background color

# Load the image and create an ImageTk object
img = Image.open('C:\\Users\\Onur\\Desktop\\RobotArmPythonTries\\university_logo.png')
img = img.resize((200, 200))  # resize the image to 100x100 pixels
logo = ImageTk.PhotoImage(img)

# Create a label for the logo and place it at (10, 10)
logo_label = tk.Label(root, image=logo)
logo_label.place(x=670, y=550)

# Add title label
title_label = tk.Label(root, text='Medication Storage Control System', font=('Arial', 24, 'bold'), bg='#34495E', fg='white')
title_label.pack(pady=20)

# Add subtitle label
subtitle_label = tk.Label(root, text='Select the shelf to retrieve medication:', font=('Arial', 14), bg='#34495E', fg='white')
subtitle_label.pack(pady=10)

# Add buttons for each shelf
button_frame = tk.Frame(root, bg='#34495E')
button_frame.pack(pady=10)

btn_shelf1 = tk.Button(button_frame, text='Shelf 1', font=('Arial', 14), width=10, height=3, command=lambda: on_click('1'))
btn_shelf2 = tk.Button(button_frame, text='Shelf 2', font=('Arial', 14), width=10, height=3, command=lambda: on_click('2'))
btn_shelf3 = tk.Button(button_frame, text='Shelf 3', font=('Arial', 14), width=10,height=3, command=lambda: on_click('3'))
btn_shelf4 = tk.Button(button_frame, text='Shelf 4', font=('Arial', 14), width=10, height=3, command=lambda: on_click('4'))
btn_shelf1.grid(row=0, column=0, padx=10, pady=10)
btn_shelf2.grid(row=0, column=1, padx=10, pady=10)
btn_shelf3.grid(row=1, column=0, padx=10, pady=10)
btn_shelf4.grid(row=1, column=1, padx=10, pady=10)

# Add log label
log_label = tk.Label(button_frame, text='Retrieval Logs:', font=('Arial', 14), bg='#34495E', fg='white')
log_label.grid(row=0, column=2, padx=10, pady=10)

# Add log text box
log_text = tk.Text(button_frame, width=60, height=8)
log_text.grid(row=1, column=2, padx=10, pady=10)

# Add status label
status_label = tk.Label(root, text="Waiting for input...", font=('Arial', 14), bg='#34495E', fg='white')
status_label.pack(pady=10)

# Add reset button
move_to_home_position = tk.Button(root, text='Home Position', font=('Arial', 14), width=10, height=2, command=move_to_home_position, bg='#F1C40F', fg='white')
move_to_home_position.pack(pady=20)

# Add footer label
footer_label = tk.Label(root, text='© 2023 Medication Storage Inc.', font=('Arial', 10), bg='#34495E', fg='white')
footer_label.pack(side=tk.BOTTOM, pady=10)
#Run the main loop
root.mainloop()


import argparse
import logging
import os
import time

import backtrader as bt  # 引入backtrader框架
import backtrader.analyzers as bta  # 添加分析函数
import joblib
from backtrader.feeds import PandasData
from backtrader_plotting import Bokeh
from pandas import DataFrame
import numpy as np
from mlstock.const import TOP_30
from mlstock.data.datasource import DataSource
from mlstock.ml import load_and_filter_data
from mlstock.ml.backtests import select_top_n, predict
from mlstock.ml.backtests.ml_strategy import MachineLearningStrategy
from mlstock.ml.data import factor_conf
from mlstock.utils import utils, df_utils
from mlstock.utils.utils import AStockPlotScheme

logger = logging.getLogger(__name__)

# TODO 2022.9.3 suspend backtrader backtest version
"""
backtrader版本的回测没有完成，也不打算继续下去了，代码仅作保留。
原因是，
1、数据初始化得一个股票一个股票的加载（for: cerebro.adddata(dataname=df_stock,name=ts_code) ），
   我已经有整个的df_daily了，还要挨个循环，真烦。
2、各项指标计算，我只能受限于backtrader analyzer，虽说也不错，但是总是不如自己写的顺手
3、整个过程其实也不是特别复杂，自己实现一遍，以后也方便调整

以后闲的没事的时候，可以把这个backtrader版本完成。
"""

def load_data_to_cerebro(cerebro, start_date, end_date, df):
    df = df.rename(columns={'vol': 'volume', 'ts_code': 'name', 'trade_date': 'datetime'})  # 列名准从backtrader的命名规范
    df['openinterest'] = 0  # backtrader需要这列，所以给他补上
    df['datetime'] = df_utils.to_datetime(df['datetime'], date_format="%Y%m%d")
    df = df.set_index('datetime')
    df = df.sort_index()
    d_start_date = utils.str2date(start_date)  # 开始日期
    d_end_date = utils.str2date(end_date)  # 结束日期
    data = PandasData(dataname=df, fromdate=d_start_date, todate=d_end_date, plot=True)
    cerebro.adddata(data)
    logger.debug("初始化股票%s~%s数据到脑波cerebro：%d 条", start_date, end_date, len(df))

def main(data_path, start_date, end_date, model_pct_path, model_winloss_path, factor_names):
    """
    datetime    open    high    low     close   volume  openi..
    2016-06-24	0.16	0.002	0.085	0.078	0.173	0.214
    2016-06-30	0.03	0.012	0.037	0.027	0.010	0.077
    """
    cerebro = bt.Cerebro()  # 初始化cerebro
    datasource = DataSource()

    df_data = predict(data_path, start_date, end_date, model_pct_path, model_winloss_path, factor_names)
    df_daily = datasource.daily(df_data.ts_codes,start_date, end_date)
    df_limit = datasource.limit_list()
    df_selected_stocks = select_top_n(df_data, df_limit)

    # 加载股票数据到脑波
    load_data_to_cerebro(cerebro, start_date, end_date, df_daily)

    start_cash = 500000.0
    cerebro.broker.setcash(start_cash)
    cerebro.broker.setcommission(commission=0.002)
    cerebro.addstrategy(MachineLearningStrategy, df_data=df_selected_stocks)

    # 添加分析对象
    cerebro.addanalyzer(bta.SharpeRatio, _name="sharpe", timeframe=bt.TimeFrame.Days)  # 夏普指数
    cerebro.addanalyzer(bt.analyzers.DrawDown, _name='DW')  # 回撤分析
    cerebro.addanalyzer(bt.analyzers.Returns, _name='returns')
    cerebro.addanalyzer(bt.analyzers.Calmar, _name='calmar')  # 卡玛比率 - Calmar：超额收益➗最大回撤
    cerebro.addanalyzer(bt.analyzers.PeriodStats, _name='period_stats')
    cerebro.addanalyzer(bt.analyzers.AnnualReturn, _name='annual')
    cerebro.addanalyzer(bt.analyzers.PyFolio, _name='PyFolio')  # 加入PyFolio分析者,这个是为了做quantstats分析用
    cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name='trade')

    # 打印
    logger.debug('回测期间：%r ~ %r , 初始资金: %r', start_date, end_date, start_cash)
    # 运行回测
    results = cerebro.run(optreturn=True)

    if not os.path.exists(f"debug/"): os.makedirs(f"debug/")
    file_name = f"debug/{utils.nowtime()}_{start_date}_{end_date}.html"

    b = Bokeh(filename=file_name, style='bar', plot_mode='single', output_mode='save', scheme=AStockPlotScheme())
    cerebro.plot(b, style='candlestick', iplot=False)

"""
# 测试用
python -m mfm_learner.example.factor_backtester \
    --factor momentum_3m \
    --start 20180101 \
    --end 20191230 \
    --num 50 \
    --period 20 \
    --index 000905.SH \
    --risk

python -m mfm_learner.example.factor_backtester \
    --factor clv \
    --start 20180101 \
    --end 20190101 \
    --index 000905.SH \
    --num 20 \
    --period 20 \
    --risk  \
    --percent 10%

python -m mfm_learner.example.factor_backtester \
    --factor synthesis:clv_peg_mv \
    --start 20180101 \
    --end 20190101 \
    --num 20 \
    --period 20 \
    --index 000905.SH

python -m mfm_learner.example.factor_backtester \
    --factor clv,peg,mv,roe_ttm,roe_ \
    --start 20180101 \
    --end 20190101 \
    --num 20 \
    --period 20 \
    --index 000905.SH
"""
if __name__ == '__main__':
    utils.init_logger()

    start_time = time.time()
    parser = argparse.ArgumentParser()
    parser.add_argument('-f', '--factor', type=str, help="单个因子名、多个（逗号分割）、所有（all）")
    parser.add_argument('-s', '--start', type=str, help="开始日期")
    parser.add_argument('-e', '--end', type=str, help="结束日期")
    parser.add_argument('-i', '--index', type=str, help="股票池code")
    parser.add_argument('-p', '--period', type=int, help="调仓周期，多个的话，用逗号分隔")
    parser.add_argument('-an', '--atr_n', type=int, default=3, help="ATR风控倍数")
    parser.add_argument('-ap', '--atr_p', type=int, default=15, help="ATR周期")
    parser.add_argument('-n', '--num', type=int, help="股票数量")
    parser.add_argument('-r', '--risk', action='store_true', help="是否风控")
    args = parser.parse_args()

    main(args.start,
         args.end,
         args.index,
         args.period,
         args.num,
         args.factor,
         args.risk,
         args.atr_p,
         args.atr_n)
    logger.debug("共耗时: %.0f 秒", time.time() - start_time)


#!/usr/bin/python3

#
# Imports
#

import json
import time
from datetime import datetime

#
# Globals
#

dogs = {}

#
# Refresh state from file
#

def refresh():
    global dogs
    with open('state.json', 'r') as f:
        dogs = json.loads(f.read())

#
# Search based on multiple criteria
#

def search(animal = None,
           shelter = None,
           name = None,
           breed = None,
           photo = None,
           pending = False,
           provider = None,
           timeFound = None,
           timePending = None,
           timeAdopted = None,
           timeSeen = None,
           includeData = False):

    results = []

    for providerId in dogs:
        if provider != None and providerId != provider:
            continue

        for shelterId in dogs[providerId]:
            if shelter != None and shelterId != shelter:
                continue

            for animalId in dogs[providerId][shelterId]:
                if animal != None and animalId != animal:
                    continue

                dog = dogs[providerId][shelterId][animalId]

                if name != None and dog['name'] != name:
                    continue
                if breed != None and breed.lower() not in dog['breed'].lower():
                    continue
                if photo != None and (dog['photo'] != None) != photo:
                    continue
                if pending != None and dog['pending'] != pending:
                    continue
                if timeFound != None and dog['timeFound'] < timeFound:
                    continue
                if timePending != None and dog['timePending'] < timePending:
                    continue
                if timeSeen != None and dog['timeSeen'] < timeSeen:
                    continue

                if not includeData:
                    dog['data'] = ''

                results.append(dog)

    return results

#
# Display search results
#

def display(results,
            animal = True,
            shelter = True,
            name = True,
            breed = True,
            photo = False,
            pending = False,
            provider = True,
            timeFound = False,
            timePending = False,
            timeAdopted = False,
            timeSeen = False,
            includeData = False):

    for result in results:
        text = ''

        if name:
            text += '{:<22} '.format(result['name'])
        if pending:
            text += '{:<12} '.format('- PENDING' if result['pending'] else '- AVAILABLE')

        if provider or shelter or animal:
            text += '('
            if provider:
                text += '{:<9}'.format(result['provider'])
                if shelter or animal:
                    text += '-'
            if shelter:
                text += '{:<5}'.format(result['shelterId'])
                if animal:
                    text += '-'
            if animal:
                text += '{:<8}'.format(result['animalId'])
            text += ') '

        if breed:
            text += '- {:<52} '.format(result['breed'])

        now = datetime.now()
        if timeFound:
            text += 'Found: {:<17.17} ago '.format(str(now - datetime.fromtimestamp(result['timeFound'])).split('.')[0])
        if timePending:
            text += 'Pending: {:<17.17} ago '.format(str(now - datetime.fromtimestamp(result['timePending'])).split('.')[0])
        if timeAdopted:
            text += 'Adopted: {:<17.17} ago '.format(str(now - datetime.fromtimestamp(result['timeAdopted'])).split('.')[0])
        if timeSeen:
            text += 'Seen: {:<17.17} ago '.format(str(now - datetime.fromtimestamp(result['timeSeen'])).split('.')[0])

        if photo:
            text += '{}'.format(result['photo'] if result['photo'] != None else 'NO_PHOTO')

        print(text)

#
# Automatically load state on import
#

refresh()


# Flappy Bird Game
# importing modules
import random   #For generating random
import pygame   #For game developing
import sys       #For system module to exit when cross
from pygame.locals import *    #Basic pygame import

#Global variables for the game
FPS = 32  #framepersecond = 32
SCREENWIDTH = 320  #screenwidth = 289
SCREENHEIGHT = 511  #screenheight = 511
SCREEN = pygame.display.set_mode((SCREENWIDTH,SCREENHEIGHT))   #screen displaying through pygame module
GROUNDY = SCREENHEIGHT * 0.8   #base height declaration
GAME_SPRITES = {}       #declaring the list of the png pics
GAME_SOUNDS = {}        #declaring the list of music files
PLAYER = 'Gallery/bird2.png'  #bird pic
BACKGROUND = 'Gallery/background.png'   #bg pic
PIPE = 'Gallery/pipe.png'  #pipe pic

def welcomeScreen():
        # starting the music when welcome screen is ok
        GAME_SOUNDS['lobby'].play()
        # birds position declaring for the welcomeScreen()
        playerx = int(SCREENWIDTH / 5)
        playery = int((SCREENHEIGHT - GAME_SPRITES['player'].get_height())/2)
        # foreground pics position declaring for the welcomeScreen()
        messagex = int((SCREENWIDTH - GAME_SPRITES['message'].get_width())/2)
        messagey = int(SCREENHEIGHT * 0.13)
        # base pic position declaring for the welcomeScreen()
        basex = 0
        # while loop to continue
        while True:
            # pygame.event is a function when key is press it is working
            for event in pygame.event.get():
                #If user clicks on X button or escape then close the game
                if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                    pygame.quit()
                    sys.exit()

                # if the user press the space or up key then start the game
                elif event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
                    return
                # otherwise show the screen
                else :
                    # show the screen through positioning of background, base, foreground, bird image
                    SCREEN.blit(GAME_SPRITES['background'],(0,0))
                    SCREEN.blit(GAME_SPRITES['player'],(playerx,playery))
                    SCREEN.blit(GAME_SPRITES['message'],(messagex,messagey))
                    SCREEN.blit(GAME_SPRITES['base'],(basex,GROUNDY))
                    # pygame display update function
                    pygame.display.update()
                    # frameperssecond starting and generating
                    FPSCLOCK.tick(FPS)

# maingame function declaration
def mainGame():
        # initializing score as 0
        score = 0
        # positioning bird and base
        playerx = int(SCREENWIDTH / 5)
        playery = int(SCREENWIDTH / 2)
        basex = 0

        #Create 2 pipes for blitting in the screen
        newPipe1 = getRandomPipe()
        newPipe2 = getRandomPipe()

        # Mylist for upperpipes
        upperPipes = [
            {'x': SCREENWIDTH + 200, 'y':newPipe1[0]['y']},
            {'x': SCREENWIDTH + 200 +(SCREENWIDTH / 2), 'y':newPipe2[0]['y']}
        ]

        # Mylist for lowerpipes
        lowerPipes = [
            {'x': SCREENWIDTH + 200, 'y':newPipe1[1]['y']},
            {'x': SCREENWIDTH + 200 +(SCREENWIDTH / 2), 'y':newPipe2[1]['y']}
        ]

        # positioning pipe in the screen
        pipeVelX = -4

        # player positioning is declared through the values
        playerVelY = -9
        playerMaxVelY = 10
        playerMinVelY = -8
        playerAccY = 1

        playerFlapAccv = -8   #Velocity while flapping
        playerFlapped = False  #It is true only when the bird flaps

        # while loop to continue
        while True:
            # pygame event works when key is pressed
            for event in pygame.event.get():
                # if user want to quit while playing game then X button or escape
                if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
                    pygame.quit()
                    sys.exit()
                # user playing the game through space button and up button
                if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP):
                    # if bird is up from the actual position that means game starts
                    if playery > 0:
                        # bird will flap according to its velocity
                        playerVelY = playerFlapAccv
                        # bird flapping will be true when its up from its actual position
                        playerFlapped = True
                        # sound of wing plays
                        GAME_SOUNDS['wing'].play()
                if event.type == KEYDOWN and event.key==K_v:
                    score+=10

            # Function which will return true if it crashes
            crashTest = isCollide(playerx, playery, upperPipes, lowerPipes)  #isCollide function
            if crashTest:
                return

            # Check score
            #bird positioning is declared
            playerMidPos = playerx + GAME_SPRITES['player'].get_width()/2
            #when bird crosses each and every upperpipes
            for pipe in upperPipes:
                # when bird is between the upperpipe and lowerpipe which means crossing the pipe
                pipeMidPos = pipe['x'] + GAME_SPRITES['pipe'][0].get_width()/2
                # when bird position is less than pipe position then score increases
                if pipeMidPos <= playerMidPos < pipeMidPos + 4:
                    score += 1
                    print(f"Your score is {score}")
                    # point music plays when each score is gained
                    GAME_SOUNDS['point'].play()

            # if the bird velocity is less than its max and also it is not flapped then increment the
            # bird acceleration which means the bird will fallmore quickly due to gravity
            if playerVelY < playerMaxVelY and not playerFlapped:
                playerVelY += playerAccY

            # when bird flaps one time and untill it flaps the playerFlapped is false
            if playerFlapped:
                playerFlapped = False

            # playerHeight is the value which determine the bird position exactly at that moment
            playerHeight = GAME_SPRITES['player'].get_height()
            # declaring the playery value again newly to get the actual playerheight which does not
            # collide with the base too
            playery = playery + min(playerVelY,GROUNDY - playery - playerHeight)

            # move pipes to the left
            for upperPipe,lowerPipe in zip(upperPipes,lowerPipes):
                upperPipe['x'] += pipeVelX
                lowerPipe['x'] += pipeVelX

            # Adding a new pipe when the first pipe is about to left the screen
            if 0 < upperPipes[0]['x'] < 5:
                # again getting new pipe when the old one is about to left
                newPipe = getRandomPipe()
                # upperpipe and lowerpipe appending newpipe
                upperPipes.append(newPipe[0])
                lowerPipes.append(newPipe[1])

            # if the pipe is out of the screen remove it
            if upperPipes[0]['x'] < -GAME_SPRITES['pipe'][0].get_width():
                upperPipes.pop(0)
                lowerPipes.pop(0)

            # lets blit our sprites now which means show the pics in the screen
            SCREEN.blit(GAME_SPRITES['background'],(0,0))
            for upperPipe,lowerPipe in zip(upperPipes,lowerPipes):
                SCREEN.blit(GAME_SPRITES['pipe'][0],(upperPipe['x'],upperPipe['y']))
                SCREEN.blit(GAME_SPRITES['pipe'][1],(lowerPipe['x'],lowerPipe['y']))

            SCREEN.blit(GAME_SPRITES['base'],(basex,GROUNDY))
            SCREEN.blit(GAME_SPRITES['player'],(playerx,playery))

            # declaring digit for the screen
            myDigits = [int(x) for x in list(str(score))]
            width = 0
            # showing digit one by one in the screen
            for digit in myDigits:
                width += GAME_SPRITES['numbers'][digit].get_width()
            xOffset = (SCREENWIDTH - width) / 2

            # showing the number png pics one by one which shows the score
            for digit in myDigits:
                SCREEN.blit(GAME_SPRITES['numbers'][digit],(xOffset,SCREENHEIGHT * 0.12))
                xOffset += GAME_SPRITES['numbers'][digit].get_width()

            # pygame display update and framepersecond clock is also updated
            pygame.display.update()
            FPSCLOCK.tick(FPS)

# function to determine if the bird collides or not
def isCollide (playerx, playery, upperPipes, lowerPipes):
    # if the bird is down from the actual position from the welcome screen or from the base then it crashed
    if playery > GROUNDY-25 or playery<0:
        # hit music plays
        GAME_SOUNDS['hit'].play()
        # return true which means it crashes
        return True
    # if the bird hits upperpipe then return true
    for pipe in upperPipes:
        # declaring pipeHeight
        pipeHeight = GAME_SPRITES ['pipe'][0].get_height()
        # if bird is less than the pipeheight  than it hits and hit music plays
        if(playery < pipeHeight + pipe['y'] and
           abs(playerx - pipe['x']) < GAME_SPRITES['pipe'][0].get_width()):
            GAME_SOUNDS['hit'].play()
            return True
    # if the bird hits lowerpipe then return true
    for pipe in lowerPipes:
        if (playery + GAME_SPRITES['player'].get_height() > pipe['y'] and
            abs(playerx - pipe['x']) < GAME_SPRITES['pipe'][0].get_width()):
            GAME_SOUNDS['hit'].play()
            return True
    # if the above three conditions not ok!, then return false which means it does not crash
    return False

# randomPipe getting function
def getRandomPipe():
        #generating two position of pipes one forward another reverse blitting in the screen
        pipeHeight = GAME_SPRITES['pipe'][0].get_height()
        # pipe height is almost screen's 3 times smaller
        offset = SCREENHEIGHT / 3
        # getting random pipe in range of the offset
        y2 = offset + random.randrange(0,int(SCREENHEIGHT - GAME_SPRITES['base'].get_height() - 1.2 * offset))
        pipex = SCREENWIDTH + 10
        y1 = pipeHeight - y2 + offset
        pipe = [
            {'x':pipex, 'y':-y1},  #Upper pipe
            {'x':pipex, 'y':y2}   #lower pipe
        ]
        # returning pipe in the screen from the randomPipe function
        return pipe

# only applicable when under these function
if __name__ == '__main__':
    pygame.init()   #initializing pygame module
    FPSCLOCK = pygame.time.Clock()   #pygame clock running function initialize which controls FPS
    pygame.display.set_caption("Flappy Bird By Majed")        #pygame caption title name set
    # number png pic loading
    GAME_SPRITES ['numbers'] = (
        pygame.image.load('Gallery/0.png').convert_alpha(),
        pygame.image.load('Gallery/1.png').convert_alpha(),
        pygame.image.load('Gallery/2.png').convert_alpha(),
        pygame.image.load('Gallery/3.png').convert_alpha(),
        pygame.image.load('Gallery/4.png').convert_alpha(),
        pygame.image.load('Gallery/5.png').convert_alpha(),
        pygame.image.load('Gallery/6.png').convert_alpha(),
        pygame.image.load('Gallery/7.png').convert_alpha(),
        pygame.image.load('Gallery/8.png').convert_alpha(),
        pygame.image.load('Gallery/9.png').convert_alpha(),
    )

    GAME_SPRITES ['message'] = pygame.image.load('Gallery/foreground.png').convert_alpha()
    GAME_SPRITES ['base'] = pygame.image.load('Gallery/base.png').convert_alpha()
    GAME_SPRITES ['pipe'] = (
        pygame.image.load(PIPE).convert_alpha(),
        pygame.transform.rotate(pygame.image.load(PIPE).convert_alpha(),180),
    )
    GAME_SPRITES ['background'] = pygame.image.load(BACKGROUND).convert_alpha()
    GAME_SPRITES ['player'] = pygame.image.load(PLAYER).convert_alpha()

    # music files setting
    GAME_SOUNDS ['die'] = pygame.mixer.Sound('Musics/die.wav')
    GAME_SOUNDS ['hit'] = pygame.mixer.Sound('Musics/hit.wav')
    GAME_SOUNDS ['point'] = pygame.mixer.Sound('Musics/point.wav')
    GAME_SOUNDS ['wing'] = pygame.mixer.Sound('Musics/wing.wav')
    GAME_SOUNDS ['swoosh'] = pygame.mixer.Sound('Musics/swoosh.wav')
    GAME_SOUNDS ['lobby'] = pygame.mixer.Sound('Musics/lobby.mp3')

    # when everything is ok while is true then continue the loop
    while True:
         welcomeScreen()  #shows the screen untill the user presses a button
         mainGame()    #this is the main game function


import datetime
import glob
import json
from json import JSONDecodeError
import os
import re
import traceback
import twitter
import utils

# # Uncomment to test import into Elastic Search database.
# from elastic_search_utils import ElasticSearchTwitterImporter

# Number of iterations that have produced no new tweets in day before sending notification to admin.
EMPTY_ITERATION_NOTIF_THRESHOLD = 3

now = datetime.datetime.now()

config_filename = 'config.json'

with open(config_filename, 'r') as config_file:
    config = json.load(config_file)

db_dir = config['db_dir']
twitter_db_dir = f"{db_dir}/twitter"
twitter_html_dir = config['twitter']['html_dir']
run_dir = config['run_dir']

rejected_expressions = []
if "black_list" in config["twitter"]:
    with open(config['twitter']['black_list'], 'r', encoding='utf-8') as rejected_expressions_file:
        for line in rejected_expressions_file:
            rejected_expressions.append(line.strip())

processed_databases = set()
empty_extractions = []

# # Uncomment to test import into Elastic Search database.
# es_importer = {
#     'ja': ElasticSearchTwitterImporter(config['elastic_search']['host'], config['elastic_search']['port'], twitter_html_dir, 'ja'),
#     'en': ElasticSearchTwitterImporter(config['elastic_search']['host'], config['elastic_search']['port'], twitter_html_dir, 'en')
# }

def extract_date_from(db_filename):
    bn = os.path.basename(db_filename)
    return bn[bn.index("_") + 1:bn.index(".txt")]

def get_tweet_text(status):
    text = status.full_text if status.tweet_mode == 'extended' else status.text
    return text

def search_black_list(tweet_text):
    for expr in rejected_expressions:
        if expr in tweet_text:
            return expr
    return None

def write_tweet_data(tweet_id, tweet_text):
    print(f"write_tweet_data tweet_id={tweet_id}")
    try:
        tweet = tweets[tweet_id]
        timestamp = now.strftime('%Y-%m-%d-%H-%M')
        tweet_timestamp = datetime.datetime.fromtimestamp(tweet['status'].created_at_in_seconds)
        country_code_dir = utils.get_country_code_dir(tweet['country_code'])
        timestamp_path = tweet_timestamp.strftime('%Y/%m/%d/%H-%M')
        html_orig_tweet_dir = os.path.join(twitter_html_dir, country_code_dir, "orig", timestamp_path)
        os.makedirs(html_orig_tweet_dir, exist_ok=True)
        temp_path = html_orig_tweet_dir
        while temp_path != twitter_html_dir:
            # An error might happen when the folder owner is different from the user running the script.
            # The permissions of such folders should already be ok so it's not needed to update them.
            try:
                os.chmod(temp_path, 0o775)
            except OSError as e:
                break
            temp_path = os.path.dirname(temp_path)

        print(f"tweet_path={html_orig_tweet_dir}")

        # EVen if the json file already exists, it's updated.
        json_filename = os.path.join(html_orig_tweet_dir, f"{tweet_id}.json")
        with open(json_filename, 'w', encoding='utf-8') as json_file:
            json.dump(tweet['json'], json_file)

        # EVen if the metadata file already exists, it's updated.
        metadata_filename = os.path.join(html_orig_tweet_dir, f"{tweet_id}.metadata")
        with open(metadata_filename, 'w', encoding='utf-8') as metadata_file:
            metadata = {
                "id": tweet_id,
                "country": tweet["country"],
                "country_code": tweet["country_code"],
                "count": tweet["count"]
            }
            json.dump(metadata, metadata_file, ensure_ascii=False)

        # Write html file only if it doesn't exist yet.
        html_filename = os.path.join(html_orig_tweet_dir, f"{tweet_id}.html")
        if not os.path.exists(html_filename):
            with open(html_filename, 'w', encoding='utf-8') as html_file:
                html_str = (
                    "<!DOCTYPE html>\n"
                    f"\n"
                    "<meta charset=\"utf-8\"/>\n"
                    "\n"
                    f"
{tweet_text}
\n"
                    "\n"
                    "\n"
                )
                html_file.write(html_str)

            new_html_filename = os.path.join(run_dir, 'new-html-files', f'new-twitter-html-files-{timestamp}.txt')
            with open(new_html_filename, 'a', encoding='utf-8') as new_html_file:
                new_html_file.write(html_filename)
                new_html_file.write("\n")

            # # Uncomment to test import into Elastic Search database.
            # es_index = config['elastic_search']['twitter_index_basename'] + '-' + tweet['status'].lang
            # es_importer[tweet['status'].lang].update_record(html_filename[:-4]+"txt", index=es_index, is_data_stream=True)

            if country_code_dir in tweet_count_per_country:
                tweet_count_per_country[country_code_dir] += 1
            else:
                tweet_count_per_country[country_code_dir] = 1
    except:
        print(f"An error has occurred in write_tweet_data(tweet_id={tweet_id}): {traceback.format_exc()}")

def write_stats_file(filename, tweet_count_per_country):
    if len(tweet_count_per_country) > 0:
        with open(filename, 'w', encoding='utf-8') as stats_file:
            json.dump(tweet_count_per_country, stats_file)

def process_tweet(tweet_id, tweet_count, tweet_lang, tweet_country, tweet_json_str):
    tweet_json = json.loads(tweet_json_str)
    tweet_status = twitter.models.Status.NewFromJsonDict(tweet_json)
    tweet_text = get_tweet_text(tweet_status)

    # Skip tweets that contain rejected words.
    rejected_expr = search_black_list(tweet_text)
    if rejected_expr is not None:
        print(f"Tweet {tweet_id} has been skipped because it contains rejected expression: {rejected_expr}.")
        return

    tweet_country_code = None
    try:
        tweet_country_code = utils.convert_country_to_iso_3166_alpha_2(tweet_country)
    except LookupError as ex:
        undefined_countries.add(tweet_country)
        print("Tweet {tweet_id} has been ignored because it refers to an undefined country: {tweet_country}.")
        return

    tweets[tweet_id] = {
        "count": tweet_count,
        "lang": tweet_lang,
        "country": tweet_country,
        "country_code": tweet_country_code,
        'json': tweet_json,
        "status": tweet_status
    }

    write_tweet_data(tweet_id, tweet_text)

#
# The heuristics should be appropriate most of the times.
#
def is_twitter_db_admin_notif_required(empty_extractions, now):
    "Returns True if EMPTY_ITERATION_NOTIF_THRESHOLD iterations have been recorded as empty today with no prior empty iterations on the previous day (to prevent unneeded repeated notifs)."
    today = now.strftime('%Y-%m-%d')
    yesterday = (now - datetime.timedelta(1)).strftime('%Y-%m-%d')

    counts_per_date = {}
    for timestamp in empty_extractions:
        date_str = timestamp[:10]
        counts_per_date[date_str] = counts_per_date.get(date_str, 0) + 1

    return counts_per_date.get(today, 0) == EMPTY_ITERATION_NOTIF_THRESHOLD and counts_per_date.get(yesterday, 0) == 0

run_filename = os.path.join(run_dir, 'twitter.json')
if os.path.exists(run_filename):
    with open(run_filename, 'r') as run_file:
        run_data = json.load(run_file)
        print(f"run_data={run_data}")
        processed_databases = set(run_data)

empty_extractions_filename = os.path.join(run_dir, 'twitter_empty_extractions.json')
if os.path.exists(empty_extractions_filename):
    with open(empty_extractions_filename, 'r') as empty_extractions_file:
        empty_extractions = json.load(empty_extractions_file)

total_tweets_for_all_db = 0
for db_filename in reversed(sorted(glob.glob(f'{twitter_db_dir}/tweets_*.txt'))):
    print(f"Processing {db_filename}")

    tweets = {}
    tweet_count_per_country = {}
    undefined_countries = set()

    with open(db_filename, 'r', encoding='latin-1') as twitter_data_file:
        for line in twitter_data_file:
            match = re.search("(\d+) (\d+) (\w+) ([-)'(\w]+) (\{.*\})", line)
            if match:
                tweet_id = int(match.group(1))
                tweet_count = int(match.group(2))
                tweet_lang = match.group(3)
                tweet_country = match.group(4)
                tweet_json_str = match.group(5)
                try:
                    process_tweet(tweet_id, tweet_count, tweet_lang, tweet_country, tweet_json_str)
                except JSONDecodeError as json_err:
                    print(f"Tweet {tweet_id} had invalid json and has been ignored. json_err={json_err}")
            else:
                print(f"Invalid line: {line}")

    processed_databases.add(extract_date_from(db_filename))

    if len(undefined_countries) > 0:
        utils.send_mail(config['mail']['from'], config['mail']['to'], config['mail']['cc'], None, "Undefined countries found",
            (f"Some tweets are referring to these countries: {sorted(undefined_countries)} but no corresponding ISO-3166-2 Alpha-2 code are defined.\n\n"
            "Adjust the country_codes.txt file accordingly to prevent this error from occurring again."))

    print(f"tweet_count_per_country={tweet_count_per_country}")
    total_tweets = sum(tweet_count_per_country.values())
    print(f"Total tweets: {total_tweets}")
    total_tweets_for_all_db += total_tweets

    stats_file = os.path.join(run_dir, 'twitter-stats', f"twitter-stats-{datetime.datetime.now().strftime('%Y-%m-%d-%H-%M')}.json")
    write_stats_file(stats_file, tweet_count_per_country)

    # Remove database to save disk space.
    if os.path.exists(db_filename):
        os.remove(db_filename)

# Remember that the file has been processed.
with open(run_filename, 'w') as run_file:
    json.dump(sorted(list(processed_databases)), run_file)

if total_tweets_for_all_db == 0:
    empty_extractions.append(now.strftime('%Y-%m-%d-%H-%M'))
    with open(empty_extractions_filename, 'w', encoding='utf-8') as empty_extractions_file:
        json.dump(empty_extractions, empty_extractions_file)
    if is_twitter_db_admin_notif_required(empty_extractions, now):
        print("Notification sent.")
        utils.send_mail(config['mail']['from'], config['mail']['to'], config['mail']['cc'], None, "No new data from Twitter databases",
            (f"There was {EMPTY_ITERATION_NOTIF_THRESHOLD} extract-tweets iterations that have not produced any new tweets. Most likely that there is an issue with the updates of the Twitter databases.\n\n"
            "Contact the person in charge to check this issue."))


# 1. feladat.
"""

kutya = {'nev': input('Kérlek add meg a kutyád nevét!\t'),
         'eletkor': int(input('Kérlek add meg a kutyád életkorát!\t')),
         'ervenyes_oltas': bool(input('Kérlek add meg hogy van-e érvényes oltása a kutyádnak!\t'))}

# Vagy:
"""

"""
kutya = {}

kutya['nev'] = input('Kérlek add meg a kutyád nevét!\t')
kutya['eletkor'] = int(input('Kérlek add meg a kutyád életkorát!\t'))
kutya['ervenyes_oltas'] = bool(input('Kérlek add meg hogy van-e érvényes oltása a kutyádnak!\t'))
"""

"""

for x in kutya:
    print(x + ':', kutya[x])

"""
# 2. feladat.
"""
macska = {
    'nev': 'Cirmos',
    'kor': 5,
}
print(macska)
macska['nev'] = input('Mi legyen a cica új neve?\t')
macska['kor'] = int(input('Mi legyen a cica új kora?\t'))

for x in macska:
    print(x + ':', macska[x])
"""

# 3. feladat.
# NINCS KÉSZ

def kiiratas(diak):
    for x in diak:
        print(x + ':', diak[x])

def ertekadas(diak):
    kulcs = input('Add meg a kulcs nevét!\t')
    ertek = input('Add meg az értéket!\t')

    if kulcs == ertek:
        pass
    elif kulcs and ertek != "":
        diak[kulcs] = ertek
        kiiratas(diak)
        return kulcs, ertek
    else:
        print('Hiányos kulcspárat adtál meg!')
    kiiratas(diak)

diak = {
    'vezeteknev': 'Polgár',
    'keresztnev': 'Judit',
    'kor': 46,
    'magyar': True,
}

def egyenloseg(veg):
    for x in veg:
        if x == veg[0] and x == veg[1]:
            return True
        else:
            return False

def main():
    kiiratas(diak)
    print('---------------------')
    veg = (0, 1)
    allitas = egyenloseg(veg)
    while not allitas:
        veg = ertekadas(diak)
        print(veg)
        allitas = egyenloseg(veg)

main()


# Name: Jonathan Louangrath
# OSU Email: louangrj@oregonstate.edu
# Course: CS261 - Data Structures
# Assignment: 6 - Hashmap Implementation
# Due Date: 9 August 2022 (two free days used)
# Description: This program uses a dynamic array to store a hash table.
# It resolves collisions by chaining through singly linked list.
# Functions include put, get, remove, contains_key, clear, empty_buckets,
# resize_table, table_load, get_keys, and find_mode.

from a6_include import (DynamicArray, LinkedList,
                        hash_function_1, hash_function_2)

class HashMap:
    def __init__(self,
                 capacity: int = 11,
                 function: callable = hash_function_1) -> None:
        """
        Initialize new HashMap that uses
        separate chaining for collision resolution
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        self._buckets = DynamicArray()

        # capacity must be a prime number
        self._capacity = self._next_prime(capacity)
        for _ in range(self._capacity):
            self._buckets.append(LinkedList())

        self._hash_function = function
        self._size = 0

    def __str__(self) -> str:
        """
        Override string method to provide more readable output
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        out = ''
        for i in range(self._buckets.length()):
            out += str(i) + ': ' + str(self._buckets[i]) + '\n'
        return out

    def _next_prime(self, capacity: int) -> int:
        """
        Increment from given number and the find the closest prime number
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        if capacity % 2 == 0:
            capacity += 1

        while not self._is_prime(capacity):
            capacity += 2

        return capacity

    @staticmethod
    def _is_prime(capacity: int) -> bool:
        """
        Determine if given integer is a prime number and return boolean
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        if capacity == 2 or capacity == 3:
            return True

        if capacity == 1 or capacity % 2 == 0:
            return False

        factor = 3
        while factor ** 2 <= capacity:
            if capacity % factor == 0:
                return False
            factor += 2

        return True

    def get_size(self) -> int:
        """
        Return size of map
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        return self._size

    def get_capacity(self) -> int:
        """
        Return capacity of map
        DO NOT CHANGE THIS METHOD IN ANY WAY
        """
        return self._capacity

    # ------------------------------------------------------------------ #

    def change_size(self, size: int) -> None:
        """Change size of hash map"""
        self._size += size

    def get_buckets(self) -> DynamicArray:
        """Getter method for dynamic array
        :return: DynamicArray object for buckets"""
        return self._buckets

    def get_hash(self, key: str) -> int:
        """Hash a key
        :param key: string of key to hash
        :return: int of index"""
        return self._hash_function(key)

    def get_linked_list(self, key: str) -> LinkedList:
        """Get linked list at key
        :param key: string of key to hash
        :param return: LinkedList object at that index"""

        index = self.get_hash(key) % self.get_buckets().length()
        return self.get_buckets().get_at_index(index)

    def put(self, key: str, value: object) -> None:
        """
        Update key/value pair in hash map
        :param key: key of new element
        :param value: value of new element
        """

        # Initialize array size and index
        array_size = self.get_buckets().length()
        index = self.get_hash(key) % array_size

        # Get linked list object at that dynamic array index
        linked_list = self.get_buckets().get_at_index(index)
        # Find if value already exists at that key
        if linked_list.contains(key) is not None:
            # Replace value
            linked_list.contains(key).value = value
            return

        # If key is not in hash map, add new key/value pair
        else:
            linked_list.insert(key, value)
            self.change_size(1)

    def empty_buckets(self) -> int:
        """
        Return number of empty buckets in hash table
        :return: int of empty buckets
        """

        # Initialize array size and return variable
        array_size = self.get_buckets().length()
        empty = 0

        # Iterate through dynamic array
        # If linked list length is 0, increment return variable
        for x in range(array_size):
            if self.get_buckets().get_at_index(x).length() == 0:
                empty += 1

        return empty

    def table_load(self) -> float:
        """
        Return current hash table factor
        :return: float of hash table factor
        """

        # Initialize hash map size and dynamic array size
        hash_size = self.get_size()
        array_size = self.get_buckets().length()

        return hash_size / array_size

    def clear(self) -> None:
        """
        Clear contents of hash map without changing capacity
        """
        # Initialize array size
        array_size = self.get_buckets().length()

        # Iterate through dynamic array. Check if there are non-empty linked lists
        for x in range(array_size):
            linked_list_length = self.get_buckets().get_at_index(x).length()
            if linked_list_length != 0:
                # Decrement size and clear linked list
                self.change_size(-1 * linked_list_length)
                self.get_buckets().set_at_index(x, LinkedList())

    def resize_table(self, new_capacity: int) -> None:
        """
        Change capacity of hash table
        :param new_capacity: int of new hash table capacity
        """

        # Check if new_capacity is less than 1
        if new_capacity < 1:
            return

        # Check if new_capacity is prime
        if self._is_prime(new_capacity) is False:
            new_capacity = self._next_prime(new_capacity)

        # Create new dynamic array with desired capacity
        resized_array = DynamicArray()
        for x in range(new_capacity):
            resized_array.append(LinkedList())

        # Populate new dynamic array with items
        array_length = self.get_buckets().length()

        for x in range(array_length):
            linked_list = self.get_buckets().get_at_index(x)
            if linked_list.length() != 0:

                # Rehash hash table links
                for node in linked_list:
                    key = node.key
                    index = self.get_hash(key) % resized_array.length()

                    # Insert node into rehashed key index
                    resized_array.get_at_index(index).insert(key, node.value)

        # Reassign hashmap's data
        self._buckets = resized_array
        self._capacity = new_capacity

    def get(self, key: str) -> object:
        """
        Return value associated with key
        :param key: key to find value
        :return: key's value
        """

        # Get linked list at index
        linked_list = self.get_linked_list(key)

        # If key matches, return the element's value
        for link in linked_list:
            if link.key == key:
                return link.value

        # If key not in hash map, return None
        return None

    def contains_key(self, key: str) -> bool:
        """
        Return True if key is in hash map, otherwise return False
        :param key: key to find
        :return: bool whether key is present
        """

        # Get linked list at index
        linked_list = self.get_linked_list(key)

        # If key matches, return True
        for link in linked_list:
            if link.key == key:
                return True

        # If key not in hash map, return False
        return False

    def remove(self, key: str) -> None:
        """
        Remove given key and value from hash map
        :param key: key of element to remove
        """

        # Get linked list at index
        linked_list = self.get_linked_list(key)

        # If key matches, remove
        for link in linked_list:
            if link.key == key:
                linked_list.remove(key)

                # Decrement hash map size
                self.change_size(-1)

    def get_keys_and_values(self) -> DynamicArray:
        """
        Return Dynamic Array where each index has a tuple of pair stored there
        :return: dynamic array object
        """

        # Create keys and values array
        keys_and_values = DynamicArray()

        # Check if nodes exist at each index
        for x in range(self.get_buckets().length()):

            # If the linked list is non-empty, append each key and value to new dynamic array
            if self.get_buckets().get_at_index(x).length != 0:
                linked_list = self.get_buckets().get_at_index(x)
                for link in linked_list:
                    keys_and_values.append((link.key, link.value))

        # Return new dynamic array
        return keys_and_values

def find_mode(da: DynamicArray) -> (DynamicArray, int):
    """
    Find mode in dynamic array
    :param da: dynamic array to find mode(s)
    :return: tuple consisting of (dynamic array with mode, int with its frequency)
    """

    # Initialize length of dynamic array and create new HashMap
    length = da.length()
    map = HashMap(length // 2)

    # Iterate through dynamic array
    for ele in range(length):

        # Get hash map index of each dynamic array element
        index = map.get_hash(da[ele]) % map.get_buckets().length()

        # Check if element is already logged
        if map.get_buckets().get_at_index(index).length() != 0:
            linked_list = map.get_buckets().get_at_index(index)

            # Check if another key has the same index
            # If so, create new node with that element's value as 1
            if linked_list.contains(da[ele]) is None:
                map.put(da[ele], 1)

            # If key is already logged, increase frequency (value) by 1
            else:
                freq = linked_list.contains(da[ele]).value + 1
                map.put(da[ele], freq)

        # If element is unique, create new node with that element's frequency (value) as 1
        else:
            map.put(da[ele], 1)

    # Find keys and values
    keys_and_values = map.get_keys_and_values()
    keys_values_length = keys_and_values.length()

    # Create new dynamic array for modes
    modes = DynamicArray()
    mode_freq = 1

    # Iterate through keys_and_values dynamic array
    for pair in range(keys_values_length):

        # Compare each element's frequency to existing mode_freq
        if keys_and_values.get_at_index(pair)[1] > mode_freq:
            mode_freq = keys_and_values.get_at_index(pair)[1]

            # Clear current modes array and append new mode
            modes = DynamicArray()
            modes.append(keys_and_values.get_at_index(pair)[0])

        # Append competing modes
        elif keys_and_values.get_at_index(pair)[1] == mode_freq:
            modes.append(keys_and_values.get_at_index(pair)[0])

    return modes, mode_freq

# ------------------- BASIC TESTING ---------------------------------------- #

if __name__ == "__main__":

    print("\nPDF - put example 1")
    print("-------------------")
    m = HashMap(53, hash_function_1)
    for i in range(150):
        m.put('str' + str(i), i * 100)
        if i % 25 == 24:
            print(m.empty_buckets(), round(m.table_load(), 2), m.get_size(), m.get_capacity())

    print("\nPDF - put example 2")
    print("-------------------")
    m = HashMap(41, hash_function_2)
    for i in range(50):
        m.put('str' + str(i // 3), i * 100)
        if i % 10 == 9:
            print(m.empty_buckets(), round(m.table_load(), 2), m.get_size(), m.get_capacity())

    print("\nPDF - empty_buckets example 1")
    print("-----------------------------")
    m = HashMap(101, hash_function_1)
    print(m.empty_buckets(), m.get_size(), m.get_capacity())
    m.put('key1', 10)
    print(m.empty_buckets(), m.get_size(), m.get_capacity())
    m.put('key2', 20)
    print(m.empty_buckets(), m.get_size(), m.get_capacity())
    m.put('key1', 30)
    print(m.empty_buckets(), m.get_size(), m.get_capacity())
    m.put('key4', 40)
    print(m.empty_buckets(), m.get_size(), m.get_capacity())

    print("\nPDF - empty_buckets example 2")
    print("-----------------------------")
    m = HashMap(53, hash_function_1)
    for i in range(150):
        m.put('key' + str(i), i * 100)
        if i % 30 == 0:
            print(m.empty_buckets(), m.get_size(), m.get_capacity())

    print("\nPDF - table_load example 1")
    print("--------------------------")
    m = HashMap(101, hash_function_1)
    print(round(m.table_load(), 2))
    m.put('key1', 10)
    print(round(m.table_load(), 2))
    m.put('key2', 20)
    print(round(m.table_load(), 2))
    m.put('key1', 30)
    print(round(m.table_load(), 2))

    print("\nPDF - table_load example 2")
    print("--------------------------")
    m = HashMap(53, hash_function_1)
    for i in range(50):
        m.put('key' + str(i), i * 100)
        if i % 10 == 0:
            print(round(m.table_load(), 2), m.get_size(), m.get_capacity())

    print("\nPDF - clear example 1")
    print("---------------------")
    m = HashMap(101, hash_function_1)
    print(m.get_size(), m.get_capacity())
    m.put('key1', 10)
    m.put('key2', 20)
    m.put('key1', 30)
    print(m.get_size(), m.get_capacity())
    m.clear()
    print(m.get_size(), m.get_capacity())

    print("\nPDF - clear example 2")
    print("---------------------")
    m = HashMap(53, hash_function_1)
    print(m.get_size(), m.get_capacity())
    m.put('key1', 10)
    print(m.get_size(), m.get_capacity())
    m.put('key2', 20)
    print(m.get_size(), m.get_capacity())
    m.resize_table(100)
    print(m.get_size(), m.get_capacity())
    m.clear()
    print(m.get_size(), m.get_capacity())

    print("\nPDF - resize example 1")
    print("----------------------")
    m = HashMap(23, hash_function_1)
    m.put('key1', 10)
    print(m.get_size(), m.get_capacity(), m.get('key1'), m.contains_key('key1'))
    m.resize_table(30)
    print(m.get_size(), m.get_capacity(), m.get('key1'), m.contains_key('key1'))

    print("\nPDF - resize example 2")
    print("----------------------")
    m = HashMap(79, hash_function_2)
    keys = [i for i in range(1, 1000, 13)]
    for key in keys:
        m.put(str(key), key * 42)
    print(m.get_size(), m.get_capacity())

    for capacity in range(111, 1000, 117):
        m.resize_table(capacity)

        m.put('some key', 'some value')
        result = m.contains_key('some key')
        m.remove('some key')

        for key in keys:
            # all inserted keys must be present
            result &= m.contains_key(str(key))
            # NOT inserted keys must be absent
            result &= not m.contains_key(str(key + 1))
        print(capacity, result, m.get_size(), m.get_capacity(), round(m.table_load(), 2))

    print("\nPDF - get example 1")
    print("-------------------")
    m = HashMap(31, hash_function_1)
    print(m.get('key'))
    m.put('key1', 10)
    print(m.get('key1'))

    print("\nPDF - get example 2")
    print("-------------------")
    m = HashMap(151, hash_function_2)
    for i in range(200, 300, 7):
        m.put(str(i), i * 10)
    print(m.get_size(), m.get_capacity())
    for i in range(200, 300, 21):
        print(i, m.get(str(i)), m.get(str(i)) == i * 10)
        print(i + 1, m.get(str(i + 1)), m.get(str(i + 1)) == (i + 1) * 10)

    print("\nPDF - contains_key example 1")
    print("----------------------------")
    m = HashMap(53, hash_function_1)
    print(m.contains_key('key1'))
    m.put('key1', 10)
    m.put('key2', 20)
    m.put('key3', 30)
    print(m.contains_key('key1'))
    print(m.contains_key('key4'))
    print(m.contains_key('key2'))
    print(m.contains_key('key3'))
    m.remove('key3')
    print(m.contains_key('key3'))

    print("\nPDF - contains_key example 2")
    print("----------------------------")
    m = HashMap(79, hash_function_2)
    keys = [i for i in range(1, 1000, 20)]
    for key in keys:
        m.put(str(key), key * 42)
    print(m.get_size(), m.get_capacity())
    result = True
    for key in keys:
        # all inserted keys must be present
        result &= m.contains_key(str(key))
        # NOT inserted keys must be absent
        result &= not m.contains_key(str(key + 1))
    print(result)

    print("\nPDF - remove example 1")
    print("----------------------")
    m = HashMap(53, hash_function_1)
    print(m.get('key1'))
    m.put('key1', 10)
    print(m.get('key1'))
    m.remove('key1')
    print(m.get('key1'))
    m.remove('key4')

    print("\nPDF - get_keys_and_values example 1")
    print("------------------------")
    m = HashMap(11, hash_function_2)
    for i in range(1, 6):
        m.put(str(i), str(i * 10))
    print(m.get_keys_and_values())

    m.resize_table(1)
    print(m.get_keys_and_values())

    m.put('20', '200')
    m.remove('1')
    m.resize_table(2)
    print(m.get_keys_and_values())

    print("\nPDF - find_mode example 1")
    print("-----------------------------")
    da = DynamicArray(["apple", "apple", "grape", "melon", "melon", "peach"])
    mode, frequency = find_mode(da)
    print(f"Input: {da}\nMode : {mode}, Frequency: {frequency}")

    print("\nPDF - find_mode example 2")
    print("-----------------------------")
    test_cases = (
        ["Arch", "Manjaro", "Manjaro", "Mint", "Mint", "Mint", "Ubuntu", "Ubuntu", "Ubuntu", "Ubuntu"],
        ["one", "two", "three", "four", "five"],
        ["2", "4", "2", "6", "8", "4", "1", "3", "4", "5", "7", "3", "3", "2"]
    )

    for case in test_cases:
        da = DynamicArray(case)
        mode, frequency = find_mode(da)
        print(f"Input: {da}\nMode : {mode}, Frequency: {frequency}\n")


from django.forms import ModelForm
from django import forms
from .models import *
from django.forms.widgets import DateInput, Select

class CategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = ['name']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['name'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Input the type of pineapple here...'})

class DateInput(forms.DateInput):
    input_type = 'date'

class CropForm(forms.ModelForm):
    class Meta:
        model = Crop
        fields = ['category', 'number_planted', 'plant_date']

        widgets = {
            'category': Select(attrs={'class': 'form-control'}),
            'number_planted': forms.TextInput(attrs={'class': 'form-control'}),
            'plant_date': DateInput(attrs={'class': 'form-control'}),
        }
        labels = {
            'number_planted': 'Total Planted',
        }
class YieldForm(forms.ModelForm):
    class Meta:
        model = Yield
        fields = ['category', 'number_yield', 'harvest_date']

        widgets = {
            'category': Select(attrs={'class': 'form-control'}),
            'number_yield': forms.TextInput(attrs={'class': 'form-control'}),
            'harvest_date': DateInput(attrs={'class': 'form-control'}),
        }
        labels = {
            'number_yield': 'Total Harvest',
        }

class BadPineForm(forms.ModelForm):
    class Meta:
        model = BadPine
        fields = ['category', 'number_yield', 'harvest_date']

        widgets = {
            'category': Select(attrs={'class': 'form-control'}),
            'number_yield': forms.TextInput(attrs={'class': 'form-control'}),
            'harvest_date': DateInput(attrs={'class': 'form-control'}),
        }

class WorkerPayForm(forms.ModelForm):
    class Meta:
        model = WorkerPays
        fields = ['name', 'price_pay', 'workers', 'date']

        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'price_pay': forms.TextInput(attrs={'class': 'form-control'}),
            'workers': forms.TextInput(attrs={'class': 'form-control'}),
            'date': DateInput(attrs={'class': 'form-control'}),
        }

        labels = {
            'name': 'Expenses for',
            'price_pay': 'Price Expense',
            'workers': 'Number of Workers or Suckers of Pineapple'
        }

class YieldSearchForm(forms.ModelForm):
   export_to_CSV = forms.BooleanField(required=False)
   class Meta:
     model = Yield
     fields = ['category',]

   def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['category'].widget.attrs.update({'class': 'form-control'})

class PriceForm(forms.ModelForm):
    class Meta:
        model = PinePrice
        fields = ['price']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['price'].widget.attrs.update({'class': 'form-control',})

class ValueForm(forms.ModelForm):
    class Meta:
        model = PineValue
        fields = ['value']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['value'].widget.attrs.update({'class': 'form-control',})

class BiddingForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(BiddingForm, self).__init__(*args, **kwargs)
        # Modify the user field queryset to only include users from the "buyer" group
        self.fields['user'].queryset = User.objects.filter(groups__name='buyer')

    class Meta:
        model = BiddingProcess
        fields = ['user', 'bid_price',]

        widgets = {
            'user': Select(attrs={'class': 'form-control'}),
            'bid_price': forms.TextInput(attrs={'class': 'form-control'}),
        }


from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi import Request
from sqlalchemy.orm import Session
from database.base import get_db
from database.models import Note
from exceptions.main import NotFoundError
from .schema import NoteSchema, NotesList, NoteCreate, NoteUpdate
from .db_operations import db_read_item, db_create_note, db_update_note, db_delete_note, db_read_all_items

notes_router = APIRouter()

@notes_router.get("/notes/all", response_model=NotesList)
async def get_all_notes(limit: int = Query(10, ge=1, le=100),
                     offset: int = Query(0, ge=0),
                     db: Session = Depends(get_db)):
    notes = db_read_all_items(limit, offset, db)
    return notes

@notes_router.get("/notes/{note_id}", response_model=NoteSchema)
async def get_a_note(note_id: int, db: Session = Depends(get_db)):
    try:
        note = db_read_item(note_id, db)
    except NotFoundError:
        raise HTTPException(status_code=404, detail="Note not found")

    return note

@notes_router.post("/notes/", response_model=NoteCreate)
async def create_note(note: NoteCreate, db: Session = Depends(get_db)):
    new_note = db_create_note(note, db)
    return new_note

@notes_router.put("/notes/{note_id}", response_model=NoteUpdate)
def update_note(note_id: int, note_update: NoteUpdate, db: Session = Depends(get_db)):
    try:
        updated_note = db_update_note(note_id, note_update, db)
    except NotFoundError:
        raise HTTPException(status_code=404, detail="Note not found")

    return updated_note

@notes_router.delete("/notes/{note_id}")
def delete_note(note_id: int, db: Session = Depends(get_db)):
    try:
        status = db_delete_note(note_id, db)
    except NotFoundError:
        raise HTTPException(status_code=404, detail="Note not found")

    return status


import os

# defaults symbols
SYMBOLS={
    "NRG": "NRG Energy Inc.",
    "VNO": "Vornado Realty Trust",
    "MGM": "MGM Resorts International",
    "ABC": "AmerisourceBergen Corp.",
    "ALGN": "Align Technology Inc.",
    "DXCM": "DexCom Inc.",
    "NVDA": "NVIDIA Corp.",
    "REGN": "Regeneron Pharmaceuticals Inc.",
    "^GSPC": "S&P 500"
}

# default data dir
DATA_DIR=os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'data')

INTERVALS_TO_SECONDS={
    '1d': 24*60*60,
}

PREDICTION_HORIZONS = [1, 7, 14, 28]  # steps of prediction in base resolution, i.e. days
TEST_LEN_DAYS = 90  # days
TRAIN_LEN_DAYS = 2 * 365  # months
EXTRA_DATA_PERIODS = 100

DASHBOARD_DATA_WINDOW_DAYS = 180

def interval_to_seconds(interval: str):

    seconds = INTERVALS_TO_SECONDS.get(interval)

    if seconds is None:
        raise ValueError("Missing reference value for given interval.")

    return seconds


"""5. Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами.
Программа должна подсчитывать сумму чисел в файле и выводить ее на экран."""
import random

sum = 0
my_list = [str(random.randrange(10, 100)) for i in range(15)]
line = ' '.join(my_list)
for i in range(len(my_list)):
    sum += int(my_list[i])

with open('task5-file1.txt', 'w', encoding='Utf-8') as f:
    f.write(line)
    f.write(f'\nСумма чисел: {sum}')


#Name: Kazi Sameen Anwar
#Email: kazisameen.anwar39@myhunter.cuny.edu
#Date: October 14, 2021
#This program is an attractions map

def main():
    n = input("Is Little Kazi stupid?")
    if n == "Yes":
        return "You are correct"
    if n == "No":
        return "You're stupid too"

main()


# TITLE
# First and last three characters of a string

# DESCRIPTION
# Write a Python program that prints the first and last three characters of the string s as a single string.

# If the string has less than six characters, print an empty string (blank output).

# EXPECTED OUTPUT
# Input         | Output
# "Blue"        | ""
# "Wonderful"   | "Wonful"
# "Amazing"     | "Amaing"

input_string = ""
is_exit = False

while not is_exit:
    input_string = input()

    if input_string == "exit":
        is_exit = True
    else:
        if len(input_string) < 6:
            print("")
        else:
            print(input_string[0:3]+input_string[-3:])


import sys
import mutagen.mp3 as mp3
import mutagen.id3 as id3

def main():
  if len(sys.argv) < 3:
    sys.exit(1)
  cmd = sys.argv[1]
  target = sys.argv[2]

  if cmd == "init":
    init(target)
  elif cmd == 'addpic':
    if len(sys.argv) < 4:
      sys.exit(1)
    addpic(target, sys.argv[3])

# convert to ID3v2.3 and outputs info
def init(filename):
  audio = mp3.MP3(filename)
  print(int(audio.info.length), end='')

  tags = id3.ID3(filename, v2_version=3)
  available_tags = {
    'TIT2': 'Title',
    'APIC': 'Artwork',
    'TPE1': 'Artist',
    'TPE2': 'AlbumArtist',
    'TALB': 'Album',
    'TYER': 'Year',
    'TRCK': 'Track',
    'TPOS': 'Disc',
    'USLT': 'Lyric',
    'TCON': 'Genre',
  }
  save_tags = []
  delete_tags = []
  for tag_name in tags:
    if tag_name[:4] in available_tags.keys():
      tag = tags.getall(tag_name)
      if tag_name[:4] != 'APIC':
        tag[0].encoding = id3.Encoding.UTF16
      tag = [tag[0]]
      save_tags.append((tag_name, tag))
    else:
      delete_tags.append(tag_name)

  for tag in save_tags:
    tags.setall(tag[0], tag[1])
  for tag_name in delete_tags:
    tags.delall(tag_name)

  tags.save(v1=id3.ID3v1SaveOptions.REMOVE, v2_version=3)

def addpic(mp3file, imgfile):
  type = None
  if imgfile.endswith('png'):
    type = "image/png"
  elif imgfile.endswith('jpg') or imgfile.endswith('jpeg'):
    type = "image/jpeg"
  else:
    sys.exit(1)
  tag = id3.ID3(mp3file, v2_version=3)
  with open(imgfile).read() as f:
    tag.add(id3.APIC(
      encoding=id3.Encoding.UTF16,
      mime=type,
      type=id3.PictureType.COVER_FRONT,
      data=f.read()
    ))
  tag.save()

if __name__ == "__main__":
  main()


arr = [0, 3, 3, 3, 4, 5, 6]
target = 3

def countDuplicates(arr, target):
    def binaryLower(l, r, arr, target):
        if l > r:
            return -1

        mid = l + (r - l) // 2

        if arr[mid] == target and (mid == 0 or arr[mid - 1] < target):
            return mid
        elif target <= arr[mid]:
            return binaryLower(l, mid - 1, arr, target)
        else:
            return binaryLower(mid + 1, r, arr, target)

    def binaryHigher(l, r, arr, target):
        if l > r:
            return -1

        mid = l + (r - l) // 2

        if arr[mid] == target and (mid == len(arr) - 1 or arr[mid + 1] > target):
            return mid
        elif target < arr[mid]:
            return binaryHigher(l, mid - 1, arr, target)
        else:
            return binaryHigher(mid + 1, r, arr, target)

    lower = binaryLower(0, len(arr) - 1, arr, target)
    higher = binaryHigher(0, len(arr) - 1, arr, target)

    return higher - lower + 1

print(countDuplicates(arr, target))

interviews/Bloomberg - Count duplicate numbers.py


a, b, c = map( int, input().split() )
k = int( input() )

def solve( a, b, c, k ):
    if a < b and b < c:
        print( "Yes" )
        exit()
    elif k == 0:
        return
    else:
        solve( 2 * a, b, c, k - 1 )
        solve( a, 2 * b, c, k - 1 )
        solve( a, b, 2 * c, k - 1 )

solve( a, b, c, k )
print( "No" )


'''
8. Em um ADN em dupla hélice, as bases, se estáveis, emparelham-se com as respectivas
bases complementares: Adenina (A) com Timina (T) e Citosina (C) com Guanina (G).
Escreva um programa que dada uma sequência lida da entrada padrão de tamanho 15,
informe a base complementar:
Entrada: AGGGATTCCCCCAG
Saída: TCCCTAAGGGGGTC
'''

adn = []
base_complementar = []

for entrada in range(15):
    espelhamento = input("Digite a entrada do ADN: "
                         "\nAdenina (A); Timina (T); Citosina (C); Guanina (G)")
    adn.append(espelhamento)

for espelhado in adn:
    if espelhado == "A":
        base_complementar.append("T")

    elif espelhado == "T":
        base_complementar.append("A")

    elif espelhado == "C":
        base_complementar.append("G")

    elif espelhado == "G":
        base_complementar.append("C")

    else:
        base_complementar.append("inválido")

print("Base de ADN inserida: \n", adn,
      "\nBases complementares da ADN : \n", base_complementar)

'''
O programa realiza o seguinte algoritmo:
Define as variáveis lista como sendo vetor de armazenamento
Entra no laço de repetição for para iteração dentro do range até 15
Espera a entrada do usuário para receber os bases de ADN
adiciona as bases de ADN no final da lista adn
Entra em outro laço de repetição for para iteração de cada base de ADN na lista adn
Faz o espelhamento da lista de ADN na lista de bases complementares
Sendo analisado a entrada, é relacionado a saída da seguinte maneira:
Adenina (A) com Timina (T) e Citosina (C) com Guanina (G)
Imprime na tela a Lista da base de ADN inserida e a sua lista espelhada com os elementos respectivos da base complementar,
Acrescidas das mensagens entre aspas
'''

Atividades/Roteiro 10 - Mais sobre listas/Programas/Roteiro 10 Questão 8.py


# Problem 1: Two Sum

"""
Constraints

1) 2 <= nums.length <= 10^4
2) -10^9 <= nums[i] <= 10^9
3) -10^9 <= target <= 10^9
4) Only one valid answer exists

"""

class Solution:

    def twoSum(self, nums: list[int], target: int) -> list[int]:

        # Using Dictionary Collect all the elements w/ indices.
        nums_dict = {}
        for n, num in enumerate(nums):
           nums_dict[num] = n

        # Iterate through the list & see if there is a key in the nums_dict
        # that adds to equal the target, then return, if so.
        for n, num in enumerate(nums):

            complement = target - num # Difference, num + complment = target
            # Check if complement is a key & if the index is not the same as n
            # as it can be the sum of the same values. If its not the sum of
            # the same value then this second condition is not important.
            if complement in nums_dict and nums_dict[complement]!=n:
                return [n,nums_dict[complement]]