from django.shortcuts import render, redirect
from django.contrib.auth import logout as auth_logout
from .forms import *
from django.views.generic import *
from .models import *
from django.contrib.auth.models import AnonymousUser
from django.http import HttpResponseRedirect
from django.conf import settings
from django.views.generic.base import TemplateView
from django.contrib.auth.models import User
import datetime
import django.contrib.auth
from django.db.models import Q

def login(request):
    if request.user.is_authenticated:
        return redirect('home')
    else:
        return render(request, 'main/login.html')

def home(request):
    if request.user.is_authenticated:
        if request.method == 'POST':
            searchedState = request.POST['inputState']
            searchedWord = request.POST['input']
            if searchedState == 'Title':
                searchedList = Listing.objects.all().filter(book_title__icontains=searchedWord)
            elif searchedState == 'Author':
                searchedList = Listing.objects.all().filter(author__icontains=searchedWord)
            elif searchedState == 'Course':
                searchedList = Listing.objects.all().filter(book_course__icontains=searchedWord)
            elif searchedState == 'ISBN':
                searchedList = Listing.objects.all().filter(isbn=searchedWord)
            return render(request, 'main/home.html', {'searchedList': searchedList, 'searched': True})

        else:
            searchedList = Listing.objects.all()
            return render(request, 'main/home.html', {'searchedList': searchedList, 'searched': False})
    else:
        return redirect('/login')

def profile(request):
    # Profile.objects.filter(user=request.user).update(phone_number=request.POST["phoneNumber"])
    if request.user.is_authenticated:
        if request.method == 'POST':
            if 'phoneNumber' in request.POST:
                if(len(request.POST['phoneNumber']) == 10):
                    Profile.objects.filter(user=request.user).update(phone_number=request.POST["phoneNumber"])
            else:
                uploaded_file = request.FILES['document']
                store = FileSystemStorage('textexchange/uploads/'+str(request.user))
                store.save(uploaded_file.name, uploaded_file)
                Profile.objects.filter(user=request.user).update(profileImage=str(request.user)+'/'+str(uploaded_file))
        userid = request.user
        phonenumber = Profile.objects.get(user=request.user).phone_number
        if Profile.objects.get(user=request.user).profileImage:
            profileImage = Profile.objects.get(user=request.user).profileImage.url
        else:
            profileImage = "https://www.indiaspora.org/wp-content/uploads/2018/10/image-not-available.jpg"
        return render(request, 'main/profile.html', {'user': userid, 'phonenumber': phonenumber, 'profileImage': profileImage})
    else:
        return redirect('/login')

def sell(request):
    if request.user.is_authenticated:
        return render(request, 'main/sell.html')
    else:
        return redirect('/login')

# need to fix redirect
def listing(request):
    if request.user.is_authenticated:
        if request.method == 'POST':
            # form = ListingForm(request.POST, request.FILES)
            # # print(form)
            # if form.is_valid():
            #     print("working")
            #     newform = form.save(commit=False)
            #     newform.userid = Profile.objects.get(user=request.user)
            #     newform.save()
            #     return redirect('/sell/')
            listing = Listing()
            # listing.book_image = request.FILES['book_image']
            listing.seller_name = request.POST['seller_name']
            listing.book_title = request.POST['book_title']
            listing.author = request.POST['author']
            listing.isbn = request.POST['isbn']
            listing.book_course = request.POST['book_course']
            listing.price = request.POST['price']
            listing.book_description = request.POST['book_description']
            listing.userid = Profile.objects.get(user=request.user)
            listing.save()
            if 'book_image' in request.FILES:
                uploaded_file = request.FILES['book_image']
                store = FileSystemStorage('textexchange/uploads/textbook/'+str(request.user))
                store.save(uploaded_file.name, uploaded_file)
                Listing.objects.filter(book_title=request.POST['book_title'], userid=Profile.objects.get(user=request.user)).update(book_image='textbook/'+str(request.user)+'/'+str(uploaded_file))
            return redirect('/sell')
        # form = ListingForm()
        return render(request, 'main/listing.html')
    else:
        return redirect('/login')

# Gets to the payment page
class PaymentView(TemplateView):
    template_name = 'main/listings.html'
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['key'] = settings.RAVE_PUBLIC_KEY
        context['price'] = 1
        return context

# Page to indicate successful payment
class paymentSuccess(TemplateView):
    template_name = 'main/paymentSuccess.html'

# displays the listings that a user created
class DisplayUserListings(ListView):
    template_name = 'main/sell.html'

    def get(self, request, *args, **kwargs):
        # checks to see if user is logged in before trying to access Profile
        if(request.user.is_authenticated):
            form = ListingForm()
            id = Profile.objects.get(user=request.user)
            listings = Listing.objects.all().filter(userid=id)
            args = {'form': form, 'listings': listings}
            return render(request, self.template_name, args,)
        else:
            return redirect('/login')

# displays the listings to remove
class DisplayListingsRemove(ListView):
    template_name = 'main/removeListing.html'

    def get(self, request, *args, **kwargs):
        # checks to see if user is logged in before trying to access Profile
        if(request.user.is_authenticated):
            # deletes a listing
            if (request.GET.get('DeleteButton')):
                id = Profile.objects.get(user=request.user)
                Listing.objects.filter(book_title = request.GET.get('DeleteButton'), userid=id).delete()
                return redirect('/removeListing/')
            form = ListingForm()
            id = Profile.objects.get(user=request.user)
            listings = Listing.objects.all().filter(userid=id)
            args = {'form': form, 'listings': listings}
            return render(request, self.template_name, args,)
        else:
            return redirect('/login')

# displays listing on individual page

class ListingList(ListView):
    model = Listing

def listingdetail(request,id):
    if request.user.is_authenticated:
        listing = Listing.objects.get(id = id)
        return render(request, 'main/listings.html', {'listing': listing})
    else:
        return redirect('/login')

def message(request):
    if request.user.is_authenticated:
        if request.method == 'POST':
            form = ListingForm(request.POST)
            if form.is_valid():
                newform = form.save(commit=False)
                newform.userid = Profile.objects.get(user=request.user)
                newform.save()
                return redirect('/sell/')
        form = ListingForm()
        return render(request, 'main/listing.html', {'form': form})
    else:
        return redirect('/login')

class InboxView(View):
    def get(self, request, *args, **kwargs):
        args = {}
        if (request.user.is_authenticated):
            people = Map.objects.all().filter(Q(user=request.user) | Q(send=request.user)).order_by('-pub_date')
            num_results = Map.objects.all().filter(Q(user=request.user) | Q(send=request.user)).order_by('-pub_date').count()
            if(num_results!=0):
                args = {'people': people, 'user':request.user}
            return render(request, 'main/inbox.html', args)
        else:
            return redirect('/login')

    def post(self, request):
        if (request.user.is_authenticated):
            other = User.objects.all().filter(username=request.POST['rec'])
            #other = User.objects.get(username=request.POST['rec'])
            o = other.last()
            if(o):
                m = Message.objects.all().filter(Q(sender=request.user, recipient=o) | Q(sender=o, recipient=request.user)).order_by('-pub_date')
                args = {'m': m, 'o': o}
                return render(request, 'main/conversation.html', args)
            return render(request, 'main/message.html')
        else:
            return redirect('/login')

class SendMessageView(View):
    def get(self, request):
        args = {}
        if (request.user.is_authenticated):
            people = Map.objects.all().filter(user=request.user).order_by('-pub_date');
            args = {'people': people}
            return render(request, 'main/message.html', args, )
        else:
            return redirect('/login')

    #When I submit it will do the post
    def post(self, request):
        args = {}
        if (request.user.is_authenticated):
            other = User.objects.all().filter(username=request.POST['recipient'])
            o = other.last()
            if (o):
                sh = Map.objects.all().filter(Q(user=request.user, send = o) | Q(send=request.user, user = o))
                s = sh.first()
                if (s):
                    s.pub_date = django.utils.timezone.now()
                    s.save()
                else:
                    map = Map.objects.create(user=request.user, send=o, pub_date=django.utils.timezone.now())
                    map.save()
                mess = Message.objects.create(sender=request.user, recipient=o, message=request.POST['textbox'],
                                              pub_date=django.utils.timezone.now())
                mess.save()
                # m = Message.objects.all().filter(recipient=o)
                m = Message.objects.all().filter(Q(sender=request.user, recipient=o) | Q(sender=o, recipient=request.user)).order_by('-pub_date')
                args = {"other": o, 'm': m}
            else:
                b = bool(True)
                args = {"boolean" : b}
            return render(request, 'main/message.html', args, )
        else:
            return redirect('/login')

def message(request):
    args = {}
    if (request.user.is_authenticated):
        other = User.objects.all().filter(username=request.POST['recipient'])
        o = other.first()
        if(o):
            sh = Map.objects.all().filter(Q(user=request.user, send = o) | Q(send=request.user, user = o))
            s = sh.first()
            if(s):
                s.pub_date=django.utils.timezone.now()
                s.save()
            else:
                maps = Map.objects.create(user=request.user,send=o,pub_date=django.utils.timezone.now())
                maps.save()
            mess = Message.objects.create(sender=request.user, recipient=o, message=request.POST['textbox'],
                                             pub_date=django.utils.timezone.now())
            mess.save()
            # m = Message.objects.all().filter(recipient=o)
            m = Message.objects.all().filter(Q(sender=request.user, recipient=o) | Q(sender=o, recipient=request.user)).order_by('-pub_date')
            args = {"other": o, 'm': m}
        return render(request, 'main/message.html', args, )
    else:
        return redirect('/login')


from iot.DB import DBSingleton
db= DBSingleton.get_instance()
db.connectDB()

from iot.models import DevicesLog
from iot.serializers import DevicesLogSerializer
from rest_framework.response import  Response
from rest_framework import status
from rest_framework.decorators import APIView

import datetime
from mongoengine import *

class DevicesLogViewSet(APIView):
    def get(self, request):
        logs = DevicesLog.objects.all()
        logs_serializer = DevicesLogSerializer(logs, many=True)
        return Response(logs_serializer.data)

class DevicesLogSearch(APIView):

    def __verify_date(self, fdate, ldate):
       if fdate > ldate:
           return False
       else:
           return True

    def get_object(self, roomID, fdate, ldate, deviceID):
        d1= fdate.split("-")
        d2= ldate.split("-")
        date1= datetime.date(int(d1[0]), int(d1[1]), int(d1[2]))
        date2= datetime.date(int(d2[0]), int(d2[1]), int(d2[2]))
        print(date1)
        print(date2)
        if self.__verify_date(date1, date2):
            logs=[]
            if deviceID != None:
                logs= DevicesLog.objects(  Q(deviceId= deviceID)
                                        & Q(atRoom= roomID) )
            else:
                logs= DevicesLog.objects(atRoom= roomID)
            res=[]
            for log in logs:
                if log._date_changed.date()>=date1 and log._date_changed.date()<=date2:
                    res.append(log)
            return res
        else:
            return []

    def get(self, request, paras):
        paralst= paras.split("+")
        roomID= paralst[0]
        fday= paralst[1]
        lday= paralst[2]
        deviceID= paralst[3] if (len(paralst) == 4) else None
        logs= self.get_object(roomID, fday, lday, deviceID)
        logs_serializer= DevicesLogSerializer(logs, many=True)
        return Response(logs_serializer.data)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from collections import defaultdict
import random

import numpy as np

from ray.rllib.env.async_vector_env import _DUMMY_AGENT_ID

