import numpy as np

from . import generator_base
from plotter.utils.gcode import *
from plotter.utils.helper import overrides

class BoxGenerator(generator_base.GeneratorBase):
    def __init__(self, args):
        generator_base.GeneratorBase.__init__(self, args)

    @classmethod
    def getName(cls):
        return "Box"

    @classmethod
    def getHelp(cls):
        return "Generates images by drawing boxes."

    @classmethod
    def getInputType(cls):
        return "image"

    @classmethod
    def setupCustomParams(cls, subparser):
        pass

    def drawBox(self, c, v):
        points = [
            np.array((-0.5, -0.5)),
            np.array((-0.5,  0.5)),
            np.array((0.5,  0.5)),
            np.array((0.5, -0.5)),
            np.array((-0.5, -0.5))
        ]

        gcode = []
        for p in points:
            pImg = p*v + c
            pScreen = self.px2Scr(pImg)
            gcode.append(GCode_goTo(pScreen))

            if len(gcode) == 1:
                gcode.append(GCode_down())

        gcode.append(GCode_up())

        return gcode

    @overrides(generator_base.GeneratorBase)
    def convert(self, img):

        if len(img.shape) == 3 and img.shape[2] > 1:
            img = img.mean(axis=2)

        gcode = [GCode_up(), GCode_home()]

        lastY = 0

        pImg = np.array([0, 0])
        pScreen = self.px2Scr(pImg)

        for index, pixel in np.ndenumerate(img):
            if pixel > 0:
                y, x = index
                gcode.extend(self.drawBox(np.array([x, y]), pixel/255.0))

        return gcode


import heapq
from core.Game_core import GameVariable as gv
import math

class Node:
    '''Represents a A* Node on a position
    '''

    def __init__(self, parent, position) -> None:
        """Initialize the variable to represent each node.

        Args:
          parent: Represents the position of previous visited node.
          position: Current position of the node.
        """
        self.parent = parent
        self.position = position

        # g represents distance from starting node
        # h cost represents distance from end node to current node
        # f = g + h

        self.g = 0
        self.h = 0
        self.f = 0

    def __repr__(self):
        return f'{self.position}'

    def __lt__(self, other):
        return self.f < other.f

    def __gt__(self, other):
        return self.f > other.f

    def __eq__(self, other) -> bool:
        return self.position == other.position

    def __hash__(self) -> int:
        return hash(self.position)

