# 90/100
# see 10-winning_ticket-03.py

tickets = input().split(", ")

for i in range(len(tickets)):
    tickets[i] = tickets[i].replace(" ", "")

winning_symbols = ["$", "@", "#", "^"]

for ticket in tickets:

    max_counter_left = 0
    max_counter_right = 0
    winning_symbol = []

    if len(ticket) == 20:
        first_half = ticket[0:10:1]
        second_half = ticket[10:21:1]
        current_counter_left = 0
        current_counter_right = 0

        for i in range(len(first_half)):
            if first_half[i] in winning_symbols:
                current_counter_left += 1
                winning_symbol.append(first_half[i])
            if i < len(first_half) - 1:
                if first_half[i + 1] not in winning_symbols:
                    if current_counter_left > max_counter_left:
                        max_counter_left = current_counter_left
                        current_counter_left = 0
            else:
                if first_half[i - 1] in winning_symbols:
                    if current_counter_left > max_counter_left:
                        max_counter_left = current_counter_left

        for i in range(len(second_half)):
            if second_half[i] in winning_symbols:
                current_counter_right += 1
            if i < len(second_half) - 1:
                if second_half[i + 1] not in winning_symbols:
                    if current_counter_right > max_counter_right:
                        max_counter_right = current_counter_right
                        current_counter_right = 0
            else:
                if second_half[i - 1] in winning_symbols:
                    if current_counter_right > max_counter_right:
                        max_counter_right = current_counter_right

        winning_symbol = (max(set(winning_symbols), key=winning_symbol.count))

        if max_counter_right >= 6 and max_counter_left >= 6:
            if max_counter_left == 10 and max_counter_right == 10:
                print(f'ticket "{ticket}" - {max_counter_left}{winning_symbol} Jackpot!')
            elif max_counter_left < max_counter_right or max_counter_left == max_counter_right:
                print(f'ticket "{ticket}" - {max_counter_left}{winning_symbol}')
            elif max_counter_left > max_counter_right:
                print(f'ticket "{ticket}" - {max_counter_right}{winning_symbol}')
        else:
            print(f'ticket "{ticket}" - no match')
    else:
        print("invalid ticket")

Fundamentals with Python/T17 - Text Processing/exercise/10. Winning Ticket.py


import numpy as np
import pandas as pd
import torch
import ast

def MovingAvg(v, size):
    avg = np.empty_like(v)
    avg[:size] = np.mean(v[:2*size])
    avg[len(v)-2*size+1:len(v)] = np.mean(v[len(v)-2*size+1:len(v)])
    for i in range(size, len(v) - size):
        avg[i] = np.mean(v[i-size:i+size])
    return avg

def ConvertTensors(df, labels):
    for label in labels:
        for i in range(len(df.index)):
            val = eval(df.loc[i, label]).cpu()
            if len(val) > 1:
                df.loc[i,label] = val.tolist()
            else:
                df.loc[i,label] = val.item()

def StrListColumnToArray(df: pd.DataFrame, src_column: str):
    return np.array(df.loc[:, src_column].apply(ast.literal_eval).to_list())

def ArrayToColumns(df: pd.DataFrame, arr: np.ndarray, new_columns: list):
    assert arr.shape[1] == len(new_columns)
    return pd.concat((df, pd.DataFrame(arr, columns=new_columns)), axis=1)

def ExpandStrArrayColumns(data: pd.DataFrame, groupby: str, ignored_columns: list=[]):
    if not groupby in ignored_columns:
        ignored_columns.append(groupby)
    expanded_subsets = []
    for subset in iter(data.groupby("epoch")):
        res = dict()
        for j, col in enumerate(subset[1].columns):
            cat = []
            for i in range(len(subset[1].index)):
                if col in ignored_columns:
                    cat = subset[1].iloc[i, j]
                else:
                    cat.extend(ast.literal_eval(subset[1].iloc[i, j]))
            res[col] = cat
        expanded_subsets.append(pd.DataFrame(res))
    return pd.concat(expanded_subsets, axis=0, ignore_index=True)


import os

import keywords
import objectDetection
import speechRecognition
import tagUtils
import videoUtils

def getOnlineTags(imgfilename, frame_keywords):
    link_obj = tagUtils.getLinks(imgfilename)
    if link_obj is not None:
        all_links = [str(i.get("href")) for i in link_obj]
        youtube_links = tagUtils.getYouTubeLinks(all_links)
        if youtube_links:
            youtube_tags = tagUtils.getYouTubeTags(youtube_links)
            return youtube_tags

    image_tags = tagUtils.getGoogleRelevantTerms(frame_keywords)
    return image_tags

def getTagsfromAudio(videofilename):
    audio = speechRecognition.video_to_text(videofilename)
    if audio is not None:
        transcript, translated = audio
        watson_features = keywords.getKeywordsWatson(translated)
        if watson_features is None:
            audio_keywords = keywords.getKeywordsRAKE(translated)
            audio_NER = keywords.getKeywordsNER(translated)
        else:
            audio_keywords = watson_features["keywords"]
            audio_NER = watson_features["entities"]
        return audio_keywords, audio_NER
    else:
        return [], []

def getFrameTags(videopath):
    path_to_images = objectDetection.getFramesFromVideo(videopath)
    frame_tags = []
    l = len(path_to_images)
    for count, p in enumerate(path_to_images):
        print("{}/{}".format(count + 1, l))
        frame_objects, frame_description = objectDetection.getFrameDetails(p)
        frame_keywords = keywords.getKeywordsRAKE(frame_description)
        #online_tags = getOnlineTags(p, frame_keywords)
        #frame_tags.extend(online_tags)
        frame_tags.extend(frame_keywords)
        frame_tags.extend(frame_objects)
    return frame_tags

def getTags(videofilename):
    videofilename = os.path.join(
        os.path.dirname(os.getcwd()), "Database", "Video", videofilename
    )
    audio_keywords, audio_NER = getTagsfromAudio(videofilename)
    frame_tags = getFrameTags(videofilename)
    return audio_keywords, audio_NER, frame_tags

def getFilteredTags(videofilename):
    audio_keywords, audio_NER, frame_tags = getTags(videofilename)
    frame_tags = videoUtils.getTopKCounter(frame_tags, 10)
    all_tags = list(set(audio_keywords + audio_NER + frame_tags))
    return [tag for tag in all_tags if len(tag.split()) <= 2]


import numpy as np
import cv2
from matplotlib import pyplot as plt

# Load the input image.
img = cv2.imread('../data/cars.jpg') # ImageSegmentation/DataInput/coins.jpg

# Convert image to grayscale
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# Display input image
plt.imshow(gray, 'gray')
plt.title('Input')
plt.show()

# Threshold using the opencv module, using otsus thresholding.
ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

# Save the output image
cv2.imwrite("../result/cars_thresh.jpg", thresh)

plt.imshow(thresh, 'gray')
plt.title('Output')
plt.show()


import cv2
import numpy as np
import HandTrackingModule as htm
import time
import autopy
import os
import pyautogui

#############################
wCam, hCam = 640, 480
frameR = 100 # frame Reduction
smoothening = 7
##############################

pTime = 0
plocX, plocY = 0, 0
clocX, clocY = 0, 0

# Volume variables
previous_length = 0
previous_vol = 0
volume_muted = False

cap = cv2.VideoCapture(0)
cap.set(3,wCam)
cap.set(4,hCam)

detector = htm.handDetector(maxHands=1)
wScr, hScr = autopy.screen.size()
#print(wScr, hScr)
while True:
    #1. Find hand landmarks
    success, img = cap.read()
    img = detector.findHands(img)
    lmList, bbox = detector.findPosition(img)

    #2. Get the tip of the index and the middle fingers
    if len(lmList)!=0:
        x1, y1 = lmList[8][1:]
        x2, y2 = lmList[12][1:]
        #print(x1, y1, x2, y2)

    #3. Check which finger are up
        fingers = detector.fingersUp()
        #print(fingers)
        cv2.rectangle(img, (frameR, frameR), (wCam-frameR, hCam-frameR), (255,0,255), 2)

    #4. Only index finger: Moving mode
        if fingers[1]==1 and fingers[2]==0:

            #5. Convert Coordinates
            x3 = np.interp(x1, (frameR,wCam-frameR), (0,wScr))
            y3 = np.interp(y1, (frameR,hCam-frameR), (0,hScr))

            #6. Smoothen Valuse
            clocX = plocX + (x3 - plocX) / smoothening
            clocY = plocY + (y3 - plocY) / smoothening

            #7. Move mouse
            autopy.mouse.move(wScr-clocX, clocY)
            cv2.circle(img, (x1, y1), 15, (255, 0, 255), cv2.FILLED)
            plocX, plocY = clocX, clocY

    #Volume control

        if fingers[1] == 1 and fingers[2] == 1:
    # 15. Find distance between fingers
            length, img, lineInfo = detector.findDistance(4, 8, img)

    # 6. Volume Range 0 - 100
            vol = np.interp(length, [20, 200], [0, 100])

    # 7. Set volume
            if vol < previous_vol:
                for i in range(int(previous_vol - vol)):
                    pyautogui.press('volumedown')
                previous_vol = int(vol)
            elif vol > previous_vol:
                for i in range(int(vol - previous_vol)):
                    pyautogui.press('volumeup')
                previous_vol = int(vol)

            # if int(vol) != previous_vol:
            #     pyautogui.press(['volumedown', 'volumeup'][int(vol) > previous_vol])
            #     previous_vol = int(vol)

    #11. Frame rate
    cTime = time.time()
    fps = 1/(cTime-pTime)
    pTime = cTime
    cv2.putText(img, str(int(fps)), (20, 50), cv2.FONT_HERSHEY_PLAIN, 3, (255,0,0),3)

    #12. Display

    cv2.imshow("AI Virtual Mouse", img)
    if cv2.waitKey(1)  == 27:
        break
cap.release()
cv2.destroyAllWindows()


from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.decorators import permission_classes
from rest_framework.permissions import IsAuthenticated, AllowAny
from django.views.decorators.csrf import csrf_exempt
# from rest_framework import status
# from rest_framework.views import APIView
# from rest_framework.response import Response

from .models import Post
from tags.models import Tag
from categories.models import Category
from .serializers import PostSerializer, TagSerializer
from .utils import add_tags
from .activities import submit_post