class MultiAgentEpisode(object):
    """Tracks the current state of a (possibly multi-agent) episode.

    The APIs in this class should be considered experimental, but we should
    avoid changing things for the sake of changing them since users may
    depend on them for custom metrics or advanced algorithms.

    Attributes:
        new_batch_builder (func): Create a new MultiAgentSampleBatchBuilder.
        add_extra_batch (func): Return a built MultiAgentBatch to the sampler.
        batch_builder (obj): Batch builder for the current episode.
        total_reward (float): Summed reward across all agents in this episode.
        length (int): Length of this episode.
        episode_id (int): Unique id identifying this trajectory.
        agent_rewards (dict): Summed rewards broken down by agent.
        custom_metrics (dict): Dict where the you can add custom metrics.
        user_data (dict): Dict that you can use for temporary storage.

    Use case 1: Model-based rollouts in multi-agent:
        A custom compute_actions() function in a policy graph can inspect the
        current episode state and perform a number of rollouts based on the
        policies and state of other agents in the environment.

    Use case 2: Returning extra rollouts data.
        The model rollouts can be returned back to the sampler by calling:

        >>> batch = episode.new_batch_builder()
        >>> for each transition:
               batch.add_values(...)  # see sampler for usage
        >>> episode.extra_batches.add(batch.build_and_reset())
    """

    def __init__(self, policies, policy_mapping_fn, batch_builder_factory,
                 extra_batch_callback):
        self.new_batch_builder = batch_builder_factory
        self.add_extra_batch = extra_batch_callback
        self.batch_builder = batch_builder_factory()
        self.total_reward = 0.0
        self.length = 0
        self.episode_id = random.randrange(2e9)
        self.agent_rewards = defaultdict(float)
        self.custom_metrics = {}
        self.user_data = {}
        self._policies = policies
        self._policy_mapping_fn = policy_mapping_fn
        self._agent_to_policy = {}
        self._agent_to_rnn_state = {}
        self._agent_to_last_obs = {}
        self._agent_to_last_action = {}
        self._agent_to_last_pi_info = {}
        self._agent_to_prev_action = {}
        self._agent_reward_history = defaultdict(list)

    def policy_for(self, agent_id=_DUMMY_AGENT_ID):
        """Returns the policy graph for the specified agent.

        If the agent is new, the policy mapping fn will be called to bind the
        agent to a policy for the duration of the episode.
        """

        if agent_id not in self._agent_to_policy:
            self._agent_to_policy[agent_id] = self._policy_mapping_fn(agent_id)
        return self._agent_to_policy[agent_id]

    def last_observation_for(self, agent_id=_DUMMY_AGENT_ID):
        """Returns the last observation for the specified agent."""

        return self._agent_to_last_obs.get(agent_id)

    def last_action_for(self, agent_id=_DUMMY_AGENT_ID):
        """Returns the last action for the specified agent, or zeros."""

        if agent_id in self._agent_to_last_action:
            return _flatten_action(self._agent_to_last_action[agent_id])
        else:
            policy = self._policies[self.policy_for(agent_id)]
            flat = _flatten_action(policy.action_space.sample())
            return np.zeros_like(flat)

    def prev_action_for(self, agent_id=_DUMMY_AGENT_ID):
        """Returns the previous action for the specified agent."""

        if agent_id in self._agent_to_prev_action:
            return _flatten_action(self._agent_to_prev_action[agent_id])
        else:
            # We're at t=0, so return all zeros.
            return np.zeros_like(self.last_action_for(agent_id))

    def prev_reward_for(self, agent_id=_DUMMY_AGENT_ID):
        """Returns the previous reward for the specified agent."""

        history = self._agent_reward_history[agent_id]
        if len(history) >= 2:
            return history[-2]
        else:
            # We're at t=0, so there is no previous reward, just return zero.
            return 0.0

    def rnn_state_for(self, agent_id=_DUMMY_AGENT_ID):
        """Returns the last RNN state for the specified agent."""

        if agent_id not in self._agent_to_rnn_state:
            policy = self._policies[self.policy_for(agent_id)]
            self._agent_to_rnn_state[agent_id] = policy.get_initial_state()
        return self._agent_to_rnn_state[agent_id]

    def last_pi_info_for(self, agent_id=_DUMMY_AGENT_ID):
        """Returns the last info object for the specified agent."""

        return self._agent_to_last_pi_info[agent_id]

    def _add_agent_rewards(self, reward_dict):
        for agent_id, reward in reward_dict.items():
            if reward is not None:
                self.agent_rewards[agent_id,
                                   self.policy_for(agent_id)] += reward
                self.total_reward += reward
                self._agent_reward_history[agent_id].append(reward)

    def _set_rnn_state(self, agent_id, rnn_state):
        self._agent_to_rnn_state[agent_id] = rnn_state

    def _set_last_observation(self, agent_id, obs):
        self._agent_to_last_obs[agent_id] = obs

    def _set_last_action(self, agent_id, action):
        self._agent_to_last_action[agent_id] = action

    def _set_last_pi_info(self, agent_id, pi_info):
        self._agent_to_last_pi_info[agent_id] = pi_info

def _flatten_action(action):
    # Concatenate tuple actions
    if isinstance(action, list) or isinstance(action, tuple):
        expanded = []
        for a in action:
            if not hasattr(a, "shape") or len(a.shape) == 0:
                expanded.append(np.expand_dims(a, 1))
            else:
                expanded.append(a)
        action = np.concatenate(expanded, axis=0).flatten()
    return action


data = open("../input/day10.txt", mode="r").read().splitlines()

c, x = 0, 1
cycles = {20: 0, 60: 0, 100: 0, 140: 0, 180: 0, 220: 0}
rows = [[" "] * 40 for _ in range(6)]

for inst in data:
    cycle_count = 1 if inst == "noop" else 2
    for _ in range(cycle_count):
        c += 1
        if c in cycles:
            cycles[c] = x * c

        row, pixel = divmod(c - 1, 40)
        if x - 1 <= pixel <= x + 1:
            rows[row][pixel] = "#"

    if cycle_count == 2:  # was addx
        x += int(inst.split()[1])

print(sum(cycles.values()))
for r in rows:
    print("".join(r))


import sys
sys.stdin = open('bj1039.txt','r')

N,K=map(int,input().split())
Q=[str(N)]
Len=len(str(N))
while K:
    que=set()
    for q in Q:
        List=list(map(str,q))
        for i in range(Len):
            for j in range(i+1,Len):
                if not i and List[j]=='0':continue
                List[i],List[j]=List[j],List[i]
                que.add(''.join(List))
                List[i],List[j]=List[j],List[i]
    Q=list(que)
    K-=1
print(max(int(x)for x in Q+[-1]))


import argparse
import logging
import re

def update_version(version : str, file : str):
  openedFile = open(file, "r")
  fileContent = openedFile.read()
  regex = r'^(\s*\"version\": )(\"[\d.]*\"),$'
  newFileContent = ''
  print(fileContent.splitlines()
  )
  for f in fileContent.splitlines():
    match = re.fullmatch(regex, f)
    if match != None:
      newFileContent += match.group(1) + f'"{version}",'
    else:
      newFileContent += f
    newFileContent += '\n'
  openedFile.close()
  openedFile = open(file, "w")
  openedFile.write(newFileContent)
  openedFile.close()

def build_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument(nargs=2,
                        action='store',
                        dest='update_version',
                        help='Apply regex to replace the current version of app.json expo pattern file'
                        )
    return parser.parse_args()

if __name__ == '__main__':
    args = build_args()
    if args.update_version:
        print("entrou")
        update_version(args.update_version[0], args.update_version[1])
        print("saiu")


from __future__ import print_function
import logging
import grpc
import cli_grpc_pb2 as pb2
import cli_grpc_pb2_grpc as pb2_grpc

default_netloc = 'localhost:50051'

def stat_client(stub, _uuid):
    uuid = pb2.Uuid(**{'value': _uuid})
    req = pb2.StatRequest(**{"uuid": uuid})
    try:
        stat_reply = stub.stat(req)
        return stat_reply
    except grpc.RpcError:
        return 404

def read_client(stub, _uuid, chunk_size=1):
    uuid = pb2.Uuid(**{'value': _uuid})
    req = pb2.ReadRequest(**{"uuid": uuid, "size": chunk_size})
    try:
        read_replies = stub.read(req)
        read_replies = list(read_replies)
    except grpc.RpcError:
        return 404
    else:
        if read_replies:
            return read_replies
        else:
            return 404

def run(_uuid, _subcommand, _netloc=default_netloc, chunk=1):
    with grpc.insecure_channel(_netloc) as channel:
        stub = pb2_grpc.FileStub(channel)
        if _subcommand == 'stat':
            return stat_client(stub, _uuid)
        elif _subcommand == 'read':
            return read_client(stub, _uuid, chunk)


from PyQt5.QtWidgets import QMainWindow, QTableWidgetItem
from PyQt5.QtGui import QPainter, QPen, QFont, QColor
from PyQt5.QtCore import Qt, QPoint

from view.forms import ExplainForm

class ExplainView(QMainWindow):
    TABLE_LABLE_TEMPLATE = "
{model_name}
"
    COLUMN_STEP_NAME = "i, step"

    def __init__(self):
        super(ExplainView, self).__init__()
        self.ui = ExplainForm(self)
        self.init_UI()

    def init_UI(self):
        self._hide_interface()

    def _hide_interface(self):
        pass

    def set_table_data(self, data: dict, model_name: str):
        rows_count = len(data.keys())
        data_values = list(data.values())
        columns_count = len(data_values[0]) + 1

        columns_names = [self.COLUMN_STEP_NAME]
        columns_names.extend(list(data_values[0].keys()))

        self.ui.ExplainTableWidget.setRowCount(rows_count)
        self.ui.ExplainTableWidget.setColumnCount(columns_count)
        self.ui.ExplainTableWidget.setHorizontalHeaderLabels(columns_names)
        self.ui.ExplainTableWidget.verticalHeader().setVisible(False)

        self.ui.PaintModelLabel.setAlignment(Qt.AlignCenter)
        self.ui.PaintModelLabel.setText(self.TABLE_LABLE_TEMPLATE.format(model_name=model_name))

        for irow in range(rows_count):
            for icol, col in enumerate(columns_names):
                if col == self.COLUMN_STEP_NAME:
                    item = QTableWidgetItem(str(irow))
                else:
                    item = QTableWidgetItem(str(data_values[irow][col]))
                self.ui.ExplainTableWidget.setItem(irow, icol, item)


#!/usr/local/bin/python3

import sys
import shutil

def copyContracts(contractsFilename, fromDir, toDir, num):
    contractsFile = open(contractsFilename)
    contracts = []

    row = -1
    for contractEntry in contractsFile:
        row += 1
        if row == 0:
            continue

        fields = contractEntry.rstrip('\n').split(",")
        contracts.append(fields)

    sortedContracts = sorted(contracts, key=lambda c: int(c[-1]), reverse=True)

    for i in range(num):
        print(sortedContracts[i])
        contract = sortedContracts[i]
        fromFile = "{fromDir}/{name}_{addr}.sol".format(fromDir = fromDir, name = contract[0], addr = contract[1])
        shutil.copy(fromFile, toDir)

if(len(sys.argv) != 5):
    print("Usage: copyContracts.py <contractsFile> <fromDir> <toDir> <num>")
    sys.exit(1)

copyContracts(sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4]))