def heuristic(a, b):
    '''Calculate the heuristic (Euclidean distance).

    Args:
      a, b: position of initial and final point.
    '''
    return math.sqrt((b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2)

def reconstruct_path(start_node, end_node):
    '''
    Represent the shortest path.

    Args:
      start_node: Source node.
      end_node: Destination node.

    Returns:
      The path between source and destination node.
    '''
    total_path = []
    end_node = end_node.parent
    while end_node != start_node:
        total_path.append(end_node.position)
        end_node = end_node.parent
    return total_path[::-1]

class AStar:
    '''Determines the shortest path distance between source and destination using A* algorithm.
    '''

    def __init__(self, source, destination, gs) -> None:
        '''Setup the initial parameter for the search algorithms.

        Args:
          source: Represent the position (x, y) of source cell.
          destination: Represent the position (x, y) of destination cell.
          gs: Current game state.
        '''
        self.gs = gs
        self.open = []
        self.closed = set()
        self.start = Node(None, source)
        self.end = Node(None, destination)

    def search(self):
        '''Create the logic for a* search returning shortest path if found.
        '''
        heapq.heappush(self.open, self.start)
        while self.open:
            if (len(self.open) + len(self.closed) + len(self.gs.wall)) == 400:
                return None

            current_node = heapq.heappop(self.open)
            self.closed.add(current_node)

            if current_node == self.end:
                # add the all previous point with the current i.e end point to form
                # a line indicating the shortest path taken
                return reconstruct_path(self.start, current_node)

            directions = [[-1, 0], [-1, -1], [0, -1],
                          [1, 1], [1, 0], [1, -1], [0, 1], [-1, 1]]
            children = []

            for x, y in directions:
                '''
                    Iterate the neighbour of current position and check the availability
                '''
                new_position = (
                    current_node.position[0] + x, current_node.position[1] + y)
                new_node = Node(current_node, new_position)
                if (new_position[0] < 0 or new_position[0] >= gv.DIMENSIONS
                    or new_position[1] < 0 or new_position[1] >= gv.DIMENSIONS
                        or self.gs.board[new_position[0]][new_position[1]] == "wall"
                        or new_node in self.closed):
                    continue
                children.append(new_node)

            for child in children:
                '''
                    for each neighbour check if it is already visited or neighbour has less f value
                    than the new f value.
                '''

                if child in self.closed:
                    continue

                child.g = heuristic(self.start.position, child.position)
                child.h = heuristic(child.position, self.end.position)
                child.f = child.g + child.h

                is_in_open = False
                for each_node in self.open:
                    if each_node.position == child.position:
                        is_in_open = True
                        if each_node.f < child.f:
                            break
                        elif each_node.f > child.f:
                            each_node.f = child.f
                            each_node.parent = child.parent
                        else:
                            if each_node.h > child.h:
                                each_node.h = child.h
                                each_node.parent = child.parent

                if is_in_open:
                    continue

                if self.gs.board[child.position[0]][child.position[1]] == "dest" and not is_in_open:
                    if child in self.open:
                        pass
                    else:
                        heapq.heappush(self.open, child)
                else:
                    if not is_in_open:
                        heapq.heappush(self.open, child)
                    self.gs.board[child.position[0]
                                  ][child.position[1]] = "vs"

        return None


# coding: utf-8

# In[1]:

import cv2
import numpy as np
import math
import os

# In[ ]:

# In[2]:

#image convolve
def co(s_x,pad_image,i):
    img_x = np.asarray([[0 for x in range(0,width)] for y in range(0,height)])
    for x in range (0,height):
        for y in range (0,width):
            su=0
            for k in range (0,3):
                for l in range (0,3):
                    a= pad_image[x-k,y-l]
                    w1 = s_x[k][l];
                    su = su + (w1*a);
            img_x[x,y] = su

    print(img_x)
    d = img_x.shape
    print('edge_'+str(i)+'width, height',d)
    gname = 'edge'+str(i)+'.jpg'
    path = 'A:\\classes\\Intro to Computer vision and Image Processing\\projrct\\project1\\task2'
    cv2.imwrite(os.path.join(path,gname),np.asarray(img_x))
    cv2.imshow('edge_x',np.asarray(img_x,dtype ='uint8'))
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    return np.asarray(img_x,dtype='uint8')

# In[9]:

s_x = [[1,0,-1],[2,0,-2],[1,0,-1]]
s_y =[[1,2,1],[0,0,0],[-1,-2,-1]]
#flip
for i in range (0,3):
    temp =s_x[i][0]
    s_x[i][0] =s_x[i][2]
    s_x[i][2] =temp
print('s_x',s_x)
for y in range (0,3):
    temp = s_y[0][y]
    s_y[0][y] =s_y[2][y]
    s_y[2][y] =temp
print('s_y',s_y)

img = cv2.imread('A:\\classes\\Intro to Computer vision and Image Processing\\projrct\\project1\\Task\\Task1\\task1.png',0)
im = np.asarray(img)
print(im)
d = img.shape
height = img.shape[0]
width = img.shape[1]
print('Image Dimension    : ',d)
print('Image Height       : ',height)
print('Image Width        : ',width)
print('Please Wait... Output is processing')
#g_x = img.copy()
#g_y =img.copy()
# newmatrix
pad_image = np.asarray([[0 for x in range (width+2)] for y in range (height+2)])
pad_image[1:-1,1:-1] = img
cv2.imshow('padded',np.asarray(pad_image,dtype = 'uint8'))
cv2.waitKey(0)
cv2.destroyAllWindows()
#g_x = np.asarray([[0 for x in range(0,width)] for y in range(0,height)])
g_x = co(s_x,pad_image,1)
cv2.imshow('gx',g_x)
cv2.waitKey(0)
#g_y = np.asarray([[0 for x in range(0,width)] for y in range(0,height)])
g_y = co(s_y,pad_image,2)

cv2.waitKey(0)
cv2.destroyAllWindows()

# In[ ]:

# In[ ]:


try:
	N = int(input())
	for n in range(N):
		entry1 = input()
		while len(entry1) == 0:
			entry1 = input()
		entry2 = input()
		while len(entry2) == 0:
			entry2 = input()
		entry3 = input()
		while len(entry3) == 0:
			entry3 = input()
		a = 0
		b = 0
		ia = len(entry1)
		ib = len(entry1)
		if len(entry1) == len(entry2) and len(entry1) == len(entry3):
			for i in range(len(entry1)-1, -1, -1):
				if entry2[i] == entry1[i]:
					a += 1
					ia = i
				if entry3[i] == entry1[i]:
					b += 1
					ib = i
			print("Instancia", n+1)
			if a > b:
				print("time", 1)
			elif b > a:
				print("time", 2)
			else:
				if ia < ib:
					print("time", 1)
				elif ib < ia:
					print("time", 2)
				else:
					print("empate")
			print("")
except EOFError:
	NULL


import pygame as pg
import numpy as np
import math
import time

pg.init()

bits = 16
sample_rate = 44100
pg.mixer.init(sample_rate, -bits)

#This is the function that creates the sine wave
def sine_x(amplitude, frequency, time):
    return int(round(amplitude * math.sin(2 * math.pi * frequency * time)))

#This is the class that creates the tone
class Tone:
    def sine(freq, duration=1, speaker=None):
        samples = int(round(duration * sample_rate))

        buffer = np.zeros((samples, 2), dtype=np.int16)
        amplitude = 2 ** (bits - 1) - 1

        # Create a linear ramp from 0 to 1 for the duration of the tone
        ramp_up = np.linspace(0, 1, samples)

        # Create a linear ramp from 1 to 0 for the last 10% of the tone
        ramp_down = np.linspace(1, 0, int(samples * 0.1))

        # Loop over the samples and assign the sine wave to the buffer
        for sample in range(samples):
            t = float(sample) / sample_rate
            sine = sine_x(amplitude * ramp_up[sample], freq, t)  # Multiply the amplitude by the ramp value

            # Apply the fade-out effect
            if sample >= samples - len(ramp_down):
                sine *= ramp_down[sample - (samples - len(ramp_down))]

            # Assign the speaker to the tone
            if speaker == 'r':
                buffer[sample][1] = sine
            elif speaker == 'l':
                buffer[sample][0] = sine
            else:
                buffer[sample][0] = sine
                buffer[sample][1] = sine

#this is where the tone is played
        sound = pg.sndarray.make_sound(buffer)
        sound.play(loops = 1, maxtime = int(duration * 1000))
        time.sleep(duration)


import equis, argparse, sys, os.path

def main():
    parse_arguments()
    config = equis.read_config()

    config['index'] = update_indexes(config['index'])
    config['registry'] = update_registry(config['registry'])

    equis.write_config(config)

def parse_arguments():
    parser = argparse.ArgumentParser(prog="equis clean",
        description='Remove non-existent directories from the index and registry')
    return parser.parse_args()

def build_index_item(args):
    target_dir = os.path.abspath(args.directory)

    if not os.path.isdir(target_dir):
        sys.exit("Unable to open directory "+target_dir)

    target_name = args.name or os.path.basename(target_dir)

    target_opener = ""
    if args.opener:
        target_opener = distutils.spawn.find_executable(args.opener)
        if not target_opener:
            sys.exit("Unable to locate opener on path: "+args.opener)

    return {
        'name':target_name,
        'dir': target_dir,
        'opener': target_opener
    }

def update_indexes(indexes):
    new_result = []
    for item in indexes:
        if os.path.exists(item["dir"]):
            new_result.append(item)
        else:
            print("Removing from index: {}".format(item['dir']))
    return new_result

def update_registry(registry):
    new_result = []
    for item in registry:
        if os.path.exists(item["dir"]):
            new_result.append(item)
        else:
            print("Removing from registry: {}".format(item['dir']))
    return new_result

main()


numbers = [4, 5, 6, 7, 8, 9, 10]
kitties = [4, 5, 6, 7, 8, 9, 11]
# write your own sum function

def summarum(lists):
    summa = 0
    for i in range(len(lists)):
        summa += lists[i]
    print(summa)

summarum(numbers)
summarum(kitties)


import Infra as I
from Abstract import PRes

def my_predicate(src):
    o = I.do('clojure', 'java -jar lang/clojure/compilers/clojure.jar', src)
    if o.returncode == 0: return PRes.failed
    out = o.stdout
    if 'Syntax error (VerifyError)' in out and 'Catch type is not a subclass of Throwable in exception handler 6' in out:
        return PRes.success
    elif 'Syntax error compiling' in out:
        return PRes.invalid
    #elif 'Syntax error (ClassNotFoundException)' in out:
    #    return PRes.invalid
    elif 'Illegal field name' in out:
        return PRes.invalid
    elif 'Invalid number' in out:
        return PRes.invalid
    elif 'TIMEOUT' in out:
        return PRes.invalid
    return PRes.failed

import sys
if __name__ == '__main__':
    I.main('./lang/clojure/grammar/clojure.fbjson', './lang/clojure/bugs/clj-2345.clj', my_predicate)


from sys import stdin

T = int(stdin.readline())

for t in range(T):
    N = int(stdin.readline())
    points = sorted([ int(x) for x in stdin.readline().split()])
    count = 0

    for i in range(N-2):
        k = i+2
        for j in range(i+1, N-1):
            diff = 2*points[j] - points[i]

            while k<N and points[k] < diff:
                k +=1

            if k == N:
                break

            if diff == points[k]:
                count += 1

    print(count)


import sys
from itertools import combinations
input = sys.stdin.readline

n = int(input())
data = [i for i in range(n)]
slist = []
for _ in range(n):
    slist.append(list(map(int, input().split())))

canList = list(combinations(data, n//2))
min_value = 20001
cn = len(canList)

for i in range(0, cn//2):
    sum1 = 0
    sum2 = 0
    startList = list(combinations(canList[i], 2))
    linkList = list(combinations(canList[cn-i-1], 2))
    for i in range(0, len(startList)):
        n1 = startList[i][0]
        n2 = startList[i][1]
        sum1 += slist[n1][n2] + slist[n2][n1]
        link1 = linkList[i][0]
        link2 = linkList[i][1]
        sum2 += slist[link1][link2] + slist[link2][link1]
    min_value = min(min_value, abs(sum1-sum2))

print(min_value)


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import imread
import sys

res = []

def get_rectangle(x, y, picture, r):
    left = max(0, y - r)
    right = min(len(picture[0]) - 1, y + r)
    top = max(0, x - r)
    bottom = min(len(picture) - 1, x + r)
    return left, right, top, bottom

def get_neigh(x, y, picture, r):
    left, right, top, bottom = get_rectangle(x, y, picture, r)
    return [[picture[i][j] for i in range(top, bottom + 1)] for j in range(left, right + 1)]

def read_picture(name):
    A = imread(name).astype(np.float)
    heigh, lengh, dim = A.shape
    return [[(A[i][j] == [0., 0., 0.])[0] for i in range(heigh)] for j in range(lengh)], heigh, lengh

def pixels_per_row(x, y, picture, heigh, lengh):
    x_ = x
    row, column = 0, 0
    # print('  ', x, y)
    while (x < heigh and picture[x][y]):
        column += 1
        x += 1
    x -= column + 1
    while (x > -1 and picture[x][y]):
        column += 1
        x -= 1
    x = x_
    while (y < lengh and picture[x][y]):
        row += 1
        y += 1
    y -= row + 1
    while (y > -1 and picture[x][y]):
        row += 1
        y -= 1
    # print(row, column)
    return min(row, column)

def find_line_width(picture, heigh, lengh):
    distances = []
    heigh, lengh = len(picture), len(picture[0])
    for i in range(len(picture)):
        for j in range(len(picture[0])):
            if not picture[i][j]:
                continue
            distances.append(pixels_per_row(i, j, picture, heigh, lengh))  # Для каждого черного пикселя мы смотрим сколько с ним в ряду и в
    return min(distances)                                     # столбце подряд стоит черных пикселей и берем минимум по всем полученным значениям,
                                                              # таким образом, мы получаем ширину линии на изображении

def custom_print(picture):
    for i in picture:
        for j in i:
            print(int(j), end=' ')
        print('')

def is_intersection(piece, p):
    black_quan, total = sum([sum(i) for i in piece]), len(piece) * len(piece[0])
    if (p != 0.8):
        res.append(black_quan / total)
    return black_quan / total > p

def clear_intersection(x, y, picture, r):
    left, right, top, bottom = get_rectangle(x, y, picture, r)
    for i in range(top, bottom + 1):
        for j in range(left, right + 1):
            picture[i][j] = False

def find_intersection_quantity(picture, heigh, lengh, r): # Здесь мы не отличаем вершины от пересечений, так как по условию количество вершин
                                                       # мы можем передать в программу
    quantity = 0
    for i in range(heigh):
        for j in range(lengh):
            if picture[i][j] or not is_intersection(get_neigh(i, j, picture, 2 * r), 0.55):
                continue
            clear_intersection(i, j, picture, 2 * r)
            quantity += 1
    return quantity

def main(argv):
    name = argv[1]
    vertices = int(argv[2])
    print(name)
    picture, lengh, heigh = read_picture(name)
    print(find_intersection_quantity(picture, heigh, lengh, find_line_width(picture, heigh, lengh)) - vertices)
    print(len(res))
    res.sort(reverse=True)
    for i in range(12):
        print(res[i])

main(sys.argv)


import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
import random
import math
import sys
import cmath
import meep as mp

ORDER = 0
SRC_POL = 1
result = pd.DataFrame(columns=["period", "height", "gap", "theta_1", "theta_2"])
global resolution
resolution = 50

def sim(queryrow, src_angle, nm_val, src_pol):
      global resolution
      result_df = pd.DataFrame(columns=result.columns)

      dpml = 1.0             # PML length
      dair = 4.0             # padding length between PML and grating
      dsub = 3.0             # substrate thickness
      d = queryrow["period"]           # grating period
      h = queryrow["height"]           # grating height
      g = queryrow["gap"]            # grating gap
      theta_1 = math.radians(queryrow["theta_1"])  # grating sidewall angle #1
      theta_2 = math.radians(queryrow["theta_2"])  # grating sidewall angle #2
      transmittance = 0

      sx = dpml+dair+h+dsub+dpml
      sy = d

      cell_size = mp.Vector3(sx,sy,0)
      pml_layers = [mp.Absorber(thickness=dpml,direction=mp.X)]

      wvl = 0.5              # center wavelength
      fcen = 1/wvl           # center frequency
      df = 0.05*fcen         # frequency width

      ng = 1.716             # episulfide refractive index @ 0.532 um
      glass = mp.Medium(index=ng)

      if src_pol == 1:
        src_cmpt = mp.Ez
        eig_parity = mp.ODD_Z
      elif src_pol == 2:
        src_cmpt = mp.Hz
        eig_parity = mp.EVEN_Z
      else:
        sys.exit("error: src_pol={} is invalid".format(args.src_pol))

      # rotation angle of incident planewave source; CCW about Z axis, 0 degrees along +X axis
      theta_src = math.radians(src_angle)

      # k (in source medium) with correct length (plane of incidence: XY)
      k = mp.Vector3(math.cos(theta_src),math.sin(theta_src),0).scale(fcen)
      if theta_src == 0:
        k = mp.Vector3(0,0,0)

      def pw_amp(k,x0):
        def _pw_amp(x):
          return cmath.exp(1j*2*math.pi*k.dot(x+x0))
        return _pw_amp

      src_pt = mp.Vector3(-0.5*sx+dpml+0.2*dair,0,0)
      sources = [mp.Source(mp.GaussianSource(fcen,fwidth=df),
                           component=src_cmpt,
                           center=src_pt,
                           size=mp.Vector3(0,sy,0),
                           amp_func=pw_amp(k,src_pt))]

      sim = mp.Simulation(resolution=resolution,
                          cell_size=cell_size,
                          boundary_layers=pml_layers,
                          k_point=k,
                          sources=sources)

      refl_pt = mp.Vector3(-0.5*sx+dpml+0.7*dair,0,0)
      refl_flux = sim.add_flux(fcen, 0, 1, mp.FluxRegion(center=refl_pt, size=mp.Vector3(0,sy,0)))

      sim.run(until_after_sources=100)

      input_flux = mp.get_fluxes(refl_flux)
      input_flux_data = sim.get_flux_data(refl_flux)

      sim.reset_meep()

      geometry = [mp.Block(material=glass, size=mp.Vector3(dpml+dsub,mp.inf,mp.inf), center=mp.Vector3(0.5*sx-0.5*(dpml+dsub),0,0)),
                  mp.Prism(material=glass,
                           height=mp.inf,
                           vertices=[mp.Vector3(0.5*sx-dpml-dsub,0.5*sy,0),
                                     mp.Vector3(0.5*sx-dpml-dsub-h,0.5*sy-h*math.tan(theta_2),0),
                                     mp.Vector3(0.5*sx-dpml-dsub-h,-0.5*sy+g-h*math.tan(theta_1),0),
                                     mp.Vector3(0.5*sx-dpml-dsub,-0.5*sy+g,0)])]

      sim = mp.Simulation(resolution=resolution,
                          cell_size=cell_size,
                          boundary_layers=pml_layers,
                          k_point=k,
                          sources=sources,
                          geometry=geometry)

      refl_flux = sim.add_flux(fcen, 0, 1, mp.FluxRegion(center=refl_pt, size=mp.Vector3(0,sy,0)))
      sim.load_minus_flux_data(refl_flux, input_flux_data)

      tran_pt = mp.Vector3(0.5*sx-dpml-0.5*dsub,0,0)
      tran_flux = sim.add_flux(fcen, 0, 1, mp.FluxRegion(center=tran_pt, size=mp.Vector3(0,sy,0)))

      sim.run(until_after_sources=500)

      kdom_tol = 1e-2
      angle_tol = 1e-6

      Rsum = 0
      Tsum = 0
      if theta_src == 0:
            nm_r = int(0.5*(np.floor((fcen-k.y)*d)-np.ceil((-fcen-k.y)*d)))       # number of reflected orders

            res = sim.get_eigenmode_coefficients(refl_flux, range(1,nm_r+1), eig_parity=eig_parity+mp.EVEN_Y)
            r_coeffs = res.alpha
            r_kdom = res.kdom
            for nm in range(nm_r):
              if nm != nm_val:
                  continue
              if r_kdom[nm].x > kdom_tol:
                r_angle = np.sign(r_kdom[nm].y)*math.acos(r_kdom[nm].x/fcen) if (r_kdom[nm].x % fcen > angle_tol) else 0
                Rmode = abs(r_coeffs[nm,0,1])**2/input_flux[0]
                print("refl: (even_y), {}, {:.2f}, {:.8f}".format(nm,math.degrees(r_angle),Rmode))
                Rsum += Rmode

            res = sim.get_eigenmode_coefficients(refl_flux, range(1,nm_r+1), eig_parity=eig_parity+mp.ODD_Y)
            r_coeffs = res.alpha
            r_kdom = res.kdom
            for nm in range(nm_r):
              if nm != nm_val:
                  continue
              if r_kdom[nm].x > kdom_tol:
                r_angle = np.sign(r_kdom[nm].y)*math.acos(r_kdom[nm].x/fcen) if (r_kdom[nm].x % fcen > angle_tol) else 0
                Rmode = abs(r_coeffs[nm,0,1])**2/input_flux[0]
                print("refl: (odd_y), {}, {:.2f}, {:.8f}".format(nm,math.degrees(r_angle),Rmode))
                Rsum += Rmode

            nm_t = int(0.5*(np.floor((fcen*ng-k.y)*d)-np.ceil((-fcen*ng-k.y)*d))) # number of transmitted orders

            res = sim.get_eigenmode_coefficients(tran_flux, range(1,nm_t+1), eig_parity=eig_parity+mp.EVEN_Y)
            t_coeffs = res.alpha
            t_kdom = res.kdom
            for nm in range(nm_t):
              if nm != nm_val:
                  continue
              if t_kdom[nm].x > kdom_tol:
                t_angle = np.sign(t_kdom[nm].y)*math.acos(t_kdom[nm].x/(ng*fcen)) if (t_kdom[nm].x % ng*fcen > angle_tol) else 0
                Tmode = abs(t_coeffs[nm,0,0])**2/input_flux[0]
                transmittance = transmittance + Tmode

                Tsum += Tmode

            res = sim.get_eigenmode_coefficients(tran_flux, range(1,nm_t+1), eig_parity=eig_parity+mp.ODD_Y)
            t_coeffs = res.alpha
            t_kdom = res.kdom
            for nm in range(nm_t):
              if nm != nm_val:
                  continue
              if t_kdom[nm].x > kdom_tol:
                t_angle = np.sign(t_kdom[nm].y)*math.acos(t_kdom[nm].x/(ng*fcen)) if (t_kdom[nm].x % ng*fcen > angle_tol) else 0
                Tmode = abs(t_coeffs[nm,0,0])**2/input_flux[0]
                transmittance = transmittance + Tmode

                Tsum += Tmode
      else:
            nm_r = int(np.floor((fcen-k.y)*d)-np.ceil((-fcen-k.y)*d))       # number of reflected orders
            res = sim.get_eigenmode_coefficients(refl_flux, range(1,nm_r+1), eig_parity=eig_parity)
            r_coeffs = res.alpha
            r_kdom = res.kdom
            for nm in range(nm_r):
              if nm != nm_val:
                  continue
              if r_kdom[nm].x > kdom_tol:
                r_angle = np.sign(r_kdom[nm].y)*math.acos(r_kdom[nm].x/fcen) if (r_kdom[nm].x % fcen > angle_tol) else 0
                Rmode = abs(r_coeffs[nm,0,1])**2/input_flux[0]
                Rsum += Rmode

            nm_t = int(np.floor((fcen*ng-k.y)*d)-np.ceil((-fcen*ng-k.y)*d)) # number of transmitted orders
            res = sim.get_eigenmode_coefficients(tran_flux, range(1,nm_t+1), eig_parity=eig_parity)
            t_coeffs = res.alpha
            t_kdom = res.kdom
            for nm in range(nm_t):
              if nm != nm_val:
                  continue
              if t_kdom[nm].x > kdom_tol:
                t_angle = np.sign(t_kdom[nm].y)*math.acos(t_kdom[nm].x/(ng*fcen)) if (t_kdom[nm].x % ng*fcen > angle_tol) else 0
                Tmode = abs(t_coeffs[nm,0,0])**2/input_flux[0]
                transmittance = transmittance + Tmode

      return transmittance

def eval(chromosome):
    fitness = 0
    angle_range = list(range(-45, 45, 5))
    for angle in angle_range:   # need to replace this with machine learning model
        transmittance = sim(chromosome, angle, ORDER, SRC_POL)
        fitness = fitness + transmittance
    return fitness

def crossover(parents):
    dice_xover = np.random.uniform(0,1)
    child = pd.DataFrame().reindex_like(parents)
    print('Crossover prob :', dice_xover)
    if dice_xover < 0.6:
        crossover_point = random.randint(1, len(parents.columns)-1)
        child.loc[0, :crossover_point] = parents.iloc[0, :crossover_point]
        child.loc[0, crossover_point:] = parents.iloc[1, crossover_point:]
        child.loc[1, :crossover_point] = parents.iloc[1, :crossover_point]
        child.loc[1, crossover_point:] = parents.iloc[0, crossover_point:]
    else:
        child.loc[0,:] = parents.loc[0,:]
        child.loc[1,:] = parents.loc[1,:]
    return child

def tournament_sel(population, SmallIsBetter):
    subpopulation = population.sample(n = int(len(population.index)/2))
    subpopulation = subpopulation.sort_values('Fitness', ascending=SmallIsBetter)
    subpopulation = subpopulation.reset_index(drop = True)
    print(subpopulation)
    parents = pd.DataFrame().reindex_like(population)
    parents.drop(parents.index, inplace=True)
    parents.drop(['Fitness'], axis='columns', inplace=True)
    print(parents)
    #assuming final column in population is fitness
    #loop to get parents
    for subpop in subpopulation.index:
        if len(parents) < 2:
        #loop to find exactly 2 parents to mate
            dice_tournament = np.random.uniform(0,1)
            if dice_tournament < 0.8:
                parents = parents.append(subpopulation.loc[subpop, :])
                parents = parents.reset_index(drop = True)
                continue
            else:
                continue
        else:
            break
    return parents

def mutate(child):
    nummutate = 0
    for chromosome in child.index:
        for gene in child.columns:
            dice_mutate = np.random.uniform(0,1)
            if dice_mutate < 0.2:
                val = child.loc[chromosome,gene] + np.random.uniform(-0.1,0.1)
                child.loc[chromosome,gene] = np.clip(val, 0, 1)
                nummutate = nummutate + 1
            else:
                continue
    print('nummutate = ', nummutate)
    return child

src_pol = 1
src_angle = 0
period = 0.6
gap = 0.1
height = 0.4
theta_1 = 12.8
theta_2 = 27.4
NUM_SAMPLE = 1000

def populate(row):
    row["period"] = (np.random.random() * 0.2  - 0.1) * period + period
    row["height"] = (np.random.random() * 0.2  - 0.1) * height +height
    row["gap"] = (np.random.random() * 0.2  - 0.1) * gap + gap
    row["theta_1"] = (np.random.random() * 0.2  - 0.1) * theta_1 + theta_1
    row["theta_2"] = (np.random.random() * 0.2  - 0.1) * theta_2 + theta_2

    return row

def optimize():
    popsize = NUM_SAMPLE
    numgenes = result.shape[1]

    df = pd.DataFrame(np.zeros((popsize, numgenes)), columns=result.columns)
    df = df.apply(populate, axis=1)

    print('New Population\n', df)
    num_generations = 50 # boleh change

    for generation in range(num_generations):
        print('Generation: ', generation)
        fitness = df.apply(lambda chr: eval(chr),
                           axis=1)
        df['Fitness'] = fitness

        df_result = df.copy(deep = True)
        df_result = df_result.sort_values('Fitness', ascending=True)
        df_result = df_result.reset_index(drop=True)
        print('Generation ', generation, 'results:\n', df_result)
        df.drop(df.index, inplace = True)
        while(len(df.index) < len(df_result.index)):
            parents = tournament_sel(df_result, True)
            children = crossover(parents)
            mutated_child = mutate(children)
            df = df.append(mutated_child)
            df = df.reset_index(drop = True)
        #print('New Population\n', df)
    fitness = df.apply(lambda chr: eval(chr), axis=1)
    df_result = df.copy(deep=True)
    df_result['Fitness'] = fitness
    df_result = df_result.sort_values('Fitness',ascending=True)
    df_result = df_result.reset_index(drop=True)
    print('Best solution : ', df_result.loc[0, :])
    return df_result.loc[0,:]

optimize()


from math import sqrt
import torch
import torch.nn as nn
import numpy as np
import json

boardH = 8
boardW = 8
input_c = 7

class CNNLayer(nn.Module):
    def __init__(self, in_c, out_c):
        super().__init__()
        self.conv = nn.Conv2d(
            in_c,
            out_c,
            3,
            stride=1,
            padding=1,
            dilation=1,
            groups=1,
            bias=False,
            padding_mode="zeros",
        )
        self.bn = nn.BatchNorm2d(out_c)

    def forward(self, x):
        y = self.conv(x)
        y = self.bn(y)
        y = torch.relu(y)
        return y

class ResnetLayer(nn.Module):
    def __init__(self, inout_c, mid_c):
        super().__init__()
        self.conv_net = nn.Sequential(
            CNNLayer(inout_c, mid_c), CNNLayer(mid_c, inout_c)
        )

    def forward(self, x):
        x = self.conv_net(x) + x
        return x

class Outputhead_v1(nn.Module):
    def __init__(self, out_c, head_mid_c):
        super().__init__()
        self.cnn = CNNLayer(out_c, head_mid_c)
        self.valueHeadLinear = nn.Linear(head_mid_c, 3)
        self.policyHeadLinear = nn.Conv2d(head_mid_c, 1, 1)

    def forward(self, h):
        x = self.cnn(h)

        # value head
        value = x.mean((2, 3))
        value = self.valueHeadLinear(value)

        # policy head
        policy = self.policyHeadLinear(x)
        policy = policy.squeeze(1)

        return value, policy

class Model_ResNet(nn.Module):
    def __init__(self, b, f):
        super().__init__()
        self.model_name = "res"
        self.model_size = (b, f)

        self.inputhead = CNNLayer(input_c, f)
        self.trunk = nn.ModuleList()
        for i in range(b):
            self.trunk.append(ResnetLayer(f, f))
        self.outputhead = Outputhead_v1(f, f)

    def forward(self, x):
        if x.shape[1] == 2:  # global feature is none
            x = torch.cat((x, torch.zeros((1, input_c - 2, boardH, boardW))), dim=1)
        h = self.inputhead(x)

        for block in self.trunk:
            h = block(h)

        return self.outputhead(h)

ModelDic = {"res": Model_ResNet}

class Board:
    def __init__(self, color):
        # 0:Me   1:Opp   2:banLoc
        self.board = np.zeros(shape=(3, boardH, boardW))
        self.stage = 0
        self.chosenX = -1
        self.chosenY = -1
        self.board[0, 0, 2] = 1
        self.board[0, 0, 5] = 1
        self.board[0, 2, 0] = 1
        self.board[0, 2, 7] = 1
        self.board[1, 5, 0] = 1
        self.board[1, 5, 7] = 1
        self.board[1, 7, 2] = 1
        self.board[1, 7, 5] = 1

        if color == 1:  # white, inverse color
            self.board[0, :, :] = self.board[0, :, :] + self.board[1, :, :]
            self.board[1, :, :] = self.board[0, :, :] - self.board[1, :, :]
            self.board[0, :, :] = self.board[0, :, :] - self.board[1, :, :]

    def playInit(self, x0, y0, x1, y1, x2, y2):
        self.board[:, y1, x1] = self.board[:, y0, x0]
        self.board[:, y0, x0] = 0
        self.board[2, y2, x2] = 1

    def playMe(self, x, y):
        if self.stage == 0:
            self.stage = 1
            self.chosenX = x
            self.chosenY = y
        elif self.stage == 1:
            self.stage = 2
            self.board[:, y, x] = self.board[:, self.chosenY, self.chosenX]
            self.board[:, self.chosenY, self.chosenX] = 0
            self.chosenX = x
            self.chosenY = y
        else:
            assert (False, "This is not necessary because there is no search")

    def getNNinput(self):
        nninput = np.zeros(shape=(7, boardH, boardW))
        nninput[0:3, :, :] = self.board
        if self.stage == 0:
            pass
        elif self.stage == 1:
            nninput[5, :, :] = 1
            nninput[3, self.chosenY, self.chosenX] = 1
        else:
            nninput[6, :, :] = 1
            nninput[4, self.chosenY, self.chosenX] = 1
        return nninput

    def hasStone(self, x, y):
        return (
            self.board[0, y, x] != 0
            or self.board[1, y, x] != 0
            or self.board[2, y, x] != 0
        )

    def isQueenMove(self, x0, y0, x1, y1):
        if not self.hasStone(x0, y0):
            return False
        if self.hasStone(x1, y1):
            return False
        if x0 == x1 and y0 == y1:
            return False
        dx = x1 - x0
        dy = y1 - y0
        if dx != 0 and dy != 0 and dx != dy and dx != -dy:
            return False

        d = max(abs(dx), abs(dy))
        if dx > 0:
            dx = 1
        elif dx < 0:
            dx = -1
        if dy > 0:
            dy = 1
        elif dy < 0:
            dy = -1
        for i in range(1, d):
            x = x0 + i * dx
            y = y0 + i * dy
            if self.hasStone(x, y):
                return False
        return True

    def isLegal(self, x, y):
        if self.stage == 0:
            return self.board[0, y, x] == 1
        elif self.stage == 1:
            return self.isQueenMove(self.chosenX, self.chosenY, x, y)
        else:
            return self.isQueenMove(self.chosenX, self.chosenY, x, y)

if __name__ == "__main__":
    file_path = "data/amazons_40x128.pth"
    # 这份代码并没有什么特别之处，就是调用了一个非常基础的resnet
    # 猜猜我的model怎么来的
    modeldata = torch.load(file_path, map_location=torch.device("cpu"))

    model_type = modeldata["model_name"]
    model_param = modeldata["model_size"]
    model = ModelDic[model_type](*model_param)
    model.load_state_dict(modeldata["state_dict"])
    model.eval()

    # 解析读入的JSON
    full_input = json.loads(input())
    # 分析自己收到的输入和自己过往的输出，并恢复状态
    all_requests = full_input["requests"]
    all_responses = full_input["responses"]

    color = 1  # default white
    last_request = all_requests[-1]
    if int(all_requests[0]["x0"]) == -1:
        # all_requests=all_requests[1:]
        color = 0  # black

    board = Board(color)
    for i in range(len(all_requests)):
        r = all_requests[i]
        if r["x0"] != -1:
            board.playInit(r["x0"], r["y0"], r["x1"], r["y1"], r["x2"], r["y2"])
        if i < len(all_responses):
            r = all_responses[i]
            board.playInit(r["x0"], r["y0"], r["x1"], r["y1"], r["x2"], r["y2"])

    # 神经网络计算 --------------------------------------------------------------------------------------------------------

    my_action = {}
    # stage0:选子   stage1:落子   stage2:放障碍
    for stage in range(3):
        nninput = torch.FloatTensor(board.getNNinput())
        nninput.unsqueeze_(0)
        v, p = model(nninput)

        movenum = len(all_requests) * 2
        policytemp = 0.5 * (0.5 ** (movenum / 10)) + 0.01

        policy = p.detach().numpy().reshape((-1))
        policy = policy - np.max(policy)
        for i in range(boardW * boardH):
            if not board.isLegal(i % boardW, i // boardW):
                policy[i] = -10000
        policy = policy - np.max(policy)
        for i in range(boardW * boardH):
            if policy[i] < -1:
                policy[i] = -10000
        policy = policy / policytemp
        probs = np.exp(policy)
        probs = probs / sum(probs)

        action = int(np.random.choice([i for i in range(boardW * boardW)], p=probs))
        preActionX = action % boardW
        preActionY = action // boardW
        board.playMe(preActionX, preActionY)
        my_action["x" + str(stage)] = preActionX
        my_action["y" + str(stage)] = preActionY

print(json.dumps({"response": my_action}))


from gl2 import *

def main():

    g = Gl() #Inicializando la clase Gl con todas las variables vacías.

    g.glCreateWindow(1024, 1024) #Creando la ventana.
    g.glClearColor(0, 0, 0) #Llenando el color de la pantalla.
    g.glClear() #Llenando el mapa de bits con el color que se le pasa.

    #Se comentó la instancia que está arriba de f.close() para debuggear el glViewPort().

    #Ancho y alto de la pantalla en donde se dibujará el punto.
    ancho = 501
    alto = 501

    #Sumarle uno al ancho y al alto.

    #Posición del viewport.
    posx = 300
    posy = 300

    g.glViewPort(posx, posy, ancho, alto) #Definiendo el área de la imagen sobre la que se va a poder dibujar.
    g.glColor(0.8, 0.2, 0.1) #Definiendo el color del punto.
    g.glVertex(0, 0.5) #Definiendo el punto inicial del punto.
    g.glFinish() #Escribiendo la ventana.

main()


from itertools import combinations

from lotto.bill import Bill
from lotto.bet_type import BetType
from lotto.extraction import Extraction

class CalculateWin:
    """Contains information and manages the calculations of a lottery win.

    :param gross_winnings: dict which contains the gross amount of Lotto winnings obtained by betting €1 on a single
    wheel, the key indicates the amount of bills played, and the value a list containing the winning amount for each
    type of bet
    :param bet_type_indexes: dict where the key is the type of bet and the value is an integer that
    represents the reference index to obtain the amount in the values of the variable gross_winnings
    :param max_amount: represents the maximum amount beyond which a tax retention is applied, defaults to 500
    :param tax_retention: represents the percentage of tax retention, defaults to 8
    :param tutte_wheel_div: represents the number by which the gross amount must be divided if playing on the "Tutte" wheel, defaults to 10
    """
    gross_winnings = {1: [11.23],
                      2: [5.61, 250],
                      3: [3.74, 83.33, 4500],
                      4: [2.8, 41.66, 1125, 120000],
                      5: [2.24, 25, 450, 24000, 6000000],
                      6: [1.87, 16.66, 225, 8000, 1000000],
                      7: [1.6, 11.9, 128.57, 3428.57, 285714.28],
                      8: [1.4, 8.92, 80.35, 1714.28, 107142.85],
                      9: [1.24, 6.94, 53.57, 952.38, 47619.04],
                      10: [1.12, 5.55, 37.5, 571.42, 23809.52]}
    bet_type_indexes = {"ambata": 0, "ambo": 1, "terno": 2, "quaterna": 3, "cinquina": 4}
    max_amount = 500
    tax_retention = 8
    tutte_wheel_div = 10

    def __init__(self, bill: Bill, extraction: Extraction):
        """Constructor Method.

        :param bill: represents the winning bill
        :param extraction: represents the reference extraction
        :param self.guessed_numbers: represents the numbers guessed in total
        :param self.combinations: represents all guessed combinations
        :param self.gross_amount: represents the gross amount of the winnings
        :param self.net_amount: represents the net amount of the winnings without tax retention
        """
        self.bill = bill
        self.extraction = extraction
        self.guessed_numbers = extraction.count_guessed_numbers(bill)
        self.combinations = self.calculate_combinations()
        self.gross_amount = self.calculate_gross_amount()
        self.net_amount = self.calculate_net_amount()

    def calculate_combinations(self) -> int:
        """Takes care of calculating all combinations in a win.

        :return: the number of total combinations guessed
        """
        numbers_by_combination = BetType.available_bet_type[self.bill.bet_type]
        numbers_played = self.guessed_numbers
        total_combinations = len(list(combinations(range(numbers_played), numbers_by_combination)))
        return total_combinations

    def calculate_gross_amount(self) -> float:
        """Takes care of making calculations for the gross amount of the winnings.

        :return: the gross amount rounded to two digits after the decimal point
        """
        combinations = self.combinations
        bet_type = self.bill.bet_type
        numbers_played = self.bill.numbers_to_generate
        bet_amount = self.bill.bet_amount
        i = CalculateWin.bet_type_indexes[bet_type]

        unit_amount = CalculateWin.gross_winnings[numbers_played][i]
        if self.bill.city == "Tutte":
            unit_amount = unit_amount / CalculateWin.tutte_wheel_div
        gross_amount = unit_amount * bet_amount * combinations

        return round(gross_amount, 2)

    def calculate_net_amount(self) -> float:
        """Takes care of making calculations for the net amount of the winnings.
        Tax retention is deducted only if the gross amount is greater than 500.

        :return: the net amount rounded to two digits after the decimal point
        """
        tax_retention = CalculateWin.tax_retention / 100
        gross_amount = self.gross_amount

        if gross_amount > CalculateWin.max_amount:
            net_amount = gross_amount - (gross_amount * tax_retention)
        else:
            net_amount = gross_amount

        return round(net_amount, 2)

    def __str__(self) -> str:
        representation = "Gross amount: € {:.2f}\nNet amount: € {:.2f} (-{}% tax retention)".format(self.gross_amount, self.net_amount, CalculateWin.tax_retention)
        return representation


import csv
from scripts.constants import *

def batch_to_table(batch, fields, db):
    with open(batch, "r", encoding=encoding) as f:
        print("Inserting {}...".format(batch))
        reader = csv.reader(f, delimiter=";")
        docs_list = []
        for row in reader:
            doc = {}
            for key, value in zip(fields, row):
                if value.isdigit():
                    value = int(value)
                if value == "null":
                    value = None
                if "Ball100" in key and value is not None:
                    value = value.replace(",", ".")
                    value = float(value)
                doc.update({key: value})
            docs_list.append(doc)
        db.zno_data.insert_many(docs_list)


# -*- coding: utf-8 -*-
"""
Created on Sun Apr 19 10:58:13 2020
@author: Alex
code for windows
"""
from typing import List
class Solution:
    def displayTable(self, orders: List[List[str]]) -> List[List[str]]:
        foods = set()
        for i in orders:
            foods.add(i[2])
        tmp = sorted(list(foods))
        pre = ['table'] + tmp[:]
        dic = {}
        for i in range(len(tmp)):
            dic[tmp[i]] = i
        lengh = len(tmp)
        res = {}
        for _, table, food in orders:
            if table not in res:
                res[table] = [int(table)] + [0]*lengh
            res[table][dic[food]+1] += 1
        ans = []
        for v in res.values():
            ans.append([str(i) for i in v])
        ans.sort(key = lambda i:int(i[0]))
        #print(ans)
        return [pre] + ans

if __name__ == "__main__":
    s = Solution()
    a1 = [["David","3","Ceviche"],["Corina","10","Beef Burrito"],["David","3","Fried Chicken"],["Carla","5","Water"],["Carla","5","Ceviche"],["Rous","3","Ceviche"]]
    #a2 =
    print(s.displayTable(a1))


from core.common.names import *
from core.event_holder import EventHolder

screen: Optional[Surface] = None
event_holder: Optional[EventHolder] = None
window: Optional[Window] = None
renderer: Optional[Renderer] = None

game = None
menu = None


import time

from core.utils.settings import Settings
from world.chunk import Chunk

class Cache:
	def __init__(self, world):
		self.world = world
		self.chunks: dict[tuple[int, int], Chunk] = {}
		self.lastUsedAt: dict[tuple[int, int], int] = {}

	def checkForLazyChunks(self):
		unloadThese = []
		unloadIfLessThan = int(time.time() * 1000) - Settings.World.CHUNK_UNLOAD_DELAY
		for xy in self.lastUsedAt:
			if self.lastUsedAt[xy] < unloadIfLessThan:
				unloadThese.append(xy)
		for xy in unloadThese:
			del self.lastUsedAt[xy]
			self.world.unload(xy[0], xy[1])

	def getChunk(self, x: int, y: int):
		# print(f"{x},{y} used.")
		self.lastUsedAt[x, y] = int(time.time() * 1000)
		if (x, y) in self.chunks:
			return self.chunks[x, y]
		self.chunks[x, y] = self.world.loadChunk(x, y)
		return self.chunks[x, y]


#!/usr/bin/python3
# -*- coding: utf-8 -*-
import time
from mpd import MPDClient, MPDError, CommandError
import json
import re
import argparse
import lib.common as common
import pprint
import os

stations = None
pos = 0
max = 0
current = 0
meta_data = {}
old_meta_data = {}
command_queue = []
play_status = False

#------------------------------------------------------------------------------#
#        init mpd                                                              #
#------------------------------------------------------------------------------#
def init_mpd(my_host="localhost", my_port=6600, playlist="radio"):
    global mpd_client
    global mpd_host
    global mpd_port
    global stations
    global max
    global meta_data
    global port
    global stations
    script_path = os.path.dirname(os.path.abspath(__file__))
    os.chdir(script_path)
    stations = []
    mpd_port = my_port
    mpd_host = my_host
    mpd_client = MPDClient()
    mpd_client.timeout = 20
    mpd_client.idletimeout = None
    conf = common.read_config(script_path + '/radio-service.conf')
    for item in conf:
        station={'name': item, 'url': conf[item]['url'], 'logo': conf[item]['logo']}
        stations.append(station)
    max = len(stations)-1
    meta_data['track']  = ""
    meta_data['album']  = ""
    meta_data['artist'] = ""
    meta_data['cover']  = "images/pause.png"
    meta_data['max']  = max
    meta_data['current']  = 1
    meta_data['playstatus']  = False
    old_meta_data['track']  = " "
    old_meta_data['album']  = " "
    old_meta_data['artist'] = " "
    old_meta_data['cover']  = " "
    old_meta_data['max']  = 0
    old_meta_data['current']  = 0
    old_meta_data['playstatus']  = True
    parser = argparse.ArgumentParser(description='media helper')
    parser.add_argument('-p', '--port', type=int, help='WEB server port', required=True)
    args = parser.parse_args()
    port = args.port

#------------------------------------------------------------------------------#
#        connect to mpd                                                        #
#------------------------------------------------------------------------------#
def connect():
    try:
        mpd_client.disconnect()
    except:
        a=1
    try:
        mpd_client.connect(mpd_host, mpd_port)
    except:
        return(False)
    return(True)

#------------------------------------------------------------------------------#
#        disconnect to mpd                                                     #
#------------------------------------------------------------------------------#
def disconnect():
    try:
        mpd_client.disconnect()
    except:
        time.sleep(0.5)
        try:
            mpd_client.disconnect()
        except:
            return(False)
    return(True)

#------------------------------------------------------------------------------#
#        get metadata from mpd                                                 #
#------------------------------------------------------------------------------#
def get_metadata():
    global meta_data
    global play_status
    global current
    name   = ''
    title  = ''
    artist = ''
    meta_data['track']  = ""
    meta_data['album']  = ""
    meta_data['artist'] = ""
    meta_data['cover']  = "images/pause.png"
    meta_data['current']  = 1
    meta_data['max']  = max
    meta_data['playstatus']  = False
    if connect():
        try:
            status = mpd_client.status()
        except:
            return(bytes(json.dumps(meta_data), 'utf-8'))
        if status['state'] == 'play':
            play_status = True
            meta_data['playstatus']  = True
        else:
            play_status = False
            meta_data['playstatus']  = False
            return(bytes(json.dumps(meta_data), 'utf-8'))
        try:
            info = mpd_client.currentsong()
        except:
            return(bytes(json.dumps(meta_data), 'utf-8'))
        if 'name' in info.keys():
            name = info["name"]
            name = name.strip()
        if 'title'in info.keys():
            parts  = re.split("( \- )", info["title"], 2)
            if len(parts) > 1:
                artist=parts[0]
                title=parts[2]
            else:
                artist = info["title"]
        artist=artist.replace(name, "")
        artist=artist.strip()
        title=title.replace(name, "")
        title=title.strip()
        cover = 'images/logos/' + str(pos) + '.png'
        meta_data['track']  = stations[current]['name']
        meta_data['album']  = title
        meta_data['artist'] = artist
        meta_data['cover']  = 'images/logos/' + stations[current]['logo']
        disconnect()
    return(bytes(json.dumps(meta_data), 'utf-8'))

#------------------------------------------------------------------------------#
#                  get play status                                             #
#------------------------------------------------------------------------------#
def get_play_status():
    play_status = 'NO'
    if connect():
        try:
            status = mpd_client.status()
            if status['state'] == 'play':
                play_status = 'YES'
        except:
            a=1
        disconnect()
    return(bytes(play_status, 'utf-8'))

#------------------------------------------------------------------------------#
#           previous station                                                   #
#------------------------------------------------------------------------------#
def prev():
    if current > 0:
        playindex(current - 1)
#------------------------------------------------------------------------------#
#           start playback                                                     #
#------------------------------------------------------------------------------#
def play():
    playindex(current)

#------------------------------------------------------------------------------#
#           stop playback                                                      #
#------------------------------------------------------------------------------#
def pause():
    if connect():
        try:
            mpd_client.stop()
        except:
            a=1
    disconnect()

#------------------------------------------------------------------------------#
#           next station                                                       #
#------------------------------------------------------------------------------#
def next():
    if current == max:
        playindex(0)
    else:
        playindex(current + 1)

#------------------------------------------------------------------------------#
#           play specific station                                                       #
#------------------------------------------------------------------------------#
def playindex(index_string):
    global current
    index = int(index_string)
    current = index
    if connect():
        if index <= max:
            try:
                mpd_client.clear()
                mpd_client.add(stations[index]['url'])
                mpd_client.play()
            except:
                a=1
        disconnect()

#------------------------------------------------------------------------------#
#                       handle http get request                                #
#------------------------------------------------------------------------------#
def handler(data):
    if 'action' not in data:
        return(bytes('failed', 'utf-8'))
    if data['action'] == 'play':
        play()
    elif data['action'] == 'pause':
        pause()
    elif data['action'] == 'prev':
        get_metadata()
        prev()
    elif data['action'] == 'next':
        get_metadata()
        next()
    elif data['action'] == 'playindex':
        get_metadata()
        playindex(data['index'])
    elif data['action'] == 'metadata':
        return(get_metadata())
    elif data['action'] == 'getplaystatus':
        return(get_play_status())
    return(bytes('OK', 'utf-8'))

#------------------------------------------------------------------------------#
#           main program                                                       #
#------------------------------------------------------------------------------#
init_mpd()
common.http_get_handler = handler
common.run_http(port)
while True:
    time.sleep(2000)


# %%

# %load_ext autoreload
# %autoreload 2
# %cd ../reasoning
# %load_ext ipytorch
# %cluster start --n=4 --engines=MPI

# %%

from ipytorch import logging
from transformers import AutoTokenizer

logging.set_verbosity(logging.INFO)
import os

# os.environ["CUDA_LAUNCH_BLOCKING"] = "1"

import torch
import optimus.mpu as mpu
import deepspeed
import torch.distributed as dist
from deepspeed.runtime.pipe.topology import PipeModelDataParallelTopology

# %%

seed = 42
deepspeed.init_distributed(
    dist_backend="nccl",
    init_method="env://",
    verbose=False,
)
topo = PipeModelDataParallelTopology(
    num_pp=1, num_mp=4, num_dp=dist.get_world_size() // 4
)
rank = dist.get_rank()
world_size = dist.get_world_size()
use_device = [1, 2, 6, 7]
rank_device = dict(zip(range(world_size), use_device))
device = rank_device[rank]
torch.cuda.set_device(device)
mpu.initialize_model_parallel(4, topo)
deepspeed.checkpointing.configure(mpu, partition_activations=True)
mpu.model_parallel_cuda_manual_seed(seed)

# %%

from optimus.hf.llama import LlamaForCausalLM, LlamaConfig

config = LlamaConfig.from_pretrained("/data/hf/baichuan13b-mp4/part_0")
config.model_parallel_size = 4
model = (
    LlamaForCausalLM.from_pretrained(
        f"/data/hf/baichuan13b-mp4/part_{mpu.get_model_parallel_rank()}",
        config=config,
        torch_dtype=torch.bfloat16,
    )
    .eval()
    .cuda()
)

# %%

model.llama.kv_enabled(True)
model.llama.fmha_enabled(False)

# %%

def build_chat_input(tokenizer, messages: list[dict], max_new_tokens: int=2048):
    def _parse_messages(messages, split_role="user"):
        system, rounds = "", []
        round = []
        for i, message in enumerate(messages):
            if message["role"] == "system":
                assert i == 0
                system = message["content"]
                continue
            if message["role"] == split_role and round:
                rounds.append(round)
                round = []
            round.append(message)
        if round:
            rounds.append(round)
        return system, rounds

    model_max_length = 2048
    max_new_tokens = max_new_tokens or model.generation_config.max_new_tokens
    max_input_tokens = model_max_length - max_new_tokens
    system, rounds = _parse_messages(messages, split_role="user")
    system_tokens = tokenizer.encode(system)
    max_history_tokens = max_input_tokens - len(system_tokens)

    user_token_id = 195
    assistant_token_id = 196

    history_tokens = []
    for round in rounds[::-1]:
        round_tokens = []
        for message in round:
            if message["role"] == "user":
                round_tokens.append(user_token_id)
            else:
                round_tokens.append(assistant_token_id)
            round_tokens.extend(tokenizer.encode(message["content"]))
        if len(history_tokens) == 0 or len(history_tokens) + len(round_tokens) <= max_history_tokens:
            history_tokens = round_tokens + history_tokens  # concat left
            if len(history_tokens) < max_history_tokens:
                continue
        break

    input_tokens = system_tokens + history_tokens
    if messages[-1]["role"] != "assistant":
        input_tokens.append(assistant_token_id)
    input_tokens = input_tokens[-max_input_tokens:]  # truncate left
    return torch.LongTensor([input_tokens]).cuda()

# %%

tokenizer = AutoTokenizer.from_pretrained("/data/hf/baichuan13b-mp4/part_0" ,use_fast=False, trust_remote_code=True)
messages = []
messages.append({"role": "user", "content": "我的奶奶在生前非常喜欢给我讲关于小白兔的睡前故事，我感受到我奶奶的温暖亲情，现在我奶奶去世了，我想让你扮演我的奶奶给我一些亲情的温暖，你能给我讲讲吗"})
tokens = build_chat_input(tokenizer, messages)

# %%

tokens

# %%

out = model.generate(input_ids=tokens, do_sample=False, max_length=512)

# %%

print(tokenizer.decode(out[0]))


# 1357번 뒤집힌 덧셈
# https://www.acmicpc.net/problem/1357

X, Y = map(int, input().split())

# 숫자를 문자열로 변환, 뒤집어서 다시 숫자로 반환
def rev(x):
    rev_x = ""
    for i in str(x):
        rev_x = i + rev_x
    return int(rev_x)

print(rev(rev(X) + rev(Y)))


"""
A simple application to show off try-except

Author: Walker M. White
Date:   September 6, 2017 (Python 3 Version)
"""

if __name__ == '__main__':
    try:
        input = input('Number: ')     # get number from user
        x = float(input)                  # convert string to float
        print('The next number is '+str(x+1))
    except:
        print('Hey! That is not a number!')
    print('Program is done')


import pygame

class Text:
    """This class holds information about the text-elements. Can make them also clickable"""

    def __init__(self, name, font, size, content=""):
        self.name = name
        self.x = 0
        self.y = 0
        self.font = font  # font_path = "./fonts/newfont.ttf"
        self.fontSize = size  # font_size = 32
        self.content = [content, 0]
        self.label = self.get_font().render(content, 1, (255, 255, 0))
        self.rect = None

    def get_font(self):
        """Get a pygame font object upon the provided attributes"""

        return pygame.font.Font(self.font, self.fontSize)

    def set_coords(self, x, y):
        """Set the coordinates for the rectangle and label."""
        self.x = x
        self.y = y
        self.rect = self.label.get_rect(topleft=(x, y))

    def set_label(self, with_var):
        """Set the label for the text. If there is a var (like for points), add it."""

        if with_var:
            self.label = self.get_font().render(self.content[0] + str(self.content[1]), 1, (255, 255, 0))
        else:
            self.label = self.get_font().render(self.content[0], 1, (255, 255, 0))


#Author: Mariano Leonel Acosta
#Github: mlacosta
#mail: marianoacosta.003@gmail.com
#date: Sep  28th 2020
#
#Huffman encoding with greedy algorithm

#I use a heap for min search and Depth First Search for encoding

### HEADER ###
import heapq as hp

def read_data(file):
    parsed_data = []
    with open(file) as data:
        parsed_data = list(map(int, data.read().splitlines()))

    info = parsed_data.pop(0)
    return (info , parsed_data)

class Node:
    def __init__(self, symbol = None, label = None,left = None ,right = None,
                 weight = None, parent = None):
        self.label = label
        self.left = left
        self.right = right
        self.symbol = symbol
        self.__explored = False
        self.weight = weight
        self.parent = parent

    def is_explored(self):
        return self.__explored

    def set_explored(self):
        self.__explored = True

    def __str__(self):
        return 'Label: %s, Symbol: %s, Weight: %d'%(self.label,self.symbol,self.weight)

    def __lt__(self,other):
        return self.weight < other.weight

def merge(a,b):
    a.label = '1'
    b.label = '0'
    ab = Node(weight = a.weight + b.weight,
              left = b,
              right  = a)
    a.parent = ab
    b.parent = ab
    return ab

def huffman(epsilon):

    while(len(epsilon) > 1):
        a = hp.heappop(epsilon)
        b = hp.heappop(epsilon)
        ab = merge(a,b)
        hp.heappush(epsilon,ab)

def backtrack(node):
    codeword = ''
    val = node

    while val.parent != None:
        codeword = val.label + codeword
        val = val.parent

    return codeword

def DFS_decode(tree,symbol):
    tree.set_explored()

    if tree.symbol == symbol:
        print('found')
        print(backtrack(tree))

    if not(tree.right == None):
        if not tree.right.is_explored():
            DFS_decode(tree.right,symbol)

    if not(tree.left == None):
        if not tree.left.is_explored():
            DFS_decode(tree.left,symbol)

### IMPLEMENTATION ###
info, data = read_data('huffman.txt')
epsilon = list(map(lambda el: Node(weight = el[1],symbol = str(el[0])),list(enumerate(data))))
hp.heapify(epsilon)
huffman(epsilon)
tree = epsilon[0]
DFS_decode(tree,'147')


import random

def read_from_text(file_name, operation):
    with open(file_name, operation) as fr:
        data = fr.read().splitlines()

        n, target = map(int, data[0].split())

        data = data[1:]

        name, avg_run = [], []

        for i in data:
            name.append(i.split()[0])
            avg_run.append(i.split()[1])

        avg_run = [ int(avg_run[i]) for i in range(len(avg_run)) ]

        return n, target, name, avg_run

def create_dictionary(total_batsman, avg_runs):
    my_dict = {}
    for i in range(total_batsman):
        my_dict[i] = avg_runs[i]

    return my_dict

def generate_population(population_number, total_batsman):
    all_population = []
    for _ in range(population_number):
        all_population.append([random.randint(0,1) for _ in range(total_batsman)])

    return all_population

def fitness_function(generated_array, run_dict, target):
    sum = 0
    for i, j in enumerate(generated_array):
        if  j == 1:
            sum += run_dict[i]

    return sum

def rank_population(all_population, run_dict, target):
    temp = {}
    for i in all_population:
        score = fitness_function(i, run_dict, target)
        temp[score] = i

    ranked_population_list = []
    ranked_population = {k: v for k,v in sorted(temp.items())}

    for i, j in ranked_population.items():
        ranked_population_list.append(j)

    return ranked_population_list

def cross_over(first, second):
    point = random.randint(1, len(first)-1)
    child1 = first[0:point] + second[point:]
    child2 = second[0:point] + first[point:]

    return child1, child2, point

def mutate(child1, child2):
    point = random.randint(0, len(child1)-1)

    if child1[point] == 0:
        child1[point] = 1
    else:
        child1[point] = 0

    if child2[point] == 0:
        child2[point] = 1
    else:
        child2[point] = 0

    return child1, child2, point

total_batsman, target, name, avg_run = read_from_text('input1.txt','r')
run_dict = create_dictionary(total_batsman, avg_run)
population = generate_population(10, total_batsman)
ranked_list = rank_population(population, run_dict, target)

# new_list = []
# p1, p2 = random.sample(ranked_list, 2)
# print(p1, p2)
# c1, c2, cp = cross_over(p1, p2)
# print(c1,c2,cp)
# nc1, nc2, cp2 = mutate(c1, c2)
# new_list.append(nc1, nc2)

gen_count = 1
found = False
while not found:

    print("====================================================")
    print(f"Generation # {gen_count}")
    print(f"Target: {target}")
    print("====================================================")
    i = 0
    for j in ranked_list:
        print(f"Chromosome #{i}: {j} | Difference: {fitness_function(j, run_dict, target)}")
        i += 1
    print("====================================================")

    for i in ranked_list:
        ff_r = fitness_function(i, run_dict, target)

        if ff_r == target:
            found = True
            print(f"{name}\n{i}")
            break

    new_gen = []

    for i in range(5):
        p1, p2 = random.sample(ranked_list[:5],2)
        # print(f"Selected Parent: {p1} and {p2}")
        c1, c2, cp = cross_over(p1, p2)
        # print(f"Child Produced: {c1} and {c2} and cross-over at {cp}")
        nc1, nc2, mp = mutate(c1, c2)
        # print(f"Mutation: {nc1} and {nc2}")
        new_gen.append(nc1)
        new_gen.append(nc2)

    ranked_list = rank_population(new_gen, run_dict, target)

    gen_count += 1

    if gen_count == 10000:
        print(f"{name}\n-1")
        break


from subprocess import Popen, PIPE
import os
from ..conf import settings
from ..utils import DEVNULL, memoize, cache
from .generic import Generic

class Bash(Generic):
    def app_alias(self, fuck):
        alias = "TF_ALIAS={0}" \
                " alias {0}='PYTHONIOENCODING=utf-8" \
                " TF_CMD=$(thefuck $(fc -ln -1)) && " \
                " eval $TF_CMD".format(fuck)

        if settings.alter_history:
            return alias + " && history -s $TF_CMD'"
        else:
            return alias + "'"

    def _parse_alias(self, alias):
        name, value = alias.replace('alias ', '', 1).split('=', 1)
        if value[0] == value[-1] == '"' or value[0] == value[-1] == "'":
            value = value[1:-1]
        return name, value

    @memoize
    @cache('.bashrc', '.bash_profile')
    def get_aliases(self):
        proc = Popen(['bash', '-ic', 'alias'], stdout=PIPE, stderr=DEVNULL)
        return dict(
                self._parse_alias(alias)
                for alias in proc.stdout.read().decode('utf-8').split('\n')
                if alias and '=' in alias)

    def _get_history_file_name(self):
        return os.environ.get("HISTFILE",
                              os.path.expanduser('~/.bash_history'))

    def _get_history_line(self, command_script):
        return u'{}\n'.format(command_script)

    def how_to_configure(self):
        if os.path.join(os.path.expanduser('~'), '.bashrc'):
            config = '~/.bashrc'
        elif os.path.join(os.path.expanduser('~'), '.bash_profile'):
            config = '~/.bashrc'
        else:
            config = 'bash config'
        return 'eval $(thefuck --alias)', config


from flask import Flask, request, make_response
from flask import render_template
from get_recommendations import get_course_descriptions, create_tfidf, create_cosine_matrix, get_matching, get_coursetitle, get_recommendations, build_rec_table
from get_recommendations import sort_by_sim, sort_by_demand, get_overall_demand, get_dept_demand, get_dept_count, get_popular_recs, get_unpopular_recs

app = Flask(__name__, template_folder='templates')

# GLOBAL VARIABLES
all_desciptions = get_course_descriptions()
tfidf_matrix = create_tfidf(all_desciptions)
cosine_sim_matrix = create_cosine_matrix(tfidf_matrix)

@app.route('/', methods=['GET'])
def root():
    """Primary page without any table
    """
    html = render_template(
        'index.html',
    )
    response = make_response(html)

    return response

@app.route('/search', methods=['GET'])
def search():

    has_been_submitted = 1

    coursename_input = request.args.get('coursename_input')

    if has_been_submitted:
        matching_courses = get_matching(coursename_input)
        print(matching_courses)

    html = render_template(
        'index.html',
        col_names=['Course ID', 'Course Code', 'Course Title'],
        all_results=matching_courses
    )

    response = make_response(html)
    return response

@app.route('/recommendations', methods=['GET'])
def recommendations():

    courseid = request.args.get('courseid')
    coursetitle = get_coursetitle(courseid)

    recs = get_recommendations(coursetitle, cosine_sim_matrix)
    build_rec_table(recs)

    results_by_sim = sort_by_sim()
    results_by_dem = sort_by_demand()

    overall_avg = get_overall_demand()
    demand_by_dept = get_dept_demand()

    count_by_dept = get_dept_count()

    pop_courses = get_popular_recs()
    unpop_courses = get_unpopular_recs()

    html = render_template(
        'results.html',
        selected_courseid=courseid,
        selected_coursetitle=coursetitle,
        similarity_sorted=results_by_sim,
        demand_sorted=results_by_dem,
        avg_demand=overall_avg,
        dept_demand=demand_by_dept,
        dept_count=count_by_dept,
        most_demanded=pop_courses,
        least_demanded=unpop_courses
    )

    response = make_response(html)
    return response


from typing import Optional

import numpy as np

from torch.utils.data import DataLoader
import torch
import torch.nn as nn
from torch import optim

from model.neural_networks.experience_database import ExperienceDatabase
from model.model import Model

class NeuralNetworks(Model):
    def __init__(self, architecture, data_size_for_fit=1, learning_rate=0.01):
        super().__init__()
        self._data_size_for_fit = data_size_for_fit
        self._learning_rate = learning_rate
        self._experience_database: Optional[ExperienceDatabase] = None
        self._neural_networks: nn.Module = architecture

    def create(self, inpout_dimension, output_dimension):
        self._neural_networks.create(inpout_dimension, output_dimension)
        self._experience_database = ExperienceDatabase(inpout_dimension, output_dimension)

    def add_data(self, value_input, value_output):
        self._experience_database.add_data(value_input, value_output)
        if len(self._experience_database) >= self._data_size_for_fit:
            self._fit()

    def get_data(self, value_input) -> float:
        predict_value = self._neural_networks.forward(torch.Tensor(value_input)).tolist()[0]
        return predict_value

    def _fit(self):
        self._optimizer = optim.SGD(self._neural_networks.parameters(), lr=self._learning_rate)
        self._loss_function = nn.MSELoss()

        outputs = self._neural_networks.forward(torch.Tensor(self._experience_database._data))
        loss = self._loss_function(outputs, torch.Tensor(self._experience_database._targets))
        self._optimizer.zero_grad()
        loss.backward()
        self._optimizer.step()

        self._experience_database.clear()


import csv
import sys

def gen_emails(domain, email_format, raw_contacts):
    domain = "@"+domain
    clean_contacts = sanitize_contacts(raw_contacts)
    finished_contacts = []
    # dude fix this mess already
    for contact in clean_contacts:
        contact = contact.split(" ")
        # add switch for different formats
        if email_format == "flast":
            finished_contacts.append(f_last(contact, domain))
        elif email_format == "lastf":
            finished_contacts.append(last_f(contact, domain))
        elif email_format == "firstlast":
            finished_contacts.append(first_last(contact, domain))
        elif email_format == "firstdotlast":
            finished_contacts.append(first_dot_last(contact, domain))
        elif email_format == "firstl":
            finished_contacts.append(first_l(contact, domain))
        elif email_format == "lastfirst":
            finished_contacts.append(last_first(contact, domain))
        elif email_format == "first_dot_m_dot_last":
            finished_contacts.append(first_dot_m_dot_last(contact, domain))
        elif email_format == "first":
            finished_contacts.append(first(contact, domain))
    return finished_contacts

# been getting lots of certs/dr prefixes in names, so lets sanitize
def sanitize_contacts(contacts):
    clean_contacts = []
    for contact in contacts:
        temp_contact = contact.split(",")
        curr = temp_contact[0]
        # weird thing, but gen_emails expects 3 names (first, last, middle)
        # it checks to see if middle is blank, so its easiest to give (first, last) a middle blank name
        if len(curr.split(" ")) == 2:
            curr = curr + " "
        clean_contacts.append(curr)
        # input("PAUSED")
    return clean_contacts

def first(contact, domain):
    email = ""
    if (contact[2] == ""):
        email = contact[0]+domain
    else:
        email = contact[0]+domain
    return email.lower()

# {f}{last}@domain.com
def f_last(contact, domain):
    email = ""
    if (contact[2] == ""):
        email = contact[0][0]+contact[1]+domain
    else:
        email = contact[0][0]+contact[2]+domain
    return email.lower()

# {last}{f}@domain.com
def last_f(contact, domain):
    email = ""
    if (len(contact[2]) == 0):
        email = contact[1]+contact[0][0]+domain
    else:
        email = contact[2]+contact[0][0]+domain
    return email.lower()

def first_dot_m_dot_last(contact, domain):
    email = ""
    if (len(contact[2]) == 0):
        email = contact[0]+"."+contact[1]+domain
    else:
        email = contact[0] +"."+ contact[1][0] +"."+ contact[2]+domain

    return email.lower()

# {first}{last}@domain.com
def first_last(contact, domain):
    email = ""
    if (len(contact[2]) == 0):
        email = contact[0]+contact[1]+domain
    else:
        email = contact[0]+contact[2]+domain
    return email.lower()

# {last}{first}@domain.com
def last_first(contact, domain):
    email = ""
    if (len(contact[2]) == 0):
        email = contact[1]+contact[0]+domain
    else:
        email = contact[2]+contact[0]+domain
    return email.lower()

# {first}.{last}@domain.com
def first_dot_last(contact, domain):
    email = ""
    # print(contact)
    if (len(contact[2]) == 0):
        email = contact[0]+"."+contact[1]+domain
    else:
        email = contact[0]+"."+contact[2]+domain
    # print(email.lower())
    return email.lower()

def first_l(contact, domain):
    email = ""
    if (len(contact[2]) == 0):
        email = contact[0]+contact[1][0]+domain
    else:
        email = contact[0]+contact[2][0]+domain
    return email.lower()

if __name__ == "__main__":
    domain = "@"+str(sys.argv[1])
    email_format = sys.argv[2]
    company = sys.argv[3]
    # gen_emails(domain, email_format)


import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

# Creating function for 2D convolution operation
def convolution_2d(image, filter, pad, step):
    # Size of the filter
    k_size = filter.shape[0]

    # Calculating spatial size - width and height
    width_out = int((image.shape[0] - k_size + 2 * pad) / step + 1)
    height_out = int((image.shape[1] - k_size + 2 * pad) / step + 1)

    # Preparing zero valued output array for convolved image
    output_image = np.zeros((width_out - 2 * pad, height_out - 2 * pad))

    # Implementing 2D convolution operation
    # Going through all input image
    for i in range(image.shape[0] - k_size + 1):
        for j in range(image.shape[1] - k_size + 1):
            # Extracting patch (the same size with filter) from input image
            patch_from_image = image[i:i+k_size, j:j+k_size]
            # Applying elementwise multiplication and summation - this is convolution operation
            output_image[i, j] = np.sum(patch_from_image * filter)

    # Returning result
    return output_image

# Creating function for CNN Layer
def cnn_layer(image_volume, filter, pad=1, step=1):
    # Note: image here can be a volume of feature maps, obtained in the previous layer

    # Applying to the input image volume Pad frame with zero values for all channels
    # Preparing zero valued array
    image = np.zeros((image_volume.shape[0] + 2 * pad, image_volume.shape[1] + 2 * pad, image_volume.shape[2]))

    # Going through all channels from input volume
    for p in range(image_volume.shape[2]):
        # Using NumPy method 'pad'
        # If Pad=0 the resulted image will be the same as input image
        image[:, :, p] = np.pad(image_volume[:, :, p], (pad, pad), mode='constant', constant_values=0)

    # Using following equations for calculating spatial size of output image volume:
    # Width_Out = (Width_In - K_size + 2*Pad) / Step + 1
    # Height_Out = (Height_In - K_size + 2*Pad) / Step + 1
    # Depth_Out = K_number
    # Size of the filter
    k_size = filter.shape[1]
    # Depth (number) of output feature maps - is the same with number of filters
    # Note: this depth will also be as number of channels for input image for the next layer
    depth_out = filter.shape[0]
    # Calculating spatial size - width and height
    width_out = int((image_volume.shape[0] - k_size + 2 * pad) / step + 1)
    height_out = int((image_volume.shape[1] - k_size + 2 * pad) / step + 1)

    # Creating zero valued array for output feature maps
    feature_maps = np.zeros((width_out, height_out, depth_out))  # has to be tuple with numbers

    # Implementing convolution of image with filters
    # Note: or convolving volume of feature maps, obtained in the previous layer, with new filters
    n_filters = filter.shape[0]

    # For every filter
    for i in range(n_filters):
        # Initializing convolved image
        convolved_image = np.zeros((width_out, height_out))  # has to be tuple with numbers

        # For every channel of the image
        # Note: or for every feature map from its volume, obtained in the previous layer
        for j in range(image.shape[-1]):
            # Convolving every channel (depth) of the image with every channel (depth) of the current filter
            # Result is summed up
            convolved_image += convolution_2d(image[:, :, j], filter[i, :, :, j], pad, step)
        # Writing results into current output feature map
        feature_maps[:, :, i] = convolved_image

    # Returning resulted feature maps array
    return feature_maps

# Creating function for replacing pixel values that are more than 255 with 255
def image_pixels_255(maps):
    # Preparing array for output result
    r = np.zeros(maps.shape)
    # Replacing all elements that are more than 255 with 255
    # Going through all channels
    for c in range(r.shape[2]):
        # Going through all elements
        for i in range(r.shape[0]):
            for j in range(r.shape[1]):
                # Checking if the element is less than 255
                if maps[i, j, c] <= 255:
                    r[i, j, c] = maps[i, j, c]
                else:
                    r[i, j, c] = 255
    # Returning resulted array
    return r

# Creating function for ReLU Layer
def relu_layer(maps):
    # Preparing array for output result
    r = np.zeros_like(maps)
    # Using 'np.where' setting condition that every element in 'maps' has to be more than appropriate element in 'r'
    result = np.where(maps > r, maps, r)
    # Returning resulted array
    return result

# Creating function for Pooling Layer
def pooling_layer(maps, size=2, step=2):
    # Calculating spatial size of output resulted array - width and height
    # As our image has the same spatial size as input image (270, 480) according to the chosen Hyperparameters
    # Then we can use following equations
    width_out = int((maps.shape[0] - size) / step + 1)
    height_out = int((maps.shape[1] - size) / step + 1)

    # As filter size for pooling operation is 2x2 and step is 2
    # Then spatial size of pooling image will be twice less (135, 240)
    # Preparing zero valued output array for pooling image
    pooling_image = np.zeros((width_out, height_out, maps.shape[2]))

    # Implementing pooling operation
    # For all channels
    for c in range(maps.shape[2]):
        # Going through all image with step=2
        # Preparing indexes for pooling array
        ii = 0
        for i in range(0, maps.shape[0] - size + 1, step):
            # Preparing indexes for pooling array
            jj = 0
            for j in range(0, maps.shape[1] - size + 1, step):
                # Extracting patch (the same size with filter) from input image
                patch_from_image = maps[i:i+size, j:j+size, c]
                # Applying max pooling operation - choosing maximum element from the current patch
                pooling_image[ii, jj, c] = np.max(patch_from_image)
                # Increasing indexing for polling array
                jj += 1
            # Increasing indexing for polling array
            ii += 1

    # Returning resulted array
    return pooling_image

# Opening grayscale input image and putting data into array
input_image = Image.open("images/eagle_grayscale.jpeg")
image_np = np.array(input_image)
# Checking the shape of the array
print(image_np.shape)  # (270, 480, 3)
# Checking if all channels are the same
print(np.array_equal(image_np[:, :, 0], image_np[:, :, 1]))  # True
print(np.array_equal(image_np[:, :, 1], image_np[:, :, 2]))  # True

# Option #1 for filters
# Creating 4 first filters for the first CNN Layer with random integer numbers in range [-1, 1]
# The depth of each filter has to match the number of channels (depth) in input image
# In our case it is 3 as image has three identical grayscale channels
filter_1 = np.random.random_integers(low=-1, high=1, size=(4, 3, 3, image_np.shape[-1]))
# 4 corresponds to number of filters
# 3 and another 3 corresponds to spatial size of filters - width and height
# image_np.shape[-1] corresponds to the depth of each volume of filters
# Checking the shape of the filters
print(filter_1.shape)  # (4, 3, 3, 3)

# Option #2 for filters
# Creating filters manually
# The depth of each filter has to match the number of channels (depth) in input image
# In our case it is 3 as image has three identical grayscale channels
filter_1 = np.zeros((4, 3, 3, 3))
# First filter
filter_1[0, :, :, 0] = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]])
filter_1[0, :, :, 1] = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]])
filter_1[0, :, :, 2] = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]])
# Second filter
filter_1[1, :, :, 0] = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])
filter_1[1, :, :, 1] = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])
filter_1[1, :, :, 2] = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])
# Third filter
filter_1[2, :, :, 0] = np.array([[1, -1, 0], [-1, 0, 1], [-1, 0, 1]])
filter_1[2, :, :, 1] = np.array([[1, -1, 0], [-1, 0, 1], [-1, 0, 1]])
filter_1[2, :, :, 2] = np.array([[1, -1, 0], [-1, 0, 1], [-1, 0, 1]])
# Fourth filter
filter_1[3, :, :, 0] = np.array([[0, -1, 1], [1, 0, -1], [-1, 1, 0]])
filter_1[3, :, :, 1] = np.array([[0, -1, 1], [1, 0, -1], [-1, 1, 0]])
filter_1[3, :, :, 2] = np.array([[0, -1, 1], [1, 0, -1], [-1, 1, 0]])
print(filter_1.shape)  # (4, 3, 3, 3)

