import math
import glob
import re
import os
import logging

import os
pat = os.getcwd()
pat = pat + '\word.txt'

kgram_len_lst = []
dct_lst = {}
filename_lst = []
path = os.getcwd()

'''
List of stop words inserted in a list.
'''

f = open(pat,'r')
stop_word = set(f.read().split())
f.close()

'''
To read files to create lists. Copy them in the current directory\
and remove any other .txt files from current directory.
'''

for filename in glob.glob(os.path.join(path, '*.txt')):
	if filename != pat:
		f = open(filename,'r')
		fw = f.read()
		f.close()

		'''
		Lower casing and removing special characters. Assuming words to be\
		with alphabets, under_score and numeric characters only.
		'''

		fw = fw.lower()
		fw = re.sub(r'[^a-z0-9_ \n]', '', fw).split()

		'''
		remove stop words and make a string of all rest of the words.
		'''
		lw = []
		for i in fw:
			if i not in stop_word:
				lw.append(i)

		l = "".join(lw)

		'''
		Storing in dct_lst with file name as key an value a string.\
		Also storing filenames in a list.
		'''

		file_name = filename.split('\\')
		path_ = path.split('\\')
		file = ''
		for i in file_name:
			if i not in path_:
				file = file + i

		filename_lst.append(file)
		dct_lst[file] = l

'''
Taking k as 5 to calculate k-grams and p as 99991 to get 0-mod p.
'''
k = 5
p = 10

class finger_printing:

	def hash(x):
		'''
		Hash function to calculate hash values of k-grams.
		'''
		h = 0
		for i in range(0,5):
			h = h + (ord(x[i]))*(k**(5-i))
		return h

	def k_Gram(l):
		'''
		k gram function takes a string and returns a list of k grams \
		with length 5.
		'''
		ls = []
		for i in range(0,len(l)-4):
			ls.append(l[i:i+5])
		return ls

	def p_mod(ls):
		'''
		p mod function takes a list of hash values and gives us p mod values\
		(p = 991) list.
		'''
		pm = []
		for i in ls:
			if i%p==0:
				pm.append(i)
		return pm

	def Fngprnt(dct1, dct2, den):
		'''
		This finger print function takes two lists of p-mods and \
		and compare those to give the match percentage.
		'''
		z = 0
		i = 0
		c = 0
		for i in range(0,len(dct1)):
			k = i
			j = 0
			c = 0
			while(k<len(dct1) and j<len(dct2)):
				while ((k<len(dct1) and j<len(dct2)) and  dct1[k]==dct2[j]):
					c += 1
					k += 1
					j += 1
				if(k<len(dct1) and j<len(dct2)):
					if dct1[k] != dct2[j]:
						k = i
						if c>z:
							z = c
						c = 0
						if dct1[k]!=dct2[j]:
							j += 1
			if c>z:
				z = c
		if c>z:
			z = c
		return ((2*z)/(den))

'''
Converting strings to k-grams.
'''
for i in dct_lst:
	dct_lst[i] = finger_printing.k_Gram(dct_lst[i])
	kgram_len_lst.append(len(dct_lst[i]))

'''
Converting k-grams to hashes.
'''
for i in dct_lst:
	for j in range(0,len(dct_lst[i])):
		dct_lst[i][j] = finger_printing.hash(dct_lst[i][j])

'''
Stores signatures in lists for each file.
'''
for i in dct_lst:
	dct_lst[i] = finger_printing.p_mod(dct_lst[i])

'''
Compare file signatures as Longest common sequence.
'''
p = ''
for i in range(0,(len(filename_lst)-1)):
	for j in range((i+1),len(filename_lst)):
		try:
			d = kgram_len_lst[i] + kgram_len_lst[j]
			s = ('Fingerprint match between '+str(filename_lst[i])+' and '+str(filename_lst[j])+\
				' is: '+str(finger_printing.Fngprnt(dct_lst[filename_lst[i]],\
				 dct_lst[filename_lst[j]],d)*100))
		except ZeroDivisionError:
			s = (str(filename_lst[i])+' and '+str(filename_lst[j])+' are either empty or are too small with little length.')
		p = p + '\n' + s + '\n'

'''
Loging into a log file.txt
'''