"""
Given a binary search tree and a node in it,
find the in-order predecessor of that node in the BST.

Example
Given root = {2,1,3}, p = 1, return null.
"""
"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: the given BST
    @param p: the given node
    @return: the in-order successor of the given node in the BST
    """

    def inorderPredecessor(self, root, p):
        self.pre = None
        self.result = None
        self.dfs(root, p)
        return self.result

    def dfs(self, root, p):
        if root is None or self.result is not None:
            return
        self.dfs(root.left, p)
        if root == p:
            self.result = self.pre
        self.pre = root
        self.dfs(root.right, p)

LintCode 915. Inorder Predecessor in BST.py


data = [(s[0], int(s[1:])) for s in """
F10
N3
F7
R90
F11
""".strip().split("\n")]
with open("input") as f:
    data = [(s[0], int(s[1:])) for s in f.read().strip().split("\n")]

ship = (0, 0, 0)

directions = {
        0: (1, 0),
        90: (0, 1),
        180: (-1, 0),
        270: (0, -1),
        }

def move(dx, dy, ship):
    x, y, a = ship
    return (x+dx, y+dy, a)

def turn(sign, degree, ship):
    x, y, a = ship
    return (x, y, (a+sign*degree)%360)

def moveF(value, ship):
    x, y, a = ship
    dx, dy = directions[a]
    dx, dy = dx*value, dy*value
    return move(dx, dy, ship)

funcs = {
        "L": lambda degree, ship: turn(1, degree, ship),
        "R": lambda degree, ship: turn(-1, degree, ship),
        "N": lambda value, ship: move(0, value, ship),
        "S": lambda value, ship: move(0, -value, ship),
        "E": lambda value, ship: move(value, 0, ship),
        "W": lambda value, ship: move(-value, 0, ship),
        "F": moveF,
        }

for op, value in data:
    ship = funcs[op](value, ship)

x, y, _ = ship
print(abs(x)+abs(y))

def turn90(waypoint):
    x, y = waypoint
    return (-y, x)
def turn(sign, degree, waypoint):
    for _ in range((360+sign*degree)%360//90):
        waypoint = turn90(waypoint)
    return waypoint
def moveF(value, waypoint, ship):
    dx, dy = waypoint
    x, y = ship
    return waypoint, (x+dx*value, y+dy*value)
def move(dx, dy, ship):
    x, y = ship
    return (x+dx, y+dy)
waypoint = (10, 1)
ship = (0, 0)

funcs = {
        "L": lambda degree, waypoint, ship: (turn(1, degree, waypoint), ship),
        "R": lambda degree, waypoint, ship: (turn(-1, degree, waypoint), ship),
        "N": lambda value, waypoint, ship: (move(0, value, waypoint), ship),
        "S": lambda value, waypoint, ship: (move(0, -value, waypoint), ship),
        "E": lambda value, waypoint, ship: (move(value, 0, waypoint), ship),
        "W": lambda value, waypoint, ship: (move(-value, 0, waypoint), ship),
        "F": moveF,
        }
for op, value in data:
    waypoint, ship = funcs[op](value, waypoint, ship)

x, y = ship
print(abs(x)+abs(y))


#!/usr/bin/env python

"""
Isolated roll mechanism for moving robot's wrists