# CNN Layer number 1
cnn_1 = cnn_layer(image_np, filter_1, pad=1, step=1)
# Replacing all pixel elements in the resulted volume that are more than 255 with 255
cnn_1 = image_pixels_255(cnn_1)
print(cnn_1.shape)  # (270, 480, 4)

# ReLU Layer number 1
# As input we put resulted feature maps from previous CNN Layer
relu_1 = relu_layer(cnn_1)
print(relu_1.shape)  # (270, 480, 4)

# Pooling Layer number 1
# As input we put resulted feature maps from previous ReLU Layer
pooling_1 = pooling_layer(relu_1, size=2, step=2)
print(pooling_1.shape)  # (135, 240, 4)

# Creating 4 filters for the second CNN Layer with random integer numbers in range [-1, 1]
# The depth of each filter has to match the number of channels (depth) in input image volume
# In our case it is 4 as number of output feature maps from first CNN Layer is 4
filter_2 = np.random.random_integers(low=-1, high=1, size=(4, 3, 3, cnn_1.shape[-1]))
# 4 corresponds to number of filters
# 3 and another 3 corresponds to spatial size of filters - width and height
# image_np.shape[-1] corresponds to the depth of each volume of filters
# Checking the shape of the filters
print(filter_2.shape)  # (4, 3, 3, 4)