log = "log file.log"
logging.basicConfig(filename=log,level=logging.DEBUG,\
	format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %H:%M:%S')
logging.info('FINGER PRINT SIMILARITIES \n' + p)

print(p)


import cv2 as cv
import numpy as np
import sys
# 白黒に閾値処理するプログラム
def main():
    # ファイルを読み込み
    image_file = 'fig/ipad.png'
    src = cv.imread(image_file, cv.IMREAD_COLOR)
    # イメージを読み込めなかった場合
    if image_file is None:
        sys.exit("File not found.")
    # グレースケール化
    img_gray = cv.cvtColor(src, cv.COLOR_RGB2GRAY)
    # しきい値指定によるフィルタリング
    retval, dst = cv.threshold(img_gray, 127, 255, cv.THRESH_TOZERO_INV )
    cv.imwrite('fig/debug_1.png', dst)
    # 白黒の反転
    dst = cv.bitwise_not(dst)
    cv.imwrite('fig/debug_2.png', dst)
    # 再度フィルタリング
    retval, dst = cv.threshold(dst, 0, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)
    # 結果を保存
    cv.imwrite('fig/result.png', dst)

    # 角検出
    src = 255 - src
    gray = cv.cvtColor(src,cv.COLOR_BGR2GRAY)
    gray= np.float32(gray)

    # Detect corner
    dst = cv.cornerHarris(gray,2,9,0.16)

    # Expand corner
    # dst = cv.dilate(dst, None)

    # Draw red points
    src[dst>0.01*dst.max()]= [0,0,255]

    # Detect red pixel
    coord = np.where(np.all(src == (0, 0, 255), axis=-1))

    # Print coordinate
    for i in range(len(coord[0])):
        print("X:%s Y:%s"%(coord[1][i],coord[0][i]))

    cv.imshow('imgWithCorner',src)
    cv.waitKey(0)

    # 画像のサイズを取得
    global height
    global width
    height, width, channels = src.shape[:3]
    print("width: " + str(width))
    print("height: " + str(height))

# 最初に当たる黒い部分を探す関数
def search():
    img = cv.imread('fig/result.png')

    for i in range(width):
        for j in range(height):
            pixelValue = img[i, j]
            if (pixelValue == [0,0,0]).all():
                kadoX = i
                kadoY = j
            # print('座標[{},{}] = '.format(i,j) + str(pixelValue))
                print(kadoX,kadoY)
    # else:
        # 格納した角の値をprint

if __name__ == '__main__':
    main()
    # search()


# Importing libraries
import pyautogui as notification
import schedule
import time
import os
from colorama import Fore, Style, init

# Initialization for the colorama lib
init(autoreset=True)

def script():
	# Defining the alert function
	def alert(message):
		# Printing text on screen
		print(Fore.GREEN + Style.BRIGHT + "[+] Notification Sent")
		# Sending the notification
		notification.alert(text=message, title="Notification System by Arshan")

	# Defining main function
	def main():
		# Loops as long as "False" isn't returned
		while True:
			# Runs any scheduled tasks
			schedule.run_pending()
			# Interval
			time.sleep(1)

	# Storing user input as variable
	messageToShow = input(Fore.YELLOW + Style.BRIGHT + "[?] Notification Message: ")

	# If variable is empty then exit the script with a message
	if messageToShow == "":
		print(Fore.RED + Style.BRIGHT + "[-] Please enter a valid value")
		exit()
	elif messageToShow == " ":
		print(Fore.RED + Style.BRIGHT + "[-] Please enter a valid value")
		exit()

	amountOfTimeToWait = input(Fore.YELLOW + Style.BRIGHT + "[?] Run every: ")
	if amountOfTimeToWait == "":
		print(Fore.RED + Style.BRIGHT + "[-] Please enter a valid value")
		exit()
	elif amountOfTimeToWait == " ":
		print(Fore.RED + Style.BRIGHT + "[-] Please enter a valid value")
		exit()
	# Clear screen, tries to run the 'cls' command and if it fails it runs the 'clear' command
	# 'cls' clears the screen on windows computers while 'clear' works on unix based systems such as linux
	os.system("cls;clear")

	# Checking if string is in variable
	if "second" in amountOfTimeToWait:
		# Fetches any numbers inside string
		time1 = int(''.join(char for char in amountOfTimeToWait if char.isdigit()))
		# Takes the number in string and converts it to a integer and then runs the scheduler
		schedule.every(int(time1)).seconds.do(alert, messageToShow)
		# Prints message
		print(Fore.MAGENTA + Style.BRIGHT + "[!] Every " + amountOfTimeToWait + " the message '" + messageToShow + "' will be displayed")
		# Runs main function
		main()
	elif "minute" in amountOfTimeToWait:
		time2 = int(''.join(char for char in amountOfTimeToWait if char.isdigit()))
		schedule.every(int(time2)).minutes.do(alert, messageToShow)
		print(Fore.MAGENTA + Style.BRIGHT + "[!] Every " + amountOfTimeToWait + " the message '" + messageToShow + "' will be displayed")
		main()
	elif "hour" in amountOfTimeToWait:
		time3 = int(''.join(char for char in amountOfTimeToWait if char.isdigit()))
		schedule.every(int(time3)).hours.do(alert, messageToShow)
		print(Fore.MAGENTA + Style.BRIGHT + "[!] Every " + amountOfTimeToWait + " the message '" + messageToShow + "' will be displayed")
		main()
	else:
		print(Fore.RED + Style.BRIGHT + "[-] Please enter a valid time")
		exit()

if __name__ == '__main__':
    try:
        script()
    except KeyboardInterrupt:
        os.system("cls;clear")
        print(Fore.RED + Style.BRIGHT + "[!] Exiting")


# -*- coding: utf-8 -*-
"""
Created on Fri Apr 20 11:36:42 2018

@author: admin
"""
def gcd(a,b):
    if a!=0 and b!=0 and a>b:
        return gcd(b,a%b)
    elif a!=0 and b!=0 and a<=b:
        return gcd(a,b%a)
    elif a==0 or b==0:
        if a==0:
            return b
        else:
            return a
def swap(a,b):
    return (b,a)

T=int(input())
out=list()
for i in range(T):
    M,N,x,y=map(int,input().split(' '))
    g=gcd(M,N)
    end=int((M*N)/g)
    if M>N:
        M,N=swap(M,N)
        x,y=swap(x,y)
    if x>=N: out.append(-1)
    else:
        count=x
        j=x
        while count < end and j != y:
            j+=M
            count+=M
            if j>N : j=j%N
        if end<count or (j!=y and end==count): out.append(-1)
        else:
            out.append(count)

for p in out:
    print(p)


from django.apps import apps as django_apps

class RequisitionPanelError(Exception):
    pass

class RequisitionPanelModelError(Exception):
    pass

class InvalidProcessingProfile(Exception):
    pass

class Names:

    def __init__(self, name=None, alpha_code=None):
        self.abbreviation = f'{name[0:2]}{name[-1:]}'.upper()
        title = ' '.join(name.split('_')).title()
        alpha_code = alpha_code or ''
        self.verbose_name = f'{title} {alpha_code} {self.abbreviation}'.replace(
            '  ', ' ')

class RequisitionPanel:

    """A panel class that contains processing profile instances.
    """

    names_cls = Names
    requisition_model = None  # set by lab profile.add_panel
    lab_profile_name = None  # set by lab profile.add_panel
    panel_model = 'edc_lab.panel'

    def __init__(self, name=None, aliquot_type=None, processing_profile=None,
                 verbose_name=None, abbreviation=None, **kwargs):
        self._panel_model_obj = None
        self.aliquot_type = aliquot_type
        self.verbose_name = None
        self.name = name
        try:
            names = self.names_cls(
                name=name, alpha_code=self.aliquot_type.alpha_code, **kwargs)
        except AttributeError as e:
            raise RequisitionPanelError(f'{self}. Got {e}.')
        self.abbreviation = abbreviation or names.abbreviation
        self.verbose_name = verbose_name or names.verbose_name
        self.processing_profile = processing_profile
        if self.processing_profile:
            if self.aliquot_type != self.processing_profile.aliquot_type:
                raise InvalidProcessingProfile(
                    f'Invalid processing profile for panel \'{self}\'. '
                    f'Got processing profile \'{self.processing_profile}\'')

    def __repr__(self):
        return f'{self.__class__.__name__}({self.name}, {self.aliquot_type})'

    def __str__(self):
        return self.verbose_name or self.name

    @property
    def panel_model_cls(self):
        return django_apps.get_model(self.panel_model)

    @property
    def panel_model_obj(self):
        """Returns the underlying panel model instance.
        """
        if not self._panel_model_obj:
            self._panel_model_obj = self.panel_model_cls.objects.get(
                name=self.name, lab_profile_name=self.lab_profile_name)
        return self._panel_model_obj

    @property
    def pk(self):
        """Returns the PK as a UUID() fo the underlying
        panel model instance.
        """
        return self.panel_model_obj.pk

    @property
    def requisition_model_cls(self):
        """Returns the requisition model associated with this
        panel by it's lab profile.
        """
        try:
            requisition_model_cls = django_apps.get_model(
                self.requisition_model)
        except (ValueError, AttributeError, LookupError):
            raise RequisitionPanelModelError(
                f'Invalid requisition model. Got {self.requisition_model}. '
                f'See {repr(self)} or the lab profile {self.lab_profile_name}.')
        return requisition_model_cls

    @property
    def numeric_code(self):
        return self.aliquot_type.numeric_code

    @property
    def alpha_code(self):
        return self.aliquot_type.alpha_code

# TODO: panel should have some relation to the interface, e.g. a mapping of test_code to test_code on interface
#       for example CD4% = cd4_perc or VL = AUVL, VL = PMH


from machine import Pin
from neopixel import NeoPixel
import urequests
import time

np = NeoPixel(Pin(13), 1) # D7

def get_next():
    resp = urequests.get('http://bindicator-api.robberwick.com')
    data = resp.json()
    resp.close()
    return data

def update():
    print('fetching...')
    data = get_next()
    print('fetched:', data)
    colour = (0,0,0)

    if data['isDue']:
        colour = (0,255,0) if data['service'].lower() == 'recycling' else (255,0,0)

    np.fill(colour)
    np.write()

while True:
    update()
    time.sleep(3600)


class student:
    def __init__(self,name,grade,number):
        self.name = name
        self.grade = grade
        self.number = number

    def __repr__(self):
        return repr((self.name, self.grade, self.number))

students = [
        student('홍길동',3.9,20165232),
        student('김범수',3.0,20165231),
        student('김지쿡',4.3,20165230),
        ]
b=sorted(students,key=lambda student:student.number)
print(b)


import torch
from torch import nn
from torch.nn import functional as F
from torch.nn import init
import numpy as np
from pprint import pprint

from .Backbone import Backbone

from ..Component.sync_batchnorm.batchnorm import SynchronizedBatchNorm2d
BatchNorm2d = SynchronizedBatchNorm2d
BN_MOMENTUM = 0.01

class RGB2DepthNet(nn.Module):
    def __init__(self, config):
        super().__init__()
        extra = config.MODEL.EXTRA

        self.encoder = Backbone(config, 3)
        self.inplanes = self.encoder.last_stage_channels
        last_inp_channels = np.int(np.sum(np.asarray(self.inplanes)))

        self.last_layer = nn.Sequential(
            nn.Conv2d(
                in_channels=last_inp_channels,
                out_channels=last_inp_channels,
                kernel_size=1,
                stride=1,
                padding=0),
            BatchNorm2d(last_inp_channels, momentum=BN_MOMENTUM),
            nn.ReLU(inplace=False),
            nn.Conv2d(
                in_channels=last_inp_channels,
                out_channels=1,
                kernel_size=extra.FINAL_CONV_KERNEL,
                stride=1,
                padding=1 if extra.FINAL_CONV_KERNEL == 3 else 0),
            nn.Sigmoid()
        )

    def forward(self, rgb):
        ori_h, ori_w = rgb.shape[2], rgb.shape[3]

        x = self.encoder(rgb)

        # Upsampling 4 times
        x0_h, x0_w = x[0].size(2), x[0].size(3)
        x1 = F.interpolate(x[1], size=(x0_h, x0_w), mode='bilinear', align_corners=True)
        x2 = F.interpolate(x[2], size=(x0_h, x0_w), mode='bilinear', align_corners=True)
        x3 = F.interpolate(x[3], size=(x0_h, x0_w), mode='bilinear', align_corners=True)

        x = torch.cat([x[0], x1, x2, x3], 1)
        x = self.last_layer(x)

        x = F.interpolate(x, size=(ori_h, ori_w), mode='bilinear', align_corners=True)

        return x

    def init_weights(self, pretrained = ''):
        pprint('=> init weights from Gaussion distribution')
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.normal_(m.weight, std=0.001)
            elif isinstance(m, SynchronizedBatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
        pprint('=> init weights from ImageNet pretraining')
        pprint('=> init weights for encoder(rgb2depth)')
        self.encoder.init_weights(pretrained)


import psycopg2
import pandas as pd

def createTable(table_name, conn):
    cur = conn.cursor()
    create_table_query = "CREATE TABLE " +  table_name + ''' (
                            ticket_id INT,
                            trans_date DATE,
                            event_id INT,
                        	event_name VARCHAR(150),
                        	event_date DATE,
                        	event_type VARCHAR(100),
                        	event_city VARCHAR(100),
                        	customer_id INT,
                        	price DECIMAL,
                        	num_tickets INT
                        )'''
    cur.execute(create_table_query)
    conn.commit() # save changes in database
    print("Table created")

def insertIntoTable(conn, row_to_input, table):
    '''
    row_to_input should be a tuple following this format:
    (1, '2020-08-01', 100, 'The North American International Auto Show', '2020-09-01', 'Exhibition', 'Michigan', 123, 35.0, 3)
    (2, '2020-08-03', 101, 'Carlisle Ford Nationals', '2020-09-30', 'Exhibition', 'Carlisle', 151, 43.0, 1)
    (3, '2020-08-03', 102, 'Washington Spirits vs Sky Blue FC', '2020-08-30', 'Sports', 'Washington DC', 223, 59.34, 5)
    ...
    '''
    cur = conn.cursor()
    insert_value_query = "INSERT INTO " + table + " VALUES " + str(row_to_input)
    cur.execute(insert_value_query)
    conn.commit() # save changes in database

def insertCSVIntoTable(conn, table, file):
    # Importing the file
    raw_data = pd.read_csv(file, header=None)

    # Adding a header to the dataframde for a better visualization
    raw_data.columns = (['ticket_id',
                         'trans_date',
                         'event_id',
                         'event_name',
                         'event_date',
                         'event_type',
                         'event_city',
                         'customer_id',
                         'price',
                         'num_tickets'])

    # Creating the tuple to be inserted in the database
    for row_number in range (0, len(raw_data)):
        row_to_input = (
            raw_data['ticket_id'][row_number],
            raw_data['trans_date'][row_number],
            raw_data['event_id'][row_number],
            raw_data['event_name'][row_number],
            raw_data['event_date'][row_number],
            raw_data['event_type'][row_number],
            raw_data['event_city'][row_number],
            raw_data['customer_id'][row_number],
            raw_data['price'][row_number],
            raw_data['num_tickets'][row_number]
        )
        insertIntoTable(conn, row_to_input, table)
    print("CSV file imported successfully")

def get_most_popular(conn, field, table):
    cur = conn.cursor()
    get_most_popular_query = "SELECT " + field + ", COUNT(ticket_id) ticket_count FROM " + table + " GROUP BY " + field + " ORDER BY COUNT(ticket_id) DESC"
    cur.execute(get_most_popular_query)
    results = cur.fetchall()
    print("Here are the most popular events")
    print(results)
    return results


# pylint: disable=no-self-use,invalid-name
import pytest

from allennlp.common import Params
from allennlp.common.util import ensure_list
from allennlp.data.dataset_readers import BabiReader
from allennlp.common.testing import AllenNlpTestCase

class TestBAbIReader:
    @pytest.mark.parametrize('keep_sentences, lazy', [(False, False), (False, True), (True, False), (True, True)])
    def test_read_from_file(self, keep_sentences, lazy):
        reader = BabiReader(keep_sentences=keep_sentences, lazy=lazy)
        instances = ensure_list(reader.read(AllenNlpTestCase.FIXTURES_ROOT / 'data' / 'babi.txt'))
        assert len(instances) == 8

        if keep_sentences:
            assert [t.text for t in instances[0].fields['context'][3].tokens[3:]] == ['of', 'wolves', '.']
            assert [t.sequence_index for t in instances[0].fields['supports']] == [0, 1]
        else:
            assert [t.text for t in instances[0].fields['context'].tokens[7:9]] == ['afraid', 'of']

    def test_can_build_from_params(self):
        reader = BabiReader.from_params(Params({'keep_sentences': True}))
        # pylint: disable=protected-access
        assert reader._keep_sentences
        assert reader._token_indexers['tokens'].__class__.__name__ == 'SingleIdTokenIndexer'


'''REVERSE GROUPS

Given a list of numbers and a positive integer k, reverse the elements of the
list, k items at a time. If the number of elements is not a multiple of k, then
the remaining items in the end should be left as is.

INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. Each line
in this file contains a list of numbers and the number k, separated by a
semicolon. The list of numbers are comma delimited. E.g.

1,2,3,4,5;2
1,2,3,4,5;3

OUTPUT SAMPLE:
Print out the new comma separated list of numbers obtained after reversing. E.g.

2,1,4,3,5
3,2,1,4,5
'''
def f(test='1,2,3,4,5;2'):
    test = test.rstrip().split(';')
    sequence = test[0].split(',')
    length = int(test[1])
    result = ""
    for index in range(0, len(sequence), length):
        if index + length > len(sequence):
            result+= ','.join(sequence[index:]) + 'X'
            break
        for reverse in range(index + length - 1, index - 1, -1):
            result+= sequence[reverse] + ','
    print(result[:-1])


from sys import stdin
input = stdin.readline

n = int(input())
a = 1
t = 1
while True:
    a = a + ((t - 1) * 6)
    if n <= a:
        break
    else:
        t += 1
print(t)


with open('day14.txt') as file:
    lines = [line.strip() for line in file.readlines() if len(line.strip()) > 0]
    template = lines[0]
    rules = {}
    for line in lines[1:]:
        left, right = line.split(' -> ')
        rules[left] = right

def add(dict, item, count=1):
    if item not in dict:
        dict[item] = count
    else:
        dict[item] += count

def polymer_from_template(template):
    polymer = {}
    n = len(template)
    for i in range(n - 1):
        pair = template[i:i+2]
        add(polymer, pair)
    return polymer

def step(polymer, rules):
    output = {}
    for pair in polymer:
        count = polymer[pair]
        if pair in rules:
            new = rules[pair]
            add(output, pair[0] + new, count)
            add(output, new + pair[1], count)
        else:
            add(output, pair, count)
    return output

def order_counts_by_frequency(polymer):
    chars = {}
    for pair in polymer:
        count = polymer[pair]
        add(chars, pair[0], count)
        add(chars, pair[1], count)
    counts = []
    for char in chars:
        counts.append((chars[char] + 1) // 2) # Not sure why we round up, but I get a wrong answer without that so...
    return sorted(counts, reverse=True)

def answer(polymer, rules, count):
    for i in range(count):
        polymer = step(polymer, rules)
    counts = order_counts_by_frequency(polymer)
    return counts[0] - counts[-1]

polymer = polymer_from_template(template)
print('Part 1:', answer(polymer, rules, 10))
print('Part 2:', answer(polymer, rules, 40))


A = [23171, 21011, 21123, 21366, 21013, 21367]

def solution(A):
    n = len(A)
    A.reverse()
    max = 0
    profit = 0
    tmp_profit = 0
    for k in range(n):
        max = A[k]
        for j in range(k, n-k):
            tmp_profit = max - A[j]
            if tmp_profit > profit:
                profit = tmp_profit
    return profit

sol = solution(A)
print(sol)


from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials

from array import array
import os
from PIL import Image
import sys
import time
import json

mcv_configuration_path = 'input/mcv_configuration.json'

'''
Authenticate
Authenticates your credentials and creates a client.
'''
subscription_key = ""
endpoint = ""

if not os.path.exists(mcv_configuration_path):
    raise RuntimeError(mcv_configuration_path + ' file is missing!')
else:
    with open(mcv_configuration_path) as f:
        config = json.load(f)
        subscription_key = config['subscriptionKey']
        endpoint = config['endpoint']

if len(subscription_key.strip()) == 0 or len(endpoint.strip()) == 0:
    raise RuntimeError('Microsoft Computer Vision Subscription key or Endpoint is missing, make sure that you have an mcv_configuration.json created!')

computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))

print('Initialized Microsoft Computer Vision.')

'''
OCR: Read File using the Read API, extract text - local
This example will extract text in an image, then print results, line by line.
This API call can also extract handwriting style text (not shown).
'''
def analyze_image(image_file_path):

    # Get an image with text
    image_file = open(image_file_path, 'rb')
    # Call API with URL and raw response (allows you to get the operation location)
    read_response = computervision_client.read_in_stream(image_file, raw=True)

    # Get the operation location (URL with an ID at the end) from the response
    read_operation_location = read_response.headers["Operation-Location"]
    # Grab the ID from the URL
    operation_id = read_operation_location.split("/")[-1]

    # Call the "GET" API and wait for it to retrieve the results
    while True:
        read_result = computervision_client.get_read_result(operation_id)
        if read_result.status not in ['notStarted', 'running']:
            break
        time.sleep(1)

    # Print the detected text, line by line
    if read_result.status == OperationStatusCodes.succeeded:
        return read_result.analyze_result
    return None


from pprint import pprint as pp
from collections import defaultdict
import sys
sys.setrecursionlimit(10 ** 7)
readlines = sys.stdin.buffer.readlines
map_readlines = lambda: map(int, readlines())
readline = sys.stdin.buffer.readline
map_readline = lambda: map(int, readline().split())
sreadline = lambda: readline().decode("utf-8").rstrip()

if __name__ == "__main__":
    a, b = map_readline()
    if (a * b) % 2 == 0:
        print("Even")
    else:
        print("Odd")
    """
    input_str = readline()
    input_num = int(readline())
    some_map = map_readline()
    data = sreadline().split(" ")
    data = list(sreadline())
    sreadlines = [sb.decode("utf-8").rstrip() for sb in readlines()]
    """


import os
import json

from qgis.PyQt import QtWidgets, uic
from qgis.core import QgsProject
from qgis.PyQt.QtGui import QDesktopServices

from qgis.PyQt.QtCore import pyqtSignal, QUrl
from qgis.utils import iface

from .api import endpoints
from .utils import (
    get_layer_config,
    sdo_to_layer,
    get_epsg_from_tm3_zone,
    readSetting
)

FORM_CLASS, _ = uic.loadUiType(
    os.path.join(os.path.dirname(__file__), "../ui/import_wilayah_admin.ui")
)

class ImportWilayahAdmin(QtWidgets.QDialog, FORM_CLASS):
    """Dialog for Peta Bidang"""

    closingPlugin = pyqtSignal()

    def __init__(self, parent=iface.mainWindow()):
        super(ImportWilayahAdmin, self).__init__(parent)
        self.setupUi(self)

        self._srid_code = [
            23830,
            23831,
            23832,
            23833,
            23834,
            23835,
            23836,
            23837,
            23838,
            23839,
            23840,
            23841,
            23842,
            23843,
            23844,
            23845
        ]
        self._kantor_id = ""
        self._tipe_kantor_id = ""

        self.cmb_propinsi.currentIndexChanged.connect(self._cmb_propinsi_selected_index_changed)
        self.cmb_kabupaten.currentIndexChanged.connect(self._cmb_kabupaten_selected_index_changed)
        self.cmb_kecamatan.currentIndexChanged.connect(self._cmb_kecamatan_selected_index_changed)
        self.btn_download_propinsi_terpilih.clicked.connect(self._download_propinsi_terpilih_click)
        self.btn_download_kabupaten_terpilih.clicked.connect(self._download_kabupaten_terpilih_click)
        self.btn_download_kecamatan_terpilih.clicked.connect(self._download_kecamatan_terpilih_click)
        self.btn_download_desa_terpilih.clicked.connect(self._download_desa_terpilih_click)
        self.btn_download_kabupatens.clicked.connect(self._btn_download_kabupatens_click)
        self.btn_download_kecamatans.clicked.connect(self._btn_download_kecamatans_click)
        self.btn_download_desas.clicked.connect(self._btn_download_desas_click)

    def closeEvent(self, event):
        self.closingPlugin.emit()
        event.accept()

    def setup_workpanel(self):
        kantor = readSetting("kantorterpilih", {})
        if not kantor:
            QtWidgets.QMessageBox.warning(
                None, "GeoKKP", "Pilih lokasi kantor lebih dahulu"
            )
            self.close()
            return

        self._kantor_id = kantor["kantorID"]
        self._tipe_kantor_id = str(kantor["tipeKantorId"])

        self.cmb_coordinate_system.clear()
        self.cmb_coordinate_system.addItem("46.2")
        self.cmb_coordinate_system.addItem("47.1")
        self.cmb_coordinate_system.addItem("47.2")
        self.cmb_coordinate_system.addItem("48.1")
        self.cmb_coordinate_system.addItem("48.2")
        self.cmb_coordinate_system.addItem("49.1")
        self.cmb_coordinate_system.addItem("49.2")
        self.cmb_coordinate_system.addItem("50.1")
        self.cmb_coordinate_system.addItem("50.2")
        self.cmb_coordinate_system.addItem("51.1")
        self.cmb_coordinate_system.addItem("51.2")
        self.cmb_coordinate_system.addItem("52.1")
        self.cmb_coordinate_system.addItem("52.2")
        self.cmb_coordinate_system.addItem("53.1")
        self.cmb_coordinate_system.addItem("53.2")
        self.cmb_coordinate_system.addItem("54.1")

        self._set_cmb_propinsi()

    def _cmb_propinsi_selected_index_changed(self):
        self._set_cmb_kabupaten()

    def _cmb_kabupaten_selected_index_changed(self):
        self._set_cmb_kecamatan()

    def _cmb_kecamatan_selected_index_changed(self):
        self._set_cmb_desa()

    def _set_cmb_propinsi(self):
        response = endpoints.get_provinsi_by_kantor(
            self._kantor_id, self._tipe_kantor_id
        )
        prop_dataset = json.loads(response.content)

        self.cmb_propinsi.clear()
        for prop in prop_dataset["PROPINSI"]:
            self.cmb_propinsi.addItem(prop["PROPNAMA"], prop["PROPINSIID"])

    def _set_cmb_kabupaten(self):
        selected_prov = self.cmb_propinsi.currentData()
        response = endpoints.get_kabupaten_by_kantor(
            self._kantor_id, self._tipe_kantor_id, selected_prov
        )
        kabu_dataset = json.loads(response.content)

        self.cmb_kabupaten.clear()
        for kab in kabu_dataset["KABUPATEN"]:
            self.cmb_kabupaten.addItem(kab["KABUNAMA"], kab["KABUPATENID"])

    def _set_cmb_kecamatan(self):
        selected_kab = self.cmb_kabupaten.currentData()
        response = endpoints.get_kecamatan_by_kantor(
            self._kantor_id, self._tipe_kantor_id, selected_kab
        )
        keca_dataset = json.loads(response.content)

        self.cmb_kecamatan.clear()
        for kec in keca_dataset["KECAMATAN"]:
            self.cmb_kecamatan.addItem(kec["KECANAMA"], kec["KECAMATANID"])

    def _set_cmb_desa(self):
        selected_kec = self.cmb_kecamatan.currentData()
        response = endpoints.get_desa_by_kantor(
            self._kantor_id, self._tipe_kantor_id, selected_kec
        )
        desa_dataset = json.loads(response.content)

        self.cmb_desa.clear()
        for des in desa_dataset["DESA"]:
            self.cmb_desa.addItem(des["DESANAMA"], des["DESAID"])

    def _download_propinsi_terpilih_click(self):
        wilayah_id = self.cmb_propinsi.currentData()
        srid = self.cmb_coordinate_system.currentIndex()
        srs = str(self._srid_code[srid])
        response = endpoints.unduh_wilayah_sdo(wilayah_id, srs, "Propinsi")
        response_json = json.loads(response.content)

        zone = srs.replace("TM3-", "")
        epsg = get_epsg_from_tm3_zone(zone)
        layer_config = get_layer_config("010200")
        if response_json["wilayahs"]:
            sdo_to_layer(
                response_json["wilayahs"],
                name=layer_config["Nama Layer"],
                symbol=layer_config["Style Path"],
                crs=epsg,
                coords_field="boundary",
            )

    def _download_kabupaten_terpilih_click(self):
        wilayah_id = self.cmb_kabupaten.currentData()
        srid = self.cmb_coordinate_system.currentIndex()
        srs = str(self._srid_code[srid])
        response = endpoints.unduh_wilayah_sdo(wilayah_id, srs, "Kabupaten")
        response_json = json.loads(response.content)
        # print(response_json)

        zone = srs.replace("TM3-", "")
        epsg = get_epsg_from_tm3_zone(zone)
        layer_config = get_layer_config("010300")
        if response_json["wilayahs"]:
            sdo_to_layer(
                response_json["wilayahs"],
                name=layer_config["Nama Layer"],
                symbol=layer_config["Style Path"],
                crs=epsg,
                coords_field="boundary",
            )

    def _download_kecamatan_terpilih_click(self):
        wilayah_id = self.cmb_kecamatan.currentData()
        srid = self.cmb_coordinate_system.currentIndex()
        srs = str(self._srid_code[srid])
        response = endpoints.unduh_wilayah_sdo(wilayah_id, srs, "Kecamatan")
        response_json = json.loads(response.content)

        zone = srs.replace("TM3-", "")
        epsg = get_epsg_from_tm3_zone(zone)
        layer_config = get_layer_config("010400")
        if response_json["wilayahs"]:
            sdo_to_layer(
                response_json["wilayahs"],
                name=layer_config["Nama Layer"],
                symbol=layer_config["Style Path"],
                crs=epsg,
                coords_field="boundary",
            )

    def _download_desa_terpilih_click(self):
        wilayah_id = self.cmb_desa.currentData()
        srid = self.cmb_coordinate_system.currentIndex()
        srs = str(self._srid_code[srid])
        response = endpoints.unduh_wilayah_sdo(wilayah_id, srs, "Desa")
        response_json = json.loads(response.content)

        zone = srs.replace("TM3-", "")
        epsg = get_epsg_from_tm3_zone(zone)
        layer_config = get_layer_config("010500")
        if response_json["wilayahs"]:
            sdo_to_layer(
                response_json["wilayahs"],
                name=layer_config["Nama Layer"],
                symbol=layer_config["Style Path"],
                crs=epsg,
                coords_field="boundary",
            )

    def _btn_download_kabupatens_click(self):
        wilayah_ids = [self.cmb_kabupaten.itemData(i) for i in range(self.cmb_kabupaten.count())]
        srid = self.cmb_coordinate_system.currentIndex()
        srs = str(self._srid_code[srid])

        sdos = []
        for wilayah_id in wilayah_ids:
            response = endpoints.unduh_wilayah_sdo(wilayah_id, srs, "Kabupaten")
            response_json = json.loads(response.content)
            sdos += response_json["wilayahs"]

        zone = srs.replace("TM3-", "")
        epsg = get_epsg_from_tm3_zone(zone)
        layer_config = get_layer_config("010300")
        if sdos:
            sdo_to_layer(
                sdos,
                name=layer_config["Nama Layer"],
                symbol=layer_config["Style Path"],
                crs=epsg,
                coords_field="boundary",
            )

    def _btn_download_kecamatans_click(self):
        wilayah_ids = [self.cmb_kecamatan.itemData(i) for i in range(self.cmb_kecamatan.count())]
        srid = self.cmb_coordinate_system.currentIndex()
        srs = str(self._srid_code[srid])

        sdos = []
        for wilayah_id in wilayah_ids:
            response = endpoints.unduh_wilayah_sdo(wilayah_id, srs, "Kecamatan")
            response_json = json.loads(response.content)
            sdos += response_json["wilayahs"]

        zone = srs.replace("TM3-", "")
        epsg = get_epsg_from_tm3_zone(zone)
        layer_config = get_layer_config("010400")
        if sdos:
            sdo_to_layer(
                sdos,
                name=layer_config["Nama Layer"],
                symbol=layer_config["Style Path"],
                crs=epsg,
                coords_field="boundary",
            )

    def _btn_download_desas_click(self):
        wilayah_ids = [self.cmb_desa.itemData(i) for i in range(self.cmb_desa.count())]
        srid = self.cmb_coordinate_system.currentIndex()
        srs = str(self._srid_code[srid])

        sdos = []
        for wilayah_id in wilayah_ids:
            response = endpoints.unduh_wilayah_sdo(wilayah_id, srs, "Desa")
            response_json = json.loads(response.content)
            sdos += response_json["wilayahs"]

        zone = srs.replace("TM3-", "")
        epsg = get_epsg_from_tm3_zone(zone)
        layer_config = get_layer_config("010500")
        if sdos:
            sdo_to_layer(
                sdos,
                name=layer_config["Nama Layer"],
                symbol=layer_config["Style Path"],
                crs=epsg,
                coords_field="boundary",
            )


#!/usr/bin/env python
# -*- encoding: utf-8

import collections

from helpers import get_all_works, save_tally_to_path

if __name__ == '__main__':
    tally_image = collections.Counter()
    tally_presentation = collections.Counter()
    tally_any = collections.Counter()

    for work in get_all_works():
        for it in work["items"]:
            digital_locations = [
                loc
                for loc in it["locations"]
                if loc["type"] == "DigitalLocation"
            ]

            tally_any[len(digital_locations)] += 1

            iiif_image = [
                loc
                for loc in digital_locations
                if loc["locationType"]["id"] == "iiif-image"
            ]

            tally_image[len(iiif_image)] += 1

            iiif_presentation = [
                loc
                for loc in digital_locations
                if loc["locationType"]["id"] == "iiif-presentation"
            ]

            tally_presentation[len(iiif_presentation)] += 1

    save_tally_to_path(
        name="digitised_images--any",
        tally=tally_any,
        headings=["# of digitised images", "# of works"]
    )

    save_tally_to_path(
        name="digitised_images--iiif-image",
        tally=tally_image,
        headings=["# of iiif-image items", "# of works"]
    )

    save_tally_to_path(
        name="digitised_images--iiif-presentation",
        tally=tally_presentation,
        headings=["# of iiif-presentation items", "# of works"]
    )


my_list = []
value = 0
a = eval(input("Enter value to be included in average(-999 quits):\n"))
while (a != -999):
    my_list = my_list + [a]
    a = eval(input("Enter a value to be included in average(-999 quits):\n"))

b = len(my_list)
if b != 0:
    for x in range(b):
        value = value + my_list[x]
    print("Your average is:", value/b)

    F = input("Do you want to see the numbers you averaged?\n")
    if F == "yes" or F == "Yes" or F == "y":
        print(my_list)

else:
    print("No values were entered(-999 quits)")


from PIL import Image
import os, sys

def topng(path):
    for dirpath, dirs, files in os.walk(path):
        #ignore finished files
        if "finished" in dirs:
            dirs.remove("finished")
        for file in files:
            try:
                imgpath = os.path.join(dirpath, file)
                im = Image.open(imgpath)
                alpha = im.split()[-1]
                if not im.mode == 'RGB':
                    print("convert to png…" + imgpath)
                    rgb_im = im.convert('RGB')
                    rgb_im.putalpha(alpha)
                    rgb_im.save(imgpath, "png")
                    # Rename the file from PNG to JPG
                    thisFile = imgpath
                    base = os.path.splitext(thisFile)[0]
                    os.rename(thisFile, base + ".png")
            except:
                pass
    print("\n所有图片修改为PNG\n")


import base64
import locale
import sys

"""
def encoder(content):
    print('編碼類型：{:10}|{}'.format('default',content.encode()))
    print('編碼類型：{:10}|{}'.format('UTF-8',content.encode(encoding='utf8')))
    print('編碼類型：{:10}|{}'.format('UTF-16',content.encode(encoding='utf16')))
    print('編碼類型：{:10}|{}'.format('UTF-32',content.encode(encoding='utf32')))
    print('編碼類型：{:10}|{}'.format('cp950',content.encode(encoding='cp950')))
"""
"""
def encoder(content):

    enc = ['utf8','utf32','cp950']
    for _ in enc:
        print('編碼類型：{:10}|{}'.format(_,content.encode(encoding = _)))
"""

"""
def decoder(content):

    enc = ['base64','utf8','utf32','cp950']
    cypher = []
    for _ in enc:
        if(_ == 'base64'):
            cypher.append(base64.b64encode(content.encode()))
            print('編碼類型：{:10}|{}'.format(_,base64.b64encode(content.encode())))

        else:
            cypher.append(content.encode(encoding = _))
            print('編碼類型：{:10}|{}'.format(_,content.encode(encoding = _)))

    print("-"*60)
    index = 0
    for _ in enc:
        if(_ == 'base64'):
            cypher.append(base64.b64encode(content.encode()))
            print('編碼類型：{:10}|{}'.format(_,base64.b64decode(cypher[index]).decode()))

        else:
            print('解碼類型：{:10}|{}'.format(_,cypher[index].decode(encoding = _)))

        index +=1
"""
def bash64Decoder(url):
    content = base64.b64decode(url)
    print(content)
    with open('a.png','wb') as f:
        f.write(content)

    #content.decode('utf-8')
    #print(content)

#print(sys.getfilesystemencoding())
#print(locale.getpreferredencoding())
url = "Oz4rPj0+LDovPiwsKDAtOw=="
bash64Decoder(url)


class Nodo:
	def __init__(self, dato=None, prox=None):
		self.dato = dato
		self.prox = prox

	def __str__(self):
		return str(self.dato)

	def ver_lista(self):
		"""Recorre todos los nodos a través de sus enlaces,
		mostrando sus contenidos."""

		while self is not None:
			print(self)
			self = self.prox

class ListaEnlazada:
	"""Modela una lista enlazada."""
	def __init__(self):
		"""Crea una lista enlazada vacía."""
		# referencia al primer nodo (None si la lista está vacía)
		self.prim = None
		# cantidad de elementos de la lista
		self.len = 0

	def pop(self, indice):

		if indice > self.len or indice < 0:
			raise Exception("Valor no valido")
		if indice == None:
			indice = self.len - 1
		if indice == 0:
			dato = self.prim.dato
			self.prim = self.prim.prox
		else:
			anterior = self.prim
			actual = anterior.prox
			for pos in range(1, indice):
				anterior = actual
				actual = anterior.prox
			dato = actual.dato
			anterior.prox = actual.prox

		self.len -= 1
		return dato
	def remove(self, valor):
		if self.len == 0:
			raise Exception("No existe ese valor")
		if self.prim.dato == valor:
			self.prim = self.prim.prox
		else:
			anterior = self.prim
			actual = anterior.prox
			while actual is not None and actual.dato != valor:
				anterior = actual
				actual = anterior.prox
			if actual is None:
				raise Exception("Este valor no esta en la lista")
			else:
				anterior.prox = actual.prox
		self.len -= 1

	def insert(self, pos, valor):
		if pos < 0 or pos > self.len:
			raise Exception("No se puede agregar en esa posicion")
		if pos == 0:
			nuevo = Nodo(valor)
			nuevo.prox = self.prim.prox
			self.prim = nuevo

		else:
			anterior = self.prim
			for i in range(1,pos):
				anterior = actual

			nuevo = Nodo(valor)
			nuevo.prox = anterior.prox
			anterior.prox = nuevo
			self.len += 1

	def __str__(self):
		actual = self.prim
		cadena = ""
		for i in range(0, self.len):
			actual = actual.prox
			cadena += f"{actual}, "
		return f"[{cadena[:-2]}]"

	def append(self, valor):
		if self.len == 0:
			nuevo = Nodo(valor)
			self.prim = nuevo
			self.prim.prox = None
		actual = self.prim
		for i in range(0, self.len):
			actual = actual.prox

		nuevo = Nodo(valor)
		actual.prox = nuevo
		self.len += 1

	def extend(self, le):
		actual_self = self.prim
		for i in range(0, self.len):
			actual_self = actual_self.prox
		actual_le = le.prim
		for i in range(0, le.len+1):
			nuevo = Nodo(actual_le.dato)
			actual_self.prox = nuevo
			nuevo.prox = None
			actual_le = actual_le.prox
			actual_self = actual_self.prox
			self.len += 1

	def remover_todos(self, valor):

		if self.prim.dato == valor:
			self.prim = self.prim.prox

		anterior = self.prim
		actual = anterior.prox
		while actual is not None:
			if actual.dato == valor:
				anterior.prox = actual.prox

				self.len -= 1
			anterior = actual
			actual = anterior.prox
	def duplicar(self, valor):
		if self.prim.dato == valor:
			nuevo = Nodo(valor)
			nuevo.prox = self.prim.prox
			self.prim.prox = nuevo
		else:
			anterior = self.prim
			actual = anterior.prox
			while actual is not None:
				if actual.dato == valor:
					nuevo = Nodo(valor)
					nuevo.prox = actual
					anterior.prox = nuevo
					self.len += 1
				anterior = actual
				actual = anterior.prox
	def filter(self, funcion):
		le = ListaEnlazada()
		if funcion(self.prim.dato) == True:
			nuevo = Nodo(self.prim.dato)
			le.prim = nuevo
			le.prox = None

		anterior_self = self.prim
		actual_self = anterior_self.prox
		anterior_le = le.prim
		while actual_self is not None:
			if funcion(actual_self.dato) == True:
				nuevo = Nodo(actual_self.dato)
				anterior_le.prox = nuevo
				nuevo.prox = None
				anterior_le = nuevo
				le.len += 1
			anterior_self = actual_self
			actual_self = anterior_self.prox
		return le

class ListaDobleEnlazada:

	def __init__(self):
		self.prim = None
		self.ultimo = None

	def append(self, valor):
		nuevo = Nodo(valor)
		if self.prim == None:
			self.prim =	nuevo
			self.ultimo = nuevo
		else:
			anterior = self.prim
			actual = anterior.prox
			while actual is not None:
				anterior = actual
				actual = anterior.prox
			anterior.prox = nuevo
			self.ultimo = nuevo
	def pop(self):
		anterior = self.prim
		actual = anterior.prox
		siguiente = actual.prox
		while siguiente is not None:
			anterior = actual
			actual = anterior.prox
			siguiente = actual.prox
		anterior.prox = None
		self.ultimo = anterior

	def insert(self, indice, valor):
		nuevo = Nodo(valor)
		if indice == 0:
			self.prim = nuevo
			if self.prim.prox == None:
				self.ultimo = nuevo
		else:
			anterior = self.prim
			actual = anterior.prox
			for i in range(1, indice):
				anterior = actual
				actual = anterior.prox
			if actual.prox == None:
				actual.prox = nuevo
			else:
				nuevo.prox = actual
				anterior.prox = nuevo
	def remove(self, valor):
		if self.prim.dato == valor:
			self.prim = self.prim.prox
		else:
			anterior = self.prim
			actual = anterior.prox
			while actual.dato != valor:
				anterior = actual
				actual = anterior.prox
			anterior.prox = actual.prox

l = ListaDobleEnlazada()

l.append(14)
l.append(1)
l.append(95)
l.append(124)
l.append(24)
l.append(3)
l.append(39)
l.append(3)
l.pop()
l.pop()
l.insert(4, 234)
l.remove(95)
nodo = l.prim
while nodo is not None:
	print(nodo.dato)
	nodo = nodo.prox


import codecs
import os

import setuptools

with open("README.md", "r") as fh:
    long_description = fh.read()

def read(rel_path):
    here = os.path.abspath(os.path.dirname(__file__))
    with codecs.open(os.path.join(here, rel_path), "r", encoding="utf-8") as fp:
        return fp.read()

def get_version(rel_path):
    for line in read(rel_path).splitlines():
        if line.startswith("__version__"):
            delim = '"' if '"' in line else "'"
            return line.split(delim)[1]
    raise RuntimeError("Unable to find version string.")

install_requires = [
    "numpy>=1.18.0",
    "tqdm",
    "six",
    "setuptools",
    "torch",
    "torchvision",
    "opencv-python",
    "scikit-image",
    "tensorflow",
    "tensorrt",
    "matplotlib",
    "pandas",
    "click",
    "progressbar",
]

setuptools.setup(
    name='whitebox-adversarial-toolbox',
    version=get_version(os.path.join("what", "__init__.py")),
    author="wuhanstudio",
    author_email="wuhanstudios@gmail.com",
    maintainer="wuhanstudio",
    maintainer_email="wuhanstudios@gmail.com",
    description='White-box Adversarial Toolbox (WHAT) - Python Library for Deep Learning Security',
    url="https://github.com/wuhanstudio/whitebox-adversarial-toolbox",
    license="MIT",
    install_requires=install_requires,
    extra_require = {
        "dev": [    "progressbar",
        ]
    },
    entry_points={
        'console_scripts': [
            'what=what._main:main',
        ],
    },
    packages=setuptools.find_packages(),
    long_description=long_description,
    long_description_content_type="text/markdown",
    classifiers=[
        "Intended Audience :: Science/Research",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "Programming Language :: Python :: 3.9",
        "Topic :: Scientific/Engineering :: Artificial Intelligence",
    ],
)


#!/usr/bin/env python

"""
Module for parsing FASTA format files.

Usage: fasta <FILE>
"""

def open_file(filename):
  """
  Opens a FASTA format file for parsing.
  """
  try:
    with open(filename) as f:
      lines = f.readlines()
      if lines[0][0] != '>':
        raise IOError
  except IOError:
    raise IOError

  return lines

def append_dict(ID, DNA, data):
  data[ID] = DNA

def append_list(ID, DNA, data):
  data.append(DNA)

def append_tuple_list(ID, DNA, data):
  data.append((ID, DNA))

def fasta(filename, data, append_function):
  """
  Produces the desired data structure holding the contents of a FASTA file.
  data is the required data structure, append_function is a method for
  appending read-in data to the structure.
  """
  lines = open_file(filename)
  try:
    line = lines[0].strip()
    if line[0] != '>':
      raise IOError
    else:
      ID = line[1:].strip()
      DNA = ""
    for line in lines[1:]:
      if line[0] == '>':
        append_function(ID, DNA, data)
        DNA = ""
        ID = line[1:].strip()
      else:
        DNA += line.strip()
    append_function(ID, DNA, data)
  except IOError:
    raise IOError

  return data

def fasta_dict(filename):
  """
  Produces a dict containing the data contents of a FASTA file. The dict is
  keyed by the info line of the FASTA file, and the value field is the DNA
  string. NB: data are not guaranteed to be in the order read from file. For
  that, use fasta_list or fasta_tuple_list.
  """
  try:
    data_dict = fasta(filename, {}, append_dict)
  except IOError:
    raise IOError

  return data_dict

def fasta_list(filename):
  """
  Produces a list containing the data contents of a FASTA file. The list
  contains only the DNA strings (the info line is ommitted), but the strings
  are in the order read in from the file. If the info line is required, use
  fasta_dict or fasta_tuple_list.
  """
  try:
    data_list = fasta(filename, [], append_list)
  except IOError:
    raise IOError

  return data_list

def fasta_tuple_list(filename):
  """
  Produces a list of tuples containing the data contents of a FASTA file. The
  list contains tuples of the form (ID, DNA), and the strings are in the order
  read in from the file. If order is not important, use fasta_dict, or if info
  is not important, use fasta_list.
  """
  try:
    data_tuple_list = fasta(filename, [], append_tuple_list)
  except IOError:
    raise IOError

  return data_tuple_list

def fasta_string(filename):
  """
  Produces the DNA string of the first DNA data in the FASTA file.
  Helper function for compatibility.
  """
  return fasta_list(filename)[0]

if __name__ == "__main__":
  import sys
  if len(sys.argv) < 2:
    print(__doc__)
    sys.exit(1)

  try:
    data_dict = fasta_dict(sys.argv[1])
    data_list = fasta_list(sys.argv[1])
    data_tuple_list = fasta_tuple_list(sys.argv[1])
  except IOError:
    print("Unable to open/read FASTA file", sys.argv[1])
    sys.exit(1)

  if len(data_dict) == 0 or len(data_list) == 0 or len(data_tuple_list) == 0:
    print("No data in FASTA file", sys.argv[1])
  else:
    print("Data in dict:")
    for ID, DNA in data_dict.items():
      print(ID, DNA, sep = '\n')
    print()
    print("Data in list:")
    for DNA in data_list:
      print(DNA)
    print()
    print("Data in tuple list:")
    for tup in data_tuple_list:
      print(tup[0], tup[1], sep = '\n')


from skimage import io, img_as_float, filters, data, color
from sklearn.decomposition import PCA
from os import listdir
from os.path import isfile, join
import pandas as pd
import numpy as np
from PIL import Image
from sklearn.linear_model import LogisticRegression
from joblib import dump, load

test_true = "test_data_true/"
test_true_resized = "test_data_true_resized/"
test_false = "test_data_false/"
test_false_resized = "test_data_false_resized/"
images_true = []
images_false = []

basewidth = 100

"""true images"""
for file in [f for f in listdir(test_true) if isfile(join(test_true, f))]:
    #images.append(color.rgb2grey(io.imread(test_dir+file)))
    with open (test_true+file, 'rb') as img:
        img = Image.open(test_true+file)
        wpercent = (basewidth/float(img.size[0]))
        hsize = int((float(img.size[1])*float(wpercent)))
        img = img.resize((basewidth, hsize), Image.ANTIALIAS)
        img.save(test_true_resized+file)
        images_true.append(color.rgb2grey(io.imread(test_true_resized+file)))
#print(images[0])

df_true = pd.DataFrame({})

if images_true:
    for dim1 in range(images_true[0].shape[0]):
        for dim2 in range(images_true[0].shape[1]):
            df_true[str(dim1)+str(dim2)] = pd.Series([images_true[i][dim1][dim2] for i in range(len(images_true))])
else:
    print('keine Bilder')

"""false images"""
for file in [f for f in listdir(test_false) if isfile(join(test_false, f))]:
    #images.append(color.rgb2grey(io.imread(test_dir+file)))
    with open (test_false+file, 'rb') as img:
        img = Image.open(test_false+file)
        wpercent = (basewidth/float(img.size[0]))
        hsize = int((float(img.size[1])*float(wpercent)))
        img = img.resize((basewidth, hsize), Image.ANTIALIAS)
        img.save(test_false_resized+file)
        images_false.append(color.rgb2grey(io.imread(test_false_resized+file)))
#print(images[0])

df_false = pd.DataFrame({})

if images_false:
    for dim1 in range(images_false[0].shape[0]):
        for dim2 in range(images_false[0].shape[1]):
            df_false[str(dim1)+str(dim2)] = pd.Series([images_false[i][dim1][dim2] for i in range(len(images_false))])
else:
    print('keine Bilder')

df = pd.concat([df_true, df_false], join='inner', axis=0)
df.reset_index(inplace=True,drop=True)

df_y_true = pd.Series(np.ones(len(images_true)))
df_y_false = pd.Series(np.zeros(len(images_false)))
df_y = pd.concat([df_y_true, df_y_false], join='inner', axis=0)
df_y.reset_index(inplace=True,drop=True)
#print(df_y)

clf = LogisticRegression()
clf.fit(df,df_y)
test = clf.predict(df)
print(test)

dump(clf, 'model/model.joblib')

#basewidth = 500
#for img in images:
#    wpercent = (basewidth/float(img.shape[0]))
#    hsize = int((float(img.shape[1])*float(wpercent)))
#    img = img.resize((basewidth, hsize), Image.ANTIALIAS)

#print(images[0].shape)
#print(images[0][0][0][0])
#print(data.camera().shape)
#print(images[0])

#if images:
#    for dim1 in range(images[0].shape[0]):
#        for dim2 in range(images[0].shape[1]):
#            for dim3 in range(images[0].shape[2]):
#                df[dim1+dim2+dim3] = pd.Series([images[i][dim1][dim2][dim3] for i in range(len(images))])
#else:
#    print('no images')

#df = pd.DataFrame.from_records(images)
#print(df)

#for i in images:
#    print(i.dtype)

"""
files = [f for f in listdir("test_data/") if isfile(join("test_data/", f))]

for file in files:
    with open("test_data/"+file, "rb") as img_file:
        my_string = base64.b64encode(img_file.read())
        img_file.close()
    #print(my_string)
"""


# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function

from collections import OrderedDict
from .. import backend as K
from ..layers.core import Layer, Merge, Siamese, SiameseHead
from six.moves import range

class Sequential(Layer):
    '''
        Simple linear stack of layers.

        inherited from Layer:
        - get_params
        - get_output_mask
        - supports_masked_input
    '''

    def __init__(self, layers=[]):
        self.layers = []
        for layer in layers:
            self.add(layer)

    def __call__(self, X, train=False):
        # set temporary input to first layer
        tmp = self.layers[0].get_input
        self.layers[0].get_input = lambda _: X
        Y = self.get_output(train=train)
        # return input to first layer to what it was
        self.layers[0].get_input = tmp
        return Y

    def set_previous(self, layer):
        self.layers[0].previous = layer

    def add(self, layer):
        self.layers.append(layer)
        if len(self.layers) > 1:
            self.layers[-1].set_previous(self.layers[-2])
            if not hasattr(self.layers[0], 'input'):
                self.set_input()

    @property
    def params(self):
        params = []
        for l in self.layers:
            if l.trainable:
                params += l.get_params()[0]
        return params

    @property
    def regularizers(self):
        regularizers = []
        for l in self.layers:
            if l.trainable:
                regularizers += l.get_params()[1]
        return regularizers

    @property
    def constraints(self):
        constraints = []
        for l in self.layers:
            if l.trainable:
                constraints += l.get_params()[2]
        return constraints

    @property
    def updates(self):
        updates = []
        for l in self.layers:
            if l.trainable:
                updates += l.get_params()[3]
        return updates

    @property
    def state_updates(self):
        """
        Returns the `updates` from all layers in the sequence that are
        stateful.  This is useful for separating _training_ updates and
        _prediction_ updates for when we need to update a layers internal state
        during a stateful prediction.
        """
        state_updates = []
        for l in self.layers:
            if getattr(l, 'stateful', False):
                state_updates += l.get_params()[3]
        return state_updates

    def reset_states(self):
        for l in self.layers:
            if hasattr(l, 'reset_states') and getattr(l, 'stateful', False):
                l.reset_states()

    @property
    def output_shape(self):
        return self.layers[-1].output_shape

    def get_output(self, train=False):
        return self.layers[-1].get_output(train)

    def set_input(self):
        for l in self.layers:
            if hasattr(l, 'input'):
                ndim = len(K.get_shape(l.input))
                self.layers[0].input = K.placeholder(ndim=ndim)
                break

    def get_input(self, train=False):
        if not hasattr(self.layers[0], 'input'):
            self.set_input()
        return self.layers[0].get_input(train)

    @property
    def input_shape(self):
        return self.layers[0].input_shape

    @property
    def input(self):
        return self.get_input()

    def get_weights(self):
        weights = []
        for layer in self.layers:
            weights += layer.get_weights()
        return weights

    def set_weights(self, weights):
        for i in range(len(self.layers)):
            nb_param = len(self.layers[i].params)
            self.layers[i].set_weights(weights[:nb_param])
            weights = weights[nb_param:]

    def get_config(self):
        return {"name": self.__class__.__name__,
                "layers": [layer.get_config() for layer in self.layers]}

    def count_params(self):
        return sum([layer.count_params() for layer in self.layers])

class Graph(Layer):
    '''
        Implement a NN graph with arbitrary layer connections,
        arbitrary number of inputs and arbitrary number of outputs.

        Note: Graph can only be used as a layer
        (connect, input, get_input, get_output)
        when it has exactly one input and one output.

        inherited from Layer:
            - get_output_mask
            - supports_masked_input
            - get_weights
            - set_weights
    '''
    def __init__(self):
        self.namespace = set()  # strings
        self.nodes = OrderedDict()  # layer-like
        self.inputs = {}  # layer-like
        self.input_order = []  # strings
        self.outputs = {}  # layer-like
        self.output_order = []  # strings
        self.input_config = []  # dicts
        self.output_config = []  # dicts
        self.node_config = []  # dicts

    @property
    def nb_input(self):
        return len(self.inputs)

    @property
    def nb_output(self):
        return len(self.outputs)

    @property
    def params(self):
        params = []
        for l in self.nodes.values():
            if l.trainable:
                params += l.get_params()[0]
        return params

    @property
    def regularizers(self):
        regularizers = []
        for l in self.nodes.values():
            if l.trainable:
                regularizers += l.get_params()[1]
        return regularizers

    @property
    def constraints(self):
        constraints = []
        for l in self.nodes.values():
            if l.trainable:
                constraints += l.get_params()[2]
        return constraints

    @property
    def updates(self):
        updates = []
        for l in self.nodes.values():
            if l.trainable:
                updates += l.get_params()[3]
        return updates

    @property
    def state_updates(self):
        """
        Returns the `updates` from all nodes in that graph for nodes that are
        stateful.  This is useful for separating _training_ updates and
        _prediction_ updates for when we need to update a layers internal state
        during a stateful prediction.
        """
        state_updates = []
        for l in self.nodes.values():
            if getattr(l, 'stateful', False):
                state_updates += l.get_params()[3]
        return state_updates

    def reset_states(self):
        for l in self.nodes.values():
            if hasattr(l, 'reset_states') and getattr(l, 'stateful', False):
                l.reset_states()

    def set_previous(self, layer, connection_map={}):
        if self.nb_input != layer.nb_output:
            raise Exception('Cannot connect layers: input count does not match output count.')
        if self.nb_input == 1:
            self.inputs[self.input_order[0]].set_previous(layer)
        else:
            if not connection_map:
                raise Exception('Cannot attach multi-input layer: no connection_map provided.')
            for k, v in connection_map.items():
                if k in self.inputs and v in layer.outputs:
                    self.inputs[k].set_previous(layer.outputs[v])
                else:
                    raise Exception('Invalid connection map.')

    def get_input(self, train=False):
        if len(self.inputs) == len(self.outputs) == 1:
            return self.inputs[self.input_order[0]].get_input(train)
        else:
            return dict([(k, v.get_input(train)) for k, v in self.inputs.items()])

    @property
    def input(self):
        return self.get_input()

    @property
    def output_shape(self):
        if self.nb_output == 1:
            # return tuple
            return self.outputs[self.output_order[0]].output_shape
        else:
            # return dictionary mapping output names to shape tuples
            return dict([(k, v.output_shape) for k, v in self.outputs.items()])

    def get_output(self, train=False):
        if len(self.inputs) == len(self.outputs) == 1:
            return self.outputs[self.output_order[0]].get_output(train)
        else:
            return dict([(k, v.get_output(train)) for k, v in self.outputs.items()])

    def add_input(self, name, input_shape=None, batch_input_shape=None, dtype='float'):
        if name in self.namespace:
            raise Exception('Duplicate node identifier: ' + name)
        self.namespace.add(name)
        self.input_order.append(name)
        layer = Layer()  # empty layer
        if input_shape:
            layer.set_input_shape((None,) + tuple(input_shape))
        elif batch_input_shape:
            layer.set_input_shape(batch_input_shape)
        if dtype == 'float':
            layer.input = K.placeholder(shape=layer.input_shape, name=name)
        else:
            if len(input_shape) == 1:
                layer.input = K.placeholder(shape=layer.input_shape,
                                            dtype='int32',
                                            name=name)
            else:
                raise Exception('Type "int" can only be used with ndim==2 (Embedding).')
        self.inputs[name] = layer
        self.input_config.append({'name': name,
                                  'input_shape': input_shape,
                                  'dtype': dtype})

    def add_node(self, layer, name, input=None, inputs=[],
                 merge_mode='concat', concat_axis=-1, dot_axes=-1,
                 create_output=False):
        if name in self.namespace:
            raise Exception('Duplicate node identifier: ' + name)
        if input:
            if input not in self.namespace:
                raise Exception('Unknown node/input identifier: ' + input)
            if input in self.nodes:
                layer.set_previous(self.nodes[input])
            elif input in self.inputs:
                layer.set_previous(self.inputs[input])
        if inputs:
            to_merge = []
            for n in inputs:
                if n in self.nodes:
                    to_merge.append(self.nodes[n])
                elif n in self.inputs:
                    to_merge.append(self.inputs[n])
                else:
                    raise Exception('Unknown identifier: ' + n)
            merge = Merge(to_merge, mode=merge_mode,
                          concat_axis=concat_axis, dot_axes=dot_axes)
            layer.set_previous(merge)

        self.namespace.add(name)
        self.nodes[name] = layer
        self.node_config.append({'name': name,
                                 'input': input,
                                 'inputs': inputs,
                                 'merge_mode': merge_mode,
                                 'concat_axis': concat_axis,
                                 'dot_axes': dot_axes,
                                 'create_output': create_output})

        if create_output:
            self.add_output(name, input=name)

    def add_shared_node(self, layer, name, inputs=[], merge_mode=None,
                        concat_axis=-1, dot_axes=-1, outputs=[],
                        create_output=False):
        '''
        Used to shared / multi input-multi output node

        Arguments
        ------------
        layer - The layer to be shared across multiple inputs
        name - Name of the shared layer
        inputs - List of names of input nodes
        merge_mode - Similar to merge_mode argument of add_node()
        concat_axis - Similar to concat_axis argument of add_node()
        dot_axes - Similar to dot_axes argument of add_node()
        outputs - Names for output nodes. Used when merge_mode = None
        create_output -  Similar to create_output argument of add_node().
            Output will be created only if merge_mode is given
        '''
        if name in self.namespace:
            raise Exception('Duplicate node identifier: ' + name)
        for o in outputs:
            if o in self.namespace:
                raise Exception('Duplicate node identifier: ' + o)
        if merge_mode:
            if merge_mode not in {'sum', 'ave', 'mul', 'dot', 'cos', 'concat', 'join'}:
                raise Exception("Invalid merge mode")
        layers = []
        for i in range(len(inputs)):
            input = inputs[i]
            if input in self.nodes:
                n = self.nodes[input]
                if n.__class__.__name__ == 'Siamese':
                    if n.merge_mode is None:
                        for j in range(len(n.inputs)):
                            sh = SiameseHead(j)
                            sh.previous = n
                            layers.append(sh)
                    else:
                        layers.append(n)
                else:
                    layers.append(n)
            elif input in self.inputs:
                n = self.inputs[input]
                layers.append(n)
            else:
                raise Exception('Unknown identifier: ' + input)
        s = Siamese(layer, layers, merge_mode, concat_axis=concat_axis, dot_axes=dot_axes)
        self.namespace.add(name)
        self.nodes[name] = s
        self.node_config.append({'name': name,
                                 'inputs': inputs,
                                 'merge_mode': merge_mode,
                                 'concat_axis': concat_axis,
                                 'dot_axes': dot_axes,
                                 'create_output': create_output if merge_mode else False})
        if not merge_mode:
            for i in range(len(outputs)):
                sh = SiameseHead(i)
                sh.previous = s
                sh_name = outputs[i]
                self.namespace.add(sh_name)
                self.nodes[sh_name] = sh
                self.node_config.append({'name': sh_name,
                                         'inputs': [s],
                                         'create_output': create_output})
                if create_output:
                    self.add_output(sh_name, input=sh_name)

        if create_output and merge_mode:
            if merge_mode == 'join':
                raise Exception("Output can not be of type OrderedDict")
            self.add_output(name, input=name)

    def add_output(self, name, input=None, inputs=[],
                   merge_mode='concat', concat_axis=-1, dot_axes=-1):
        if name in self.output_order:
            raise Exception('Duplicate output identifier: ' + name)
        if input:
            if input not in self.namespace:
                raise Exception('Unknown node/input identifier: ' + input)
            if input in self.nodes:
                self.outputs[name] = self.nodes[input]
            elif input in self.inputs:
                self.outputs[name] = self.inputs[input]
        if inputs:
            to_merge = []
            for n in inputs:
                if n not in self.nodes:
                    raise Exception('Unknown identifier: ' + n)
                to_merge.append(self.nodes[n])
            merge = Merge(to_merge, mode=merge_mode,
                          concat_axis=concat_axis, dot_axes=dot_axes)
            self.outputs[name] = merge

        self.output_order.append(name)
        self.output_config.append({'name': name,
                                   'input': input,
                                   'inputs': inputs,
                                   'merge_mode': merge_mode,
                                   'concat_axis': concat_axis,
                                   'dot_axes': dot_axes})

    def get_config(self):
        return {"name": self.__class__.__name__,
                "input_config": self.input_config,
                "node_config": self.node_config,
                "output_config": self.output_config,
                "input_order": self.input_order,
                "output_order": self.output_order,
                "nodes": dict([(c["name"], self.nodes[c["name"]].get_config()) for c in self.node_config])}

    def count_params(self):
        return sum([layer.count_params() for layer in self.nodes.values()])

    def get_weights(self):
        weights = []
        for layer in self.nodes.values():
            weights += layer.get_weights()
        return weights

    def set_weights(self, weights):
        for layer in self.nodes.values():
            nb_param = len(layer.get_weights())
            layer.set_weights(weights[:nb_param])
            weights = weights[nb_param:]


# -*- coding: utf-8 -*-
"""
Created on Fri Jul  2 20:45:19 2021

@author: ankon
"""
#%%Importing modules and the data
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from kneed import KneeLocator
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA

df = pd.read_csv('TASK-2 DATA.csv')

print("Info on training examples:")
print(df.info())

print("First 5 samples:\n",df.head())
print("Last 5 samples:\n",df.tail())

#%%Data Cleaning and Manipulation

#Checking fo null values
print("Null Values:")
print(df.isnull().sum())

#Converting dataframe to a 2-D numpy array
ndarr=df.to_numpy()
#Dropping features  Id and Species
ndarr=ndarr[:,1:5]

#Feature Scaling
scaler = StandardScaler()
scaled_ndarr = scaler.fit_transform(ndarr)

print("First 5 samples after Feature Scaling:\n",scaled_ndarr[:5,])
print("Last 5 samples after Feature Scaling:\n",scaled_ndarr[-5:,])

#%%Obtainig the optimal value of the no. of clusters
#Elbow method
#Array to hold Sum of Squared Errors for each value of k(2 to 10)
SSE=[]

for k in range(1,11):
    iriskm=KMeans(n_clusters=k, init='k-means++', n_init=10, max_iter=300)
    iriskm.fit(scaled_ndarr)
    SSE.append(iriskm.inertia_)

#Plotting graph SSE v/s No. of Clusters
plt.style.use("fivethirtyeight")
plt.plot(range(1, 11), SSE)
plt.xticks(range(1, 11))
plt.xlabel("Number of Clusters")
plt.ylabel("SSE")
plt.show()

#Confirmation of elbow using KneeLocator(package kneed)
kl = KneeLocator(
    range(1, 11), SSE, curve="convex", direction="decreasing")
print("Elbow:",kl.elbow)

#%%Performing K-means with obtained optimal value of No. of clusters

K=kl.elbow

iriskm=KMeans(n_clusters=K, init='k-means++', n_init=10, max_iter=300)
iriskm.fit(scaled_ndarr)

print("Labels:\n",iriskm.labels_,"\nSSE:",iriskm.inertia_,"\nNo. of iterations run:",iriskm.n_iter_)

centers=scaler.inverse_transform(iriskm.cluster_centers_)
print("Cluster Centers:\n",centers)

#%%Interpreting the results
#Performing PCA to obtain two principal components of maximal amount of variance

pca_ndarr=PCA(n_components=2).fit(scaled_ndarr)
print("Variance Ratio:",round(sum(pca_ndarr.explained_variance_ratio_)*100,3),"%")

#print("PCs of data:\n",pca_ndarr.transform(ndarr).shape)
reduceddf=pd.DataFrame(pca_ndarr.transform(ndarr),index=df.index,columns=['PC1','PC2'])
reduceddf['Cluster']=iriskm.labels_
reducedcenters=pca_ndarr.transform(centers)
print("Reduced Centers:\n",reducedcenters)

#%%Visualization

clusters=reduceddf.Cluster.unique()
#print(clusters)
colors = np.array(["red","green","blue","yellow","pink","black","orange","purple","beige","brown","gray","cyan","magenta"])

for x in clusters:
    temp=reduceddf[reduceddf['Cluster']==x]
    plt.scatter(temp['PC1'],temp['PC2'],c=colors[x])
plt.scatter(reducedcenters[:,0],reducedcenters[:,1],marker='X',c="black")
plt.show()


print ("************************")
print ("* Activity 6-Iteration *")
print ("************************")
name = input("Name:")
print ("Hello ",name, "!")
print ("--------------------------------")
count=0
total=0
average=0
while True:
    num= input (" Enter a number:")
    if num == 'done':
        break
    try :
        number= float(num)
    except:
        print (' Invalid Input')
        continue
    count = count+1
    total=total+ number
    average=total/count
print('------------------------------')
print(' Count:', count)
print(' Total:', total)
print(' Average:', average)


from django.urls import path
from .views import (ShopIndexView, GroupsListView,
                    ProductDetailsView, ProductsListView,
                    OrdersListView, OrdersDetailsView,
                    CreateProductView, UpdateProductView,
                    DeleteProductView, CreateOrderView,
                    UpdateOrderView, DeleteOrderView)

app_name = "shopapp"

urlpatterns = [
    path("", ShopIndexView.as_view(), name="index"),
    path("groups/", GroupsListView.as_view(), name="groups_list"),

    path("products/", ProductsListView.as_view(), name="products_list"),
    path("products/create/", CreateProductView.as_view(), name="create_product"),
    path("products/<int:pk>/", ProductDetailsView.as_view(), name="products_details"),
    path("products/<int:pk>/update", UpdateProductView.as_view(), name="product_update"),
    path("products/<int:pk>/delete", DeleteProductView.as_view(), name="product_delete"),

    path("orders/", OrdersListView.as_view(), name="orders_list"),
    path("orders/create/", CreateOrderView.as_view(), name="create_order"),
    path("orders/<int:pk>/", OrdersDetailsView.as_view(), name="order_details"),
    path("orders/<int:pk>/update", UpdateOrderView.as_view(), name="order_update"),
    path("orders/<int:pk>/delete", DeleteOrderView.as_view(), name="order_delete"),
]


from django.shortcuts import render
from django.http import HttpResponse
from .models import Product,Comment,Favorite,User

import csv
import pandas as pd
import random
# Create your views here.
gender_list = ['M','W']
type_list = ['TOP','BOTTOM']

# 랜덤된 이미지를 보여준다
# 메인페이지
def index(request):

    answer=request.POST.getlist('check')

    w, m, t, b = 0, 0, 0, 0

    if 'Woman' in answer:
        w = 1
    if 'Man' in answer:
        m = 1
    if 'top' in answer:
        t = 1
    if 'bottoms' in answer:
        b = 1

    with open("C:/Users/ssy01/OneDrive - 고려대학교/인공지능사관학교/TEAM8/team8_project/ssy/dataset/all_combined.csv", 'r') as f2:
        dr2 = csv.DictReader(f2)
        s2 = pd.DataFrame(dr2)

    if w != m:
        if w:
            s2 = s2[s2.gender == 'W']
        else:
            s2 = s2[s2.gender == 'M']

    if t != b:
        if t:
            s2 = s2[s2.type == 'TOP']
        else:
            s2 = s2[s2.type == 'BOTTOM']

    details = []
    nums = random.sample(range(len(s2)),100)
    for num in nums:
        link, gender, type_, image, idx = s2.iloc[num]
        prod_num = str(gender_list.index(gender)) + str(type_list.index(type_)) + str(idx)
        details.append([prod_num, image])

    context = {
        'products' : details
    }

    return render(request,'index.html',context)

# 관련된 이미지를 보여준다
# 서브페이지
def sub(request, prod_num):

    gender = gender_list[int(prod_num[0])]
    type_ = type_list[int(prod_num[1])]
    prod_num = int(prod_num[2:])

    # 유사도 top30
    with open(f"C:/Users/ssy01/OneDrive/바탕 화면/similarity_v2/{gender}_{type_}/{prod_num}_similarity.csv", 'r') as f:
        dr = csv.DictReader(f)
        s = pd.DataFrame(dr)

    # 상품 실제 링크와 이미지 가져오기
    with open(f"C:/Users/ssy01/OneDrive - 고려대학교/인공지능사관학교/TEAM8/team8_project/ssy/dataset/{gender}_{type_}_combined.csv", 'r') as f2:
        dr2 = csv.DictReader(f2)
        s2 = pd.DataFrame(dr2)

    target = s2.iloc[prod_num]

    details = []
    for i in range(1,31):
        sub_prod_num = int(s['prod_num'][i])
        image = s2['images'][sub_prod_num]
        href = s2['link'][sub_prod_num]
        details.append([href, image])

    context={

        'target' : target,
        'details' : details,
    }

    return render(request,'sub.html',context)


import asyncio
from unittest.mock import patch, MagicMock

import pytest
from httpx import AsyncClient
from tests.data_test import Activate, ItemData

class TestItems:
    ITEM_DATA = ItemData.DATA_LIST
    ACTIVATE_DATA = Activate.DATA_LIST

    @patch('app.routers.items.orders')
    @patch('app.routers.items.database_access_check')
    @pytest.mark.parametrize('db_check_value, item_status, code, expected_response', ITEM_DATA)
    @pytest.mark.asyncio
    async def test_check_status(self, mock_db_check: MagicMock, status: MagicMock, tokens: dict, db_check_value: bool,
                                item_status: any, code: int, expected_response: tuple, a_client: AsyncClient):
        access_token = tokens['access_token']
        mock_db_check.return_value = db_check_value
        mock_orders = MagicMock()
        mock_orders.return_value = item_status
        status.find_one.return_value = asyncio.Future()
        status.find_one.return_value.set_result(mock_orders.return_value)
        response = await a_client.get(f'check_status?item_number=129',
                                      headers={'Authorization': f'Bearer {access_token}'})

        assert response.status_code == code, f'Server returned {response.status_code} code'
        assert response.json() == expected_response, response.json()

    @patch('app.routers.items.datetime.datetime')
    @patch('app.routers.items.orders')
    @patch('app.routers.items.call_producer')
    @patch('app.routers.items.database_access_check')
    @pytest.mark.parametrize('item, db_check_value, item_status, code, expected_response', ACTIVATE_DATA)
    @pytest.mark.asyncio
    async def test_activate_item(self, db_check: MagicMock, mock_producer: MagicMock, status: MagicMock,
                                 mock_time: MagicMock, tokens: dict, db_check_value: bool, item_status: any,
                                 item: dict, code: int, expected_response: tuple, a_client: AsyncClient):
        access_token = tokens['access_token']
        db_check.return_value = db_check_value
        mock_producer.return_value = True
        mock_orders = MagicMock()
        mock_orders.return_value = item_status
        status.find_one.return_value = asyncio.Future()
        status.find_one.return_value.set_result(mock_orders.return_value)
        mock_time.now.return_value = '1945-07-16'
        response = await a_client.post('activate', headers={'Authorization': f'Bearer {access_token}'},
                                       json=item)
        assert response.status_code == code, response.text
        assert response.json() == expected_response, response.json()


import numpy as np
from utils.homography import RansacModel, make_homog, H_from_ransac

class Match(object):
    def __init__(self, detector, img_left, img_right):
        self.img_left = img_left
        self.img_right = img_right

        self.img_shape = img_left.shape

        self.detector = detector

        self.is_fitted = False
        self.kp_l = None
        self.kp_r = None
        self.matches = None
        self.H = None

    def fit(self):
        """ compute the keypoints and descriptors """
        self.kp_l, des_l = self.detector.detect(self.img_left)
        self.kp_r, des_r = self.detector.detect(self.img_right)
        self.matches = self.detector.match(des_l, des_r)
        self.is_fitted = True

    def select_matches(self, match_threshold=None):
        if match_threshold is None:
            match_threshold = 0.2*self.img_shape[0]
        if not self.is_fitted:
            raise ValueError("must fit Match object first")
        self.matches, self.H = select_matches(self.kp_l, self.kp_r, self.matches, match_threshold)

class MultiMatch(object):
    def __init__(self, detector, img_list):
        self.img_list = img_list
        self.img_shape = img_list[0].shape
        self.n_img = len(img_list)

        self.detector = detector

        self.is_fitted = False

        self.kp_list = []
        self.matches = []

    def fit(self, match_threshold=None):
        """ We match each image with the following one """

        # We will first compute the keypoints and descriptors for each images
        i = 0
        des_list = []
        for img in self.img_list:
            kp, des = self.detector.detect(img)
            self.kp_list.append(kp)
            des_list.append(des)

            i += len(kp)

        print("Keypoints Detection done.")

        if match_threshold is None:
            match_threshold = 0.1*self.img_shape[0]

        matches = []

        # Here we match each image with the following
        for i in range(self.n_img-1):
            match, _ = select_matches(self.kp_list[i], self.kp_list[i+1],
                                      self.detector.match(des_list[i], des_list[i+1]), match_threshold)

            matches.append(match)
            print("Selected %i Matches between image %i and %i" % (match.shape[0], i, i+1))

        self.matches = matches
        self.is_fitted = True

        print("Matching Done")

    def get_match(self, i):
        """ return a "Match" object between the i and i+1 image """
        match = Match(self.detector, self.img_list[i], self.img_list[i+1])
        match.is_fitted = True
        match.kp_l = self.kp_list[i]
        match.kp_r = self.kp_list[i+1]
        match.matches = self.matches[i]
        return match

def select_matches(kp1, kp2, matches, match_threshold=100):
    """Select robust matches using the RANSAC algorithm"""

    model = RansacModel()

    pts1 = make_homog(np.transpose(np.array([kp1[m.queryIdx].pt for m in matches])))
    pts2 = make_homog(np.transpose(np.array([kp2[m.trainIdx].pt for m in matches])))

    H, inliers = H_from_ransac(pts1, pts2, model, maxiter=1000, match_threshold=match_threshold)
    inliers = np.sort(inliers)

    return matches[inliers], H


__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyue@mit.edu"
__date__ = "Mar 18, 2012"

import os
import unittest
import warnings

from pymatgen.apps.borg.hive import VaspToComputedEntryDrone
from pymatgen.apps.borg.queen import BorgQueen
from pymatgen.util.testing import PymatgenTest

class BorgQueenTest(unittest.TestCase):
    def setUp(self):
        warnings.simplefilter("ignore")

    def tearDown(self):
        warnings.simplefilter("default")

    def test_get_data(self):
        drone = VaspToComputedEntryDrone()
        self.queen = BorgQueen(drone, PymatgenTest.TEST_FILES_DIR, 1)
        data = self.queen.get_data()
        self.assertEqual(len(data), 12)

    def test_load_data(self):
        drone = VaspToComputedEntryDrone()
        queen = BorgQueen(drone)
        queen.load_data(os.path.join(PymatgenTest.TEST_FILES_DIR, "assimilated.json"))
        self.assertEqual(len(queen.get_data()), 1)

if __name__ == "__main__":
    unittest.main()


with open('source', 'r') as file:
    file = file.read().splitlines()
    games = [(game[0], game[2]) for game in file]

points = {
    'X': 1,
    'Y': 2,
    'Z': 3
}

tie_against = {
    'A': 'X',
    'B': 'Y',
    'C': 'Z'
}

win_against = {
    'A': 'Y',
    'B': 'Z',
    'C': 'X'
}

lose_against = {
    'A': 'Z',
    'B': 'X',
    'C': 'Y'
}

def first_puzzle():
    score = 0

    for foe, me in games:
        score += points[me]

        if me == tie_against[foe]:
            score += 3
        elif me == win_against[foe]:
            score += 6
    print(score)

def second_puzzle():
    score = 0

    for foe, result in games:
        if result == 'Z':
            score += 6 + points[win_against[foe]]
        elif result == 'Y':
            score += 3 + points[tie_against[foe]]
        else:
            score += points[lose_against[foe]]

    print(score)

first_puzzle()
second_puzzle()


# El objetivo del ejercicio es crear un sistema de calificaciones, como sigue:
# El usuario proporcionará un valor entre 0 y 10.
# Si está entre 9 y 10: imprimir una A
# Si está entre 8 y menor a 9: imprimir una B
# Si está entre 7 y menor a 8: imprimir una C
# Si está entre 6 y menor a 7: imprimir una D
# Si está entre 0 y menor a 6: imprimir una F
# cualquier otro valor debe imprimir: Valor desconocido
# Por ejemplo:
#  Proporciona un valor entre 0 y 10:
#  A
# Puedes utilizar el IDE de tu preferencia para codificar la solución y después pegar tu solución en esta herramienta.

nota = int(input('proporcionará un valor entre 0 y 10: '))

mensaje = None

if nota >= 0 and nota < 6:
    mensaje = 'F'
elif nota >= 6 and nota < 7:
    mensaje = 'D'
elif nota >=  7 and nota < 8:
    mensaje = 'C'
elif nota >= 8 and nota < 9:
    mensaje = 'B'
elif nota >= 9 and nota <= 10:
    mensaje = 'A'

else:
    mensaje = 'Valor desconocido'
print(mensaje)

02 - Prof Ubaldo Acosta/05 - Sentencias de Control/Tarea 06 sistema de calificaciones.py


import argparse
import tempfile
import shutil

from utils import *

BASE_DIR = 'benchmark'
TARGET = "band/tool:band_benchmark"
DEFAULT_CONFIG = 'script/config_samples/benchmark_config.json'

def benchmark_local(debug, trace, platform, backend, build_only, config_path):
    build_cmd = make_cmd(
        build_only=build_only,
        debug=debug,
        trace=trace,
        platform=platform,
        backend=backend,
        target=TARGET
    )
    run_cmd(build_cmd)
    copy('bazel-bin/band/tool/band_benchmark', BASE_DIR)
    run_cmd(
        f'chmod 777 {BASE_DIR}/band_benchmark'
    )
    if platform == "linux":
        run_cmd(
            f'{BASE_DIR}/band_benchmark {config_path}'
        )
    else:
        run_cmd(
            f'{BASE_DIR}/band_benchmark.exe {config_path}'
        )

def benchmark_android(debug, trace, platform, backend, docker, config_path=""):
    target_base_dir = BASE_DIR
    # build android targets only (specified in band_cc_android_test tags)

    build_command = make_cmd(
        build_only=True,
        debug=debug,
        trace=trace,
        platform="android",
        backend=backend,
        target=TARGET,
    )
    if docker:
        run_cmd_docker(build_command)
        # create a local path
        subprocess.call(['mkdir', '-p', f'{target_base_dir}'])
        # run_cmd(
        #     f'sh script/docker_util.sh -d bazel-bin/band/tool/band_benchmark {target_base_dir}')
        copy_docker('bazel-bin/band/tool/band_benchmark', target_base_dir)
    elif platform.system() == 'Linux':
        run_cmd(build_command)
        copy('bazel-bin/band/tool/band_benchmark', target_base_dir)

    config_paths = []
    if os.path.isfile(config_path):
        config_paths.append(config_path)
    elif os.path.isdir(config_path):
        for file in os.listdir(config_path):
            if file.endswith('.json'):
                config_paths.append(f'{config_path}/{file}')

    for config_path in config_paths:
        name = os.path.basename(config_path)
        shutil.copy(config_path, f'{target_base_dir}/{name}')
        print (f'Push {name} to Android')

    push_to_android(f'{target_base_dir}', '')

    for config_path in config_paths:
        name = os.path.basename(config_path)
        print(f'Run {name}')
        run_binary_android('', f'{target_base_dir}/band_benchmark',
                           f'{target_base_dir}/{name}')

if __name__ == '__main__':
    parser = get_argument_parser("Run Band benchmarks for specific target platform. "
                                 "The user should prepare/specify dependent files either absolute path or relative path depending on an execution mode. "
                                 "This script executes the benchmark from (Android: /data/local/tmp, Other: current working directory)")
    parser.add_argument('-c', '--config', default=f'{DEFAULT_CONFIG}',
                        help=f'Target config file or directory (default = {DEFAULT_CONFIG})')
    args = parser.parse_args()

    # copy from band/test/data/benchmark_config.json
    if args.config == DEFAULT_CONFIG:
        if args.android:
            shutil.copy('script/config_samples/benchmark_heft.json', f'{DEFAULT_CONFIG}')
        else:
            args.config = 'band/test/data/benchmark_config.json'

    if args.rebuild:
        clean_bazel(args.docker)

    if os.path.isdir(BASE_DIR):
        shutil.rmtree(BASE_DIR)

    if args.android:
        # Need to set Android build option in ./configure
        print('Benchmark Android')
        benchmark_android(args.debug, args.trace, get_platform(), args.backend,
                          args.docker, args.config)
    else:
        print(f'Benchmark {get_platform()}')
        benchmark_local(args.debug, args.trace, get_platform(),
                        args.backend, args.build, args.config)


"""
'datadir' and 'plotdir' hold the location of my data and plots which is different on different systems, so it is
modified here rather than in each script individually.
"""
import os

import numpy as np

from metpy import constants

homepath = os.path.expanduser('~/Documents/meteorology/')
datadir = homepath + 'data/'
plotdir = homepath + 'output/'

def haversine(lon1, lat1, lon2, lat2):
    lon1 = np.deg2rad(lon1)
    lon2 = np.deg2rad(lon2)
    lat1 = np.deg2rad(lat1)
    lat2 = np.deg2rad(lat2)

    dlon = lon2 - lon1
    dlat = lat2 - lat1

    a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2)**2
    c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1-a))

    return constants.earth_avg_radius * c