"""

import robot
import copy
import constants

RH_rolling = False
LH_rolling = False

def roll (roll_limb):

    global LH_initial_angle
    global RH_initial_angle

    if roll_limb == 'left':
        limb = robot.left_limb
        mode = robot.LH_roll_mode
        rolling =LH_rolling
        wrist = 'left_w2'
    else:
        limb = robot.right_limb
        mode = robot.RH_roll_mode
        rolling = RH_rolling
        wrist = 'right_w2'

    currAngles = limb.joint_angles()
    currAnglesCopy = copy.deepcopy(currAngles)

    if roll_limb == 'left':
        if rolling == False:
            LH_initial_angle= limb.joint_angles()
        currAnglesCopy = add_roll(currAnglesCopy, LH_initial_angle, 'left')
    else:
        if rolling == False:
            RH_initial_angle = limb.joint_angles()
        currAnglesCopy = add_roll(currAnglesCopy, RH_initial_angle, 'right')

    while ((abs(currAngles[wrist]- currAnglesCopy[wrist]) >= constants.PRECISION_TOLERANCE/2) & mode == True):
        limb.set_joint_positions(currAnglesCopy)
        currAngles= limb.joint_angles()

    return

def add_roll(curr_joint_angles, initial_angle, limb):
    if limb == 'left':
        wrist = 'left_w2'
        yaw = robot.goalPose.LH_yaw
    else:
        wrist = 'right_w2'
        yaw = robot.goalPose.RH_yaw

    angles = curr_joint_angles

    if yaw + initial_angle[wrist] <= constants.WRIST_ROLL_MIN:
        angles[wrist] = constants.WRIST_ROLL_MIN
    elif yaw + initial_angle[wrist] >= constants.WRIST_ROLL_MAX:
        angles[wrist] = constants.WRIST_ROLL_MAX
    else:
        angles[wrist] = yaw + initial_angle[wrist]
    return angles


# -*- coding: utf-8 -*-
import scrapy
from selenium import webdriver
from ..items import WangyiproItem
class WangyiSpider(scrapy.Spider):
    name = 'wangyi'
    # allowed_domains = ['www.xx.com']
    start_urls = ['http://war.163.com/']
    def __init__(self):
        self.bro = webdriver.Chrome(executable_path='D:\迅雷下载\开发工具\chromedriver1.exe')

    def detail_parse(self,response):
        item = response.meta['item']
        content = response.xpath('//*[@id="endText"]/p[4]/text()').extract_first()
        item['content'] = content

        yield item
    def parse(self, response):
        div_list = response.xpath('//div[@class="data_row news_article clearfix "]')
        for div in div_list:
            # while enumerate(div_list) == 10:
            #     break
            item = WangyiproItem()

            title = div.xpath('.//div/div[1]/h3/a/text()').extract_first()
            print(title)
            detail_url = div.xpath('.//div/div[1]/h3/a/@href').extract_first()
            item['title'] = title

            yield scrapy.Request(url=detail_url,callback=self.detail_parse,meta={'item':item})
    def closed(self,spider):
        print('关闭浏览器对象')
        self.bro.quit()


import requests
import sys
# SO, lets create a function to access the API
# Also lets create a function to find pairs of players
# Finally create a summoning function

def accessAPI():
    # Gets a request summoning
    # returns the list of NBA Players
    response = requests.get('https://mach-eight.uc.r.appspot.com/')
    data = response.json()
    return data["values"]

def findPairs(listOfPlayers, height: int):
    # Navigate the list of players
    # Take current player, go to each next player after him
    # sum both players, if sum of heights is equal to value, add pair to return list
    # repeat for each player after selected player
    i = 0
    result = []
    while i < len(listOfPlayers) - 1:
        j = i + 1
        while j < len(listOfPlayers):
            player_a = listOfPlayers[i]
            player_b = listOfPlayers[j]
            value = int(player_a["h_in"]) + int(player_b["h_in"])
            if value == height:
                result.append({
                    "player_a": player_a,
                    "player_b": player_b
                })
            j = j + 1
        i = i + 1
    if len(result) > 0:
        return result
    else:
        return "No matches found"

if __name__ == "__main__":  # pragma: no cover
    if len(sys.argv) < 2:
        print("::Error:: height is required. Use python nba_finder.py _height_")
    else:
        players = accessAPI()
        expected_height = int(sys.argv[1])
        print(f"Getting players with height of {expected_height}:", findPairs(players, expected_height))


import pickle
from io import BytesIO

import requests
import yfinance as yf
from PIL import Image
from os import listdir
from os.path import isfile, join

curentList = []

import json, os
import pandas as pd

def makeDir():
    curDir = os.getcwd()
    try:
        os.mkdir('sectorData')
        os.mkdir('data')

    except Exception as e:
        print(e)

    dataDir = os.path.join(curDir, 'data')
    sectorDataDir = os.path.join(curDir, 'SectorData')

def temp(sortBy='yearReturn'):
    dfList = []
    x = []
    y = []
    z = []
    sectorList = []
    sl = []
    for a, b, c in os.walk(dataDir):
        z.append(a)
        sectorList.append(b)
        sl.append(c)
        fileList = []
    fileList = sl

    # print(fileList)
    sectorList = sectorList[0]
    # print(sectorList)
    sector = sectorList[4]  ####change
    fileList = []
    filePathList = []
    for i in range(len(sl) - 1):
        sectorPath = os.path.join(sectorDataDir, sector)
        fileList.append(sl[i + 1])
    myDict = dict(zip(sectorList, fileList))
    x = myDict
    keys = list(x.keys())
    vals = list(x.values())
    # print(keys)
    # print(vals)
    symbol_list = []
    for i in range(len(keys)):
        x = vals

    # print(keys)
    # print(x)
    for i in range(len(keys)):

        key = keys[i]
        # print(key)
        symbols = []
        vl = []
        na = sortBy

        for val in x[i]:
            message = val

            # check if the message ends with fun
            if message.endswith('json'):
                p = os.path.join(dataDir, key, val)

                # JSON file
                # print(p)

                f = open(p)

                # Reading from file
                data = json.loads(f.read())

                # print(f"{data['symbol']} {data['yearReturn']}")
                symbols.append(data['symbol'])
                symbol_list.append(data['symbol'])
                vl.append(data[na])

        data = {
            "symbols": symbols,
            na: vl
        }
        df = pd.DataFrame(data)
        # df['rank']=df.yearReturn.sort()
        dfList.append(df)

        df = df.sort_values(by=na, ascending=False)
        print(df)
        try:
            p = os.path.join(sectorDataDir, sortBy)
            os.mkdir(p)

        except Exception as e:
            # print(f'89 {e}')
            pass
        p = os.path.join(p, f'{key}.csv')
        df.to_csv(p)

    import pickle
    with open('universe.pickel', 'wb') as f:
        pickle.dump(symbol_list, f)
    # with open("universe.txt", 'w') as f:
    #     for item in symbol_list:
    #         f.write("%s\n" % item)

curDir = os.getcwd()
try:
    os.mkdir('data')
except:
    pass
dataDir = os.path.join(curDir, 'data')
sectorDataDir = os.path.join(curDir, 'sectorData')

class Stock:
    def __init__(self, symbol, p='1y'):
        self.path = dataDir
        curentList.append(symbol)
        self.symbol = symbol
        self.ticker = yf.Ticker(symbol)
        self.info = self.ticker.info
        self.sector = self.info['sector']
        try:
            self.sectorDir = os.path.join(dataDir, self.sector)
            os.mkdir(self.sectorDir)
        except:
            pass
        self.filePath = os.path.join(dataDir, self.sector, self.symbol) + '.json'
        self.hist = self.ticker.history(period=p)
        try:
            self.news = self.ticker.news
        except:
            self.news = None
        self.yearReturn = self.info['52WeekChange']
        self.pegRatio = self.info['pegRatio']
        self.shortPercentOfFloat = self.info['shortPercentOfFloat']
        self.marketCap = self.info['marketCap']
        self.payoutRatio = self.info['payoutRatio']
        try:
            self.fullTimeEmployees = self.info['fullTimeEmployees']
        except Exception as e:
            print(f'136: {e}')
            self.fullTimeEmployees = 0
        try:
            self.teps = self.info['trailingEps']
            self.feps = self.info['forwardEps']
            self.ebitdaMargins = self.info['ebitdaMargins']
            self.fpe = self.info['forwardPE']
            self.logo = self.info['logo_url']
            self.response = requests.get(self.logo)
            self.img = Image.open(BytesIO(self.response.content))
            self.ptb = self.info['priceToBook']
            self.roe = self.info['returnOnEquity']
            self.currentRatio = self.info['currentRatio']
            self.debtEquityRatio = self.info['debtToEquity']
            self.insiders = self.info['heldPercentInsiders']
            self.tcps = self.info['totalCashPerShare']
            self.quickRatio = self.info['quickRatio']
            self.shortName = self.info['shortName']
            self.lastDividendValue = self.info['lastDividendValue']
            self.beta = self.info['beta']
            self.threeYearAverageReturn = self.info['threeYearAverageReturn']
            self.sharesPercentSharesOut = self.info['sharesPercentSharesOut']
        except Exception as e:
            print(f'err: {e}')

        self.method_list = [method for method in dir(self) if method.startswith('__') is False]
        self.mySave()

    def mySave(self):
        fp = os.path.join(dataDir, self.sector, self.symbol) + '.pickle'
        with open(fp, 'wb') as f:
            # Pickle the 'data' dictionary using the highest protocol available.
            pickle.dump(self, f, pickle.HIGHEST_PROTOCOL)
        x = json.dumps(self.__dict__, indent=4, sort_keys=True, default=str)
        j = json.loads(x)
        with open(self.filePath, 'w') as f:
            json.dump(j, f)

    def __repr__(self):
        return self.filePath

def updateUniverse():
    with open('universe.pickle', 'rb') as pickle_file:
        content = pickle.load(pickle_file)
    sc = []
    for c in content:
        sc.append(c.strip())
    final = set(sc)
    for s in final:
        print(s)
        x = Stock(s, '1y')

def sortUniverse():
    ml = ['payoutRatio', 'pegRatio', 'fullTimeEmployees', 'yearReturn', 'beta', 'currentRatio', 'debtEquityRatio',
          'ebitdaMargins', 'feps', 'fpe', 'insiders' 'ptb',
          'quickRatio', 'marketCap']
    for m in set(ml):
        try:
            temp(sortBy=m)
        except Exception as e:
            print(e)

def sortStocks(sector, sortBy):
    r = requests.get(f'http://127.0.0.1:8000/stocks/{sector}/{sortBy}').json()
    keys = []
    vals = []
    ranks = []
    rank = 0

    for i in range(len(r)):
        try:
            val = r[i][sortBy]
        except:
            val = None
            print(r[i])
        if val != None:
            rank += 1
            symbol = r[i]["symbol"]
            keys.append(symbol)
            ranks.append(rank)
            vals.append(val)

    dictionary = dict(zip(keys, vals))
    return dictionary

sectorList = ['Basic%20Materials', 'Consumer%20Defensive', 'Healthcare', 'Communication%20Services', 'Energy',
              'Industrials',
              'Consumer%20Cyclical', 'Financial%20Services', 'Technology']

sectorLL = ['Basic Materials', 'Consumer Defensive', 'Healthcare', 'Communication Services', 'Energy','Industrials','Consumer Cyclical', 'Financial Services', 'Technology']
sectorsDict=dict(zip(sectorList,sectorLL))
# ml = ['ptb','pegRatio', 'yearReturn'
#       , 'fpe', 'insiders', 'marketCap']
# ml = [
#     'ebitdaMargins',
#     'yearReturn',
#     'pegRatio',
#     'shortPercentOfFloat',
#     'marketCap',
#     'payoutRatio',
#     'fullTimeEmployees',
#     'teps',
#     'feps',
#     'fpe',
#     'ptb',
#     'roe',
#     'currentRatio',
#     'debtEquityRatio',
#     'insiders',
#     'tcps',
#     'quickRatio',
#     'beta',
#     'sharesPercentSharesOut']
ml= ['zip', 'sector', 'fullTimeEmployees', 'longBusinessSummary', 'city', 'phone', 'state', 'country',
         'companyOfficers', 'website', 'maxAge', 'address1', 'industry', 'address2', 'ebitdaMargins', 'profitMargins',
         'grossMargins', 'operatingCashflow', 'revenueGrowth', 'operatingMargins', 'ebitda', 'targetLowPrice',
         'recommendationKey', 'grossProfits', 'freeCashflow', 'targetMedianPrice', 'currentPrice', 'earningsGrowth',
         'currentRatio', 'returnOnAssets', 'numberOfAnalystOpinions', 'targetMeanPrice', 'debtToEquity',
         'returnOnEquity', 'targetHighPrice', 'totalCash', 'totalDebt', 'totalRevenue', 'totalCashPerShare',
         'financialCurrency', 'revenuePerShare', 'quickRatio', 'recommendationMean', 'exchange', 'shortName',
         'longName', 'exchangeTimezoneName', 'exchangeTimezoneShortName', 'isEsgPopulated', 'gmtOffSetMilliseconds',
         'quoteType', 'symbol', 'messageBoardId', 'market', 'annualHoldingsTurnover', 'enterpriseToRevenue',
         'beta3Year', 'enterpriseToEbitda', '52WeekChange', 'morningStarRiskRating', 'forwardEps',
         'revenueQuarterlyGrowth', 'sharesOutstanding', 'fundInceptionDate', 'annualReportExpenseRatio', 'totalAssets',
         'bookValue', 'sharesShort', 'sharesPercentSharesOut', 'fundFamily', 'lastFiscalYearEnd',
         'heldPercentInstitutions', 'netIncomeToCommon', 'trailingEps', 'lastDividendValue', 'SandP52WeekChange',
         'priceToBook', 'heldPercentInsiders', 'nextFiscalYearEnd', 'yield', 'mostRecentQuarter', 'shortRatio',
         'sharesShortPreviousMonthDate', 'floatShares', 'beta', 'enterpriseValue', 'priceHint',
         'threeYearAverageReturn', 'lastSplitDate', 'lastSplitFactor', 'legalType', 'lastDividendDate',
         'morningStarOverallRating', 'earningsQuarterlyGrowth', 'priceToSalesTrailing12Months', 'dateShortInterest',
         'pegRatio', 'ytdReturn', 'forwardPE', 'lastCapGain', 'shortPercentOfFloat', 'sharesShortPriorMonth',
         'impliedSharesOutstanding', 'category', 'fiveYearAverageReturn', 'previousClose', 'regularMarketOpen',
         'twoHundredDayAverage', 'trailingAnnualDividendYield', 'payoutRatio', 'volume24Hr', 'regularMarketDayHigh',
         'navPrice', 'averageDailyVolume10Day', 'regularMarketPreviousClose', 'fiftyDayAverage',
         'trailingAnnualDividendRate', 'open', 'toCurrency', 'averageVolume10days', 'expireDate', 'algorithm',
         'dividendRate', 'exDividendDate', 'circulatingSupply', 'startDate', 'regularMarketDayLow', 'currency',
         'regularMarketVolume', 'lastMarket', 'maxSupply', 'openInterest', 'marketCap', 'volumeAllCurrencies',
         'strikePrice', 'averageVolume', 'dayLow', 'ask', 'askSize', 'volume', 'fiftyTwoWeekHigh', 'fromCurrency',
         'fiveYearAvgDividendYield', 'fiftyTwoWeekLow', 'bid', 'tradeable', 'dividendYield', 'bidSize', 'dayHigh',
         'regularMarketPrice', 'preMarketPrice', 'logo_url']

def add_stock(symbol):
    url = ('http://127.0.0.1:8000/stocks/all/yearReturn/up')
    myobj = {"symbol": symbol}
    x = requests.post(url, data=myobj)

def sortStocks(sector, sortBy, dir='up'):
    r = requests.get(f'http://127.0.0.1:8000/stocks/{sector}/{sortBy}/{dir}').json()
    keys = []
    vals = []
    ranks = []
    rank = 0
    for i in range(len(r)):
        val = r[i][sortBy]
        if val != None:
            rank += 1
            symbol = r[i]["symbol"]
            keys.append(symbol)
            ranks.append(rank)
            vals.append(val)

    dictionary = dict(zip(keys, vals))
    return dictionary

def sortSectors(sortBy='yearReturn', dir='up',normalize='True'):
    r = requests.get(f'http://127.0.0.1:8000/sectors/{sortBy}/{dir}').json()
    print(f'len:{len(r)} r[0]:{r[0]["ave"]}')

    keys = []
    vals = []
    ranks = []
    rank = 0
    for i in range(len(r)):
        val=r[i]["ave"]
        sec=r[i]["name"]
        if val != None:
            rank += 1
            keys.append(sec)
            ranks.append(rank)
            vals.append(val)

    dictionary = dict(zip(keys, vals))
    return dictionary

info = {
    "payoutRatio":
        "The payout ratio shows the proportion of earnings a company pays its shareholders in the form of dividends,"
        " expressed as a percentage of the company's total earnings. The calculation is derived by dividing the "
        "total dividends being paid out by the net income generated.",
"ebitdaMargins":"The EBITDA margin is a measure of a company's operating profit as a percentage of its revenue. The "
                "acronym EBITDA stands for earnings before interest, taxes, depreciation, and amortization. Knowing "
                "the EBITDA margin allows for a comparison of one company's real performance to others in its "
                "industry.",

"marketCap":"Market cap—or market capitalization—refers to the total value of all a company's shares of stock. It is calculated by multiplying the price of a stock by its total number of outstanding shares. For example, a company with 20 million shares selling at $50 a share would have a market cap of $1 billion.",
"ptb": "Companies use the price-to-book ratio (P/B ratio) to compare a firm's market capitalization to its book value. It's calculated by dividing the company's stock price per share by its book value per share (BVPS). An asset's book value is equal to its carrying value on the balance sheet, and companies calculate it netting the asset against its accumulated depreciation. Book value is also the tangible net asset value of a company calculated as total assets minus intangible assets (.e.g. patents, goodwill) and liabilities. For the initial outlay of an investment, book value may be net or gross of expenses, such as trading costs, sales taxes, and service charges. Some people may know this ratio by its less common name, the price-equity ratio.",
"fullTimeEmployees": "Number of employees",
"pegRatio":"The price/earnings to growth ratio (PEG ratio) is a stock's price-to-earnings (P/E) ratio divided by the growth rate of its earnings for a specified time period. The PEG ratio is used to determine a stock's value while also factoring in the company's expected earnings growth, and it is thought to provide a more complete picture than the more standard P/E ratio. ",
"yearReturn":"change in share price last year",
"fpe":"A variation of the price-to-earnings ratio (P/E ratio) is the forward P/E ratio, which is based on a prediction of a company's future earnings. Earnings used in the forward P/E ratio are estimates of future earnings, while the standard P/E ratio uses actual earnings per share from the company's previous four quarters.",
"quickRatio":" QR = (Current Assets - Inventories - Prepaid Expenses) / Current Liabilities.The quick ratio is an indicator of a company’s short-term liquidity position and measures a company’s ability to meet its short-term obligations with its most liquid assets. Since it indicates the company’s ability to instantly use its near-cash assets (assets that can be converted quickly to cash) to pay down its current liabilities, it is also called the acid test ratio. An 'acid test' is a slang term for a quick test designed to produce instant results. ",
"currentRatio":" The current ratio is a liquidity ratio that measures a company’s ability to pay short-term obligations or those due within one year. It tells investors and analysts how a company can maximize the current assets on its balance sheet to satisfy its current debt and other payables.A current ratio that is in line with the industry average or slightly higher is generally considered acceptable. A current ratio that is lower than the industry average may indicate a higher risk of distress or default. Similarly, if a company has a very high current ratio compared with its peer group, it indicates that management may not be using its assets efficiently.The current ratio is called current because, unlike some other liquidity ratios, it incorporates all current assets and current liabilities. The current ratio is sometimes called the working capital ratio. ",
"roe":"Return on equity (ROE) is a measure of financial performance calculated by dividing net income by shareholders' equity. Because shareholders' equity is equal to a company’s assets minus its debt, ROE is considered the return on net assets. ROE is considered a gauge of a corporation's profitability and how efficient it is in generating profits. ",
    "teps":
        " Trailing earnings per share (EPS) is a company's earnings generated over a prior period (often a fiscal year) reported on a per-share basis."
"The term trailing moreover implies a value calculated on a rolling basis. That is, trailing EPS may describe the most recent 12-month period or four earnings releases. The period used for a trailing EPS will change as the most recent earnings are added to the calculation and earnings from five quarters ago are dropped from the calculation. ",
    "feps":"The Forward Price-to-Earnings or Forward P/E Ratio. The forward P/E ratio (or forward price-to-earnings ratio) divides the current share price of a company by the estimated future earnings per share (EPS) of that company.",
    "debtEquityRatio":"The debt-to-equity (D/E) ratio compares a company's total liabilities to its shareholder equity and can be used to evaluate how much leverage a company is using. Higher-leverage ratios tend to indicate a company or stock with higher risk to shareholders.",
    "shortPercentOfFloat":"The short percentage of float is the percentage of a company's stock that has been shorted by institutional traders, compared to the number of shares of a company's stock that are available to the public.",
    "beta":"Beta is a measure of a stock's volatility in relation to the overall market. By definition, the market, such as the S&P 500 Index, has a beta of 1.0, and individual stocks are ranked according to how much they deviate from the market. A stock that swings more than the market over time has a beta above 1.0.",
    "insiders":"The insiders percentage is the percentage of float is the percentage of a company's stock that has been shorted by institutional traders,ort percentage of float is owned by employees",
}


# -*- coding: utf-8 -*-

import pymysql, os
import shutil,os

db = pymysql.connect("localhost", "root", "123456", "testdb", charset="utf8")
cursor = db.cursor()

idalls = open("C:/Users/Administrator/Desktop/ids.txt", encoding='utf8').readlines()

def selectINFObyID(productID):
    path = ''
    number = 0

    #sqlstring = 'select idproduct, product_breadcrumbs, product_title, product_desc from origin_zalora.product where idproduct = %s'
    sqlstring = 'SELECT product_sku, product_img_number FROM testdb.product where idproduct= %s'
    cursor.execute(sqlstring, int(productID))
    fetch_result = cursor.fetchone()

    if fetch_result is not None:
        path = fetch_result[0]
        number = fetch_result[1]
    return path, number

for eachrow in idalls:
    eachrow = eachrow.strip('\n')
    print(eachrow)
    product_path, product_number = selectINFObyID(eachrow)
    with open('C:/Users/Administrator/Desktop/pathandnumber.txt','a', encoding='utf8') as f:
        f.write(str(eachrow) + '\t' + product_path + '\t'  + str(product_number) + '\t' + '\n')

db.close()


import argparse

def parse():
    parser = argparse.ArgumentParser(description="Parse and play card games.")
    parser.add_argument("game", help="the name of the game")
    parser.add_argument("--log", nargs="?", const="output.txt", metavar="FILENAME", help="logs the output of the game")
    parser.add_argument('--debug', dest='debug', action='store_true', help="starts the game in debug mode")
    parser.set_defaults(debug=False)

    return parser.parse_args()


from functools import cache
from collections import deque
import numpy as np

@cache
def _get_input(input_file):
    with open(input_file, "r") as f:
        return np.array([list(map(int, line.strip())) for line in f.readlines() if line.strip() != ""])

def part_1(input_file):
    tree = _get_input(input_file)
    seen = np.zeros_like(tree)

    nothing   = lambda t: t
    reverse   = lambda t: t[::-1]
    transpose = lambda t: t.transpose()
    ops = deque([reverse, transpose, reverse, nothing])

    while ops:
        op = ops.pop()
        tree = op(tree)
        seen = op(seen)
        print(tree)

        for col in range(tree.shape[1]):
            index = 0
            seen[index, col] = 1
            current = tree[index, col]
            for index in range(1, tree.shape[0]):
                if tree[index, col] > current:
                    seen[index, col] = 1
                    current = tree[index, col]
        print(seen)
        print("===")

    return np.sum(seen)

def part_2(input_file):
    tree = _get_input(input_file)
    seen = np.zeros_like(tree)
    best = 0
    print(tree)

    for i in range(1, tree.shape[1] - 1):
        for j in range(1, tree.shape[0] - 1):
            stop = tree[i,j]

            # print(f"{i}, {j}: ", end="")
            dirs = [0, 0, 0, 0]
            los = [tree[i+1::1,j],
                   tree[i-1::-1,j],
                   tree[i,j+1::1],
                   tree[i,j-1::-1]]

            for d in range(len(dirs)):
                curr = -1
                for t in los[d]:
                    dirs[d] += 1
                    if t >= stop:
                        break

            # print(dirs)

            b = np.product(dirs)
            seen[i,j] = b
            if b > best:
                best = b

    print(seen)
    return best

if __name__=="__main__":
    # print(part_1("sample.txt"))
    # print(part_1("input.txt"))
    print(part_2("sample.txt"))
    print(part_2("input.txt"))


import pygame
from Sprites.player import Player
from Sprites.turtle_animated import TurtleSinker

def animate_sprites(*args):
    """
    Helper function used for animating turtles.

    - :param args:
        A list containing two lanes of turtles to be animated, the current frame count, and the net_group used to let the neural network 'see' sprites, respectively
    - :return:
        None
    """
    animate_turtles(args[0], args[1], args[2], args[3])

def animate_lane(lane, framecount, net_group):
    """
    Contains the logic that starts and advances the animation of one lane of turtles at the appropriate times.

    - :param lane:
        A pygame sprite Group object containing all of the turtles in one "lane". The function handles determining which turtles to animate and when.
    - :param framecount:
        An int containing the count of the current frame being rendered
    - :param net_group:
        A pygame sprite Group object containing all of the sprites which we want the AI to "see"
    - :return:
        None
    """
    for sprite in lane.sprites():
        if isinstance(sprite, TurtleSinker):
            if not sprite.animation_started and framecount - sprite.last_animation >= 30:
                sprite.start_animation(framecount, net_group)

            else:
                sprite.next_frame(framecount, net_group)

        elif not isinstance(sprite, Player):
            sprite.next_frame(framecount)

def animate_turtles(lane1: pygame.sprite.Group, lane2: pygame.sprite.Group, framecount,
                    net_group=pygame.sprite.Group()):
    """
    Helper function. Animates each individual lane of turtles.

    - :param lane1:
        A pygame sprite Group object containing all of the turtles in one "lane"
    - :param lane2:
        A pygame sprite Group object containing all of the turtles in one "lane"
    - :param framecount:
        An int containing count of the current frame being rendered
    - :param net_group:
        A pygame sprite Group object containing all of the sprites which we want the AI to "see"
    - :return:
        None
    """
    animate_lane(lane1, framecount, net_group)
    animate_lane(lane2, framecount, net_group)


# Importing necessary libraries
from Cryptodome.Cipher import AES
from Cryptodome.Util.Padding import pad, unpad
import os

# Defining the CBC mode encryption function
# this function accepts a plaintext (entered by the user, uses the initialized random key, and initialized vector)
# the AES.new creates a new cipher object, where it passes they key, in CBC mode, and the initialized vector
#Then, it encrypts the plaintext using this cipher object by calling its encrypt() method on the plaintext that is padded to the block size of the algorithm
# The pad() function is used to ensure that the plaintext is a multiple of the block size required by the AES encryption algorithm.
# This is necessary because AES (Advanced Encryption Standard) works on fixed-size blocks of 128 bits (16 bytes) each, and if the plaintext is not a multiple of the block size,
# it needs to be padded with additional bytes to make it a complete block.

def cbc_encrypt(plaintext, key, iv):
    cipher = AES.new(key, AES.MODE_CBC, iv)      # Creating a new cipher object using AES encryption algorithm with CBC mode and initialization vector iv
    ciphertext = cipher.encrypt(pad(plaintext, AES.block_size))    # Encrypting the plaintext by padding it to the block size and passing it to the cipher object
    return ciphertext

# Defining the CBC mode decryption function
def cbc_decrypt(ciphertext, key, iv):
    cipher = AES.new(key, AES.MODE_CBC, iv)      # Creating a new cipher object using AES encryption algorithm with CBC mode and initialization vector iv
    plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)   # Decrypting the ciphertext by passing it to the cipher object and then unpadding it to the block size
    return plaintext

# Defining the CFB mode encryption function
def cfb_encrypt(plaintext, key, iv):
    cipher = AES.new(key, AES.MODE_CFB, iv)     # Creating a new cipher object using AES encryption algorithm with CFB mode and initialization vector iv
    ciphertext = cipher.encrypt(plaintext)      # Encrypting the plaintext by passing it to the cipher object
    return ciphertext

# Defining the CFB mode decryption function
def cfb_decrypt(ciphertext, key, iv):
    cipher = AES.new(key, AES.MODE_CFB, iv)     # Creating a new cipher object using AES encryption algorithm with CFB mode and initialization vector iv
    plaintext = cipher.decrypt(ciphertext)      # Decrypting the ciphertext by passing it to the cipher object
    return plaintext

# Main function to get user input and execute the encryption and decryption
def main():
    plaintext = input("Enter plaintext to encrypt: ")    # Get the plaintext input from user
    key = os.urandom(16)    # Generating a 16-byte (128-bit) random key using os.urandom function
    iv = os.urandom(16)     # Generating a 16-byte (128-bit) random initialization vector using os.urandom function
    print("Plaintext:", plaintext)  # Print the plaintext
    print(f'Key: {key}')           # Print the randomly generated key
    print(f'IV: {iv}')             # Print the randomly generated initialization vector

    # CBC mode encryption and decryption
    ciphertext = cbc_encrypt(plaintext.encode('utf-8'), key, iv)  # Encrypt the plaintext using CBC mode and the randomly generated key and iv
    print("CBC Mode")
    print("Ciphertext:", ciphertext.hex())     # Print the ciphertext
    decrypted_plaintext = cbc_decrypt(ciphertext, key, iv).decode()   # Decrypt the ciphertext using CBC mode and the randomly generated key and iv
    print("Decrypted plaintext:", decrypted_plaintext)   # Print the decrypted plaintext

    # CFB mode encryption and decryption
    ciphertext = cfb_encrypt(plaintext.encode('utf-8'), key, iv)  # Encrypt the plaintext using CFB mode and the randomly generated key and iv
    print("\nCFB Mode")
    print("Ciphertext:", ciphertext.hex())     # Print the ciphertext
    decrypted_plaintext = cfb_decrypt(ciphertext, key, iv).decode()   # Decrypt the ciphertext using CFB mode and the randomly generated key and iv
    print("Decrypted plaintext:", decrypted_plaintext)   # Print the decrypted plaintext

if __name__ == '__main__':
    main()


import io
import os
from time import strftime

import pandas as pd
from datetime import datetime

from django.conf import settings
from django.db.models import Count, DateField, DateTimeField
from django.db.models.functions import Cast, TruncDate
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.core.exceptions import ObjectDoesNotExist
from django.views.generic import ListView, DetailView
from django.views.generic.edit import UpdateView, CreateView, DeleteView
from django.template.loader import render_to_string
from django.urls import reverse_lazy, reverse
from django.http import FileResponse

from reportlab.lib.enums import TA_CENTER, TA_RIGHT

from reportlab.lib.units import cm
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4, letter
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import Table, TableStyle, Frame
from reportlab.graphics.shapes import Line
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import Paragraph, SimpleDocTemplate, PageBreak, Spacer

from django.views import View

from weasyprint import HTML, CSS

from turnverein.settings import BASE_DIR

from .models import Vereine, Teilnehmer, Wettkampfteilnahme, Geraete, Riegen, BezirksturnfestErgebnisse, Meisterschaften
from .forms import UploadFileForm, ErgebnisTeilnehmerSuchen, VereinErfassenForm, TeilnehmerErfassenForm, \
    ErgebnisTeilnehmererfassenForm, TablesDeleteForm

# assert False

##########################################################################
# Area allgemeine Seiten
##########################################################################
def index(request):
    return render(request, 'turnfest/index.html')

def bezirksturnfest(request):
    return render(request, 'turnfest/bezirksturnfest.html')

def ligawettkampf(request):
    return render(request, 'turnfest/ligawettkampf.html')

def impressum(request):
    return render(request, 'turnfest/impressum.html')

def datenschutz(request):
    return render(request, 'turnfest/datenschutz.html')

##########################################################################
# Area Verein create and change
##########################################################################
class VereineCreateView(CreateView):
    model = Vereine
    template_name = "turnfest/vereine_create.html"
    form_class = VereinErfassenForm
    success_url = reverse_lazy("turnfest:vereine_list")

class VereineListView(ListView):
    model = Vereine

class VereineDetailView(DetailView):
    model = Vereine

class VereineUpdateView(UpdateView):
    model = Vereine
    template_name = "turnfest/vereine_update.html"
    fields = '__all__'
    success_url = "/turnfest/vereine_list/"

class VereineDeleteView(DeleteView):
    model = Vereine
    template_name = "turnfest/vereine_delete.html"
    success_url = reverse_lazy("turnfest:vereine_list")

def report_vereine(request):
    vereine = Vereine.objects.all()

    html_file = 'pdf_templates/report_vereine.html'
    css_file = '/css/report_vereine.css'

    filename = "vereine.pdf"

    html_string = render_to_string(html_file, {'vereine': vereine})

    html = HTML(string=html_string, base_url=request.build_absolute_uri())

    pdf = html.write_pdf(stylesheets=[CSS(settings.STATIC_ROOT + css_file)])
    response = HttpResponse(pdf, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=' + filename

    return response

##########################################################################
# Area Teilnehmer create and change
##########################################################################
class TeilnehmerCreateView(CreateView):
    model = Teilnehmer
    template_name = "turnfest/teilnehmer_create.html"
    form_class = TeilnehmerErfassenForm
    # fields = '__all__'
    success_url = reverse_lazy("turnfest:teilnehmer_list")

class TeilnehmerList(ListView):
    model = Teilnehmer

    ordering = ['teilnehmer_verein', '-teilnehmer_gender', 'teilnehmer_name']

class TeilnehmerDetailView(DetailView):
    model = Teilnehmer

class TeilnehmerUpdateView(UpdateView):
    model = Teilnehmer
    template_name = "turnfest/teilnehmer_update.html"
    # fields = '__all__'
    form_class = TeilnehmerErfassenForm
    success_url = reverse_lazy("turnfest:teilnehmer_list")

class TeilnehmerDeleteView(DeleteView):
    model = Teilnehmer
    template_name = "turnfest/teilnehmer_delete.html"
    success_url = reverse_lazy("turnfest:teilnehmer_list")

##########################################################################
# Area Wettkampfteilnehmer create and change
##########################################################################
class WettkampfteilnahmeCreateView(CreateView):
    model = Wettkampfteilnahme
    template_name = "turnfest/wettkampfteilnahme_create.html"
    fields = '__all__'
    success_url = "/"

class WettkampfteilnahmeList(ListView):
    model = Wettkampfteilnahme

class WettkampfteilnahmeDetailView(DetailView):
    model = Wettkampfteilnahme

class WettkampfteilnahmeUpdateView(UpdateView):
    model = Wettkampfteilnahme
    template_name = "turnfest/wettkampfteilnahme_update.html"
    fields = '__all__'
    success_url = "/"

##########################################################################
# Area Wettkampflisten erzeugen
##########################################################################

def report_geraetelisten_old(request):
    riegen = Riegen.objects.all()
    geraete = Geraete.objects.all()
    # teilnehmer_geburtsjahr_group = Teilnehmer.objects.values('teilnehmer_geburtsjahr').annotate(
    #    count=Count('teilnehmer_geburtsjahr'))

    # Definieren Sie die gewünschte Schriftart und laden Sie sie
    font_path = BASE_DIR / "ttf/dejavu-sans/ttf/DejaVuSans.ttf"
    pdfmetrics.registerFont(TTFont("DejaVuSans", font_path))

    font_path = BASE_DIR / "ttf/dejavu-sans/ttf/DejaVuSans-Bold.ttf"
    pdfmetrics.registerFont(TTFont("DejaVuSans-Bold", font_path))

    # Create a file-like buffer to receive PDF data.
    buffer = io.BytesIO()

    # Create the PDF object, using the buffer as its "file."
    p = canvas.Canvas(buffer, pagesize=A4)

    # Holen der Seitenabmessung
    breite, hoehe = A4

    for riege in riegen:
        for geraet in geraete:

            h = 2

            p.setFont('DejaVuSans-Bold', 18)
            p.drawCentredString(breite / 2, hoehe - (1 * cm), riege.riege + " " + geraet.geraet_name)

            if geraet.geraet_db_name == "teilnehmer_sprung":
                teilnehmer_alle = Teilnehmer.objects.filter(teilnehmer_sprung__gt=0,
                                                            teilnehmer_geburtsjahr__range=[riege.riege_ab,
                                                                                riege.riege_bis]).values_list(
                    'teilnehmer_name',
                    'teilnehmer_vorname')

            elif geraet.geraet_db_name == "teilnehmer_mini":
                teilnehmer_alle = Teilnehmer.objects.filter(teilnehmer_mini__gt=0,
                                                            teilnehmer_geburtsjahr__range=[riege.riege_ab,
                                                                                riege.riege_bis]).values_list(
                    'teilnehmer_name',
                    'teilnehmer_vorname')
            elif geraet.geraet_db_name == "teilnehmer_reck_stufenbarren":
                teilnehmer_alle = Teilnehmer.objects.filter(teilnehmer_reck_stufenbarren__gt=0,
                                                            teilnehmer_geburtsjahr__range=[riege.riege_ab,
                                                                                riege.riege_bis]).values_list(
                    'teilnehmer_name',
                    'teilnehmer_vorname')
            elif geraet.geraet_db_name == "teilnehmer_balken":
                teilnehmer_alle = Teilnehmer.objects.filter(teilnehmer_balken__gt=0,
                                                            teilnehmer_geburtsjahr__range=[riege.riege_ab,
                                                                                riege.riege_bis]).values_list(
                    'teilnehmer_name',
                    'teilnehmer_vorname')
            elif geraet.geraet_db_name == "teilnehmer_barren":
                teilnehmer_alle = Teilnehmer.objects.filter(teilnehmer_barren__gt=0,
                                                            teilnehmer_geburtsjahr__range=[riege.riege_ab,
                                                                                riege.riege_bis]).values_list(
                    'teilnehmer_name',
                    'teilnehmer_vorname')
            elif geraet.geraet_db_name == "teilnehmer_boden":
                teilnehmer_alle = Teilnehmer.objects.filter(teilnehmer_boden__gt=0,
                                                            teilnehmer_geburtsjahr__range=[riege.riege_ab,
                                                                                riege.riege_bis]).values_list(
                    'teilnehmer_name',
                    'teilnehmer_vorname')

            headers = ['Start-Nr.', 'Nachname', 'Vorname', 'Verein', 'Jahrgang', 'Meldung', 'A-Note', 'B-Note', 'Summe']
            table_data = [headers] + [list(row) + [''] * (len(headers) - len(row)) for row in teilnehmer_alle]

            if table_data:
                table = Table(table_data)

                # Stil für die Tabelle festlegen
                style = TableStyle([('BACKGROUND', (0, 0), (-1, 0), colors.grey),
                                    ('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
                                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                                    ('FONTNAME', (0, 0), (-1, -1), 'DejaVuSans'),
                                    ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
                                    ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
                                    ('GRID', (0, 0), (-1, -1), 1, colors.black)])

                # Tabelle mit Stil rendern
                table.setStyle(style)

                table.wrapOn(p, breite, hoehe)
                table.drawOn(p, 1 * cm, 25 * cm)
            p.showPage()  # Erzwingt eine neue Seite

    # Close the PDF object cleanly, and we're done.
    p.save()

    # FileResponse sets the Content-Disposition header so that browsers
    # present the option to save the file.
    buffer.seek(0)
    return FileResponse(buffer, as_attachment=True, filename="Wettkampfliste.pdf")

def report_geraetelisten(request):
    riegen = Riegen.objects.all()
    geraete = Geraete.objects.all()

    # Definieren Sie die gewünschte Schriftart und laden Sie sie
    font_path = BASE_DIR / "ttf/dejavu-sans/ttf/DejaVuSans.ttf"
    pdfmetrics.registerFont(TTFont("DejaVuSans", font_path))

    font_path = BASE_DIR / "ttf/dejavu-sans/ttf/DejaVuSans-Bold.ttf"
    pdfmetrics.registerFont(TTFont("DejaVuSans-Bold", font_path))

    response = HttpResponse(content_type='application/pdf')
    # response['Content-Disposition'] = 'inline; filename="Wettkampfliste.pdf"'
    response['Content-Disposition'] = 'attachment; filename="Wettkampfliste.pdf"'

    # Create the PDF object, using the buffer as its "file."
    pdf = SimpleDocTemplate(response,
                            rightMargin=10,
                            leftMargin=10,
                            topMargin=10,
                            bottomMargin=10,
                            pagesize=A4,
                            )

    # Create styles
    styles = getSampleStyleSheet()

    styles.add(ParagraphStyle(name='CenterAlign20',
                              fontName='DejaVuSans-Bold',
                              fontSize=20,
                              alignment=TA_CENTER))

    styles.add(ParagraphStyle(name='CenterAlign14',
                              fontName='DejaVuSans-Bold',
                              fontSize=14,
                              alignment=TA_CENTER))

    normal_style = styles['Normal']
    heading_style = styles['Heading1']
    heading_style.alignment = TA_CENTER

    # Create a list to store the content for the PDF
    content = []
    # teilnehmer_alle = []
    for riege in riegen:
        for geraet in geraete:

            if geraet.geraet_db_name == "teilnehmer_sprung":
                teilnehmer_alle = Teilnehmer.objects.filter(
                    teilnehmer_sprung__gt=0,
                    teilnehmer_geburtsjahr__range=[riege.riege_ab,
                                                   riege.riege_bis]).values_list('id',
                                                                                'teilnehmer_name',
                                                                                'teilnehmer_vorname',
                                                                                'teilnehmer_verein__verein_name_kurz',
                                                                                'teilnehmer_geburtsjahr',
                                                                                'teilnehmer_sprung'
                                                                                )

            elif geraet.geraet_db_name == "teilnehmer_mini":
                teilnehmer_alle = Teilnehmer.objects.filter(
                    teilnehmer_mini__gt=0,
                    teilnehmer_geburtsjahr__range=[riege.riege_ab,
                                                   riege.riege_bis]).values_list('id',
                                                                                'teilnehmer_name',
                                                                                'teilnehmer_vorname',
                                                                                'teilnehmer_verein__verein_name_kurz',
                                                                                'teilnehmer_geburtsjahr',
                                                                                'teilnehmer_sprung'
                                                                                )
            elif geraet.geraet_db_name == "teilnehmer_reck_stufenbarren":
                teilnehmer_alle = Teilnehmer.objects.filter(
                    teilnehmer_reck_stufenbarren__gt=0,
                    teilnehmer_geburtsjahr__range=[riege.riege_ab,
                                                   riege.riege_bis]).values_list('id',
                                                                                'teilnehmer_name',
                                                                                'teilnehmer_vorname',
                                                                                'teilnehmer_verein__verein_name_kurz',
                                                                                'teilnehmer_geburtsjahr',
                                                                                'teilnehmer_sprung'
                                                                                )
            elif geraet.geraet_db_name == "teilnehmer_balken":
                teilnehmer_alle = Teilnehmer.objects.filter(
                    teilnehmer_balken__gt=0,
                    teilnehmer_geburtsjahr__range=[riege.riege_ab,
                                                   riege.riege_bis]).values_list('id',
                                                                                'teilnehmer_name',
                                                                                'teilnehmer_vorname',
                                                                                'teilnehmer_verein__verein_name_kurz',
                                                                                'teilnehmer_geburtsjahr',
                                                                                'teilnehmer_sprung'
                                                                                )
            elif geraet.geraet_db_name == "teilnehmer_barren":
                teilnehmer_alle = Teilnehmer.objects.filter(
                    teilnehmer_barren__gt=0,
                    teilnehmer_geburtsjahr__range=[riege.riege_ab,
                                                   riege.riege_bis]).values_list('id',
                                                                                'teilnehmer_name',
                                                                                'teilnehmer_vorname',
                                                                                'teilnehmer_verein__verein_name_kurz',
                                                                                'teilnehmer_geburtsjahr',
                                                                                'teilnehmer_sprung'
                                                                                )
            elif geraet.geraet_db_name == "teilnehmer_boden":
                teilnehmer_alle = Teilnehmer.objects.filter(
                    teilnehmer_boden__gt=0,
                    teilnehmer_geburtsjahr__range=[riege.riege_ab,
                                                   riege.riege_bis]).values_list('id',
                                                                                'teilnehmer_name',
                                                                                'teilnehmer_vorname',
                                                                                'teilnehmer_verein__verein_name_kurz',
                                                                                'teilnehmer_geburtsjahr',
                                                                                'teilnehmer_sprung'
                                                                                )

            # Add a heading to the PDF
            content.append(Paragraph('Bezirksturnfest 2024', styles['CenterAlign20']))
            content.append(Spacer(1, 4))

            # Add a line to the PDF
            content.append(Paragraph(
                "____________________________________________________________________________________________________",
                normal_style))
            content.append(Spacer(1, 4))

            content.append(Paragraph(riege.riege + " " + geraet.geraet_name, styles['CenterAlign14']))
            content.append(Spacer(1, 12))

            headers = ['Start-Nr.', 'Nachname', 'Vorname', 'Verein', 'Jahrgang', 'Meldung', 'A-Note', 'B-Note',
                       'Summe']
            table_data = [headers] + [list(row) + [''] * (len(headers) - len(row)) for row in teilnehmer_alle]
            if table_data:
                t = Table(table_data)
                content.append(t)
                content.append(Spacer(1, 4))
            t.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, -1), colors.white),
                                   ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                                   ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                                   ('FONT', (0, 0), (-1, -1), 'DejaVuSans'),
                                   ('ALIGN', (0, 0), (0, -1), 'CENTER'),
                                   ('ALIGN', (5, 0), (5, -1), 'CENTER')
                                   ]))
            content.append(PageBreak())

    # Add more content as needed...
    # Build the PDF
    pdf.build(content)

    return response

def teilnehmer_upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            handle_uploaded_file(request.FILES['file'])
            return redirect('/turnfest/teilnehmer_list/')
    else:
        form = UploadFileForm()
    return render(request, 'turnfest/teilnehmer_upload.html', {'form': form})

def handle_uploaded_file(file):
    # Lese die Daten aus der Excel-Datei
    df = pd.read_excel(file)

    # Iteriere durch die Zeilen und speichere die Daten in der Datenbank
    for index, row in df.iterrows():
        Teilnehmer_neu = Teilnehmer(teilnehmer_name=row['Nachname'],
                                    teilnehmer_vorname=row['Vorname'],
                                    teilnehmer_gender=row['Geschlecht'],
                                    teilnehmer_geburtsjahr=row['Geburtsjahr'],
                                    teilnehmer_verein_id=row['Verein'],
                                    teilnehmer_anwesend="True",
                                    teilnehmer_sprung=row['Sprung'],
                                    teilnehmer_mini=row['Minitrampolin'],
                                    teilnehmer_reck_stufenbarren=row['Reck_Stufenbarren'],
                                    teilnehmer_balken=row['Schwebebalken'],
                                    teilnehmer_barren=row['Barren'],
                                    teilnehmer_boden=row['Boden'],
                                    )
        try:
            Teilnehmer_neu.save()
        except:
            pass

##########################################################################
# Area Ergebnisse erfassen
##########################################################################

def ergebnis_erfassen_suche(request):
    if request.method == "POST":
        startnummer = request.POST['startnummer']
        teilnehmer = Teilnehmer.objects.get(id=startnummer)
        if teilnehmer:
            try:
                ergebnis = BezirksturnfestErgebnisse.objects.get(ergebnis_teilnehmer=startnummer)
                # return redirect("/turnfest/ergebnis_edit/" + str(ergebnis.id) + '/')
                return redirect("/turnfest/edit/ergebnis/" + str(ergebnis.id) + '/')
            except:
                # return redirect("turnfest:ergebnis_create")
                return redirect("/turnfest/add/ergebnis" + "/?start=" + startnummer)

        else:
            form = ErgebnisTeilnehmerSuchen()
            return render(request, 'turnfest/ergebnis_erfassen_suche.html', {'form': form})

    else:
        form = ErgebnisTeilnehmerSuchen()

    return render(request, 'turnfest/ergebnis_erfassen_suche.html', {'form': form})

def ergebnis_erfassen(request):
    if request.method == "POST":
        pass

    else:
        form = ErgebnisTeilnehmerSuchen()

    return render(request, 'turnfest/ergebnis_erfassen_suche.html', {'form': form})

class ErgebnisCreateView(CreateView):
    model = BezirksturnfestErgebnisse
    template_name = "turnfest/ergebnis_erfassen.html"
    form_class = ErgebnisTeilnehmererfassenForm
    # fields = '__all__'
    success_url = reverse_lazy("turnfest:ergebnis_erfassen_suche")

class ErgebnisUpdateView(UpdateView):
    model = BezirksturnfestErgebnisse
    template_name = "turnfest/ergebnis_erfassen.html"
    form_class = ErgebnisTeilnehmererfassenForm
    success_url = reverse_lazy("turnfest:ergebnis_erfassen_suche")

def add_ergebnis(request):
    if request.method == "POST":
        form = ErgebnisTeilnehmererfassenForm(request.POST)
        # assert False
        if form.is_valid():
            item = form.save(commit=False)
            item.save()
            return redirect('/turnfest/ergebnis_erfassen_suche/')
    else:
        startnummer = request.GET.get('start')
        teilnehmer = Teilnehmer.objects.get(id=startnummer)

        form = ErgebnisTeilnehmererfassenForm()
        form.turnerin = teilnehmer.teilnehmer_name + " " + teilnehmer.teilnehmer_vorname
        form.teilnehmer_id = teilnehmer.id
    return render(request, 'turnfest/ergebnis_erfassen.html', {'form': form})

def edit_ergebnis(request, id=None):
    item = get_object_or_404(BezirksturnfestErgebnisse, id=id)
    form = ErgebnisTeilnehmererfassenForm(request.POST or None, instance=item)
    # assert False
    if form.is_valid():
        form.save()
        return redirect('/turnfest/ergebnis_erfassen_suche/')

    form.id = item.id
    form.turnerin = item.ergebnis_teilnehmer
    form.teilnehmer_id = item.ergebnis_teilnehmer.id
    return render(request, 'turnfest/ergebnis_erfassen.html', {'form': form})

##########################################################################
# Area Auswertung Bezirksturnfest erfassen
##########################################################################

def report_auswertung(request):
    meisterschaften = Meisterschaften.objects.order_by('-meisterschaft_gender')

    font_path = BASE_DIR / "ttf/dejavu-sans/ttf/DejaVuSans.ttf"
    pdfmetrics.registerFont(TTFont("DejaVuSans", font_path))

    font_path = BASE_DIR / "ttf/dejavu-sans/ttf/DejaVuSans-Bold.ttf"
    pdfmetrics.registerFont(TTFont("DejaVuSans-Bold", font_path))

    # Create a file-like buffer to receive PDF data.
    buffer = io.BytesIO()

    # Create the PDF object, using the buffer as its "file."
    p = canvas.Canvas(buffer, pagesize=A4)

    # Holen der Seitenabmessung
    breite, hoehe = A4

    for meisterschaft in meisterschaften:

        ergebnisse = BezirksturnfestErgebnisse.objects.filter(
            ergebnis_teilnehmer__teilnehmer_geburtsjahr__gte=str(meisterschaft.meisterschaft_ab),
            ergebnis_teilnehmer__teilnehmer_geburtsjahr__lte=str(meisterschaft.meisterschaft_bis),
            ergebnis_teilnehmer__teilnehmer_gender=meisterschaft.meisterschaft_gender
        ).order_by('ergebnis_teilnehmer__teilnehmer_geburtsjahr', '-ergebnis_summe')

        h = 1
        p.setFont('DejaVuSans-Bold', 18)
        p.drawCentredString(breite / 2, hoehe - (h * cm), "Ergebnisliste Bezirksturnfest 2024")
        h = h + 0.8
        p.setFont('DejaVuSans-Bold', 14)
        p.drawCentredString(breite / 2, hoehe - (h * cm), meisterschaft.meisterschaft + " " +
                            meisterschaft.meisterschaft_gender)
        h = h + 1

        p.setFont('DejaVuSans', 8)

        p.setFillGray(0.75)
        p.rect(0.2 * cm, hoehe - (h * cm), 20.6 * cm, 0.6 * cm, stroke=0, fill=1)

        p.setFillGray(0.0)
        p.drawString(0.5 * cm, hoehe - (h * cm) + 0.2 * cm, 'Rang')
        p.drawString(1.5 * cm, hoehe - (h * cm) + 0.2 * cm, 'Teilnehmer/in')
        p.drawString(5 * cm, hoehe - (h * cm) + 0.2 * cm, 'Verein')
        p.drawString(8 * cm, hoehe - (h * cm) + 0.2 * cm, 'Sprung')
        p.drawString(9.6 * cm, hoehe - (h * cm) + 0.2 * cm, 'Minitr.')
        p.drawString(11.2 * cm, hoehe - (h * cm) + 0.2 * cm, 'Reck/Stuf.')
        p.drawString(12.8 * cm, hoehe - (h * cm) + 0.2 * cm, 'Balken')
        p.drawString(14.4 * cm, hoehe - (h * cm) + 0.2 * cm, 'Barren')
        p.drawString(16.0 * cm, hoehe - (h * cm) + 0.2 * cm, 'Boden')
        p.drawString(17.6 * cm, hoehe - (h * cm) + 0.2 * cm, 'Gesamt')
        p.drawString(19.3 * cm, hoehe - (h * cm) + 0.2 * cm, 'Medaillie')

        # p.setFillColorRGB(0, 0, 0.77)

        # h = h + 1
        jahr_2 = ""
        rang = 1
        ergebnis_summe_vorheriger = 0
        for ergebnis in ergebnisse:
            jahr = datetime.strptime(str(ergebnis.ergebnis_teilnehmer.teilnehmer_geburtsjahr), "%Y-%m-%d").year
            if jahr != jahr_2:
                h = h + 1
                p.setFillColor(colors.aquamarine)
                p.rect(0.2 * cm, hoehe - (h * cm) + 0.4 * cm, 20.6 * cm, 0.6 * cm, stroke=0, fill=1)
                p.setFillColor(colors.black)
                p.drawString(0.5 * cm, hoehe - (h * cm) + 0.6 * cm, "Jahrgang: " + str(jahr))
                jahr_2 = jahr
                rang = 1
                ergebnis_summe_vorheriger = 0

            if ergebnis_summe_vorheriger == ergebnis.ergebnis_summe:
                rang = rang - 1
                p.drawString(0.5 * cm, hoehe - (h * cm), str(rang))
                rang = rang + 1
            else:
                p.drawString(0.5 * cm, hoehe - (h * cm), str(rang))

            p.drawString(1.5 * cm, hoehe - (h * cm), str(ergebnis.ergebnis_teilnehmer.teilnehmer_name) + " " +
                         str(ergebnis.ergebnis_teilnehmer.teilnehmer_vorname))
            p.drawString(5.0 * cm, hoehe - (h * cm),
                         str(ergebnis.ergebnis_teilnehmer.teilnehmer_verein.verein_name_kurz))
            p.drawString(8 * cm, hoehe - (h * cm), str(ergebnis.ergebnis_sprung_s))
            p.drawString(9.6 * cm, hoehe - (h * cm), str(ergebnis.ergebnis_mini_s))
            p.drawString(11.2 * cm, hoehe - (h * cm), str(ergebnis.ergebnis_reck_s))
            p.drawString(12.8 * cm, hoehe - (h * cm), str(ergebnis.ergebnis_balken_s))
            p.drawString(14.4 * cm, hoehe - (h * cm), str(ergebnis.ergebnis_barren_s))
            p.drawString(16.0 * cm, hoehe - (h * cm), str(ergebnis.ergebnis_boden_s))
            p.drawString(17.6 * cm, hoehe - (h * cm), str(ergebnis.ergebnis_summe))
            ergebnis_summe_vorheriger = ergebnis.ergebnis_summe

            if 16 <= ergebnis.ergebnis_summe < 48:
                medaille = 'Bronze'
            elif 48 <= ergebnis.ergebnis_summe < 64:
                medaille = 'Silber'
            elif ergebnis.ergebnis_summe >= 64:
                medaille = 'Gold'
            else:
                medaille = "-"

            p.drawString(19.3 * cm, hoehe - (h * cm), medaille)

            h = h + 0.5
            rang = rang + 1

        if ergebnisse:
            h = h + 1
            p.line(0.2 * cm, hoehe - (h * cm), 20.8 * cm, hoehe - (h * cm))

            h = h + 1
            p.setFillColorRGB(1, 0.6, 0.8)
            p.rect(0.2 * cm, hoehe - (h * cm), 20.6 * cm, 0.6 * cm, stroke=0, fill=1)

            p.setFillGray(0.0)
            p.drawString(0.5 * cm, hoehe - (h * cm) + 0.2 * cm,
                         meisterschaft.meisterschaft + " " + meisterschaft.meisterschaft_gender)

            meister_innen = BezirksturnfestErgebnisse.objects.filter(
                ergebnis_teilnehmer__teilnehmer_geburtsjahr__gte=str(meisterschaft.meisterschaft_ab),
                ergebnis_teilnehmer__teilnehmer_geburtsjahr__lte=str(meisterschaft.meisterschaft_bis),
                ergebnis_teilnehmer__teilnehmer_gender=meisterschaft.meisterschaft_gender).order_by("-ergebnis_summe")
            #            assert False
            h = h + 0.5

            i = 0  # zähler
            ergebnis_zwischen = 0  # zwischenspeicherung des vorherigen ergebnisses
            for meister_in in meister_innen:
                if i > 0:
                    if ergebnis_zwischen == meister_in.ergebnis_summe:
                        p.drawString(1.5 * cm, hoehe - (h * cm), str(meister_in.ergebnis_teilnehmer))
                        p.drawString(5.0 * cm, hoehe - (h * cm),
                                     str(meister_in.ergebnis_teilnehmer.teilnehmer_verein.verein_name_kurz))
                        p.drawString(9.5 * cm, hoehe - (h * cm), str(meister_in.ergebnis_summe) + " " + "Punkte")
                else:
                    p.drawString(1.5 * cm, hoehe - (h * cm), str(meister_in.ergebnis_teilnehmer))
                    p.drawString(5.0 * cm, hoehe - (h * cm),
                                 str(meister_in.ergebnis_teilnehmer.teilnehmer_verein.verein_name_kurz))
                    p.drawString(9.5 * cm, hoehe - (h * cm), str(meister_in.ergebnis_summe) + " " + "Punkte")

                ergebnis_zwischen = meister_in.ergebnis_summe
                i = i + 1
                h = h + 0.4

        current_dateTime = datetime.now().strftime("%d.%m.%Y %H:%M Uhr")
        p.drawString(0.5 * cm, hoehe - (29 * cm), str(current_dateTime))

        p.showPage()  # Erzwingt eine neue Seite

    # Close the PDF object cleanly, and we're done.
    p.save()

    # FileResponse sets the Content-Disposition header so that browsers
    # present the option to save the file.
    buffer.seek(0)
    return FileResponse(buffer, as_attachment=True, filename="Ergebnislisten.pdf")

def report_urkunden(request):
    meisterschaften = Meisterschaften.objects.order_by('-meisterschaft_gender')

    font_path = BASE_DIR / "ttf/dejavu-sans/ttf/DejaVuSans.ttf"
    pdfmetrics.registerFont(TTFont("DejaVuSans", font_path))

    font_path = BASE_DIR / "ttf/dejavu-sans/ttf/DejaVuSans-Bold.ttf"
    pdfmetrics.registerFont(TTFont("DejaVuSans-Bold", font_path))

    # Create a file-like buffer to receive PDF data.
    buffer = io.BytesIO()

    # Create the PDF object, using the buffer as its "file."
    p = canvas.Canvas(buffer, pagesize=A4)

    # Holen der Seitenabmessung
    breite, hoehe = A4

    for meisterschaft in meisterschaften:
        ergebnisse = BezirksturnfestErgebnisse.objects.filter(
            ergebnis_teilnehmer__teilnehmer_geburtsjahr__gte=str(meisterschaft.meisterschaft_ab),
            ergebnis_teilnehmer__teilnehmer_geburtsjahr__lte=str(meisterschaft.meisterschaft_bis),
            ergebnis_teilnehmer__teilnehmer_gender=meisterschaft.meisterschaft_gender
        ).order_by('ergebnis_teilnehmer__teilnehmer_geburtsjahr', '-ergebnis_summe')

        jahr_2 = ""
        rang = 1
        ergebnis_summe_vorheriger = 0
        for ergebnis in ergebnisse:
            h = 15
            jahr = datetime.strptime(str(ergebnis.ergebnis_teilnehmer.teilnehmer_geburtsjahr), "%Y-%m-%d").year
            if jahr != jahr_2:
                jahr_2 = jahr
                rang = 1
                ergebnis_summe_vorheriger = 0

            if 16 <= ergebnis.ergebnis_summe < 48:
                medaille = 'Bronze'
            elif 48 <= ergebnis.ergebnis_summe < 64:
                medaille = 'Silber'
            elif ergebnis.ergebnis_summe >= 64:
                medaille = 'Gold'
            else:
                medaille = "-"

            h = 18
            p.setFont('DejaVuSans-Bold', 18)
            p.drawCentredString(breite / 2, hoehe - (h * cm), "81. Bezirksturnfest")
            h = h + 1
            p.drawCentredString(breite / 2, hoehe - (h * cm), meisterschaft.meisterschaft)
            h = h + 1
            p.drawCentredString(breite / 2, hoehe - (h * cm), meisterschaft.meisterschaft_gender)
            h = h + 1
            p.drawCentredString(breite / 2, hoehe - (h * cm), medaille)
            h = h + 1
            p.drawCentredString(breite / 2, hoehe - (h * cm), "Jahrgang: " + str(jahr))
            h = h + 1

            if ergebnis_summe_vorheriger == ergebnis.ergebnis_summe:
                rang = rang - 1
                p.drawCentredString(breite / 2, hoehe - (h * cm), "Rang: " + str(rang))
                rang = rang + 1
            else:
                p.drawCentredString(breite / 2, hoehe - (h * cm), "Rang: " + str(rang))

            h = h + 1
            p.drawCentredString(breite / 2, hoehe - (h * cm), str(ergebnis.ergebnis_teilnehmer))

            ergebnis_summe_vorheriger = ergebnis.ergebnis_summe
            rang = rang + 1
            p.showPage()

    # Close the PDF object cleanly, and we're done.
    p.save()

    buffer.seek(0)
    return FileResponse(buffer, as_attachment=False, filename="Urkunden_Bezirksturnfest.pdf")

def vereine_upload(request):
    if request.method == 'POST':
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            vereine_handle_uploaded_file(request.FILES['file'])
            return redirect('/turnfest/vereine_list/')
    else:
        form = UploadFileForm()
    return render(request, 'turnfest/vereine_upload.html', {'form': form})

def vereine_handle_uploaded_file(file):
    # Lese die Daten aus der Excel-Datei
    df = pd.read_excel(file, na_filter=False)

    # Iteriere durch die Zeilen und speichere die Daten in der Datenbank
    for index, row in df.iterrows():
        vereine_neu = Vereine(verein_name=row['verein_name'],
                              verein_name_kurz=row['verein_name_kurz'],
                              verein_strasse=row['verein_strasse'],
                              verein_plz=row['verein_plz'],
                              verein_ort=row['verein_ort'],
                              verein_telefon=row['verein_telefon'],
                              verein_email=row['verein_email']
                              )
        try:
            vereine_neu.save()
        except:
            pass

##########################################################################
# Area Löschen Bezirksturnfest
##########################################################################

def delete_tables_bezirksturnfest(request):
    if request.method == 'POST':
        count_ergebnisse = BezirksturnfestErgebnisse.objects.all().delete()
        count_teilnehmer = Teilnehmer.objects.all().delete()
        #count_vereine = Vereine.objects.all().delete()
        #UPDATE sqlite_sequence SET seq = (SELECT MAX(col) FROM Tbl) WHERE name="Tbl"
        #print(count_teilnehmer)
        return redirect('/turnfest/teilnehmer_list/')
    else:
        pass

    form = TablesDeleteForm()
    return render(request, 'turnfest/tables_delete.html', {'form': form})


import random

logo = '''
 _____                 _                    _
|   __|___ ___ ___ ___| |_    ___ _ _ _____| |_ ___ ___
|__   | -_|  _|  _| -_|  _|  |   | | |     | . | -_|  _|
|_____|___|___|_| |___|_|    |_|_|___|_|_|_|___|___|_|
'''

def secret_number():
    print(logo)

    number = random.randint(1, 100)
    print('I chose a number between 1 and 100. Guess it.')

    print('Select a difficulty:')
    print('\teasy\t(10 tries)')
    print('\tnormal\t(7 tries)')
    print('\thard\t(5 tries)')
    difficulty = input('Difficulty? ')
    if difficulty == 'easy':
        tries = 10
    elif difficulty == 'normal':
        tries = 7
    else:
        tries = 5

    gameover = False
    while not gameover:
        print(f'You have {tries} tries left.')
        guess = int(input('Your guess? '))
        if guess == number:
            print('You found the right number. You won.')
            gameover = True
        else:
            if guess > number:
                print('Too high.')
            else:
                print('Too low.')
            tries -= 1
            if tries == 0:
                print('You have no more tries left. You lost.')
                gameover = True

def main():
    keep_playing = True
    while keep_playing:
        secret_number()
        keep_playing_answer = input('Do you want to play again? \'y\' or \'n\': ')
        if keep_playing_answer != 'y':
            keep_playing = False

main()