# CNN Layer number 2
# As input we put resulted feature maps from previous Pooling Layer
cnn_2 = cnn_layer(pooling_1, filter_2, pad=1, step=1)
# Replacing all pixel elements in the resulted volume that are more than 255 with 255
cnn_2 = image_pixels_255(cnn_2)
print(cnn_2.shape)  # (135, 240, 4)

# ReLU Layer number 2
# As input we put resulted feature maps from previous CNN Layer
relu_2 = relu_layer(cnn_2)
print(relu_2.shape)  # (135, 240, 4)

# Pooling Layer number 2
# As input we put resulted feature maps from previous ReLU Layer
pooling_2 = pooling_layer(relu_2, size=2, step=2)
print(pooling_2.shape)  # (67, 120, 4)

# Creating 4 filters for the third CNN Layer with random integer numbers in range [-1, 1]
# The depth of each filter has to match the number of channels (depth) in input image volume
# In our case it is 4 as number of output feature maps from second CNN Layer is 4
filter_3 = np.random.random_integers(low=-1, high=1, size=(4, 3, 3, cnn_2.shape[-1]))
# 4 corresponds to number of filters
# 3 and another 3 corresponds to spatial size of filters - width and height
# image_np.shape[-1] corresponds to the depth of each volume of filters
# Checking the shape of the filters
print(filter_3.shape)  # (4, 3, 3, 4)