from django.db.models import Q, Prefetch
from django.db.models.base import ModelBase

from service.models import Orders, OrderComments

def get_choices_from_query(model: ModelBase, filter_params: dict) -> list:
    """Return choices list for select widget from model by filter"""

    query = model.objects.filter(**filter_params)
    choices = list()

    for q in query:
        choices.append((q.pk, str(q)))

    return choices

def is_user_read(user, instance: Orders) -> bool:
    """Return:
        True if user read last comments in the instance,
            False if user doesn't read last comments,
                and if user is staff and somebody make order.
    """
    if instance.is_read:
        return True

    order_comments = list(instance.ordercomments_set.all())
    last_comment = None
    if order_comments:
        last_comment = order_comments[0]

    if last_comment is None and user.is_staff:
        return False
    elif last_comment is None and not user.is_staff:
        return True
    elif last_comment.author == user:
        return True
    return False

def get_notifications_count(user) -> dict:
    """Return count of user unread comments in Orders"""

    if not user.is_authenticated:
        return {}

    if user.is_staff:
        queryset = Orders.objects.filter((Q(executor=user) | Q(executor=None) | Q(customer=user)) & Q(is_read=False))\
            .prefetch_related(Prefetch('ordercomments_set',
                                       queryset=OrderComments.objects.all().order_by('-datetime')
                                       .select_related('author')))
    else:
        queryset = Orders.objects.filter(Q(customer=user) & Q(is_read=False)).prefetch_related(
            Prefetch('ordercomments_set',
                     queryset=OrderComments.objects.all().order_by('-datetime').select_related('author')))

    count = len(queryset)

    for instance in queryset:
        if is_user_read(user, instance):
            count -= 1

    return {"notifications_count": count}