class PostList(ListAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

    def get_queryset(self):
        qs = super(PostList, self).get_queryset()

        # Filter by tag
        tag = self.kwargs.get('tag')
        if tag:
            tag = Tag.objects.get(slug=tag)
            return qs.filter(tags=tag)

        # Filter by category
        category = self.kwargs.get('category')
        if category:
            category = Category.objects.get(slug=category)
            return qs.filter(category=category)

        return qs

@permission_classes((IsAuthenticated, ))
class PostCreate(CreateAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

    def perform_create(self, serializer):
        post = serializer.save()

        # Set category
        try:
            category = str(self.request.data['category'])
        except:
            category = ""
        if category:
            category = Category.objects.get(slug=category)
            post.category = category

        # Add tags
        try:
            tag_string = self.request.data['tags']
        except:
            tag_string = ""
        if tag_string:
            post = add_tags(post, tag_string)

        post.save()

        # Ignore this.
        # Experimenting with submitting posts using ActivityPub.
        try:
            submit_post(post)
        except:
            pass

# @permission_classes((IsAuthenticated, ))
# @permission_classes((AllowAny, ))
class PostRetrieveUpdateDestroy(RetrieveUpdateDestroyAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    lookup_field = 'slug'

    def perform_update(self, serializer):
        post = serializer.save()

        # Set category
        try:
            category = str(self.request.data['category'])
        except:
            category = ""
        if category:
            category = Category.objects.get(slug=category)
            post.category = category

        # Replace tags
        try:
            tags = str(self.request.data['tags'])
        except:
            tags = ""
        if tags:
            post = add_tags(post, tags)

        post.save()

class TagListCreate(ListCreateAPIView):
    queryset = Tag.objects.all()
    serializer_class = TagSerializer

class TagRetrieveUpdateDestroy(RetrieveUpdateDestroyAPIView):
    queryset = Tag.objects.all()
    serializer_class = TagSerializer
    lookup_field = 'slug'


#!/usr/bin/env python
"""
This is a utility that wraps a CLI application for consumption by
a foxpro program. Designed to fox-wrap any application, not just python

Features:
   -- Catches exceptions and if one happens does not terminate until user presses "enter"
   -- Writes output to log and to screen
"""
try:
    import sys
    import os
    os.environ.pop('TZ', None)  # call this first before some library somewhere used datetime with bad windoz timezone
    import datetime
    import subprocess
    import traceback
except Exception as e:
    traceback.print_exc()
    print("\nTHERE WAS AN ERROR LOADING FOXWRAP:")
    print(e)
    input("Press Enter to exit...")
    raise

def main():
    try:
        foxwrap_args = sys.argv[1:]
        progname = os.path.splitext(os.path.basename(foxwrap_args[0]))[0]
        progparams = [os.path.basename(p) for p in foxwrap_args[1:]]
        logfile_name = "{}_{}_{}.LOG".format(progname, '_'.join(progparams), datetime.datetime.now().strftime('%Y%m%d_%H%M%S'))

        proc = subprocess.Popen(foxwrap_args, stderr=subprocess.PIPE)
        with open(logfile_name, "w") as log_file:

            while proc.poll() is None:
                line = proc.stderr.readline().decode()
                #print('.', end='')
                if line:
                    print(line)
                    log_file.write(line)

        if proc.returncode != 0:
            raise Exception("USER PROCESS FAILED")

    except Exception as e:
        traceback.print_exc()
        print("\nTHERE WAS AN ERROR PROCESSING YOUR REQUEST:", e)
        input("Press Enter to exit...")

    except:   # pylint: disable=broad-except
        traceback.print_exc()
        print("\nTHERE WAS AN ERROR PROCESSING YOUR REQUEST")
        input("Press Enter to exit...")

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
from django.contrib.admin.checks import ModelAdminChecks
from django.core import checks
from django.core.checks import register
from django.template import TemplateDoesNotExist
from django.template.loader import get_template

def treebeard_in_installed_apps(cls):
    from django.conf import settings
    errors = []
    if 'treebeard' not in settings.INSTALLED_APPS:
        errors.append(checks.Warning(
            "`treebeard` should be in your INSTALLED_APPS so that "
            "it's templates may be discovered", hint=None, obj=cls.__name__,
            id='menuhin.W1'))
    return errors

def treebeard_template_found(cls):
    errors = []
    try:
        get_template("admin/tree_change_list.html")
    except TemplateDoesNotExist:
        errors.append(checks.Error(
            "template `admin/tree_change_list.html` was not found by any of "
            "your TEMPLATE_LOADERS",
            hint="put `treebeard` into INSTALLED_APPS",
            obj=cls.__name__, id='menuhin.E1',
        ))
    return errors

def treebeard_has_request_context_processor(cls):
    from django.conf import settings
    errors = []
    if 'django.core.context_processors.request' not in settings.TEMPLATE_CONTEXT_PROCESSORS:  # noqa
        errors.append(checks.Error(
            "treebeard requires the request be in the template context",
            hint="put `django.core.context_processors.request` "
                 "into TEMPLATE_CONTEXT_PROCESSORS",
            obj=cls.__name__, id='menuhin.E2',
        ))
    return errors

@register('menuhin', 'settings')
def settings_defined(app_configs):
    from django.conf import settings
    errors = []
    try:
        handlers = settings.MENUHIN_MENU_HANDLERS
    except AttributeError:
        errors.append(checks.Error(
            "You won't be able to use the `menuhin` app without setting "
            "`MENUHIN_MENU_HANDLERS`",
            hint="use dotted paths to MenuItemGroup subclasses",
            obj=__name__, id='menuhin.E2',
        ))
    else:
        if len(handlers) == 0:
            errors.append(checks.Warning(
                "You haven't defined any handlers for `menuhin`",
                hint="make the MENUHIN_MENU_HANDLERS setting a tuple of dotted "
                     "paths to MenuItemGroup subclasses.",
                obj=__name__, id='menuhin.W2',
            ))
    return errors

class MenuhinAdminChecks(ModelAdminChecks):
    def check(self, cls, model, **kwargs):
        checks = super(MenuhinAdminChecks, self).check(cls, model, **kwargs)
        checks.extend(treebeard_in_installed_apps(cls=cls))
        checks.extend(treebeard_template_found(cls=cls))
        checks.extend(treebeard_has_request_context_processor(cls=cls))
        return checks


import re
from typing import Any, Callable, Dict, List, Set, Tuple, Type, Union

import vbml

from vkbottle.dispatch.handlers import FromFuncHandler
from vkbottle.dispatch.rules import ABCRule
from vkbottle.dispatch.rules.bot import (
    AttachmentTypeRule,
    ChatActionRule,
    CommandRule,
    CoroutineRule,
    FromPeerRule,
    FromUserRule,
    FuncRule,
    LevensteinRule,
    MessageLengthRule,
    PayloadContainsRule,
    PayloadMapRule,
    PayloadRule,
    PeerRule,
    RegexRule,
    StateGroupRule,
    StateRule,
    StickerRule,
    MacroRule,
    VBMLRule,
)
from vkbottle.dispatch.views import ABCView, HandlerBasement, MessageView, RawEventView
from vkbottle.tools.dev_tools.utils import convert_shorten_filter

from .abc import ABCBotLabeler, LabeledHandler, LabeledMessageHandler

ShortenRule = Union[ABCRule, Tuple[ABCRule, ...], Set[ABCRule]]
DEFAULT_CUSTOM_RULES: Dict[str, Type[ABCRule]] = {
    "from_chat": PeerRule,
    "command": CommandRule,
    "from_user": FromUserRule,
    "peer_ids": FromPeerRule,
    "sticker": StickerRule,
    "attachment": AttachmentTypeRule,
    "levenstein": LevensteinRule,
    "lev": LevensteinRule,
    "length": MessageLengthRule,
    "action": ChatActionRule,
    "payload": PayloadRule,
    "payload_contains": PayloadContainsRule,
    "payload_map": PayloadMapRule,
    "func": FuncRule,
    "coro": CoroutineRule,
    "coroutine": CoroutineRule,
    "state": StateRule,
    "state_group": StateGroupRule,
    "regexp": RegexRule,
    "macro": MacroRule,
    "text": VBMLRule,
}

class BotLabeler(ABCBotLabeler):
    """ BotLabeler - shortcut manager for router
    Can be loaded to other BotLabeler
    >>> bl = BotLabeler()
    >>> ...
    >>> bl.load(BotLabeler())
    Views are fixed. Custom rules can be set locally (they are
    not inherited to other labelers). Rule config is accessible from
    all custom rules from ABCRule.config
    """

    def __init__(self, **kwargs):
        # Default views are fixed in BotLabeler,
        # if you need to create your own implement
        # custom labeler
        self.message_view = MessageView()
        self.raw_event_view = RawEventView()

        self.custom_rules = kwargs.get("custom_rules") or DEFAULT_CUSTOM_RULES
        self.auto_rules: List["ABCRule"] = []

        # Rule config is accessible from every single custom rule
        self.rule_config: Dict[str, Any] = {
            "vbml_flags": re.MULTILINE,  # Flags for VBMLRule
            "vbml_patcher": vbml.Patcher(),  # Patcher for VBMLRule
        }

    @property
    def vbml_ignore_case(self) -> bool:
        """ Gets ignore case flag from rule config flags """
        return re.IGNORECASE in self.rule_config["flags"]

    @vbml_ignore_case.setter
    def vbml_ignore_case(self, ignore_case: bool):
        """ Adds ignore case flag to rule config flags or removes it
        """
        if not ignore_case:
            self.rule_config["vbml_flags"] ^= re.IGNORECASE
        else:
            self.rule_config["vbml_flags"] |= re.IGNORECASE

    @property
    def vbml_patcher(self) -> vbml.Patcher:
        return self.rule_config["vbml_patcher"]

    @vbml_patcher.setter
    def vbml_patcher(self, patcher: vbml.Patcher):
        self.rule_config["vbml_patcher"] = patcher

    @property
    def vbml_flags(self) -> re.RegexFlag:
        return self.rule_config["vbml_flags"]

    @vbml_flags.setter
    def vbml_flags(self, flags: re.RegexFlag):
        self.rule_config["vbml_flags"] = flags

    def message(
        self, *rules: ShortenRule, blocking: bool = True, **custom_rules
    ) -> LabeledMessageHandler:
        def decorator(func):
            self.message_view.handlers.append(
                FromFuncHandler(
                    func,
                    *map(convert_shorten_filter, rules),
                    *self.auto_rules,
                    *self.get_custom_rules(custom_rules),
                    blocking=blocking,
                )
            )
            return func

        return decorator

    def chat_message(
        self, *rules: ShortenRule, blocking: bool = True, **custom_rules
    ) -> LabeledMessageHandler:
        def decorator(func):
            self.message_view.handlers.append(
                FromFuncHandler(
                    func,
                    PeerRule(True),
                    *map(convert_shorten_filter, rules),
                    *self.auto_rules,
                    *self.get_custom_rules(custom_rules),
                    blocking=blocking,
                )
            )
            return func

        return decorator

    def private_message(
        self, *rules: ShortenRule, blocking: bool = True, **custom_rules
    ) -> LabeledMessageHandler:
        def decorator(func):
            self.message_view.handlers.append(
                FromFuncHandler(
                    func,
                    PeerRule(False),
                    *map(convert_shorten_filter, rules),
                    *self.auto_rules,
                    *self.get_custom_rules(custom_rules),
                    blocking=blocking,
                )
            )
            return func

        return decorator

    def raw_event(
        self,
        event: Union[str, List[str]],
        dataclass: Callable = dict,
        *rules: ShortenRule,
        **custom_rules,
    ) -> LabeledHandler:

        if not isinstance(event, list):
            event = [event]

        def decorator(func):
            for e in event:
                self.raw_event_view.handlers[e] = HandlerBasement(
                    dataclass,
                    FromFuncHandler(
                        func,
                        *map(convert_shorten_filter, rules),
                        *self.auto_rules,
                        *self.get_custom_rules(custom_rules),
                    ),
                )
            return func

        return decorator

    def load(self, labeler: "BotLabeler"):
        self.message_view.handlers.extend(labeler.message_view.handlers)
        self.message_view.middlewares.extend(labeler.message_view.middlewares)
        self.raw_event_view.handlers.update(labeler.raw_event_view.handlers)
        self.raw_event_view.middlewares.extend(labeler.raw_event_view.middlewares)

    def get_custom_rules(self, custom_rules: Dict[str, Any]) -> List["ABCRule"]:
        return [self.custom_rules[k].with_config(self.rule_config)(v) for k, v in custom_rules.items()]  # type: ignore

    def views(self) -> Dict[str, "ABCView"]:
        return {"message": self.message_view, "raw": self.raw_event_view}


import numpy as np
import os
import glob

zonelist = np.loadtxt('zones_todo4-30.txt')
zones = np.array(zonelist)
z_chunks = np.array_split(zones, 40)
for i, z in enumerate(z_chunks):
    f = open('z' + str(i).zfill(2) + '.txt', 'w')
    for line in z:
        f.write('%d \n'%line)
    f.close()

for i, z in enumerate(z_chunks):
    zstr = 'z' + str(i).zfill(2) + '.txt'
    cmd = 'qsub -l h_vmem=10G -l des -cwd -b y -N Det%s python detection_efficiency_folio.py '%str(i) + '/data3/garyb/tno/matcher ' + zstr
    os.system(cmd)


"""If metadata doesn't have version information, adds it
"""
from __future__ import print_function

import glob
import os
import yaml

from medleydb import METADATA_PATH

def add_version(fpath):
    with open(fpath, 'r') as fhandle:
        data = yaml.load(fhandle)

    if 'version' not in data.keys():
        data['version'] = 1.2
        with open(fpath, 'w') as fhandle:
            yaml.dump(data, fhandle, indent=2, default_flow_style=False)

def remove_release_date(fpath):
    with open(fpath, 'r') as fhandle:
        data = yaml.load(fhandle)

    if 'release date' in data.keys():
        data.pop('release date', None)
        with open(fpath, 'w') as fhandle:
            yaml.dump(data, fhandle, indent=2, default_flow_style=False)

def main():
    """Loops over all metadata files and adds version information
    """
    metadata_files = glob.glob(os.path.join(METADATA_PATH, '*.yaml'))
    for fpath in metadata_files:
        add_version(fpath)
        remove_release_date(fpath)

if __name__ == "__main__":
    main()


#!/usr/bin/python3

import csv
import collections

dic = collections.defaultdict(lambda: 0)

with open("train.csv", "r") as in_f:

    csv_reader = csv.reader(in_f)

    for row in csv_reader:

        text_id, emotion, text = row

        dic[emotion] += 1

print(dic)


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

from setuptools import setup

lint_deps = ["black==20.8b1", "mypy==0.790"]

extra_require = {
    "lint": lint_deps,
}

setup(
    name="echidna-parade",
    version="0.1",
    description="Meta-tool to test a contract with various configs, using Echidna processes",
    long_description_content_type="text/markdown",
    long_description=open("README.md").read(),
    packages=[
        "echidna_parade",
    ],
    license="AGPL3",
    entry_points="""
    [console_scripts]
    echidna-parade = echidna_parade.__main__:main
    """,
    keywords="echidna smart-contracts testing fuzzing swarm test-diversity",
    test_suite="nose.collector",
    tests_require=["nose"],
    classifiers=[
        "Intended Audience :: Developers",
        "Development Status :: 4 - Beta",
        "Programming Language :: Python :: 3",
    ],
    install_requires=["pyyaml", "slither-analyzer", "crytic-compile"],
    extras_require=extra_require,
    url="https://github.com/crytic/echidna-parade",
)


def solution(maps):
    answer = []
    m = len(maps[0])
    visited = [[0] * m for _ in range(len(maps))]
    dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]

    for i in range(len(maps)):
        for j in range(m):
            if maps[i][j] != "X" and visited[i][j] == 0:
                period = 0
                q = [(i, j)]

                while q:
                    x, y = q.pop()
                    if visited[x][y]:
                        continue
                    visited[x][y] = 1
                    period += int(maps[x][y])

                    for k in range(4):
                        nx, ny = x + dx[k], y + dy[k]
                        if -1 < nx < len(maps) and -1 < ny < m and maps[nx][ny] != 'X' and not visited[nx][ny]:
                            q.append((nx, ny))

                answer.append(period)

    return sorted(answer) if answer else [-1]

solution(["X591X", "X1X5X", "X231X", "1XXX1"])


n = int(input())
k = list(map(int,input().split()))
c = -1
score = 0
for i in range(n):
    if(k[i]==1):
        c+=1
        score = score + c + k[i]

    else:
        c = -1
print(score)


from datasets.adult_full import AdultFullDataset
import torch
import random
import torch.nn as nn
import torch.optim as optim
import numpy as np
from torch.distributions.multivariate_normal import MultivariateNormal
import argparse
from mlp import MLP2

################################
# Parse and set args

parser = argparse.ArgumentParser(description='Fairness')
parser.add_argument('--mode', type=str, default='train')
parser.add_argument('--dataset', type=str, default='adult_full')
parser.add_argument('--sigma_scale', type=float, default=0.5)
parser.add_argument('--seed', type=int, default=1)
parser.add_argument('--filename', type=str, default='../weights/adult.csv')
args = parser.parse_args()

# Seed and device
seed = args.seed
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device)

# params
model_name = f'adult'
batch_sz = 256
nb_epochs = 50
lr = 0.01
nb_classes = 2

# Load the dataset
train_dataset = AdultFullDataset('train', None)
val_dataset = AdultFullDataset('validation', None)
test_dataset = AdultFullDataset('test', None)

train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_sz, shuffle=True)
val_loader = torch.utils.data.DataLoader(dataset=val_dataset, batch_size=batch_sz, shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_sz, shuffle=False)