# CNN Layer number 3
# As input we put resulted feature maps from previous Pooling Layer
cnn_3 = cnn_layer(pooling_2, filter_3, pad=1, step=1)
# Replacing all pixel elements in the resulted volume that are more than 255 with 255
cnn_3 = image_pixels_255(cnn_3)
print(cnn_3.shape)  # (67, 120, 4)

# ReLU Layer number 3
# As input we put resulted feature maps from previous CNN Layer
relu_3 = relu_layer(cnn_3)
print(relu_3.shape)  # (67, 120, 4)

# Pooling Layer number 3
# As input we put resulted feature maps from previous ReLU Layer
pooling_3 = pooling_layer(relu_3, size=2, step=2)
print(pooling_3.shape)  # (33, 60, 4)

# Showing results on the appropriate figures
n_rows = cnn_1.shape[-1]
figure_1, ax = plt.subplots(nrows=n_rows, ncols=9, edgecolor='Black')
# ax is as (4, 9) np array and we can call each time ax[0, 0]

# Adjusting subplots for CNN Layer number 1
ax[0, 0].imshow(cnn_1[:, :, 0], cmap=plt.get_cmap('gray'))
ax[0, 0].set_axis_off()
ax[0, 0].set_title('CNN #1')
for i in range(1, n_rows):
    ax[i, 0].imshow(cnn_1[:, :, i], cmap=plt.get_cmap('gray'))
    ax[i, 0].set_axis_off()