def make_read(user, instance: Orders) -> None:
    """Make order field is read True"""

    if not is_user_read(user, instance):
        instance.is_read = True
        instance.save()

def make_unread(instance: Orders) -> None:
    """Make order field is read False"""

    instance.is_read = False
    instance.save()


from faker import Faker
from kafka import KafkaProducer
from time import sleep
from random import randint
import json
from dataclasses import dataclass, asdict
from typing import List
from datetime import datetime, timedelta

fake = Faker("en_GB")

total_riders = 0
total_time = 0

@dataclass
class Rider:
    name: str
    address: str
    event_time: str
    event_type: str

def generate_start_time(num: int) -> List[Rider]:
    print(f"Generating {num} riders data...")
    riders = []
    for _ in range(num):
        riders.append(
            Rider(
                name=fake.name(),
                address=fake.address(),
                event_time=datetime.now().isoformat(),
                event_type="START",
            )
        )
    return riders

def push_end_times(producer: KafkaProducer, riders: List[Rider]) -> None:

    global total_riders
    global total_time

    for rider in riders:
        rider.event_type = "END"
        cur_time = datetime.fromisoformat(rider.event_time)
        extra_minutes = randint(1, 100)
        new_time = cur_time + timedelta(minutes=extra_minutes)
        rider.event_time = new_time.isoformat()

        total_riders += 1
        total_time += extra_minutes
        print(rider)

    push_to_kafka(producer, riders)

def push_to_kafka(producer: KafkaProducer, riders: List[Rider]) -> None:
    print(f"Pushing {len(riders)} to kafka")
    for rider in riders:
        producer.send("riders", value=asdict(rider))

def report_average() -> None:
    global total_riders
    global total_time

    print(
        f"Total riders: {total_riders} - Total time: {total_time} - Avg time: {total_time/total_riders}"
    )

def produce() -> None:
    producer = KafkaProducer(
        bootstrap_servers=["localhost:9092"],
        value_serializer=lambda x: json.dumps(x).encode("utf-8"),
    )

    while True:
        riders = generate_start_time(randint(1, 10))

        print("BATCH START")
        push_to_kafka(producer, riders)
        sleep(randint(0, 200) / 100)
        push_end_times(producer, riders)
        print("BATCH END")
        report_average()
        sleep(randint(0, 200) / 100)

if __name__ == "__main__":
    produce()