# Uncomment to save data for Phoenix
"""
with open('../data/adult_test_15060.csv', 'w') as f:
    for i in range(test_dataset.features.shape[0]):
        l = test_dataset.features[i].ravel().cpu().numpy().tolist()
        s = ','.join([f'{x:.10f}' for x in l])
        f.write(f'input{i},{s}\n')
        f.write(f'target{i},{int(test_dataset.labels[i].cpu().item())}\n')
    print('test data written!')
"""

input_sz = train_dataset.features.shape[1]
cont_sz = 6

# Defining the similarity for fairness
# Cont features: age, fnlwgt, education_num, capital_gain, capital_loss, hrs_per_week
# "Assuming other features are fixed, how much should 2 SIMILAR people differ in age at most" -> (2)
sim_thresh = torch.FloatTensor([4, 10000, 1, 500, 50, 8]).to(device)
sim_thresh /= train_dataset.std # normalize

sigma = torch.diag(sim_thresh).to(device)
S = torch.diag(1.0 / torch.diag(sigma))
sqrtinvL = 1

print(f'Original sigma={sigma}\n S={S}\n sqrtinvL={sqrtinvL}')

# Normalize s.t. total variation is input_sz * scale
total_var = sim_thresh.sum().cpu().item()
scaling_factor = (cont_sz / total_var) * args.sigma_scale
sigma *= scaling_factor
S = torch.diag(1.0 / torch.diag(sigma))
sqrtinvL = (1.0 / scaling_factor)
eigs, _ = torch.linalg.eigh(sigma)

print(f'Final sigma={sigma}\n S={S}\n sqrtinvL={sqrtinvL}')
print(f'Total variation of sigma: {eigs.sum().item()} (should be 6*sigma scale)')
print(f'(L={(1 / (sqrtinvL * sqrtinvL)):.3f})')

# Make a noise generator
noise_gen = MultivariateNormal(torch.zeros(sigma.shape[0]).to(device), sigma)

# Training
outs = 1
model = MLP2(input_sz, 32, outs).to(device)

# Training params
criterion = nn.BCEWithLogitsLoss()
opt = optim.Adam(model.parameters(), lr=lr, weight_decay=1e-4)
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
    opt, 'min', patience=5, factor=0.5
)

# Helper to get accuracy
def accuracy(loader):
    correct, total = 0, 0
    for inputs, targets, protected in loader:
        inputs, targets = inputs.to(device), targets.to(device)
        outs = model(inputs.view(-1, input_sz)).squeeze()
        preds = (outs > 0).int()
        total += targets.shape[0]
        correct += (preds == targets).sum()
    acc = 100 * correct.item() / total
    return acc

# Training loop
for epoch in range(nb_epochs):
    sum_loss = 0
    nb_examples = 0
    for i, (inputs, targets, protected) in enumerate(train_loader):
        inputs, targets = inputs.to(device), targets.to(device)
        # If not clean add noise to the input before passing
        noise = torch.stack([noise_gen.sample() for _ in range(inputs.shape[0])], dim=0)
        if input_sz > cont_sz:
            zeros = torch.zeros((noise.shape[0], input_sz-cont_sz)).to(device)
            noise = torch.cat([noise, zeros], dim=1)
        assert noise.shape == inputs.shape ###
        inputs += noise.to(device)

        opt.zero_grad()
        outs = model(inputs.view(-1, input_sz)).squeeze()
        loss = criterion(outs, targets)
        loss.backward()
        opt.step()

        sum_loss += loss
        nb_examples += inputs.shape[0]

    # Test in each epoch
    train_acc = accuracy(train_loader)
    val_acc = accuracy(val_loader)
    test_acc = accuracy(test_loader)
    if (epoch+1)%1 == 0:
        print(f'[Epoch {epoch+1}] | loss: {(sum_loss/nb_examples):.5f} | train: {train_acc:.3f} | val: {val_acc:.3f} | test: {test_acc:.3f}')
    scheduler.step(val_acc)

# Save
#torch.save(model.state_dict(), f'out/{model_name}.pt')
mats = {
        'w1': model.d1.weight,
        'b1': model.d1.bias,
        'act1_a': model.act1.a,
        'act1_b': model.act1.b,
        'w2': model.d2.weight,
        'b2': model.d2.bias
    }
with open(f'../weights/adult.csv', 'w') as f:
    for k, v in mats.items():
        l = v.ravel().detach().cpu().numpy().tolist()
        s = ','.join([f'{x:.32f}' for x in l])
        f.write(f'{k},{s}\n')


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 12 11:08:07 2020