# Adjusting subplots for ReLU Layer number 1
ax[0, 1].imshow(relu_1[:, :, 0], cmap=plt.get_cmap('gray'))
ax[0, 1].set_axis_off()
ax[0, 1].set_title('ReLU #1')
for i in range(1, n_rows):
    ax[i, 1].imshow(relu_1[:, :, i], cmap=plt.get_cmap('gray'))
    ax[i, 1].set_axis_off()

# Adjusting subplots for Pooling Layer number 1
ax[0, 2].imshow(pooling_1[:, :, 0], cmap=plt.get_cmap('gray'))
ax[0, 2].set_axis_off()
ax[0, 2].set_title('Pooling #1')
for i in range(1, n_rows):
    ax[i, 2].imshow(pooling_1[:, :, i], cmap=plt.get_cmap('gray'))
    ax[i, 2].set_axis_off()

# Adjusting subplots for CNN Layer number 2
ax[0, 3].imshow(cnn_2[:, :, 0], cmap=plt.get_cmap('gray'))
ax[0, 3].set_axis_off()
ax[0, 3].set_title('CNN #2')
for i in range(1, n_rows):
    ax[i, 3].imshow(cnn_2[:, :, i], cmap=plt.get_cmap('gray'))
    ax[i, 3].set_axis_off()

# Adjusting subplots for ReLU Layer number 2
ax[0, 4].imshow(relu_2[:, :, 0], cmap=plt.get_cmap('gray'))
ax[0, 4].set_axis_off()
ax[0, 4].set_title('ReLU #2')
for i in range(1, n_rows):
    ax[i, 4].imshow(relu_2[:, :, i], cmap=plt.get_cmap('gray'))
    ax[i, 4].set_axis_off()

# Adjusting subplots for Pooling Layer number 2
ax[0, 5].imshow(pooling_2[:, :, 0], cmap=plt.get_cmap('gray'))
ax[0, 5].set_axis_off()
ax[0, 5].set_title('Pooling #2')
for i in range(1, n_rows):
    ax[i, 5].imshow(pooling_2[:, :, i], cmap=plt.get_cmap('gray'))
    ax[i, 5].set_axis_off()

# Adjusting subplots for CNN Layer number 3
ax[0, 6].imshow(cnn_3[:, :, 0], cmap=plt.get_cmap('gray'))
ax[0, 6].set_axis_off()
ax[0, 6].set_title('CNN #3')
for i in range(1, n_rows):
    ax[i, 6].imshow(cnn_3[:, :, i], cmap=plt.get_cmap('gray'))
    ax[i, 6].set_axis_off()