@author: user
"""

import torch
import torch.nn as nn
import torch.nn.functional as F
from dgl import nn as dglnn
from dgl import utils as du
import dgl.function as fn
from sklearn import preprocessing
import numpy as np

def scaling(x):
    scaler = preprocessing.MinMaxScaler()
    if len(x.shape) != 2:
        x = x.reshape(-1, 1)
    return scaler.fit_transform(x)
class PyTMinMaxScaler(object):
    """
    Transforms each channel to the range [0, 1].
    """
    def __call__(self, tensor):
        tensor = tensor.clone()
        if tensor.shape[-1] == 1:
            tensor = torch.squeeze(tensor, dim = -1)
        for ch in tensor:
            if len(ch) != 1:
                min_ = ch.min(dim=0)[0]
                scale = ch.max(dim=0)[0].sub(min_)
                ch.sub_(min_).div_(scale)
        return torch.unsqueeze(tensor, dim = -1)
scaler = PyTMinMaxScaler()
class EWConv(nn.Module):
    def __init__(self, in_feats, out_feats, edge_func, aggregator_type='mean', device = 'cpu'):
        super().__init__()
        self._in_src_feats, self._in_dst_feats = du.expand_as_pair(in_feats)
        self.device = device
        self.out_feats = out_feats
        self.edge_func = edge_func
        self.aggregator_type = aggregator_type
        self.pool_func = nn.Linear(self._in_src_feats, self.out_feats)
        if aggregator_type == 'lstm':
            self.lstm = nn.LSTM(self.out_feats, self.out_feats, batch_first=True)
        self.self_func = nn.Linear(self._in_src_feats, self.out_feats)
        self.reset_parameters()

    def reset_parameters(self):
        gain = nn.init.calculate_gain('relu')
        nn.init.xavier_uniform_(self.pool_func.weight, gain=gain)
        if self.aggregator_type == 'lstm':
            self.lstm.reset_parameters()
        # nn.init.xavier_uniform_(self.fc_neigh.weight, gain=gain)

    def udf_edge(self, edges):
        return {'edge_features': edges.data['w'], 'neighbors' : edges._src_data['h']}

    def udf_u_mul_e(self, nodes):
        m = self.edge_func
        weights = nodes.mailbox['edge_features']

        # weights = torch.div(weights.squeeze(dim = 2), weights.sum(1)).unsqueeze(dim = 2)
        # soft_ed = m(weights)
        # soft_ed = m(scaler(weights))
        # soft_ed_ = m(scaler(weights))
        soft_ed = m(torch.FloatTensor(np.squeeze(np.apply_along_axis(scaling, 1, weights.cpu().numpy()), axis = 2))).to(self.device)

        res = soft_ed * nodes.mailbox['neighbors']
        if self.aggregator_type == 'sum':
            res = res.sum(axis = 1)
        elif self.aggregator_type == 'mean':
            res = res.mean(axis = 1)
        elif self.aggregator_type == 'max':
            res = res.max(axis = 1)[0]
        elif self.aggregator_type == 'lstm':
            batch_size = res.shape[0]
            hid = (res.new_zeros((1, batch_size, self.out_feats)), res.new_zeros((1, batch_size, self.out_feats)))
            _, (res, _) = self.lstm(res, hid) # only get hidden state
            res = res.permute(1, 0, 2)
        return {'h_reduced' : res}

    def forward(self, graph, feat, efeat):
        with graph.local_scope():
            feat_src, feat_dst = du.expand_as_pair(feat, graph)
            graph.srcdata['h'] = self.pool_func(feat_src)
            graph.edata['w'] = efeat
            graph.update_all(self.udf_edge, self.udf_u_mul_e)
            result = self.self_func(feat_dst) + graph.dstdata['h_reduced'].squeeze()

            return result

class DWGNN(nn.Module):
    def __init__(self, in_feats, hid_feats, out_feats, edge_feats, num_layers, aggregator_type, device):
        super().__init__()
        self.num_layers = num_layers
        self.layers = torch.nn.ModuleList()
        self.batch_norms = torch.nn.ModuleList()
        # self.edge_funcs = torch.nn.ModuleList()
        if aggregator_type not in ['sum', 'mean', 'max', 'lstm']:
            raise KeyError("invalid aggregator type(sum, mean, max)")
        for layer in range(self.num_layers - 1):
            if layer == 0:
                # self.edge_funcs.append(torch.nn.Linear(edge_feats, in_feats * hid_feats))
                self.layers.append(EWConv(in_feats=in_feats, out_feats=hid_feats, edge_func = nn.Softmin(dim = 1), aggregator_type=aggregator_type, device = device))
            else:
                # self.edge_funcs.append(torch.nn.Linear(edge_feats, hid_feats*hid_feats))
                self.layers.append(EWConv(in_feats=hid_feats, out_feats=hid_feats, edge_func = nn.Softmin(dim = 1), aggregator_type=aggregator_type, device = device))
        # self.edge_funcs.append(torch.nn.Linear(edge_feats, hid_feats * out_feats))
        self.layers.append(EWConv(in_feats=hid_feats, out_feats=out_feats, edge_func = nn.Softmin(dim = 1), aggregator_type=aggregator_type, device = device))

        for layer in range(self.num_layers - 1):
            self.batch_norms.append(nn.BatchNorm1d((hid_feats)))

    def forward(self, graph, inputs, edge_features, batch_norm = True):
        h = inputs
        e = edge_features
        for i in range(self.num_layers):
            if i != self.num_layers - 1:
                h = F.relu(self.layers[i](graph, h, e))
                if batch_norm == True:
                    h = self.batch_norms[i](h)
            else:
                h = self.layers[i](graph, h, e)

        h = F.log_softmax(h, dim=1)

        return h

class MLP(nn.Module):
    def __init__(self, num_layers, input_dim, hidden_dim, output_dim):
        super(MLP, self).__init__()

        self.linear_or_not = True #default is linear model
        self.num_layers = num_layers

        if num_layers == 1:
            #Linear model
            self.linear = nn.Linear(input_dim, output_dim)
        else:
            self.linear_or_not = False #linear model
            self.linears = torch.nn.ModuleList()
            self.batch_norms = torch.nn.ModuleList()

            for layer in range(num_layers - 1):
                if layer == 0:
                    self.linears.append(nn.Linear(input_dim, hidden_dim))
                else:
                    self.linears.append(nn.Linear(hidden_dim, hidden_dim))
            self.linears.append(nn.Linear(hidden_dim, output_dim))

            for layer in range(num_layers - 1):
                self.batch_norms.append(nn.BatchNorm1d((hidden_dim)))

    def forward(self, x, batch_norm):
        if self.linear_or_not:
            #If linear model
            return self.linear(x)
        else:
            #If MLP
            h = x
            for layer in range(self.num_layers - 1):
                if batch_norm == True:
                    h = F.relu(self.batch_norms[layer](self.linears[layer](h)))
                else:
                    h = F.relu(self.linears[layer](h))
            return self.linears[self.num_layers - 1](h)

class GCN(nn.Module):
    def __init__(self, in_feats, hid_feats, out_feats, num_layers):
        super().__init__()
        self.num_layers = num_layers
        self.layers = torch.nn.ModuleList()
        self.batch_norms = torch.nn.ModuleList()

        for layer in range(self.num_layers - 1):
            if layer == 0:
                self.layers.append(dglnn.GraphConv(in_feats=in_feats, out_feats=hid_feats, norm = 'both'))
            else:
                self.layers.append(dglnn.GraphConv(in_feats=hid_feats, out_feats=hid_feats, norm = 'both'))
        self.layers.append(dglnn.GraphConv(in_feats=hid_feats, out_feats=out_feats, norm = 'both'))

        for layer in range(self.num_layers - 1):
            self.batch_norms.append(nn.BatchNorm1d((hid_feats)))

    def forward(self, graph, inputs, edge_feautes = None, batch_norm = False):
        h = inputs
        for i in range(self.num_layers):
            if i != self.num_layers - 1:
                h = F.relu(self.layers[i](graph, h))
                if batch_norm == True:
                    h = self.batch_norms[i](h)
            else:
                h = self.layers[i](graph, h)

        h = F.log_softmax(h, dim=1)

        return h

class MPNN(nn.Module):
    def __init__(self, in_feats, hid_feats, out_feats, edge_feats, num_layers, aggregator_type, residual = False):
        super().__init__()
        self.num_layers = num_layers
        self.layers = torch.nn.ModuleList()
        self.batch_norms = torch.nn.ModuleList()
        self.edge_funcs = torch.nn.ModuleList()
        if aggregator_type not in ['sum', 'mean', 'max']:
            raise KeyError("invalid aggregator type(sum, mean, max)")
        for layer in range(self.num_layers - 1):
            if layer == 0:
                self.edge_funcs.append(torch.nn.Linear(edge_feats, in_feats * hid_feats))
                self.layers.append(dglnn.NNConv(in_feats=in_feats, out_feats=hid_feats, edge_func = self.edge_funcs[layer], aggregator_type=aggregator_type, residual = residual))
            else:
                self.edge_funcs.append(torch.nn.Linear(edge_feats, hid_feats*hid_feats))
                self.layers.append(dglnn.NNConv(in_feats=hid_feats, out_feats=hid_feats, edge_func = self.edge_funcs[layer], aggregator_type=aggregator_type, residual = residual))
        self.edge_funcs.append(torch.nn.Linear(edge_feats, hid_feats * out_feats))
        self.layers.append(dglnn.NNConv(in_feats=hid_feats, out_feats=out_feats, edge_func = self.edge_funcs[self.num_layers - 1], aggregator_type=aggregator_type, residual = residual))

        for layer in range(self.num_layers - 1):
            self.batch_norms.append(nn.BatchNorm1d((hid_feats)))

    def forward(self, graph, inputs, edge_features, batch_norm = True):
        h = inputs
        e = edge_features
        for i in range(self.num_layers):
            if i != self.num_layers - 1:
                h = F.relu(self.layers[i](graph, h, e))
                if batch_norm == True:
                    h = self.batch_norms[i](h)
            else:
                h = self.layers[i](graph, h, e)

        h = F.log_softmax(h, dim=1)

        return h

class SAGE(nn.Module):
    def __init__(self, in_feats, hid_feats, out_feats, num_layers, aggregator_type):
        super().__init__()
        self.num_layers = num_layers
        self.layers = torch.nn.ModuleList()
        self.batch_norms = torch.nn.ModuleList()
        # self.sumpool = dglnn.pytorch.glob.SumPooling()

        for layer in range(self.num_layers - 1):
            if layer == 0:
                self.layers.append(dglnn.SAGEConv(in_feats=in_feats, out_feats=hid_feats, aggregator_type=aggregator_type))
            else:
                self.layers.append(dglnn.SAGEConv(in_feats=hid_feats, out_feats=hid_feats, aggregator_type=aggregator_type))
        self.layers.append(dglnn.SAGEConv(in_feats=hid_feats, out_feats=out_feats, aggregator_type=aggregator_type))

        for layer in range(self.num_layers - 1):
            self.batch_norms.append(nn.BatchNorm1d((hid_feats)))

    def forward(self, graph, inputs, edge_feautes = None, batch_norm = True):
        h = inputs
        for i in range(self.num_layers):
            if i != self.num_layers - 1:
                h = F.relu(self.layers[i](graph, h))
                if batch_norm == True:
                    h = self.batch_norms[i](h)
            else:
                h = self.layers[i](graph, h)

        h = F.log_softmax(h, dim=1)

        return h

class GIN(nn.Module):
    def __init__(self, in_feats, hid_feats, out_feats, num_layers, num_mlp_layers, aggregator_type):
        super().__init__()
        self.num_layers = num_layers
        self.layers = torch.nn.ModuleList()
        self.batch_norms = torch.nn.ModuleList()

        for layer in range(self.num_layers - 1):
            if layer == 0:
                cur_func = MLP(num_mlp_layers, in_feats, hid_feats, hid_feats)
                self.layers.append(dglnn.GINConv(cur_func, aggregator_type))
            else:
                cur_func = MLP(num_mlp_layers, hid_feats, hid_feats, hid_feats)
                self.layers.append(dglnn.GINConv(cur_func, aggregator_type))
        cur_func = MLP(num_mlp_layers, hid_feats, hid_feats, out_feats)
        self.layers.append(dglnn.GINConv(cur_func, aggregator_type))

        for layer in range(self.num_layers - 1):
            self.batch_norms.append(nn.BatchNorm1d((hid_feats)))

    def forward(self, graph, inputs, edge_feautes = None, batch_norm = True):
        h = inputs
        for i in range(self.num_layers):
            if i != self.num_layers - 1:
                h = F.relu(self.layers[i](graph, h, batch_norm))
                if batch_norm == True:
                    h = self.batch_norms[i](h)
            else:
                h = self.layers[i](graph, h, batch_norm)

        h = F.log_softmax(h, dim=1)

        return h


import pickle
import numpy as np
import torch
import torch.nn as nn
from metahuman.lbs_metahuman import lbs, batch_rodrigues
from flame.lbs_flame import to_tensor, to_np, Struct

class MetaHuman(nn.Module):
    """
    Given metahuman parameters this class generates a differentiable metahuman function
    which outputs the a mesh and 3D facial landmarks
    """
    def __init__(self, metahuman_model_path):
        super(MetaHuman, self).__init__()
        print("creating the metahuman Decoder")
        with open(metahuman_model_path, 'rb') as f:
            metahuman_model = Struct(**pickle.load(f, encoding='latin1'))

        self.dtype = torch.float32
        self.register_buffer('faces_tensor', to_tensor(to_np(metahuman_model.f, dtype=np.int64), dtype=torch.long))
        # The vertices of the template model
        self.register_buffer('v_template', to_tensor(to_np(metahuman_model.v_template), dtype=self.dtype))
        # The expression components and expression
        self.register_buffer('expdirs', to_tensor(to_np(metahuman_model.expression_basis), dtype=self.dtype))
        # The jaw components
        self.register_buffer('jaw_pose_basis', to_tensor(to_np(metahuman_model.jaw_pose_basis), dtype=self.dtype))
        # The pose components
        self.register_buffer('posedirs', to_tensor(to_np(metahuman_model.pose_basis), dtype=self.dtype))
        self.register_buffer('J_coordinate', to_tensor(to_np(metahuman_model.J_coordinate), dtype=self.dtype))
        self.register_buffer('parents', to_tensor(to_np(metahuman_model.parents)).long())
        self.register_buffer('lbs_weights', to_tensor(to_np(metahuman_model.lbs_weights), dtype=self.dtype))
        self.register_buffer('lmks_idx', to_tensor(to_np(metahuman_model.lmks_idx), dtype=torch.long))
        self.register_buffer('global_matrix', to_tensor(torch.eye(3)))
        self.register_buffer('J_root', to_tensor(torch.tensor([[0, 0, 0]])))

    def forward(self, params):
        """
            Input:
                params: N X number of parameters
            return:
                vertices: N X V X 3
                landmarks: N X number of landmarks X 3
        """
        batch_size = params.shape[0]

        jaw_pose9 = batch_rodrigues(torch.multiply(self.jaw_pose_basis[0].unsqueeze(0).repeat(batch_size, 1), params[:, 9:10]))
        jaw_pose8 = batch_rodrigues(torch.multiply(self.jaw_pose_basis[1].unsqueeze(0).repeat(batch_size, 1), params[:, 8:9]))
        jaw_pose7 = batch_rodrigues(torch.multiply(self.jaw_pose_basis[2].unsqueeze(0).repeat(batch_size, 1), params[:, 7:8]))
        jaw_matrix = torch.matmul(torch.matmul(jaw_pose9, jaw_pose8), jaw_pose7).view(batch_size, 1, 9)

        full_pose = torch.concat([self.global_matrix.unsqueeze(0).repeat([batch_size, 1, 1]).view(batch_size, 1, 9), jaw_matrix], 1)

        template_vertices = self.v_template.unsqueeze(0).repeat(batch_size, 1, 1)

        exp_coeffs = torch.concat([params[:, :7], params[:, 10:]], dim=1)

        vertices, _ = lbs(exp_coeffs, full_pose, template_vertices,
                            self.expdirs, self.posedirs,
                            torch.concat([self.J_root, self.J_coordinate], dim=0).repeat(batch_size, 1, 1), self.parents,
                            self.lbs_weights, pose2rot=False)

        landmarks = vertices[:, self.lmks_idx, :]

        return vertices, landmarks

# params = torch.zeros([1, 35])
# model = MetaHuman('metahuman_model.pkl')
# vertices, landmarks = model(params)


import numpy as np

def build_confusion_matrix(pred_y, actual_y):
    """build confusion matrix from predictions and actual labels

    :param pred_y: np array of labels
    :param actual_y: np array of labels
    """
    # compute the size of the matrix
    confusion_matrix_size = int(max(max(pred_y), max(actual_y)))

    # initialise confusion matrix to matrix of zeros
    confusion_matrix = [[0 for _ in range(confusion_matrix_size)]
                        for _ in range(confusion_matrix_size)]

    # for each pair, update correct position of the matrix
    for x, y in zip(actual_y, pred_y):
        confusion_matrix[int(x) - 1][int(y) - 1] += 1

    return np.array(confusion_matrix)

def stats(cm):
    """compute statistics using confusion matrix

    :param cm: 2d array
    """
    # initialise the statistics
    statistics = {}
    recalls = []
    precisions = []
    f1_measures = []
    accuracy_sum = 0
    num_entries = 0
    # loop through the confusion matrix
    for i in range(len(cm)):
        # accumulate the diagonol values as sum of accurate predictions
        accuracy_sum += cm[i, i]
        # true positive
        tp = cm[i, i]
        # update row and column
        row = cm[i]
        col = cm[:, i]

        # sum row values
        row_sum = sum(row)
        num_entries += row_sum

        # if row sum to 0, then recall is 1
        if row_sum == 0:
            recall = 1
        # otherwise calculate recall by dividing true positive from row sums
        else:
            recall = tp / row_sum

        # sum column values
        col_sum = sum(col)
        # if column sum to 0, then precision is 1
        if col_sum == 0:
            precision = 1
        # otherwise calculate column my dividing true positive from column sums
        else:
            precision = tp / col_sum

        # if number of true positive is 0, then f1 measure is 1
        if tp == 0:
            f1_measure = 1
        # otherwise update the f1 measure
        else:
            f1_numerator = (recall * precision)
            f1_denominator = (recall + precision)
            f1_measure = 2 * (f1_numerator / f1_denominator)
        # append these measures to their respective list
        recalls.append(recall)
        precisions.append(precision)
        f1_measures.append(f1_measure)
    # update the dictionary of statistics
    statistics['accuracy'] = accuracy_sum / num_entries
    statistics['recalls'] = recalls
    statistics['precisions'] = precisions
    statistics['f1'] = f1_measures

    return statistics


from math import sin
from time import sleep

from pygame import Surface, Color, SRCALPHA, draw

from src.game import Game
from src.launcher import Launcher

game, launcher = Game(), Launcher()
center_x = int(game.config.width / 2)
center_y = int(game.config.height / 2)
dot_color = Color('white')

def draw_coordinate_plane():
    game.screen.fill((0, 0, 0))
    x_axis = Surface((game.config.width, 3))
    y_axis = Surface((3, game.config.height))
    x_axis.fill((50, 50, 50))
    y_axis.fill((50, 50, 50))
    game.screen.blit(x_axis, (0, game.config.height / 2))
    game.screen.blit(y_axis, (game.config.width / 2, 0))

def draw_dot(x, y):
    game.context['plane'].set_at((x, y), dot_color)

def track_time():
    try:
        game.context['tick'] += 1
        if game.context['tick'] == game.config.width:
            game.activate_kill_switch()
    except KeyError:
        game.context['tick'] = 0

def add_drawing_plane():
    surface = Surface(game.config.window_size, SRCALPHA)
    game.context['plane'] = surface
    game.context['previous_positive_point'] = (center_x , center_y)
    game.context['previous_negative_point'] = (center_x , center_y)

def squared(x: int) -> int:
    return int(1/(game.config.width / 2) * x * x)

def linear(x: int) -> int:
    return x

def sinwave(x: int) -> int:
    return int(100*sin((1/10)*x))

def draw_parabola():
    if game.context['tick'] <= game.config.width / 2:
        # positive side
        x = game.context['tick'] + center_x
        y = 0 - linear(game.context['tick']) + center_y
        print(f'Point: ({x}, {y})')
        draw.line(
            game.context['plane'],
            Color('green'),
            game.context['previous_positive_point'],
            (x, y)
        )
        draw_dot(x, y)
        game.context['previous_positive_point'] = (x, y)

        #negative side
        x = center_x - game.context['tick']
        y = 0 - linear(x - center_x) + center_y
        draw.line(
            game.context['plane'],
            Color('red'),
            game.context['previous_negative_point'],
            (x, y)
        )
        draw_dot(x, y)
        game.context['previous_negative_point'] = (x, y)

        # put it on the screen!
        game.screen.blit(game.context['plane'], (0, 0))

def wait_a_few_seconds():
    sleep(5)

# game.add_task('launch', launcher.open)
game.add_task('start', draw_coordinate_plane)
game.add_task('start', add_drawing_plane)
game.add_task('loop', track_time)
game.add_task('loop', draw_parabola)
game.add_task('close', wait_a_few_seconds)
game.prime_engine()
game.start_loop()


from tkinter import *

root = Tk()
root.geometry("930x400")
root['bg'] = 'yellow'
root.title("Restaurant Mangement Systems")

head_text = Label(font = ('times new roman', 50 , 'bold'), text = "Restaurant Mangement Systems", fg = "white", bg = "black").grid(row = 0, column = 0, columnspan = 5)

#entry goods
goods_1 = Label(font = ('times new roman', 12 , 'bold'), text = "Goods: 1", fg = "white", bg = "black").grid(row = 1, column = 0)
goods_2 = Label(font = ('times new roman', 12 , 'bold'), text = "Goods: 2", fg = "white", bg = "black").grid(row = 2, column = 0)
goods_3 = Label(font = ('times new roman', 12 , 'bold'), text = "Goods: 3", fg = "white", bg = "black").grid(row = 3, column = 0)

#entry function

entry_1 = Entry(root, justify = "right", borderwidth = 3)
entry_1.grid(row = 1, column = 1)

entry_2 = Entry(root, justify = "right", borderwidth = 3)
entry_2.grid(row = 2, column = 1)

entry_3 = Entry(root, justify = "right", borderwidth = 3)
entry_3.grid(row = 3, column = 1)

#insert total cost

entry_4 = Entry(root, justify = "right", borderwidth = 3)
entry_4.grid(row = 4, column = 1)

#goods cost
cost_1 = Label(font = ('times new roman', 12 , 'bold'), text = "2$", bg = 'yellow').grid(row = 1, column = 2)
cost_2 = Label(font = ('times new roman', 12 , 'bold'), text = "2$", bg = 'yellow').grid(row = 2, column = 2)
cost_3 = Label(font = ('times new roman', 12 , 'bold'), text = "2$", bg = 'yellow').grid(row = 3, column = 2)

#calculating

def btn_ttl():
    a = entry_1.get()
    a_1 = entry_1.get()
    a_2 = entry_1.get()

    sum = int(a) + int(a_1) + int(a_2)
    entry_4.insert(0, sum)

def btn_clr():
    entry_1.delete(0, END)
    entry_2.delete(0, END)
    entry_3.delete(0, END)
    entry_4.delete(0, END)

btn_ttl = Button(root, text = "Total", font = ('times new roman', 12 , 'bold'), fg = "white", bg = "black", command = btn_ttl).grid(row = 4, column = 0)

btn_clr = Button(root, text = "Clear", font = ('times new roman', 12 , 'bold'), fg = "white", bg = "black", command = btn_clr).grid(row = 5, column = 0)

#cancel
cancel = Button(root, text = "OK", font = ('times new roman', 12 , 'bold'), fg = "white", bg = "black", command = root.destroy).grid(row = 5, column = 3)

root.mainloop()


#공딕셔너리에서 반복문을 통한 중첩딕셔너리 값저장 불가
#C = {{}}
#for i in range(5):
    #for j in range(5):
        #C[i][j] = 1
#print(C)

D = {
    1 : {1: 1, 2: 2},
    2 : {1: 1, 2: 2}
}

# 중첩딕셔너리에서 첫번째 key값들에 대해서는 중복불가
# key 내부딕셔너리에서의 두번째 key값들에 대해선 중복가능
print(D[1][1])
print(D[2][1])

# 중첩딕셔너리도 중첩배열과 마찬가지.
# for문을 이용하여 공딕셔너리로의 직접적인 값 저장은 불가
# 딕셔너리가 이미 선언된 상태에서, 값을 바꾸는 형식으로 저장만 가능
for i in range (1,2+1):
    for j in range(1,2+1):
        D[i][j] = i + j

print(D)


from collections import Counter

class Solution:
    def checkAlmostEquivalent(self, word1: str, word2: str) -> bool:
        c1 = Counter(word1)
        c2 = Counter(word2)

        s = set(word1 + word2)

        for c in s:
            if abs(c1[c] - c2[c]) > 3:
                return False

        return True


from MicroPythonListClass import MicroPythonList

def facto (x : int) -> int :
  if x == 1 :
    s = 1;
  else :
    s = x * facto (x - 1);
  return s

def main () -> int :
  print (facto (int (input ())))
  return 0


from pipeline.dag import DAG

class Pipeline:
    """Create a pipeline by chaining multiple tasks and identifying dependencies."""

    def __init__(self):
        self.tasks = DAG()

    def task(self, depends_on=None):
        """Add new task to the pipeline and specify dependency task (optional)."""
        def inner(func):
            if depends_on:
                self.tasks.add(depends_on, func)
            else:
                self.tasks.add(func)
            return func
        return inner

    def run(self, *args):
        """Execute the pipeline and return each task results."""
        sorted_tasks = self.tasks.sort()
        completed = {}

        for task in sorted_tasks:
            for depend_on, nodes in self.tasks.graph.items():
                if task in nodes:
                    completed[task] = task(completed[depend_on])
            if task not in completed:
                if sorted_tasks.index(task) == 0:
                    completed[task] = task(*args)
                else:
                    completed[task] = task()

        return completed


from rest_framework import permissions
from posts.models import Post

class IsAuthorOrReadOnly(permissions.BasePermission):
    """
    Custom permission to restrict write access to object authors,
    or user objects writing to themselves.
    """

    def has_object_permission(self, request, view, obj):
        # Permission open on GET, HEAD, OPTIONS requests.
        if request.method in permissions.SAFE_METHODS:
            return True

        if isinstance(obj, Post):
            # Write permission allowed to any user for a vote.
            if request.query_params.get('vote'):
                # Write permission restricted on unsafe non-vote operations.
                return (set(request.data.keys()) == set(['score']))
            else:
                # Write permission only allowed to post author.
                return obj.author == request.user
        else:
            # Write permission only allowed to self user.
            return obj == request.user


import os,sys
import time
import openpyxl
import pandas as pd
import random
"""定义变量以及列表初始化"""
coe=[]
rex=[]
re=[]
part=0
count=0

while True:

	os.system('clear')

	print('\033[1;32;40m============================================================================')
	print('这是一个用来调整价格的脚本，首先要将需要调整的全部价格导入到一个Excel 表格中')
	print('然后调用该脚本即可完成操作。第一列列名要改成total！')
	print('============================================================================')
	print('\033[0m')

	path=input('\033[1;33;40m请输入Excel文件路径,输入exit退出: ')
	print('\033[0m')
	path=path.strip()
	if path=='exit':
		sys.exit()

	elif os.path.exists(path)==False:
		print('\033[1;37;31m未找到该文件，请检查文件路径！\033[1;37;31m')
		print('\033[0m')
		time.sleep(1)
		continue

	target=input("请输入目标价格： ")
	#extracting data from excel
	data=pd.DataFrame(pd.read_excel(path))
	for i in data['total']:
		coe.append(i)
	for i in coe:
		count=i+count

	r=float(target)/count
	for i in range(len(coe)-1):
		rex.append(r+random.uniform(-1/(10**(round(len(target)/2)+1)),1/(10**(round(len(target)/2)+1))))

	for i in range(len(coe)-1):
		part=part+coe[i]*rex[i]
	lastrex=(float(target)-part)/coe[-1]
	rex.append(round(lastrex,3))

	#writing to excel
	wb=openpyxl.load_workbook(path)
	ws=wb['Sheet1']

	ws.cell(row=1,column=2).value='系数'
	for i in range(1,len(rex)+1):
		re=rex[i-1]
		ws.cell(row=i+1,column=2).value=re

	ws.cell(row=1,column=3).value='结果'
	for i in range(1,len(rex)+1):
		er=rex[i-1]*coe[i-1]
		ws.cell(row=i+1,column=3).value=er

	save=wb.save(path)
	if save==None:
		print('\033[1;32;40m文件保存成功!\033[1;32;40m')
		print('\033[0m')
		time.sleep(2)
	else:
		print('\033[1;37;31m文件保存失败！\033[1;37;31m')
		print('\033[0m')
		time.sleep(2)


import time

# Homogenize sensor data to contain all fields expected.
# Fill in default values where value isn't available.
def homogenize(sensors):
    out = {}
    for device_id, device in sensors.items():
        if device_id not in out:
            out[device_id] = {}
        out[device_id]['name'] = device['name']

        for field in [
                { 'key': 'temperature', 'default': None, 'type': float },
                { 'key': 'humidity', 'default': None, 'type': float },
                { 'key': 'lastSeen', 'default': int(time.time()*1000), 'type': int }
                ]:
            key = field['key']
            default = field['default']
            type_cast = field['type']
            if key in device['state'] and device['state'][key] is not None:
                # Also make sure values conform to the right types
                out[device_id][key] = type_cast(device['state'][key])
            else:
                out[device_id][key] = default
    return list(out.values())


from typing import Optional, Union
from numpy.typing import NDArray
from shape import Shape
import numpy as np
import arrays
import images
import fit

def prepare(n_target_pixels: int,
            tile_height: int,
            target_src: Optional[Union[str, bytes]] = None,
            tiles_src: Optional[Union[str, list[bytes]]] = None
            ) -> tuple[NDArray[np.uint8], NDArray[np.uint8], Shape, Shape]:

    target_array = images.preprocess(tile_height=tile_height, n_pixels=n_target_pixels, src=target_src)

    tile_shape = Shape(tile_height, tile_height, images.N_COLOURS)
    output_shape = Shape(*target_array.shape)

    target_array = arrays.unroll(target_array, tile_shape)

    tile_arrays = images.tile_images_as_arrays(tile_shape, tiles_src)
    return target_array, tile_arrays, tile_shape, output_shape

def create(target_array: NDArray[np.uint8],
           tile_arrays: NDArray[np.uint8],
           tile_shape: Shape,
           output_shape: Shape
           ) -> NDArray:
    comparisons = fit.evaluate(rgb_mean(target_array), rgb_mean(tile_arrays))
    best_comparison = fit.best_fit(comparisons)
    results_array = tile_arrays[best_comparison]
    return arrays.rollup(results_array, tile_shape, output_shape)

def rgb_mean(array: NDArray[np.uint8]) -> NDArray[np.float32]:
    """Turns an array of multiple images/tiles and returns the average rgb values for each"""
    return array.sum(axis=1).sum(axis=1) / (array.shape[1] * array.shape[1])


from os import stat
from weakref import ref
import numpy as np
from cost import Cost
from dynamics import Dynamics
import matplotlib.pyplot as plt
import time

class iLQR():
    def __init__(self, ref_path, params):

        self.T = params['T']
        self.N = params['N']

        self.ref_path = ref_path

        self.steps = 30

        self.tol = 1e-4
        self.lambad = 100
        self.lambad_max = 1000
        self.lambad_min = 1e-3

        self.dynamics = Dynamics(params)
        self.alphas = 1.1**(-np.arange(10)**2)

        self.dim_x = self.dynamics.dim_x
        self.dim_u = self.dynamics.dim_u

        self.cost = Cost(params)

    def forward_pass(self, nominal_states, nominal_controls, K_closed_loop, k_open_loop, alpha):
        X = np.zeros_like(nominal_states)
        U = np.zeros_like(nominal_controls)

        X[:,0] = nominal_states[:,0]
        for i in range(self.N-1):
            K = K_closed_loop[:,:,i]
            k = k_open_loop[:,i]
            u = nominal_controls[:,i]+alpha*k+ K @ (X[:, i] - nominal_states[:, i])
            X[:,i+1], U[:,i] = self.dynamics.forward_step(X[:,i], u)

        closest_pt, slope, theta = self.ref_path.get_closest_pts(X[:2,:])

        J = self.cost.get_cost(X, U, closest_pt, slope, theta)

        return X, U, J, closest_pt, slope, theta

    def backward_pass(self, nominal_states, nominal_controls, closest_pt, slope):
        L_x, L_xx, L_u, L_uu, L_ux = self.cost.get_derivatives(nominal_states, nominal_controls, closest_pt, slope)

        fx, fu = self.dynamics.get_AB_matrix(nominal_states, nominal_controls)

        k_open_loop = np.zeros((self.dim_u, self.N-1))
        K_closed_loop = np.zeros((self.dim_u, self.dim_x, self.N-1))
        # derivative of value function at final step
        V_x = L_x[:,-1]
        V_xx = L_xx[:,:,-1]

        #expected_cost_red = 0
        reg_mat = self.lambad*np.eye(self.dim_u)

        Q_u_hist = np.zeros([self.dim_u, self.N-1])
        Q_uu_hist = np.zeros([self.dim_u, self.dim_u, self.N-1])
        for i in range(self.N-2, -1, -1):
            Q_x = L_x[:,i] + fx[:,:,i].T @ V_x
            Q_u = L_u[:,i] + fu[:,:,i].T @ V_x
            Q_xx = L_xx[:,:,i] + fx[:,:,i].T @ V_xx @ fx[:,:,i]
            Q_ux =  fu[:,:,i].T @ V_xx @ fx[:,:,i]+L_ux[:,:,i]
            Q_uu = L_uu[:,:,i] + fu[:,:,i].T @ V_xx @ fu[:,:,i]

            Q_uu_inv = np.linalg.inv(Q_uu+reg_mat)
            k_open_loop[:,i] = -Q_uu_inv@Q_u
            K_closed_loop[:, :, i] = -Q_uu_inv@Q_ux

            # Update value function derivative for the previous time step
            V_x = Q_x - K_closed_loop[:,:,i].T @ Q_uu @ k_open_loop[:,i]
            V_xx = Q_xx - K_closed_loop[:,:,i].T @ Q_uu @ K_closed_loop[:,:,i]

            Q_u_hist[:,i] = Q_u
            Q_uu_hist[:,:,i] = Q_uu

        expected_cost_red = -np.sum(np.einsum('an, bn->n', Q_u_hist, k_open_loop) + \
                0.5*np.einsum('an, bn->n', k_open_loop, np.einsum('abn,bn->an', Q_uu_hist, k_open_loop)))

        return K_closed_loop, k_open_loop, expected_cost_red

    def solve(self, cur_state, controls = None):
        status = 0
        self.lambad = 100

        time0 = time.time()

        if controls is None:
            controls = np.zeros((self.dim_u, self.N))
        states = np.zeros((self.dim_x, self.N))
        states[:,0] = cur_state

        for i in range(1,self.N):
            states[:,i],_ = self.dynamics.forward_step(states[:,i-1], controls[:,i-1])
        closest_pt, slope, theta = self.ref_path.get_closest_pts(states[:2,:])

        J = self.cost.get_cost(states, controls,  closest_pt, slope, theta)

        converged = False
        expected_cost_red_prev = 0

        for i in range(self.steps):
            K_closed_loop, k_open_loop, expected_cost_red = self.backward_pass(states, controls, closest_pt, slope)

            updated = False
            for alpha in self.alphas :
                X_new, U_new, J_new, closest_pt_new, slope_new, theta_new = self.forward_pass(states, controls, K_closed_loop, k_open_loop, alpha)
                if J_new<=J:
                    if np.abs((J - J_new) / J) < self.tol:
                        converged = True
                    J = J_new
                    states = X_new
                    controls = U_new
                    closest_pt = closest_pt_new
                    slope = slope_new
                    theta = theta_new
                    updated = True
                    break
            if updated:
                self.lambad *= 0.7
            else:
                self.lambad *= 2
                if abs(expected_cost_red_prev - expected_cost_red)<1e-6:
                    status = 2
                    # print("early exit")
                    break
                else:
                    expected_cost_red_prev = expected_cost_red
            self.lambad = min(max(self.lambad_min, self.lambad), self.lambad_max)

            if converged:
                status = 1
                break
        t_process = time.time()-time0
        return states, controls, t_process, status, theta


from collections import namedtuple
from ..cached_property import cached_property
from .channel import Channel

Annotation = namedtuple('Annotation', 'start duration label')

class AnnotationChannel(Channel):

    sep_annotations = b'\x14\x00'  # after each annotation
    sep_timestamp = b'\x15'  # between duration and label (optional)
    sep_duration = b'\x14'  # after timestamp

    @cached_property
    def annotations(self):

        def strip_trash(event):
            return event.lstrip(b'\x00').rstrip(self.sep_timestamp)

        def is_true_event(event):
            return len(event.split(self.sep_timestamp)) > 1

        def parse_event(event):
            timestamp_str, event = event.split(self.sep_timestamp)
            timestamp = float(timestamp_str)
            optional = event.split(self.sep_duration)
            duration = None
            if len(optional) == 2:
                duration, label = optional
                duration = float(duration)
            else:
                label = optional[0]

            label = label.decode('ascii')
            return Annotation(timestamp, duration, label)

        events = self.signal[:].tobytes()
        events = events.split(self.sep_annotations)
        events = map(strip_trash, events)
        events = filter(is_true_event, events)
        events = map(parse_event, events)
        return list(events)


# SUDOKU_PC, pc will do it itself
# FINISHED !!!
# but it's random based, so it won't learn itself how to complete, it's just on serendipity

import numpy as np
import pandas as pd
import random as rd

# to create this Dataframe of sudoku, 9*9
# nulls = np.full((9, 9), 'x')
# board = pd.DataFrame(nulls, index=['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'], columns=list(range(1, 10)), )

# index_col[0] will not include Unnamed column
board = pd.read_csv('sudoku_board.csv', index_col=[0])

# the list of all row names
rows = list(board.index)
# the list of all column names
columns = list(board.columns)

additional_stuff = \
    ('''
list_positions = []
for letter in rows:
    for number in columns:
        list_positions.append(list(letter + str(number)))
''')

# an array which is 9*9, and we will be checking if the number is in the right row and column
array_rows_columns = np.full((9, 9), 'x')
# an array which is 9 times of 3*3 arrays, we'll be checking blocks 3*3, in sudoku, there must be one unique value in the block
array_blocks = np.full((9, 3, 3), 'x')

# this will add a position which corresponds to array_blocks array
# A1, A2, A3, B1, B2, B3, C1, C2, C3 is position 0
# then A4 A5 A6 B4 B5 B6 C4 C5 C6 is position 1 etc, it just goes for the number (position) of each block in array_blocks array
array_blocks_position = {}
for letter in rows:

    # for A1, A2, A3, B1, B2, B3, C1, C2, C3 is position 0
    # for A4 A5 A6 B4 B5 B6 C4 C5 C6 is position 1
    # for A7 A8 A9 B7 B8 B9 C7 C8 C9 is position 2
    if rows.index(letter) + 1 >= 1 and rows.index(letter) + 1 <= 3:
        position = 0
        for num in columns:
            array_blocks_position[letter + num] = position

            if int(num) % 3 == 0:
                position += 1

                if position > 2:
                    position = 0

    # for D1 D2 D3 E1 E2 E3 F1 F2 F3 is position 3
    # for D4 D5 D6 E4 E5 E6 F4 F5 F6 is position 4
    # for D7 D8 D9 E7 E8 E9 F7 F8 F9 is positon 5
    elif rows.index(letter) + 1 >= 4 and rows.index(letter) + 1 <= 6:
        position = 3

        for num in columns:
            array_blocks_position[letter + num] = position

            if int(num) % 3 == 0:
                position += 1

                if position > 5:
                    position = 3

    # for G1 G2 G3 H1 H2 H3 I1 H2 H3 is position 6
    # for G4 G5 G6 H4 H5 H6 I4 I5 I6 is position 7
    # for G7 G8 G9 H7 H8 H9 I7 I8 I9 is position 8
    elif rows.index(letter) + 1 >= 7  and rows.index(letter) + 1 <= 9:
        position = 6

        for num in columns:
            array_blocks_position[letter + num] = position

            if int(num) % 3 == 0:
                position += 1

                if position > 8:
                    position = 6

# columns position for only array_blocks array it is 0-2
# 3*3 block is max 2 position and min 0
# '1', '4', '7' = 0; '2', '5', '8' = 1; '3', '6', '9' = 2
column_dict = {}
# start from -1 'cause right from the start of for loop there will be +1 and we want position 0 as min
setter_name = -1
for column_name in columns:
    setter_name += 1

    column_dict[column_name] = setter_name
    # if it gets more than 2, set it again to 0
    if setter_name >= 2:
        setter_name = -1

# rows position for only array_blocks array it is 0-2
# 3*3 block is max 2 position and min 0
# 'A', 'D', 'G' = 0; 'B', 'E', 'H' = 1; 'C', 'F', 'I' = 2
row_dict = {}
# start from -1 'cause right from the start of for loop there will be +1 and we want position 0 as min
setter_name = -1
for row_name in rows:
    setter_name += 1

    row_dict[row_name] = setter_name
    # if it gets more than 2, set it again to 0
    if setter_name >= 2:
        setter_name = -1

def sudoku():
    ide = True

    while ide:

        # random number between 1-9
        number = rd.randint(1, 9)

        # pick a random key in list of array_blocks_position (contains A1, A2, A3 ...)
        random_row_column = rd.choice(list(array_blocks_position.keys()))

        # random block is the value of random_row_column of array_blocks_position dict
        random_block = array_blocks_position[random_row_column]
        # random block row is the value of random_row_column[0] (A, B, C) of dict row_dict, the value is between 0-2
        random_block_row = row_dict[random_row_column[0]]
        # random block column is the value of random_row_column[1] (1, 2, 3) of dict column_dict, the value is between 0-2
        random_block_column = column_dict[random_row_column[1]]

        # you cannot sign the different number, cannot change the number in array_row_columns array
        # if str(number) in array_rows_columns[rows.index(random_row_column[0]), columns.index(random_row_column[1])]:
            # pass

        # you cannot sign the different number, cannot change the number in array_blocks array
        # elif str(number) in array_blocks[random_block, random_block_row, random_block_column]:
            # pass

        # if the same number appears to be in the same column, don't add it to the board just pass
        if str(number) in array_rows_columns[:, columns.index(random_row_column[1])]:
            pass

        # if the same number appears to be in the same row, don't add it to the board just pass
        elif str(number) in array_rows_columns[rows.index(random_row_column[0]), :]:
            pass

        # if the same number appears to be in the same block, don't add it to the board just pass
        elif str(number) in array_blocks[random_block, :, :]:
            pass

        # if it passes the exceptions
        else:
            # .at[row_name, int(column_name)] --> to a specific cell change
            board.at[random_row_column[0], random_row_column[1]] = str(number)

            # add that number even into the np matrix (9, 9) shape = array_row_columns
            array_rows_columns[rows.index(random_row_column[0]), columns.index(random_row_column[1])] = str(number)

            # add that number into the np matrix (9, 3, 3) shape = array_blocks
            array_blocks[random_block, random_block_row, random_block_column] = str(number)

            print('PROCESSING...')
            print(board)

        # if the board does not contain any 'x' in it, end the process
        if 'x' not in array_rows_columns[:, :]:
            print('')
            print("""PC HAS COMPLETED THE SUDOKU
THANK YOU FOR TRYING MY SUDOKU PC, BYE...""")

            print('')
            print(board)

            ide = False

sudoku()


from PyQt5.QtWidgets import *
from view.GUI import ApplicationWindow

class GUIController(ApplicationWindow):
    def __init__(self, code_analyzer_facade):
        ApplicationWindow.__init__(self)
        self.target_files = list()
        self.code_analyzer_facade = code_analyzer_facade
        self.vulnerability_dictionary = [
            "Уязвимость переполнения буфера в строках:",
            "Предупреждение: использование небезопасной функции (переполнение буфера): ",
            "Уязвимость ошибка форматной строки в строках:",
            "Предупреждение: использование небезопасной функции (форматная строка): ",
            "Уязвимость внедрение SQL-кода в строках",
            "Уязвимость внедрения команд в строках:",
            "Уязвимость небезопасного хранения данных в строках:",
            "Уязвимость  утечки памяти в строках: ",
            "Уязвимость некорректного доступа к файлам в строках:",
            "Уязвимость разыменования нулевого указателя в строках:",
            "Уязвимость переполнения целых чисел в строках:",
            "Уязвимость состояния гонки в строках:",
            "Уязвимость некорректной синхронизации типа читатели - писатели в стоках: ",
            "Уязвимость неинициализированных переменных в строках:"
        ]
        self.analyse_result = []

    def addFile(self):  # ф-я, которая отвечает за открытие файла
        file_path = QFileDialog.getOpenFileName(self, 'Open file', "")[0]
        if not file_path == "":
            self.file_list.addItem(str(file_path))
            source = open(file_path).readlines()
            format_source = []
            for i in range(len(source)):
                format_source.append("%2d.   %s" % (i, source[i]))
            self.target_files.append([file_path, source, format_source])
            self.showFileContent()

    def deleteFile(self):  # ф-я, которая отвечает за удаление файла (из программы)
        if self.file_list.currentRow() != -1:
            current_row = self.file_list.currentRow()
            self.file_list.takeItem(current_row)
            self.target_files.pop(current_row)
            self.code_text.setText('')
            self.code_label.setText("Листинг программы: ")
            self.file_list.setCurrentRow(-1)

    def showFileContent(self):
        row = self.file_list.currentRow()
        self.code_text.setText(''.join(self.target_files[row][2]))
        self.code_label.setText("Листинг программы: " + self.target_files[row][0])

    def generateTests(self):  # ф-я, которая отвечает за запуск генератора тестов
        self.code_analyzer_facade.generateTests()

    def analyseCode(self):  # ф-я, которая отвечает за запуск анализатора
        self.mssg_err.setText("")
        self.mssg_err.clear()
        for filename, source, format_source in self.target_files:
            self.mssg_err.append(filename + ":  ")
            self.analyse_result = self.code_analyzer_facade.get_analyse_result(self, source)

            isEmpty = True
            for i in range(len(self.analyse_result)):
                if self.analyse_result[i]:
                    isEmpty = False
                    self.mssg_err.append("  " + self.vulnerability_dictionary[i] + " " + str(self.analyse_result[i]))
            if isEmpty:
                self.mssg_err.append("  Уязвимостей выбранного типа не обнаружено")
            self.analyse_result = []
            self.mssg_err.append("")


from django import forms
from localflavor.br.forms import BRCNPJField

class DadosBasicosForm(forms.Form):
	user	 	= forms.CharField(label='Usuário', max_length=100, widget=forms.TextInput(
																attrs={
																	"value":"user.username"
																}
															)
														)
	email 		= forms.EmailField(label='E-mail', max_length=100)
	firstName 	= forms.CharField(label='Nome', max_length=100)
	lastName 	= forms.CharField(label='Sobrenome', max_length=100)
#	cnpj 		= BRCNPJField(label='CNPJ', min_length=14, max_length=18)
	cnpj 		= BRCNPJField(label='CNPJ', max_length=14, widget=forms.TextInput(
																attrs={
																	"name":"cnpj",
																	"type":"text",
																	"id":"cnpj",
																	"onfocus":"javascript: retirarFormatacao(this);",
																	"onblur":"javascript: formatarCampo(this);",
																	"placeholder":"00.000.000/0000-00"
																	}
																)
															)

#	def __init__(self, *args, **kwargs):
#		user = kwargs.pop('user', None)
#		super(DadosBasicosForm, self).__init__(*args, **kwargs)
#		if user is not None:
#			self.fields['board'].queryset = Board.objects.filter(user=user)


caffe_root = '../'
image_dir = caffe_root + "working/The Oxford-IIIT Pet Dataset/"
import sys
sys.path.insert(0, caffe_root + 'python')
MEAN_FILE = caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy'
MODEL_FILE = caffe_root + 'models/bvlc_reference_caffenet/deploy_feature.prototxt'
PRETRAINED = caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'
FEAT_LAYER = 'fc6wi'

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', metavar='Inputs', type=str, default='filenames.npy',
                   help='npy filename containing image filenames')
parser.add_argument('-o', metavar='Outputs', type=str, default='features.npy',
                    help='npy filename wirtes extracted features in')
args = parser.parse_args()

import caffe
import numpy as np
caffe.set_mode_cpu()
net = caffe.Net(MODEL_FILE, PRETRAINED, caffe.TEST)
# input preprocessing: 'data' is the name of the input blob == net.inputs[0]
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
transformer.set_transpose('data', (2,0,1))
transformer.set_mean('data', np.load(MEAN_FILE).mean(1).mean(1))
transformer.set_raw_scale('data', 255)
transformer.set_channel_swap('data', (2,1,0))

features = []
IMAGE_FILES = np.load(args.i)
N = len(IMAGE_FILES)
net.blobs['data'].reshape(N,3,227,227)
for i in range(N):
    LOAD_IMAGE = image_dir + IMAGE_FILES[i]
    net.blobs['data'].data[i] = \
        transformer.preprocess('data', caffe.io.load_image(LOAD_IMAGE))
net.forward()
features = net.blobs[FEAT_LAYER].data
np.save(args.o, features)


def Autokey_cipher_encrypt(plain_text, key):
    encryptedtext = ""
    for c in plain_text:
        if c.isupper():
            index = ord(c) - ord('A')
            c_shift = (index + key) % 26 + ord('A')
            c_new = chr(c_shift)
            encryptedtext += c_new
            key = index
        elif c.islower():
            index = ord(c) - ord('a')
            c_shift = (index + key) % 26 + ord('a')
            c_new = chr(c_shift)
            encryptedtext += c_new
            key = index
        else:
            encryptedtext += c
    return encryptedtext
def Autokey_cipher_decrypt(ciphertext, key):
    decryptedtext = ""
    for c in ciphertext:
        if c.isupper():
            index = ord(c) - ord('A')
            e_position = (index - key) % 26 + ord('A')
            e = chr(e_position)
            decryptedtext += e
            key = (index - key) % 26
        elif c.islower():
            index = ord(c) - ord('a')
            e_position = (index - key) % 26 + ord('a')
            e = chr(e_position)
            decryptedtext += e
            key = (index - key) % 26
        else:
            decryptedtext += c

    return decryptedtext


from model import db, Congressperson, BillCategory, Bill
from model.helpers import remove_middle_name
from model.consts import REPRESENTATIVE_URL, CIVIC_KEY, BILL_BY_CATEGORY_URL, PROPUBLICA_KEY
from model.helpers import format_category_name
import requests

def find_representatives(user):
    """Finds the politicians that represent the user based on user's address
    :param user: user whose representatives you want to find
    :return [Congressperson]: congresspeople associated with User's address
    """

    # Retrieves json from google api to get json of local politicians
    search_address = "&address=" + user.address
    request = requests.get(REPRESENTATIVE_URL + CIVIC_KEY + search_address)
    politician_json = request.json()

    politician_info = politician_json['officials']

    # instantiate list for politicians and loop through json
    congresspeople = []
    for politician in politician_info:
        # eliminate middle names so we can find politicians based on first and last name
        name = remove_middle_name(politician['name'])

        # check if congressperson is in database, if so, add them to list
        congressperson = Congressperson.query.filter_by(name=name).first()

        if congressperson:
            congresspeople.append(congressperson)
    return congresspeople

def parse_bills_by_category(category):
    """Grabs 20 most recent bills from ProPublica api associated with specific subject/category
        :param category: Category which you want to associate bills with
        :return None: Update database with bills associated with category
    """

    # Create subject so it can be passed into REST call and place in URL
    subject = format_category_name(category)
    search_url = BILL_BY_CATEGORY_URL.replace("{subject}", subject)
    print(search_url)

    # Send request and parse it
    fill_bill_request = requests.get(search_url, headers={'X-API-Key': PROPUBLICA_KEY})
    print(fill_bill_request.text)
    bill_json = fill_bill_request.json()

    parse_bills_from_json(bill_json, category)

def parse_bills_from_json(json, category):
    """Takes bill json and category and updates database with new bill information
    :param json: Bill JSON
    :param category: Category
    :return None: updates database with new bill information
    """

    # Check to make sure there are no errors in database
    if json.get('error') or json.get('errors') or json.get('status') == "ERROR":
        print("No results found")
        return

    bills = json['results']
    for bill in bills:

        bill_id = bill['bill_id']

        # Check to see if bill already exists, if so just add new BillCategory
        if Bill.query.filter_by(bill_id=bill_id).first():
            bill_category = BillCategory(bill_id=bill_id, category_id=category.category_id)
            db.session.add(bill_category)

        # Parse JSON and get information needed
        else:
            bill_title = bill['short_title']
            bill_uri = bill['congressdotgov_url']
            summary = bill['summary']

            bill = Bill(bill_id=bill_id,
                        bill_title=bill_title,
                        bill_uri=bill_uri,
                        summary=summary,
                        )
            bill_category = BillCategory(bill_id=bill_id, category_id=category.category_id)
            db.session.add(bill_category)
            db.session.add(bill)

    db.session.commit()


def create_matrix(key):
    matrix = []
    key = key.upper().replace('J', 'I')
    alphabet = 'ABCDEFGHIKLMNOPQRSTUVWXYZȘȚĂÎÂ'
    for char in key:
        if char in alphabet and char not in matrix:
            matrix.append(char)
            alphabet = alphabet.replace(char, '')
    matrix.extend(list(alphabet))
    matrix = [matrix[i:i+6] for i in range(0, len(matrix), 6)]
    return matrix

def find_position(matrix, char):
    for i in range(6):
        for j in range(6):
            if matrix[i][j] == char:
                return i, j

def encrypt_pair(matrix, char1, char2):
    row1, col1 = find_position(matrix, char1)
    row2, col2 = find_position(matrix, char2)
    print(matrix)

    if row1 == row2:
        return matrix[row1][(col1 + 1) % 6], matrix[row2][(col2 + 1) % 6]
    elif col1 == col2:
        return matrix[(row1 + 1) % 6][col1], matrix[(row2 + 1) % 6][col2]
    else:
        return matrix[row1][col2], matrix[row2][col1]

def decrypt_pair(matrix, char1, char2):
    row1, col1 = find_position(matrix, char1)
    row2, col2 = find_position(matrix, char2)

    if row1 == row2:
        return matrix[row1][(col1 - 1) % 6], matrix[row2][(col2 - 1) % 6]
    elif col1 == col2:
        return matrix[(row1 - 1) % 6][col1], matrix[(row2 - 1) % 6][col2]
    else:
        return matrix[row1][col2], matrix[row2][col1]

def playfair_cipher(key, text, mode='encrypt', original_length=None):
    matrix = create_matrix(key)
    text = text.upper().replace('J', 'I')
    pairs = []

    for i in range(0, len(text), 2):
        pair = text[i:i + 2]
        if len(pair) < 2:
            pair += 'X'
        pairs.append(pair)

    result = []
    for pair in pairs:
        if mode == 'encrypt':
            encrypted_pair = encrypt_pair(matrix, pair[0], pair[1])
        else:
            encrypted_pair = decrypt_pair(matrix, pair[0], pair[1])
        result.append(encrypted_pair[0] + encrypted_pair[1])

    if mode == 'decrypt' and original_length is not None and original_length % 2 != 0:

        return ''.join(result)[:-1]

    return ''.join(result)

if __name__ == "__main__":
    operation = input("Choose the operation (encryption/decryption): ").strip().lower()
    key = input("Enter the key (at least 7 characters long): ")

    while len(key) < 7:
        key = input("Key is too short. Please enter a key with at least 7 characters: ")

    if operation == "encryption":
        message = input("Enter the message to encrypt: ")
        while len(message) % 2 != 0:
            message += "X"
        print("Encrypted message:", playfair_cipher(key, message))
    elif operation == "decryption":
        cryptogram = input("Enter the cryptogram to decrypt: ")
        original_length = len(cryptogram)
        while len(cryptogram) % 2 != 0:
            cryptogram += "X"
        print("Decrypted message:", playfair_cipher(key, cryptogram, mode='decrypt', original_length=original_length))
    else:
        print("Invalid operation chosen.")


# Урок 5 задание 3
# "Кто твой папа?"
# Вводим имя человека - получяем имя его отца

liste = {"Александ Македонский" : "Филипп II",  # Список сын-отец
         "Александр Дюма" : "Тома-Алексанр Дюма",
         "Чарли Чаплин" : "Чарльз Спенсер Чаплин-старший"}
choice = ''

print('Добрый день, это программа позваляет узнать имя отца интресного вам'\
      'человекa')

while choice != '0':

    print("""
    0 - Выход
    1 - Посмотреть список имён
    2 - Ввод имени сына, вывод имени отца
    3 - Добавить пару сын-отец
    4 - Изменить пару сын-отец
    5 - Удалить пару  сын-отец
    """
    )

    choice = input('Ваш выбор: ')

    # Выход
    if choice == '0':
        break

    # Список
    elif choice == '1':
        for i in liste:
            print(i, '\t --\t', liste[i])

    # Сын => отец
    elif choice == '2':
        son = input("Введите имя человека, отца которого хотите узнать: ")

        if son in liste:
            print(liste[son]) # Вывод имени отца
        else:
            print('Я не знаю его отца. Если узнаешь, то не забудь сказать')

    # Добавить пару
    elif choice == '3':
        son, father = input('Введите имя сына, а затем имя отца: '), input()

        if son not in liste:            # Если нет в списке, то добавляем
            liste[son] = father
            print('Я добавил пару ', son,'- ', father)

        else:
            print("Я знаю его отца, это ", liste[son])

    # Изменить пару
    elif choice == '4':
        son = input('Кто сын? ')
        if son in liste:
            father = input('Кто его отец? ')
            liste[son] = father
            print('Я заменил пару ', son,'- ', father)

        else:
            print('Я не знаю этого человека!')

    # Удаляем пару
    elif choice == '5':
        son = input('Кто сын? ')
        if son in liste:
            del liste[son]
            print('Ок, пара удалена.')
        else:
            print('Пара не найдена!')

    # На остальную хрень
    else:
        print("Вашего выбора нет в списке")

input('Enter для выхода')