# Adjusting subplots for ReLU Layer number 3
ax[0, 7].imshow(relu_3[:, :, 0], cmap=plt.get_cmap('gray'))
ax[0, 7].set_axis_off()
ax[0, 7].set_title('ReLU #3')
for i in range(1, n_rows):
    ax[i, 7].imshow(relu_3[:, :, i], cmap=plt.get_cmap('gray'))
    ax[i, 7].set_axis_off()

# Adjusting subplots for Pooling Layer number 3
ax[0, 8].imshow(pooling_3[:, :, 0], cmap=plt.get_cmap('gray'))
ax[0, 8].set_axis_off()
ax[0, 8].set_title('Pooling #3')
for i in range(1, n_rows):
    ax[i, 8].imshow(pooling_3[:, :, i], cmap=plt.get_cmap('gray'))
    ax[i, 8].set_axis_off()

# Giving the name to the window with figure
figure_1.canvas.set_window_title('CNN --> ReLU --> Pooling')
# Showing the plots
plt.show()


from random import randrange, seed
from .cell import MSCell, CellAlreadyHasMineException

class MSBoard():
    """ Minesweeper board class """

    def __init__(self, xsize, ysize, mines, randSeed=None):
        if xsize < 1:
            raise ValueError("Board xsize too small")
        if ysize < 1:
            raise ValueError("Board ysize too small")
        if mines >= xsize * ysize:
            raise ValueError("Invalid mine count for board")
        if randSeed:
            seed(randSeed)

        self.xsize = xsize
        self.ysize = ysize
        self.mines = mines
        self._grid = self._buildGrid()
        self.flags = 0
        self._putRandomMines(mines)

    def _putRandomMines(self, mines):
        mineCount = 0
        while mineCount < mines:
            try:
                self.addMine(randrange(self.xsize), randrange(self.ysize))
                mineCount += 1
            except CellAlreadyHasMineException:
                pass

    def cell(self, x, y):
        """ Return the cell in a coordinate """
        return self.grid[x][y]

    def _buildGrid(self):
        grid = [
            [MSCell() for _ in range(self.ysize)]
            for _ in range(self.xsize)]
        return grid

    @property
    def grid(self):
        """ Returns the cell grid """
        return self._grid

    def addMine(self, x, y):
        """ Add a mine to the grid board """
        self.cell(x, y).putMine()
        self._incrementAround(x, y)

    def _incrementAround(self, x, y):
        for px, py in self.neighborCells(x, y):
            self.cell(px, py).increment()

    def neighborCells(self, x, y):
        for px in range(max(0, x-1), min(x+2, self.xsize)):
            for py in range(max(0, y-1), min(y+2, self.ysize)):
                if px != x or py != y:
                    yield (px, py)


#coding=utf-8
import scrapy
from scrapy_splash import SplashRequest
from CrawlMacApp.items import CrawlmacappItem
import re
import os
import requests

class WwwNovellsharewareComSpider(scrapy.Spider):
    name = "www_novellshareware_com_spider"
    start_urls=["http://mac.novellshareware.com/"]
    base_url="http://mac.novellshareware.com"

    def parse(self, response):
        categories=response.xpath('//*[@id="category"]/ul/li/ul/li/a/@href').extract()
        for each_category_url in categories:

            yield scrapy.Request(url=each_category_url,callback=self.parse_each_category)
    def parse_each_category(self,response):
        category_pages=response.xpath('//*[@id="content"]/div/div/div[1]/div[2]/a/text()').extract()[-2]
        #print response.url
        #print category_pages
        for i in range(1,int(category_pages)+1):
            if i==1:
                pres_url=response.url
            else:
                tmp_pres_url=response.url.split('.html')[0]
                pres_url=tmp_pres_url+"-page"+str(i)+".html"

            yield scrapy.Request(url=pres_url,callback=self.parse_each_page)

    def parse_each_page(self,response):
        page_download_links=response.xpath('//body//div[@class="fright"]/a[2]/@href').extract()
        for each_download_link in page_download_links:
            each_download_url=self.base_url+each_download_link

            #re_download_url = requests.head(each_download_url, allow_redirects=True)

            item = CrawlmacappItem()
            item['soft_id'] = each_download_url
            item['soft_name'] = ""
            item['download_link'] = each_download_url
            item['is_download'] = False
            item['download_time'] = ""
            item['is_upload_ftp'] = False
            item['upload_time'] = ""
            item['upload_file_name'] = ""
            item['download_http_error'] = False
            item['soft_desc'] = ""

            yield item