import argparse

import numpy
import scipy.sparse

VERBOSE = False

def get_space_offsets(space: list):
    return numpy.cumprod((1, *space[::-1]))[len(space) - 1::-1]

'''Use only to get indices of exisiting values'''

def get_indices(index: int, offsets: numpy.ndarray):
    if offsets is None:
        offsets = get_space_offsets(space)
    if offsets.ndim > 1:
        offsets = offsets.flatten()
    indices = numpy.zeros(shape=offsets.shape, dtype=numpy.int)
    for i in range(offsets.shape[0]):
        indices[i] = index // offsets[i]
        index %= offsets[i]
    return indices

def get_index(indices: numpy.ndarray, offsets: numpy.ndarray, upper_bound):
    if numpy.any(indices < 0):
        return -1
    index = numpy.dot(indices, offsets)
    return index if index < upper_bound else -1

'''
Returns index of the neighbor voxels in linear space.
@:param indices Location of the voxel in N-Dimensional space.
@:param offsets Linear offsets for each dimension.
@:param upper_bound Maximum valid index in linear space.

@:return Set of linear space indices for neighboring voxels. Any index outside the bounds return a -1 value.
'''

def get_neighbors(indices, offsets, upper_bound=None):
    if upper_bound is None:
        upper_bound = numpy.prod(offsets)
    one_hot = numpy.zeros(offsets.shape, dtype=numpy.int)
    one_hot[0] = 1
    neighbors = []
    for i in range(one_hot.shape[0]):
        neighbors.append(get_index(indices + one_hot, offsets, upper_bound))
        neighbors.append(get_index(indices - one_hot, offsets, upper_bound))
        one_hot = numpy.roll(one_hot, 1)
    return set(neighbors)

def compute_boundary_from_sparse(mtx, space, start_sample=0, features=0):
    '''The output of this matrix is True where the voxel does not fall on the boundary of the volume'''
    num_samples = mtx.shape[0] - start_sample
    num_values = mtx.shape[1] - features
    if num_samples < 1:
        raise ValueError('Bad start_sample. No samples remaining in data.')
    if num_values < 1:
        raise ValueError('Bad features. No label values remaining in data.')
    if start_sample == 0 and features == 0:
        m = mtx
    else:
        m = mtx[start_sample:, features:]
    offsets = get_space_offsets(space)
    upper_bound = numpy.prod(offsets)
    print(
        f'Using: Matrix with {mtx.shape[0]} samples of {mtx.shape[1]} values. Skipping {start_sample} samples. Skipping {features} values of each sample as input features.\nResulting data matrix has {m.shape[0]} samples and {m.shape[1]} label values.\n\nSpace parameters:\n  Dimensions: {space}\n  Offsets: {offsets.tolist()}\n  Linear: {numpy.prod(offsets)}, Matches Label Count? {"yes" if numpy.prod(offsets) == m.shape[1] else "no"}')
    del mtx
    d = numpy.zeros(m.shape, dtype=numpy.int).astype(numpy.bool)
    for sample_index in range(d.shape[0]):
        voxel_indices = set(m.indices[m.indptr[sample_index]:m.indptr[sample_index + 1]].tolist())
        for voxel_index in voxel_indices:
            not_boundary = get_neighbors(get_indices(voxel_index, offsets), offsets, upper_bound).issubset(
                voxel_indices)
            d[sample_index, voxel_index] = not not_boundary
    return d


from PIL import Image

source = input("Source image path: ")
output = input("Output image path: ")

scaleFactor = int(input("Size of blur: "))

img = Image.open(source)
size = img.size

pix = img.load()

def boxAverage(i, j):
	col = (0, 0, 0)
	count = 0
	for x in range(-scaleFactor, scaleFactor-1):
		for y in range(-scaleFactor, scaleFactor-1):
			if((i + x) < 0 or (i + x) >= size[0] or (j + y) < 0 or (j + y) >= size[1]):
				continue

			c = pix[i + x, j + y]
			col = (col[0] + c[0], col[1] + c[1], col[2] + c[2])
			count += 1
	return (int(col[0]/count), int(col[1]/count), int(col[2]/count))

for i in range(0, size[0]) :
	for j in range(0, size[1]) :
		pix[i, j] = boxAverage(i, j)

img.save(output)
print("Blur Finished")


alp="abcdefghigklmnopqrstuvwxyz"

st=input("Input binary numbers: ")

n=0

for i in range(len(st)) :
  if st[i]=='1':
    print(alp[n] , end=' ')
    n=0

  else:
    n+=1

# 1 -->  0 --> n=1
# 2 -->  1 --> n=1  > b
# 3 -->  0 --> n=2
# 4 -->  0 --> n=3
# 5 -->  1 --> n=3  > c


import sys
import random
import gym
import numpy as np
import pygame
from gym import spaces
from scipy.spatial import distance

class SnakeGameEnv(gym.Env):
    metadata = {'render.modes': ['human']}
    difficulty = 25

    # Window size --> smaller window is easier to find food
    frame_size_x = 600
    frame_size_y = 450

    # Colors (R, G, B)
    black = pygame.Color(0, 0, 0)
    white = pygame.Color(255, 255, 255)
    red = pygame.Color(255, 0, 0)
    green = pygame.Color(0, 255, 0)
    blue = pygame.Color(0, 0, 255)

    # Action
    LEFT = 0
    UP = 1
    RIGHT = 2
    DOWN = 3

    # set maximum steps
    max_steps = 10000

    def __init__(self):
        super().__init__()
        pygame.init()

        # Initialise game window
        pygame.display.set_caption('Snake Eater')

        # FPS (frames per second) controller
        self.fps_controller = pygame.time.Clock()
        self.game_window = pygame.display.set_mode((self.frame_size_x, self.frame_size_y))

        # Game variables
        self.snake_pos = [100, 50]
        self.prev_snake_pos = [100, 50]
        self.snake_body = [[100, 50], [100 - 10, 50], [100 - (2 * 10), 50]]
        self.food_pos = [random.randrange(1, (self.frame_size_x // 10)) * 10,
                         random.randrange(1, (self.frame_size_y // 10)) * 10]
        self.food_spawn = True
        self.score = 0
        self.direction = 'RIGHT'
        self.change_to = self.direction
        self.step_count = 0

        # action --> UP, DOWN, LEFT, RIGHT
        self.action_space = spaces.Discrete(4)

        # x_snake_head, y_snake_head,
        # x_snake_tail, y_snake_tail,
        # x_food, y_food,
        # x_snake_to_food, y_snake_to_food,
        # distance_to_food,
        # snake_length
        self.observation_space = spaces.Box(low=-np.inf, high=np.inf, shape=(10,), dtype=np.float32)

    def step(self, action):
        # 0 --> LEFT
        # 1 --> UP
        # 2 --> RIGHT
        # 3 --> DOWN

        reward = 0
        done = False
        info = {}

        if action == self.UP:
          self.change_to = 'UP'
        elif action == self.DOWN:
            self.change_to = 'DOWN'
        elif action == self.LEFT:
            self.change_to = 'LEFT'
        elif action == self.RIGHT:
            self.change_to = 'RIGHT'

        # Making sure the snake cannot move in the opposite direction instantaneously
        if self.change_to == 'UP':
            if self.direction != 'DOWN': self.direction = 'UP'
            else: self.direction = 'DOWN'

        elif self.change_to == 'DOWN':
            if self.direction != 'UP': self.direction = 'DOWN'
            else: self.direction = 'UP'

        elif self.change_to == 'LEFT':
            if self.direction != 'RIGHT': self.direction = 'LEFT'
            else: self.direction = 'RIGHT'

        elif self.change_to == 'RIGHT':
            if self.direction != 'LEFT': self.direction = 'RIGHT'
            else: self.direction = 'LEFT'

        # Moving the snake
        if self.direction == 'UP':
            self.snake_pos[1] -= 10
        elif self.direction == 'DOWN':
            self.snake_pos[1] += 10
        elif self.direction == 'LEFT':
            self.snake_pos[0] -= 10
        elif self.direction == 'RIGHT':
            self.snake_pos[0] += 10
        reward -= 1 # reduce reward in every move
        self.step_count += 1

        # get reward if move closer to food
        prev_distance = distance.euclidean(self.prev_snake_pos, self.food_pos)
        curr_distance = distance.euclidean(self.snake_pos, self.food_pos)
        if curr_distance < prev_distance:
            reward += 1
        # else:
        #     reward -= 1
        self.prev_snake_pos = self.snake_pos.copy()

         # Snake body growing mechanism
        self.snake_body.insert(0, list(self.snake_pos))
        if self.snake_pos[0] == self.food_pos[0] and self.snake_pos[1] == self.food_pos[1]:
            reward += 50 * len(self.snake_body)# reward increase with body length
            self.score += 1 # score when render
            self.food_spawn = False
        else:
            self.snake_body.pop()

        # Spawning food on the screen
        if not self.food_spawn:
          self.food_pos = [random.randrange(1, (self.frame_size_x // 10)) * 10,
                           random.randrange(1, (self.frame_size_y // 10)) * 10]
        self.food_spawn = True

        # Game Over conditions

            ## Getting out of bounds
        if self.snake_pos[0] < 0 or self.snake_pos[0] > self.frame_size_x - 10:
            info['GameOver'] = 'Out of bound X'
            done = True
        if self.snake_pos[1] < 0 or self.snake_pos[1] > self.frame_size_y - 10:
            info['GameOver'] = 'Out of bound Y'
            done = True

            ## Touching the snake body
        for block in self.snake_body[1:]:
            if self.snake_pos[0] == block[0] and self.snake_pos[1] == block[1]:
                info['GameOver'] = 'Eat itself'
                done = True

            ## reach maximum steps
        if self.step_count >= self.max_steps:
            info['GameOver'] = 'reach maximum steps'

        # new observation
        snake_length = len(self.snake_body)
        x_snake_head, y_snake_head = self.snake_body[0]
        x_snake_tail, y_snake_tail = self.snake_body[-1]
        x_food, y_food = self.food_pos
        x_snake_to_food = x_snake_head - x_food
        y_snake_to_food = y_snake_head - y_food
        distance_to_food = distance.euclidean(self.snake_pos, self.food_pos)

        observation = np.array([x_snake_head, y_snake_head,
                                x_snake_tail, y_snake_tail,
                                x_food, y_food,
                                x_snake_to_food, y_snake_to_food,
                                distance_to_food,
                                snake_length],
                                dtype=np.float32)

        return observation, reward, done, info

    def reset(self):
        self.snake_pos = [100, 50]
        self.prev_snake_pos = [100, 50]
        self.snake_body = [[100, 50], [100 - 10, 50], [100 - (2 * 10), 50]]
        self.food_pos = [random.randrange(1, (self.frame_size_x // 10)) * 10,
                         random.randrange(1, (self.frame_size_y // 10)) * 10]
        self.food_spawn = True
        self.score = 0
        self.direction = 'RIGHT'
        self.change_to = self.direction
        self.step_count = 0

        # observation
        snake_length = len(self.snake_body)
        x_snake_head, y_snake_head = self.snake_body[0]
        x_snake_tail, y_snake_tail = self.snake_body[-1]
        x_food, y_food = self.food_pos
        x_snake_to_food = x_snake_head - x_food
        y_snake_to_food = y_snake_head - y_food
        distance_to_food = distance.euclidean(self.snake_pos, self.food_pos)

        observation = np.array([x_snake_head, y_snake_head,
                                x_snake_tail, y_snake_tail,
                                x_food, y_food,
                                x_snake_to_food, y_snake_to_food,
                                distance_to_food,
                                snake_length],
                                dtype=np.float32)

        return observation

    def render(self, mode='human'):
        # GFX
        self.game_window.fill(self.black)
        for pos in self.snake_body:
            # Snake body
            # .draw.rect(play_surface, color, xy-coordinate)
            # xy-coordinate -> .Rect(x, y, size_x, size_y)
            pygame.draw.rect(self.game_window, self.green, pygame.Rect(pos[0], pos[1], 10, 10))

        # Snake food
        pygame.draw.rect(self.game_window, self.white, pygame.Rect(self.food_pos[0], self.food_pos[1], 10, 10))
        self.show_score(1, self.white, 'consolas', 20)
        # Refresh game screen
        pygame.display.update()
        # Refresh rate
        self.fps_controller.tick(self.difficulty)

    def close (self):
      pygame.quit()
      sys.exit()

    def show_score(self, choice, color, font, size):
      score_font = pygame.font.SysFont(font, size)
      score_surface = score_font.render('Score : ' + str(self.score), True, color)
      score_rect = score_surface.get_rect()
      if choice == 1:
          score_rect.midtop = (self.frame_size_x / 10, 15)
      else:
          score_rect.midtop = (self.frame_size_x / 2, self.frame_size_y / 1.25)
      self.game_window.blit(score_surface, score_rect)
      # pygame.display.flip()


import cv2
import numpy

def get_intensity_callback(event,x,y,flags,image):
    if event == cv2.EVENT_LBUTTONDOWN:
        print(x)
        print(y)
        print(image[y,x])
        print("---")

def create_breadcrumb_map(faces, height, width):
    breadcrumby, breadcrumbx = numpy.mgrid[0:height, 0:width]
    breadcrumb = numpy.zeros((height, width), numpy.float)
    for (x_face, y_face, width_face, height_face) in faces:
        x_face_centre = x_face+width_face/2
        y_face_centre = y_face+height_face/2
        breadcrumb -= numpy.sqrt(numpy.maximum(abs(breadcrumbx - x_face_centre) - width_face / 2, 0) ** 2 + numpy.maximum(abs(breadcrumby - y_face_centre) - height_face / 2, 0)**2).astype(float)
    breadcrumb -= numpy.min(breadcrumb)
    breadcrumb /= numpy.max(breadcrumb)
    return breadcrumb

def get_breadcrumb_map_to_faces(imageLocation):
    img = cv2.imread(imageLocation, 0)
    face_cascade = cv2.CascadeClassifier("resources/haarcascade_frontalface_default.xml")
    faces = face_cascade.detectMultiScale(img, 1.3, 5)
    height, width = img.shape
    return create_breadcrumb_map(faces, height, width)

breadcrumb = get_breadcrumb_map_to_faces('resources/tennis-b.jpg')

cv2.imshow('breadcrumb', breadcrumb)
cv2.setMouseCallback('breadcrumb', get_intensity_callback, breadcrumb)
cv2.imwrite('resources/facebreadcrumb.jpg',breadcrumb)
cv2.waitKey(0)
cv2.destroyAllWindows()


import open3d as o3d
import os
import igl
import train as tt
import numpy as np
path="dataset/"
label=[]
points=[]
cll=os.listdir(path)

for cl in cll:
    fll=os.listdir(path+"/"+cl+"/"+"test/")
    for fl in fll:
        if(".off" not in fl):
            continue
        mesh = o3d.io.read_triangle_mesh(path+"/"+cl+"/"+"test/"+fl)
        pcd=o3d.geometry.PointCloud()
        V_mesh = np.asarray(mesh.vertices)
        pcd = o3d.geometry.TriangleMesh.sample_points_uniformly(mesh, number_of_points=tt.sz)
        pc = np.asarray(pcd.points)
        label.append(cll.index(cl))
        centroid = np.mean(pc, axis=0)
        pc = pc - centroid
        m = np.max(np.sqrt(np.sum(pc ** 2, axis=1)))
        pc = pc / m
        points.append(pc)
np.save("data1.npy",np.asarray(points))
np.save("label1.npy",np.asarray(label))
for cl in cll:
    fll=os.listdir(path+"/"+cl+"/"+"train/")
    for fl in fll:
        if(".off" not in fl):
            continue
        mesh = o3d.io.read_triangle_mesh(path+"/"+cl+"/"+"train/"+fl)
        pcd=o3d.geometry.PointCloud()
        pcd = o3d.geometry.TriangleMesh.sample_points_uniformly(mesh, number_of_points=tt.sz)
        pc = np.asarray(pcd.points)
        centroid = np.mean(pc, axis=0)
        pc = pc - centroid
        m = np.max(np.sqrt(np.sum(pc ** 2, axis=1)))
        pc = pc / m
        points.append(pc)
        label.append(cll.index(cl))
np.save("data.npy",np.asarray(points))
np.save("label.npy",np.asarray(label))


class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        result = []
        dist = [0]*len(points)
        l = len(dist)
        temp = []
        for i in range(l):
            dist[i] = sqrt(((points[i][0])**2) + ((points[i][1])**2))
            temp.append((points[i],dist[i]))
        v = sorted(temp, key=lambda tup: (tup[1]))
        result = [v[a][0] for a in range(k)]
        return result


import RPi.GPIO as gpio
import time
import requests
import json
import datetime
import csv
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import urllib.request
from urllib.request import urlopen

gpio.setmode(gpio.BCM)

trig = 23
echo = 24
maxsize = 5
store = {}
counter = 0
traffic_poll = 0
buses_file = None
data_file = None

print("Distance Measurement in Progress")

gpio.setup(trig,gpio.OUT)
gpio.setup(echo,gpio.IN)

gpio.output(trig,False)
print("Waiting for Sensor to Settle")
time.sleep(2)
def initGoogleSheet(sheetname,sheet):
    scope = ['https://spreadsheets.google.com/feeds',
             'https://www.googleapis.com/auth/drive']
    credentials = ServiceAccountCredentials.from_json_keyfile_name('SIOT-bbab5a9d0c4f.json', scope)
    gc = gspread.authorize(credentials)
    wks = gc.open(sheetname).get_worksheet(sheet)
    entries = len(wks.col_values(1)) + 1
    print('initiate sheet')
    return entries, wks
def updateSheet(entries,worksheet,data):
    print('updatingSheet')
    worksheet.append_row(data)
    print('updatedSheet')
    entries += 1
    return entries
def unix_time(dt):
    epoch = datetime.datetime.utcfromtimestamp(0)
    delta = dt - epoch
    return delta.total_seconds()
def timeConverter(timestamp,timeToStation):
    if len(timestamp) == 28:
        timestamp = timestamp[0:25]+timestamp[27]
    a = datetime.datetime.strptime(timestamp, "%Y-%m-%dT%H:%M:%S.%fZ") + datetime.timedelta(seconds = timeToStation)
    return time.ctime(int(unix_time(a))), unix_time(a)
def weatherRequest(response, tic):
    if time.time()-tic > 300 or response == {}:
        response = requests.get("http://api.openweathermap.org/data/2.5/weather?lat=51.474520&lon=-0.13234&APPID=6be8e1e50dafc734a74f13e0360e68df")
        tic = time.time()
    main = response.json()['weather'][0]['main']
    description = response.json()['weather'][0]['description']
    feels_like = response.json()['main']['feels_like']
    temp = response.json()['main']['temp']
    clouds = response.json()['clouds']['all']
    wind_speed = response.json()['wind']['speed']
    return response, main, description, feels_like, temp, clouds,wind_speed, tic
def pulse(delay):
    pulse_start = 0
    pulse_end = 0
    gpio.output(trig,True)
    time.sleep(0.00001)
    gpio.output(trig,False)
    now = time.time()
    while gpio.input(echo) == 0:
        pulse_start = time.time()
        if time.time() - now > 60:
            pulse_start = 0
            break
    while gpio.input(echo) == 1:
        pulse_end = time.time()
        if time.time() - now > 60:
            pulse_end = 0
            break

    if pulse_start == pulse_end:
        time.sleep(60)

    pulse_duration = pulse_end - pulse_start
    distance = round(pulse_duration * 17150, 2)
    time.sleep(delay)
    return distance

def trafficRequest(store):
    responseTo = requests.get("https://api.tfl.gov.uk/StopPoint/490008978N2/Arrivals")
    if responseTo.status_code == 200:
        responseTo = responseTo.json()
    else:
        return store
    responseFrom = requests.get("https://api.tfl.gov.uk/StopPoint/490008978N1/Arrivals")
    if responseFrom.status_code == 200:
        responseFrom = responseFrom.json()
    else:
        return store
    for i in range(len(responseTo)):
        responseItem = responseTo[i]
        if responseItem['timeToStation'] < 200:
            timestamp = responseItem['timestamp']
            timeToStation = responseItem['timeToStation']
            timestamp, ts = timeConverter(timestamp,timeToStation)
            store[responseItem['id']] = [responseItem['lineId'], timestamp, ts,'to']
    for i in range(len(responseFrom)):
        responseItem = responseFrom[i]
        if responseItem['timeToStation'] < 200:
            timestamp = responseItem['timestamp']
            timeToStation = responseItem['timeToStation']
            timestamp, ts = timeConverter(timestamp,timeToStation)
            store[responseItem['id']] = [responseItem['lineId'], timestamp, ts,'from']
    return store

try:
    gate = False
    tic = 0
    response = {}
    while True:
        time.sleep(20)
        print('sleeping')
        while datetime.datetime.today().hour < 23 and  datetime.datetime.today().hour > 5:
            if time.time() - traffic_poll > 40:
                store = trafficRequest(store)
                traffic_poll = time.time()
            todelete = []
            for i in store.keys():
                if time.time() - store[i][2]  > 120:
                    current_bus = [i,store[i][0],store[i][1],store[i][2],store[i][3]]
                    bus_entries, bus_gs = initGoogleSheet('Buses',0)
                    if bus_entries > 1000:
                        bus_entries, bus_gs = initGoogleSheet('Buses',0)
                    bus_entries = updateSheet(bus_entries,bus_gs,current_bus)
                    with open('buses.csv','a',newline='') as buses_file:
                        buses_writer = csv.writer(buses_file, delimiter = ',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
                        buses_writer.writerow(current_bus)
                    todelete.append(i)
            for i in todelete:
                del(store[i])
            current = pulse(0.1)
            if current < 40 or current > 2000:
                timestampI = time.time()
                timestamp = time.ctime(int(timestampI))
                response, main, description, feels_like, temp, clouds,wind_speed, tic = weatherRequest(response,tic)
                now = time.time()
                sectionCounter = 0
                while time.time() - now < 5:
                    current = pulse(0.1)
                    if current < 40 or current > 2000:
                        now = time.time()
                        if gate == False:
                            counter += 1
                            sectionCounter += 1
                            gate = True
                            print(sectionCounter)
                    elif current > 50 and current < 100:
                        gate = False
                recentbuses = []
                mostrecent = None
                for i in store.keys():
                    if time.time()-store[i][2] > 0:
                        if mostrecent == None:
                            mostrecent = i
                        else:
                            if store[i][2] > store[mostrecent][2]:
                                mostrecent = i
                        recentbuses.append(i)
                current_data = [timestamp, sectionCounter, main, description, feels_like, temp, clouds,wind_speed, ' '.join(recentbuses) , mostrecent]
                data_entries, data_gs = initGoogleSheet('SIOT_data',0)
                if data_entries > 1000:
                    data_entries, data_gs = initGoogleSheet('SIOT_data',0)
                data_entries = updateSheet(data_entries,data_gs,current_data)
                with open('data.csv','a',newline='') as data_file:
                    data_writer = csv.writer(data_file, delimiter = ',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
                    data_writer.writerow(current_data)
                urllib.request.urlopen("https://api.thingspeak.com/update?api_key=M47T7FFSVW26V7CR&field2=0"+str(sectionCounter))
                time.sleep(20)
finally:
    if buses_file != None:
        buses_file.close()
    if data_file != None:
        data_file.close()
    gpio.cleanup()
    print(counter)


n = int(input())
arr = []
count = 1
for i in range(n):
    arr.append(list(map(int, input().split())))
arr = sorted(arr, key=lambda x: (x[1], x[0]))
last = arr[0]
for i in range(1, n):
    if arr[i][0] >= last[1]:
        count += 1
        last = arr[i]

print(count)


from django.contrib import admin
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils.translation import gettext_lazy as _

from feincms.admin.item_editor import FeinCMSInline
from feincms.utils.tuple import AutoRenderTuple

try:
    from filer.fields.file import FilerFileField
    from filer.fields.image import FilerImageField
except ImportError:
    __all__ = ()

else:
    __all__ = (
        "MediaFileContentInline",
        "ContentWithFilerFile",
        "FilerFileContent",
        "FilerImageContent",
    )

    class MediaFileContentInline(FeinCMSInline):
        radio_fields = {"type": admin.VERTICAL}

    class ContentWithFilerFile(models.Model):
        """
        File content
        """

        feincms_item_editor_inline = MediaFileContentInline

        class Meta:
            abstract = True

        def render(self, **kwargs):
            return AutoRenderTuple(
                (
                    [
                        f"content/filer/{self.file_type}_{self.type}.html",
                        "content/filer/%s.html" % self.type,
                        "content/filer/%s.html" % self.file_type,
                        "content/filer/default.html",
                    ],
                    {"content": self},
                )
            )

    class FilerFileContent(ContentWithFilerFile):
        mediafile = FilerFileField(
            verbose_name=_("file"), related_name="+", on_delete=models.CASCADE
        )
        file_type = "file"
        type = "download"

        class Meta:
            abstract = True
            verbose_name = _("file")
            verbose_name_plural = _("files")

    class FilerImageContent(ContentWithFilerFile):
        """
        Create a media file content as follows::

            from feincms.contents import FilerImageContent
            Page.create_content_type(FilerImageContent, TYPE_CHOICES=(
                ('inline', _('Default')),
                ('lightbox', _('Lightbox')),
                ('whatever', _('Whatever')),
            ))

        For a media file of type 'image' and type 'lightbox', the following
        templates are tried in order:

        * content/mediafile/image_lightbox.html
        * content/mediafile/lightbox.html
        * content/mediafile/image.html
        * content/mediafile/default.html

        The context contains ``content`` and ``request`` (if available).

        The content.mediafile attribute are as follows (selection):
        label, description, default_caption, default_alt_text,
        author, must_always_publish_author_credit,
        must_always_publish_copyright, date_taken, file, id, is_public, url
        """

        mediafile = FilerImageField(
            verbose_name=_("image"), related_name="+", on_delete=models.CASCADE
        )
        caption = models.CharField(_("caption"), max_length=1000, blank=True)
        url = models.CharField(_("URL"), max_length=1000, blank=True)

        file_type = "image"

        class Meta:
            abstract = True
            verbose_name = _("image")
            verbose_name_plural = _("images")

        @classmethod
        def initialize_type(cls, TYPE_CHOICES=None):
            if TYPE_CHOICES is None:
                raise ImproperlyConfigured(
                    "You have to set TYPE_CHOICES when" " creating a %s" % cls.__name__
                )

            cls.add_to_class(
                "type",
                models.CharField(
                    _("type"),
                    max_length=20,
                    choices=TYPE_CHOICES,
                    default=TYPE_CHOICES[0][0],
                ),
            )


from canvas_sdk import client, utils

def list_authorization_configs(request_ctx, account_id, per_page=None, **request_kwargs):
    """
    Returns the list of authorization configs

        :param request_ctx: The request context
        :type request_ctx: :class:RequestContext
        :param account_id: (required) ID
        :type account_id: string
        :param per_page: (optional) Set how many results canvas should return, defaults to config.LIMIT_PER_PAGE
        :type per_page: integer or None
        :return: List Authorization Configs
        :rtype: requests.Response (with array data)

    """

    if per_page is None:
        per_page = request_ctx.per_page
    path = '/v1/accounts/{account_id}/account_authorization_configs'
    payload = {
        'per_page' : per_page,
    }
    url = request_ctx.base_api_url + path.format(account_id=account_id)
    response = client.get(request_ctx, url, payload=payload, **request_kwargs)

    return response

def create_authorization_config(request_ctx, account_id, **request_kwargs):
    """
    Add external account authentication service(s) for the account.
    Services may be CAS, SAML, or LDAP.

    Each authentication service is specified as a set of parameters as
    described below. A service specification must include an 'auth_type'
    parameter with a value of 'cas', 'saml', or 'ldap'. The other recognized
    parameters depend on this auth_type; unrecognized parameters are discarded.
    Service specifications not specifying a valid auth_type are ignored.

    Any service specification may include an optional 'login_handle_name'
    parameter. This parameter specifies the label used for unique login
    identifiers; for example: 'Login', 'Username', 'Student ID', etc. The
    default is 'Email'.

    You can set the 'position' for any configuration. The config in the 1st position
    is considered the default.

    For CAS authentication services, the additional recognized parameters are:

    - auth_base

      The CAS server's URL.

    - log_in_url [Optional]

      An alternate SSO URL for logging into CAS. You probably should not set
      this.

    For SAML authentication services, the additional recognized parameters are:

    - idp_entity_id

      The SAML IdP's entity ID - This is used to look up the correct SAML IdP if
      multiple are configured

    - log_in_url

      The SAML service's SSO target URL

    - log_out_url

      The SAML service's SLO target URL

    - certificate_fingerprint

      The SAML service's certificate fingerprint.

    - change_password_url [Optional]

      Forgot Password URL. Leave blank for default Canvas behavior.

    - identifier_format

      The SAML service's identifier format. Must be one of:

      - urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress
      - urn:oasis:names:tc:SAML:2.0:nameid-format:entity
      - urn:oasis:names:tc:SAML:2.0:nameid-format:kerberos
      - urn:oasis:names:tc:SAML:2.0:nameid-format:persistent
      - urn:oasis:names:tc:SAML:2.0:nameid-format:transient
      - urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified
      - urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName
      - urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName

    - requested_authn_context

      The SAML AuthnContext

    For LDAP authentication services, the additional recognized parameters are:

    - auth_host

      The LDAP server's URL.

    - auth_port [Optional, Integer]

      The LDAP server's TCP port. (default: 389)

    - auth_over_tls [Optional]

      Whether to use TLS. Can be '', 'simple_tls', or 'start_tls'. For backwards
      compatibility, booleans are also accepted, with true meaning simple_tls.
      If not provided, it will default to start_tls.

    - auth_base [Optional]

      A default treebase parameter for searches performed against the LDAP
      server.

    - auth_filter

      LDAP search filter. Use !{{login}} as a placeholder for the username
      supplied by the user. For example: "(sAMAccountName=!{{login}})".

    - identifier_format [Optional]

      The LDAP attribute to use to look up the Canvas login. Omit to use
      the username supplied by the user.

    - auth_username

      Username

    - auth_password

      Password

    - change_password_url [Optional]

      Forgot Password URL. Leave blank for default Canvas behavior.

    - account_authorization_config[n] (deprecated)
      The nth service specification as described above. For instance, the
      auth_type of the first service is given by the
      account_authorization_config[0][auth_type] parameter. There must be
      either a single CAS or SAML specification, or one or more LDAP
      specifications. Additional services after an initial CAS or SAML service
      are ignored; additional non-LDAP services after an initial LDAP service
      are ignored.

    _Deprecated_ Examples:

    This endpoint still supports a deprecated version of setting the authorization configs.
    If you send data in this format it is considered a snapshot of how the configs
    should be setup and will clear any configs not sent.

    Simple CAS server integration.

      account_authorization_config[0][auth_type]=cas&
      account_authorization_config[0][auth_base]=cas.mydomain.edu

    Single SAML server integration.

      account_authorization_config[0][idp_entity_id]=http://idp.myschool.com/sso/saml2
      account_authorization_config[0][log_in_url]=saml-sso.mydomain.com&
      account_authorization_config[0][log_out_url]=saml-slo.mydomain.com&
      account_authorization_config[0][certificate_fingerprint]=1234567890ABCDEF&
      account_authorization_config[0][identifier_format]=urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress

    Two SAML server integration with discovery url.

      discovery_url=http://www.myschool.com/sso/identity_provider_selection
      account_authorization_config[0][idp_entity_id]=http://idp.myschool.com/sso/saml2&
      account_authorization_config[0][log_in_url]=saml-sso.mydomain.com&
      account_authorization_config[0][log_out_url]=saml-slo.mydomain.com&
      account_authorization_config[0][certificate_fingerprint]=1234567890ABCDEF&
      account_authorization_config[0][identifier_format]=urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress&
      account_authorization_config[1][idp_entity_id]=http://idp.otherschool.com/sso/saml2&
      account_authorization_config[1][log_in_url]=saml-sso.otherdomain.com&
      account_authorization_config[1][log_out_url]=saml-slo.otherdomain.com&
      account_authorization_config[1][certificate_fingerprint]=ABCDEFG12345678789&
      account_authorization_config[1][identifier_format]=urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress

    Single LDAP server integration.

      account_authorization_config[0][auth_type]=ldap&
      account_authorization_config[0][auth_host]=ldap.mydomain.edu&
      account_authorization_config[0][auth_filter]=(sAMAccountName={{login}})&
      account_authorization_config[0][auth_username]=username&
      account_authorization_config[0][auth_password]=password

    Multiple LDAP server integration.

      account_authorization_config[0][auth_type]=ldap&
      account_authorization_config[0][auth_host]=faculty-ldap.mydomain.edu&
      account_authorization_config[0][auth_filter]=(sAMAccountName={{login}})&
      account_authorization_config[0][auth_username]=username&
      account_authorization_config[0][auth_password]=password&
      account_authorization_config[1][auth_type]=ldap&
      account_authorization_config[1][auth_host]=student-ldap.mydomain.edu&
      account_authorization_config[1][auth_filter]=(sAMAccountName={{login}})&
      account_authorization_config[1][auth_username]=username&
      account_authorization_config[1][auth_password]=password

        :param request_ctx: The request context
        :type request_ctx: :class:RequestContext
        :param account_id: (required) ID
        :type account_id: string
        :return: Create Authorization Config
        :rtype: requests.Response (with AccountAuthorizationConfig data)

    """

    path = '/v1/accounts/{account_id}/account_authorization_configs'
    url = request_ctx.base_api_url + path.format(account_id=account_id)
    response = client.post(request_ctx, url, **request_kwargs)

    return response

def update_authorization_config(request_ctx, account_id, id, **request_kwargs):
    """
    Update an authorization config using the same options as the create endpoint.
    You can not update an existing configuration to a new authentication type.

        :param request_ctx: The request context
        :type request_ctx: :class:RequestContext
        :param account_id: (required) ID
        :type account_id: string
        :param id: (required) ID
        :type id: string
        :return: Update Authorization Config
        :rtype: requests.Response (with AccountAuthorizationConfig data)

    """

    path = '/v1/accounts/{account_id}/account_authorization_configs/{id}'
    url = request_ctx.base_api_url + path.format(account_id=account_id, id=id)
    response = client.put(request_ctx, url, **request_kwargs)

    return response

def get_authorization_config(request_ctx, account_id, id, **request_kwargs):
    """
    Get the specified authorization config

        :param request_ctx: The request context
        :type request_ctx: :class:RequestContext
        :param account_id: (required) ID
        :type account_id: string
        :param id: (required) ID
        :type id: string
        :return: Get Authorization Config
        :rtype: requests.Response (with AccountAuthorizationConfig data)

    """

    path = '/v1/accounts/{account_id}/account_authorization_configs/{id}'
    url = request_ctx.base_api_url + path.format(account_id=account_id, id=id)
    response = client.get(request_ctx, url, **request_kwargs)

    return response

def delete_authorization_config(request_ctx, account_id, id, **request_kwargs):
    """
    Delete the config

        :param request_ctx: The request context
        :type request_ctx: :class:RequestContext
        :param account_id: (required) ID
        :type account_id: string
        :param id: (required) ID
        :type id: string
        :return: Delete Authorization Config
        :rtype: requests.Response (with void data)

    """

    path = '/v1/accounts/{account_id}/account_authorization_configs/{id}'
    url = request_ctx.base_api_url + path.format(account_id=account_id, id=id)
    response = client.delete(request_ctx, url, **request_kwargs)

    return response

def get_discovery_url(request_ctx, account_id, **request_kwargs):
    """
    Get the discovery url

        :param request_ctx: The request context
        :type request_ctx: :class:RequestContext
        :param account_id: (required) ID
        :type account_id: string
        :return: GET discovery url
        :rtype: requests.Response (with DiscoveryUrl data)

    """

    path = '/v1/accounts/{account_id}/account_authorization_configs/discovery_url'
    url = request_ctx.base_api_url + path.format(account_id=account_id)
    response = client.get(request_ctx, url, **request_kwargs)

    return response

def set_discovery_url(request_ctx, account_id, **request_kwargs):
    """
    If you have multiple IdPs configured, you can set a `discovery_url`.
    If that is set, canvas will forward all users to that URL when they need to
    be authenticated. That page will need to then help the user figure out where
    they need to go to log in.

    If no discovery url is configured, the 1st auth config will be used to
    attempt to authenticate the user.

        :param request_ctx: The request context
        :type request_ctx: :class:RequestContext
        :param account_id: (required) ID
        :type account_id: string
        :return: Set discovery url
        :rtype: requests.Response (with DiscoveryUrl data)

    """

    path = '/v1/accounts/{account_id}/account_authorization_configs/discovery_url'
    url = request_ctx.base_api_url + path.format(account_id=account_id)
    response = client.put(request_ctx, url, **request_kwargs)

    return response

def delete_discovery_url(request_ctx, account_id, **request_kwargs):
    """
    Clear discovery url

        :param request_ctx: The request context
        :type request_ctx: :class:RequestContext
        :param account_id: (required) ID
        :type account_id: string
        :return: Delete discovery url
        :rtype: requests.Response (with void data)

    """

    path = '/v1/accounts/{account_id}/account_authorization_configs/discovery_url'
    url = request_ctx.base_api_url + path.format(account_id=account_id)
    response = client.delete(request_ctx, url, **request_kwargs)

    return response


#!/usr/bin/env python

import os
from glob import glob
import papermill as pm
import intake
import nbscuid.util
import nbscuid.cache
import sys
from dask.distributed import Client
import dask
import time

def run():

    # Get control structure
    config_path = str(sys.argv[1])
    control = nbscuid.util.get_control_dict(config_path)
    nbscuid.util.setup_book(config_path)

    if control['computation_config']['use_cluster']:
        # Cluster management
        # Notebooks are configured to connect to this cluster
        cluster = nbscuid.util.get_Cluster(account=control['computation_config']['account'])
        cluster.scale(4) # Should this be user modifiable?
    else:
        cluster = None

    # Grab paths

    ### This code seems repetitive, is there a better way to do this?
    run_dir = os.path.realpath(os.path.expanduser(control['data_sources']['run_dir']))
    output_dir = run_dir + "/computed_notebooks/" + control['data_sources']['sname']
    cache_metadata_path = run_dir + "/cache_metadata_path"
    cache_data_path = run_dir + "/cache_data_path"
    temp_data_path = run_dir + "/temp_data"
    nb_path_root = os.path.realpath(os.path.expanduser(control['data_sources']['nb_path_root']))

    # Access catalog if it exists

    cat_path = None

    if 'path_to_cat_json' in control['data_sources']:
        use_catalog = True
        full_cat_path = os.path.realpath(os.path.expanduser(control['data_sources']['path_to_cat_json']))
        full_cat = intake.open_esm_datastore(full_cat_path)

    # Doing initial subsetting on full catalog, e.g. to only use certain cases

        if 'subset' in control['data_sources']:
            first_subset_kwargs = control['data_sources']['subset']
            cat_subset = full_cat.search(**first_subset_kwargs)
            # This pulls out the name of the catalog from the path
            cat_subset_name = full_cat_path.split("/")[-1].split('.')[0] + "_subset"
            cat_subset.serialize(directory=temp_data_path, name=cat_subset_name, catalog_type="file")
            cat_path = temp_data_path + "/" + cat_subset_name + ".json"
        else:
            cat_path = full_cat_path

    # Grabbing global params if they're included

    global_params = dict()

    if 'global_params' in control:
        global_params = control['global_params']

    #####################################################################
    # Organizing notebooks into three lists

    precompute_nbs = dict()
    regular_nbs = dict()
    dependent_nbs = dict()

    for nb, info in control['compute_notebooks'].items():
        if 'dependency' in info:
            dependent_nbs[nb] = info

            called_nb = info['dependency']

            precompute_nbs[called_nb] = control['compute_notebooks'][called_nb]
            precompute_nbs[called_nb]["needed by"] = list()
            precompute_nbs[called_nb]["needed by"].append(nb)

        else:
            regular_nbs[nb] = info

    # Removing the precompute nbs that got added to regular_nbs

    for key, item in precompute_nbs.items():
        if key in regular_nbs:
            regular_nbs.pop(key)

    #####################################################################
    # Pausing to wait for workers to avoid timeout error

    if control['computation_config']['use_cluster']:

        dask.config.set({'distributed.comm.timeouts.connect': '90s'})

        client = Client(cluster.scheduler_address)

        nworkers = 1

        waiting_count = 0

        while ((client.status == "running") and (len(client.scheduler_info()["workers"]) < nworkers)):
            time.sleep(1.0)
            if waiting_count == 0:
                print("Waiting for Dask workers", end = '')
            else:
                print(".", end = '')
            waiting_count += 1

        print("\n")

        client.close()

    #####################################################################
    # Calculating precompute notebooks

    ### To do: figure out how to organize the caching code better, keeping the whole block for now

    for nb, info in precompute_nbs.items():

        parameter_groups = info['parameter_groups']

        use_cluster = control['computation_config']['use_cluster'] and info['use_cluster']

        ### passing in subset kwargs if they're provided
        if 'subset' in info:
            subset_kwargs = info['subset']
        else:
            subset_kwargs = {}

        default_params = {}
        if 'default_params' in info:
            default_params = info['default_params']

        for key, parms in parameter_groups.items():

            ### fix this input path (and also organize this code better)
            input_path = f'{nb_path_root}/{nb}.ipynb'
            output_path = (
                f'{output_dir}/{nb}-{key}.ipynb'
                if key != 'none' else f'{output_dir}/{nb}.ipynb'
            )

            result_df = nbscuid.cache.gen_df_query(cache_metadata_path, input_path,
                                   full_cat_path, first_subset=first_subset_kwargs,
                                                 second_subset=subset_kwargs,
                                   params=parms)

            if not result_df.empty:
                #if multiple matches exist, grabs an arbitrary one (FIX LATER)
                asset_path = result_df.loc[0,'assets']
                precompute_nbs[nb]["asset_path"] = asset_path
                print("Fetching result from cache")

            else:

                asset_path = nbscuid.cache.make_filename(cache_data_path, input_path, full_cat_path) + ".nc"

                parms_in = dict(**default_params)
                parms_in.update(**global_params)
                parms_in.update(dict(**parms))
                parms_in['path_to_cat'] = cat_path

                if use_cluster:
                    parms_in['cluster_scheduler_address'] = cluster.scheduler_address
                else:
                    parms_in['cluster_scheduler_address'] = None

                parms_in['subset_kwargs'] = subset_kwargs
                parms_in['asset_path'] = asset_path

                print(f'executing {input_path}')
                o = pm.execute_notebook(
                    input_path=input_path,
                    output_path=output_path,
                    kernel_name=info['kernel_name'],
                    parameters=parms_in,
                    engine_name='md_jinja',
                    jinja_data=parms,
                    cwd=nb_path_root
                )

                nbscuid.cache.make_sidecar_entry(cache_metadata_path,
                                               input_path,
                                               full_cat_path,
                                               asset_path=asset_path,
                                               first_subset=first_subset_kwargs,
                                               second_subset= subset_kwargs,

                                               ### this might need to be changed to parms_in, not parms, to include global parms
                                               params=parms)

                # this can only properly handle one save per notebook (FIX LATER)
                precompute_nbs[nb]["asset_path"] = asset_path

    # Calculating regular notebooks

    for nb, info in regular_nbs.items():

        use_cluster = control['computation_config']['use_cluster']and info['use_cluster']

        nbscuid.util.run_notebook(nb, info, use_cluster, cat_path, nb_path_root, output_dir, global_params, cluster=cluster)

    # Calculating notebooks with dependencies

    for nb, info in dependent_nbs.items():

        use_cluster = control['computation_config']['use_cluster'] and info['use_cluster']

        ### getting necessary asset:
        dependent_asset_path = precompute_nbs[info['dependency']]["asset_path"]

        nbscuid.util.run_notebook(nb, info, use_cluster, cat_path, nb_path_root, output_dir, global_params, dependent_asset_path=dependent_asset_path, cluster=cluster)

    if control['computation_config']['use_cluster']:
        # Closing cluster
        cluster.close()

    return None


from ..命令行接口 import 全局配置
from ..基础接口 import 操作
#===============================================================================
# 模式
#===============================================================================
class C全局配置m6000(全局配置.I全局配置):
	def __init__(self, a):
		全局配置.I全局配置.__init__(self, a)
	#命令
	def fg进入命令(self):
		return "configure terminal"
	#模式
	def f模式_接口(self, a接口, a操作 = 操作.E操作.e设置):
		from . import 接口
		v接口 = 接口.f创建接口m6000(a接口)
		return 接口.C接口m6000(self, v接口)
	#数据结构
	def f模式_访问控制列表(self, a名称, a类型 = None, a操作 = 操作.E操作.e设置):
		from ..基础接口 import 访问控制列表 as 北向列表
		from ..命令行接口 import 访问控制列表 as 南向列表
		from . import 访问控制列表 as 实现列表
		if a类型 in (北向列表.E类型.e标准4, 北向列表.E类型.e扩展4):
			v模式 = 实现列表.C扩展4_m6000(self, a名称)
		else:
			raise ValueError("未知的访问控制列表类型")
		return v模式

网络设备脚本/中兴命令行/全局配置.py


'''
给定一个整数数组 nums 和一个目标值 target，请你在该数组中找出和为目标值的那 两个 整数，并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是，你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

链接：https://leetcode-cn.com/problems/two-sum
'''
class Solution:
    def twoSum(self, nums: list, target: int) -> list:
        '''
        解法：1遍字典
        '''
        dic = {}
        for i, v in enumerate(nums):
            diff = target - v   # 计算差值
            if diff in dic: return [dic[diff], i]   # 检查差值是否在字典中
            dic[v] = i

人生苦短/两数之和.py


def dict_sorting_by_values(d):
    return {k: v for k, v in sorted(d.items(), key=lambda item: item[1])}

with open("./war_n_peace.txt", encoding="utf-8") as file:
    line_counter = 0
    word_counter = 0
    res_lst = []
    words_dict = {}
    letters_dict = {}
    for line in file:
        if "Princesse, ma parole" in line:
            print(f'Princesse, ma parole found in {line_counter}')

        line = line.replace("Анна Павловна", "Anna Pavlovna")

        res_lst += line.split()
        line_counter += 1
print(f'4) {len(res_lst)}')

res_lst = list(map(str.lower, res_lst))
# print(res_lst)
check_rus_let = lambda a: True if ord("я") >= ord(a) >= ord("а") else False

res_lst = list(filter(lambda a: a, map(lambda a: "".join(filter(check_rus_let, a)), res_lst)))

# res_lst = list(map())
# print(res_lst)
letters_quantity = sum(map(len, res_lst))
average_len = letters_quantity / len(res_lst)
print(f'7) {average_len}')
print(f'8) {letters_quantity}')

for word in res_lst:
    if word in words_dict:
        words_dict.update({word: words_dict[word] + 1})
    else:
        words_dict.update({word: 1})

    for letter in word:
        if letter in letters_dict:
            letters_dict.update({letter: letters_dict[letter] + 1})
        else:
            letters_dict.update({letter: 1})

words_top = [(k, v,) for k, v in dict_sorting_by_values(words_dict).items()]
letters_top = [(k, v,) for k, v in dict_sorting_by_values(letters_dict).items()]
print(f'10) {words_top[-1:-11:-1]}')
print(f'11) {letters_top[-1:-11:-1]}' )

# print(words_top)
# print(res_lst)


from django.http import JsonResponse
from django.shortcuts import render
from django.db.models import F, Q
from .models import *

# N+1 문제
def user_list(request):
    # N+1이 발생하는 쿼리셋
    # users = User.objects.all()

    # N+1은 select_related(), prefetch_related()라는 메서드로 Eager Loading하여 방지할 수 있다.
    # select_related() : 정방향 참조 필드
    # prefetch_related() : 역방향 참조 필드
    users = User.objects.select_related('userinfo')

    for user in users:
        user.userinfo

    return render(request, 'index.html')

# F() => python 메모리에 저장을 하지 않고 쿼리문을 만들어 DB 자체에서 연산을 수행.
def age_for_f(request):
    userinfo_hong = Userinfo.objects.get(first_name='hong')

    # not used F()
    #userinfo_hong.age += 1

    # use F()
    userinfo_hong.age = F('age') + 1
    userinfo_hong.save()

    # F() 사용시 주의점 => 모델 필드에 할당된 F() 객체는 저장 후에도 유지된다.
    # userinfo_hong.age = F('age') + 1
    # userinfo_hong.save()
    #
    # userinfo_hong.first_name = 'hooong'
    # userinfo_hong.save()    # 'hong'을 가지고 있던 userinfo는 age가 2만큼 증가하게 된다.

    return render(request, 'index.html')

# Q() => Where절에 or 또는 AND를 추가할때 사용할 수 있는 함수
def q_function(request):

    userinfo_with_25_or_21 = Userinfo.objects.filter(
                                                Q(age=21) | Q(age=25))
    # SELECT * FROM "orm_test_userinfo"
    # WHERE ("orm_test_userinfo"."age" = 21 OR "orm_test_userinfo"."age" = 25) LIMIT 21;
    print(userinfo_with_25_or_21)

    q = Q()
    q.add(Q(age=20), q.OR)
    q.add(Q(first_name='a'), q.AND)     # 두번째 인자값은 해당 조건문 앞으로 붙는다.
    userinfo_a = Userinfo.objects.filter(q)
    # SELECT * FROM "orm_test_userinfo"
    # WHERE ("orm_test_userinfo"."age" = 20 AND "orm_test_userinfo"."first_name" = 'a') LIMIT 21;
    print(userinfo_a)

    return render(request, 'index.html')


class Identitas():
    namaJurusan = "Informatika"
    def __init__(self, nama, nim):
        self.nama = nama
        self.nim = nim

na = Identitas("David", "D0219003")
print("Nama     : "+na.nama)
print("Nim      : "+na.nim)
print("Jurusan  : "+na.namaJurusan)


# Ejercicio Vehiculo

from blinker import *
from engine import *
from fuel import *
from enviroment import *
from light import *

class Vehicle:
    def __init__(self):
        self.blinker_front = Blinker(BLINKER_FRONT)
        self.blinker_rear = Blinker(BLINKER_REAR)
        self.engine = Engine()
        self.fuel = Fuel(self.engine)
        self.enviroment = Enviroment()
        self.light = Light(self.enviroment)

    def __str__(self):
        status = ""
        status += str(self.blinker_front) + "  BLINKERS  " + str(self.blinker_rear) + "\n"
        status += str(self.engine) + "\n"
        status += str(self.fuel) + "\n"
        status += str(self.enviroment) + "\n"
        status += str(self.light)
        return status

    def do_work(self):

        while self.fuel.level > 0:
            print(self)
            key = input('next action (q quit): ')

            if key == 's':
                self.blinker_front.change()
            if key == 'a':
                self.blinker_rear.change()
            if key == 'w':
                self.engine.modify_rpm(100)
            if key == 'z':
                self.engine.modify_rpm(-100)
            if key == 'e':
                self.engine.modify_gear(1)
            if key == 'd':
                self.engine.modify_gear(-1)
            if key == 'r':
                self.enviroment.modify_lum(10)
            if key == 'f':
                self.enviroment.modify_lum(-10)

            if key == 'q':
                exit()

            self.light.update()
            self.fuel.update()
            print("\n")

if __name__ == "__main__":
    vehicle1 = Vehicle()
    vehicle1.do_work()


from modules.count_songs import count_songs
from modules.count_songs_key import count_songs_key
from modules.count_occurances import count_occurances
csv_path = "spotify-2023.csv"

if __name__ == "__main__":

    # Challenge One
    song_count = count_songs(csv_path)

    if song_count == -404:
        print("CSV file not found.")
    elif song_count == -400:
        print("Something went wrong.")
    else:
        print(f"Number of songs : {song_count}")

    # Challenge Two
    column_name = "key" # You can modify the column
    key_value = "E"    # and the value to be counted

    songs_in_key = count_songs_key(csv_path, column_name, key_value)
    print(f"Number of songs in the key of E: {songs_in_key}")

    # Challange Three

    result = count_occurances(csv_path, column_name)

    if result:
        most_common_value, most_common_count = result
        print(f"The most common value in the specified column is '{most_common_value}' with {most_common_count} occurrences.")
    else:
        print("An error occurred. Please check the CSV file and column name.")


from myhdl import block, Signal, intbv, modbv, delay, instance, instances, always_comb, always_seq, always
from gluelogic import lane
from random import randrange
import inspect
from utils import functionStat
import numpy as np
np.set_printoptions(formatter={'int':hex})

class bus:
    def __init__(self, DATA=8, WORDS=4, ADDR=8, UPPER=2**8-4, LOWER=4, OFFSET=8, U_SIZE=1):
        self.tvalid  = Signal(bool(0))
        self.tready  = Signal(bool(0))
        self.tdata   = Signal(modbv(0)[DATA*WORDS:])
        self.tkeep   = Signal(modbv(0)[WORDS:])
        self.tlast   = Signal(bool(0))
        self.tuser   = Signal(modbv(0)[U_SIZE:])
        self.DATA    = DATA
        self.WORDS   = WORDS
        self.ADDR    = ADDR
        self.UPPER   = UPPER
        self.LOWER   = LOWER
        self.OFFSET  = OFFSET
        self.U_SIZE  = U_SIZE

    @block
    def sConnector(self, axiBus):
        functionStat(inspect.currentframe().f_code.co_name, __name__)
        @always_comb
        def logic():
            self.tvalid.next   = axiBus.tvalid
            axiBus.tready.next = self.tready
            self.tdata.next    = axiBus.tdata
            self.tkeep.next    = axiBus.tkeep
            self.tlast.next    = axiBus.tlast
            self.tuser.next    = axiBus.tuser
        return instances()

    @block
    def muxT(self, clk, rst, axiBusA, axiBusB, en, sel):

        @always_seq(clk.posedge, reset = rst)
        def muxlogic():
            if en:
                if sel:
                    axiBusA.tready.next = self.tready
                    axiBusB.tready.next = 0
                    self.tvalid.next    = axiBusA.tvalid
                    self.tdata.next     = axiBusA.tdata
                    self.tlast.next     = axiBusA.tlast
                    self.tkeep.next     = axiBusA.tkeep
                    self.tuser.next     = axiBusA.tuser
                else:
                    axiBusA.tready.next = 0
                    axiBusB.tready.next = self.tready
                    self.tvalid.next    = axiBusB.tvalid
                    self.tdata.next     = axiBusB.tdata
                    self.tlast.next     = axiBusB.tlast
                    self.tkeep.next     = axiBusB.tkeep
                    self.tuser.next     = axiBusB.tuser
            else:
                axiBusA.tready.next = 0
                axiBusB.tready.next = 0
                self.tvalid.next    = 0
                self.tdata.next     = 0
                self.tlast.next     = 0
                self.tkeep.next     = 0
                if sel:
                    self.tuser.next  = axiBusA.tuser
                else:
                    self.tuser.next  = axiBusB.tuser
        return instances()

    @block
    def demuxT(self, clk, rst, axiBusA, axiBusB, sel):

        @always_seq(clk.posedge, reset = rst)
        def demuxlogic():
            if sel:
                self.tready.next    = axiBusA.tready
                axiBusA.tvalid.next = self.tvalid
                axiBusA.tdata.next  = self.tdata
                axiBusA.tlast.next  = self.tlast
                axiBusA.tkeep.next  = self.tkeep
                axiBusA.tuser.next  = self.tuser
                axiBusB.tvalid.next = 0
                axiBusB.tdata.next  = 0
                axiBusB.tlast.next  = 0
                axiBusB.tkeep.next  = 0
                axiBusB.tuser.next  = 0
            else:
                self.tready.next    = axiBusB.tready
                axiBusB.tvalid.next = self.tvalid
                axiBusB.tdata.next  = self.tdata
                axiBusB.tlast.next  = self.tlast
                axiBusB.tkeep.next  = self.tkeep
                axiBusB.tuser.next  = self.tuser
                axiBusA.tvalid.next = 0
                axiBusA.tdata.next  = 0
                axiBusA.tlast.next  = 0
                axiBusA.tkeep.next  = 0
                axiBusA.tuser.next  = 0

        return instances()

    @block
    def axi2fifo(self, clk, rst, fifoBus):
        functionStat(inspect.currentframe().f_code.co_name, __name__)
        @always_comb
        def writeLogic():
            self.tready.next = not fifoBus.inbusy
            if self.tvalid:
                fifoBus.din.next = self.tdata
                fifoBus.we.next  = 1
            else:
                fifoBus.din.next = 0
                fifoBus.we.next  = 0
        return instances()

    @block
    def fifo2axi(self, clk, rst, fifoBus):
        functionStat(inspect.currentframe().f_code.co_name, __name__)
        readFlag = Signal(bool(0))

        @always_comb
        def readLogic():
            fifoBus.rd.next = self.tready and readFlag
            self.tvalid.next = fifoBus.rdout
            if fifoBus.rdout:
                self.tdata.next = fifoBus.dout
                self.tkeep.next = 0xFFFFFFFFFFFFFFFF
                self.tlast.next = fifoBus.outbusy
            else:
                self.tdata.next = 0x0
                self.tkeep.next = 0x0
                self.tlast.next = 0x0

        @always_seq(clk.posedge, reset = rst)
        def readSeqLogic():
            if fifoBus.hfull:
                readFlag.next = 1
            if fifoBus.outbusy:
                readFlag.next = 0
        return instances()

@block
def axi2fifo(clk, rst, axiBus, fifoBus):
    functionStat(inspect.currentframe().f_code.co_name, __name__)
    axi2fifoInst = axiBus.axi2fifo(clk, rst, fifoBus)
    return instances()

@block
def fifo2axi(clk, rst, axiBus, fifoBus):
    functionStat(inspect.currentframe().f_code.co_name, __name__)
    fifo2axiInst = axiBus.fifo2axi(clk, rst, fifoBus)
    return instances()

class axi4Stream:
    def __init__(self, DATA=8, WORDS=4, ADDR=8, UPPER=2**8-4, LOWER=4, OFFSET=8, U_SIZE=1):
        self.axiMBus = bus(DATA=DATA, WORDS=WORDS, ADDR=ADDR, UPPER=UPPER, LOWER=LOWER, OFFSET=OFFSET, U_SIZE=U_SIZE)
        self.axiSBus = bus(DATA=DATA, WORDS=WORDS, ADDR=ADDR, UPPER=UPPER, LOWER=LOWER, OFFSET=OFFSET, U_SIZE=U_SIZE)
        self.laneBus = lane.bus(DATA=DATA*WORDS, ADDR=ADDR, UPPER=UPPER, LOWER=LOWER, OFFSET=OFFSET)

        self.DATA    = DATA
        self.WORDS   = WORDS
        self.ADDR    = ADDR
        self.UPPER   = UPPER
        self.LOWER   = LOWER
        self.OFFSET  = OFFSET
        self.U_SIZE  = U_SIZE

    def clone(self):
        return axi4Stream(DATA=self.DATA, WORDS=self.WORDS,
                          ADDR=self.ADDR, UPPER=self.UPPER,
                          LOWER=self.LOWER, OFFSET=self.OFFSET,
                          U_SIZE=self.U_SIZE)

    @block
    def connector(self, axi4StreamBus):
        functionStat(inspect.currentframe().f_code.co_name, __name__)
        sConnectorInst = self.axiSBus.sConnector(axi4StreamBus.axiMBus)
        mConnectorInst = axi4StreamBus.axiSBus.sConnector(self.axiMBus)
        return instances()

    @block
    def connectorT(self, clk, rst, axi4StreamBus, axi4StreamBusDown, en, sel):
        functionStat(inspect.currentframe().f_code.co_name, __name__)
        muxTInst   = self.axiSBus.demuxT  (clk, rst, axi4StreamBus.axiSBus, axi4StreamBusDown.axiSBus, sel)
        demuxTInst = self.axiMBus.muxT    (clk, rst, axi4StreamBus.axiMBus, axi4StreamBusDown.axiMBus, en, sel)
        return instances()

    @block
    def axi2lane(self, clk, rst):
        functionStat(inspect.currentframe().f_code.co_name, __name__)
        axi2fifoInst = self.axiSBus.axi2fifo(clk, rst, self.laneBus.busA)
        fifo2axiInst = self.axiMBus.fifo2axi(clk, rst, self.laneBus.busA)
        laneInst     = lane.lane(clk, clk, rst, self.laneBus)
        return instances()

@block
def axi2lane(clk, rst, axi4StreamBus):
    functionStat(inspect.currentframe().f_code.co_name, __name__)
    axi2laneInst = axi4StreamBus.axi2lane(clk, rst)
    return instances()

def toModbv(data, DATA = 512):
    i = 0
    vector = 0
    vectors = []
    for d in data:
        vector ^= int(d) << (i * 64)
        i += 1
        if i == int(DATA/64):
            i = 0
            vectors.append(modbv(vector)[DATA:])
            vector = 0
    return vectors


import unittest

from statistics import Statistics
from statistics import SortBy
from player import Player

class PlayerReaderStub:
    def get_players(self):
        return [
            Player("Semenko", "EDM", 4, 12),
            Player("Lemieux", "PIT", 45, 54),
            Player("Kurri",   "EDM", 37, 53),
            Player("Yzerman", "DET", 42, 56),
            Player("Gretzky", "EDM", 35, 89)
        ]

class TestStatistics(unittest.TestCase):
    def setUp(self):
        # annetaan Statistics-luokan oliolle "stub"-luokan olio
        self.statistics = Statistics(
            PlayerReaderStub()
        )

    def test_search_returns_correct_players_when_found(self):
        search_name = "Semenko"
        result = self.statistics.search(name=search_name)
        self.assertEqual(result.name, search_name)

    def test_search_returns_none_when_not_found(self):
        search_name = "asdf"
        result = self.statistics.search(name=search_name)
        self.assertIsNone(result)

    def test_team_search_returns_correct_players(self):
        search_name = "EDM"
        result = self.statistics.team(team_name=search_name)
        names = [player.name for player in result]
        self.assertEqual(names, ["Semenko", "Kurri", "Gretzky"])

    def test_top_points_returns_correct_players(self):
        result = self.statistics.top(how_many=0, sort_by=SortBy.POINTS)
        names = [player.name for player in result]
        self.assertEqual(names, ["Gretzky"])

    def test_top_goals_returns_correct_players(self):
        result = self.statistics.top(how_many=0, sort_by=SortBy.GOALS)
        names = [player.name for player in result]
        self.assertEqual(names, ["Lemieux"])

    def test_top_assists_returns_correct_players(self):
        result = self.statistics.top(how_many=0, sort_by=SortBy.ASSISTS)
        names = [player.name for player in result]
        self.assertEqual(names, ["Gretzky"])


import math
import functools
import torch

def master_only(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        if get_rank() == 0:
            return func(*args, **kwargs)
        else:
            return None
    return wrapper

@master_only
def master_only_print(*args):
    """master-only print"""
    print(*args)

def get_rank():
    if torch.distributed.is_initialized():
        rank = torch.distributed.get_rank()
    else:
        rank = 0
    return rank

class LR_Scheduler(object):
    """Learning Rate Scheduler
    Step mode: ``lr = baselr * 0.1 ^ {floor(epoch-1 / lr_step)}``
    Cosine mode: ``lr = baselr * 0.5 * (1 + cos(iter/maxiter))``
    Poly mode: ``lr = baselr * (1 - iter/maxiter) ^ 0.9``
    Args:
        args:  :attr:`args.lr_scheduler` lr scheduler mode (`cos`, `poly`),
          :attr:`args.lr` base learning rate, :attr:`args.epochs` number of epochs,
          :attr:`args.lr_step`
        iters_per_epoch: number of iterations per epoch
    """
    def __init__(self, mode, base_lr, num_epochs, iters_per_epoch=0,
                 lr_step=0, warmup_epochs=0, quiet=False,
                 logger=None):
        self.mode = mode
        self.quiet = quiet
        self.logger = logger
        if not quiet:
            msg = 'Using {} LR scheduler with warm-up epochs of {}!'.format(self.mode, warmup_epochs)
            if self.logger:
                self.logger.info(msg)
            else:
                master_only_print()
        if mode == 'step':
            assert lr_step
        self.base_lr = base_lr
        self.lr_step = lr_step
        self.iters_per_epoch = iters_per_epoch
        self.epoch = -1
        self.warmup_iters = warmup_epochs * iters_per_epoch
        self.total_iters = (num_epochs - warmup_epochs) * iters_per_epoch

    def __call__(self, optimizer, i, epoch, best_pred):
        T = epoch * self.iters_per_epoch + i
        # warm up lr schedule
        if self.warmup_iters > 0 and T < self.warmup_iters:
            lr = self.base_lr * 1.0 * T / self.warmup_iters
        elif self.mode == 'cos':
            T = T - self.warmup_iters
            lr = 0.5 * self.base_lr * (1 + math.cos(1.0 * T / self.total_iters * math.pi))
        elif self.mode == 'poly':
            T = T - self.warmup_iters
            lr = self.base_lr * pow((1 - 1.0 * T / self.total_iters), 0.9)
        elif self.mode == 'step':
            lr = self.base_lr * (0.1 ** (epoch // self.lr_step))
        else:
            raise NotImplementedError
        if epoch > self.epoch and (epoch == 0 or best_pred > 0.0):
            if not self.quiet:
                msg = '\n=>Epoch %i, learning rate = %.4f, \
                    previous best = %.4f' % (epoch, lr, best_pred)
                if self.logger:
                    self.logger.info(msg)
                else:
                    master_only_print()
            self.epoch = epoch
        assert lr >= 0
        self._adjust_learning_rate(optimizer, lr)

    def _adjust_learning_rate(self, optimizer, lr):
        for i in range(len(optimizer.param_groups)):
            optimizer.param_groups[i]['lr'] = lr


import copy

from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
import datetime as dt
from datetime import timedelta

from account.decorators import manager_required
from care_point.forms import WorksheetForm
from care_point.models import Worksheet, Decision
from care_point.utils import _prepare_duties_for_decisoin

@manager_required
def worksheet(request):
    worksheet = Worksheet.objects.all()
    return render(request, 'care_point/worksheet/worksheet.html', {'worksheet': worksheet})

@manager_required
def worksheet_add(request):
    if request.method == 'POST':
        form = WorksheetForm(data=request.POST)
        if form.is_valid():
            new_worksheet = form.save(commit=False)
            quantity = form.cleaned_data.get('quantity')
            if quantity and quantity > 1:
                return _add_multiple_worksheets(request, form, quantity)
            return create_worksheet(request, new_worksheet, path='care_point/worksheet/worksheet_add.html')
    else:
        form = WorksheetForm()
        return render(request, 'care_point/worksheet/worksheet_add.html', {'form': form})

@login_required
def worksheet_details(request, worksheet_id):
    worksheet = get_object_or_404(Worksheet, pk=worksheet_id)
    decision = Decision.objects.filter(pk=worksheet.decision_id).first()
    illnesses, activities = _prepare_duties_for_decisoin(decision)
    return render(request, 'care_point/worksheet/worksheet_details.html', {'worksheet': worksheet,
                                                                           'illnesses': illnesses,
                                                                           'decision': decision,
                                                                           'activities': activities})

@manager_required
def worksheet_update(request, worksheet_id):
    worksheet = get_object_or_404(Worksheet, pk=worksheet_id)
    form = WorksheetForm(data=request.POST or None, instance=worksheet)
    if request.method == 'POST':
        if form.is_valid():
            new_worksheet = form.save(commit=False)
            return create_worksheet(request, new_worksheet, path='care_point/worksheet/worksheet_update.html')
        return redirect('care_point:worksheet')
    return render(request, 'care_point/worksheet/worksheet_update.html', {'form': form})

@manager_required
def worksheet_delete(request, worksheet_id):
    worksheet = get_object_or_404(Worksheet, pk=worksheet_id)
    worksheet.delete()
    return redirect('care_point:worksheet')

@manager_required
def create_worksheet(request, new_worksheet, path):
    caregiver_worksheet_at_date, ward_worksheet_at_date = get_caregiver_and_ward_worksheets_for_date(new_worksheet)
    is_caregiver_free = check_available(caregiver_worksheet_at_date, new_worksheet)
    is_ward_free = check_available(ward_worksheet_at_date, new_worksheet)
    if not is_new_worksheet_time_valid(new_worksheet):
        info = "Nieprawidłowe godziny"
        form = WorksheetForm(data=request.POST, instance=new_worksheet)
        return render(request, path, {'form': form, "info": info})
    elif is_caregiver_free and is_ward_free:
        new_worksheet.save()
        return redirect('care_point:worksheet')
    elif not is_caregiver_free:
        info = "W godzinach " + new_worksheet.hour_from.__str__() + " - " + new_worksheet.hour_to.__str__() + " pracownik " + new_worksheet.caregiver.__str__() + " wykonuje inne obowiazki"
        form = WorksheetForm(data=request.POST, instance=new_worksheet)
        return render(request, path, {'form': form, "info": info})
    elif not is_ward_free:
        info = "W godzinach " + new_worksheet.hour_from.__str__() + " - " + new_worksheet.hour_to.__str__() + " podopieczny " + new_worksheet.ward.__str__() + " ma inna wizyte"
        form = WorksheetForm(data=request.POST, instance=new_worksheet)
        return render(request, path, {'form': form, "info": info})

def check_available(worksheets, new_worksheet):
    new_worksheet_time_from = dt.datetime.combine(dt.date(1, 1, 1), new_worksheet.hour_from)
    new_worksheet_time_to = dt.datetime.combine(dt.date(1, 1, 1), new_worksheet.hour_to)
    compare_time = dt.timedelta(0, 0, 0)
    is_free = True
    if len(worksheets) > 0:
        for i in worksheets:
            worksheet_time_from = dt.datetime.combine(dt.date(1, 1, 1), i.hour_from)
            worksheet_time_to = dt.datetime.combine(dt.date(1, 1, 1), i.hour_to)
            if worksheet_time_from - new_worksheet_time_from < compare_time:
                if worksheet_time_to - new_worksheet_time_from > compare_time or worksheet_time_to - new_worksheet_time_to > compare_time:
                    is_free = False
            elif worksheet_time_from - new_worksheet_time_from > compare_time:
                if worksheet_time_from - new_worksheet_time_to < compare_time or worksheet_time_to - new_worksheet_time_to < compare_time:
                    is_free = False
            else:
                is_free = False
    return is_free

def get_caregiver_and_ward_worksheets_for_date(worksheet):
    caregiver_worksheets = Worksheet.objects.filter(caregiver=worksheet.caregiver).filter(date=worksheet.date)
    ward_worksheets = Worksheet.objects.filter(ward=worksheet.ward).filter(date=worksheet.date)
    return caregiver_worksheets, ward_worksheets

def is_new_worksheet_time_valid(new_worksheet):
    new_time_from = dt.datetime.combine(dt.date(1, 1, 1), new_worksheet.hour_from)
    new_time_to = dt.datetime.combine(dt.date(1, 1, 1), new_worksheet.hour_to)
    compare_time = dt.timedelta(0, 0, 0)
    if new_time_from - new_time_to < compare_time:
        return True
    return False

def _add_multiple_worksheets(request, form, quantity):
    new_worksheet = form.save(commit=False)
    interval = form.cleaned_data.get('interval')
    date = form.cleaned_data.get('date')
    worksheets = prepare_worksheet_list(new_worksheet, interval, date, quantity - 1)
    info = save_correct_worksheets(worksheets)
    worksheet_all = Worksheet.objects.all()
    return render(request, 'care_point/worksheet/worksheet.html', {'info': info, 'worksheet': worksheet_all})

def prepare_worksheet_list(worksheet, interval, date, quantity):
    worksheets = []
    worksheets.append(worksheet)
    for i in range(quantity):
        delta = timedelta(days=+interval)
        date = date + delta
        next_worksheet = copy.deepcopy(worksheet)
        next_worksheet.date = date
        worksheets.append(next_worksheet)
    return worksheets

def save_correct_worksheets(worksheets):
    info = ''
    worksheet_to_save = []
    for w in worksheets:
        message, worksheet = create_worksheet_for_multiple_creator(w)
        if worksheet:
            worksheet_to_save.append(worksheet)
        info += message
    Worksheet.objects.bulk_create(worksheet_to_save)
    return info

def create_worksheet_for_multiple_creator(new_worksheet):
    caregiver_worksheet_at_date, ward_worksheet_at_date = get_caregiver_and_ward_worksheets_for_date(new_worksheet)
    is_caregiver_free = check_available(caregiver_worksheet_at_date, new_worksheet)
    is_ward_free = check_available(ward_worksheet_at_date, new_worksheet)
    if not is_new_worksheet_time_valid(new_worksheet):
        info = "Karta pracy z dnia " + new_worksheet.date.__str__() + " ma błedne godziny początek:" + new_worksheet.hour_from.__str__() + " ,koniec: " + new_worksheet.hour_to.__str__() + '.' + ' \n'
        return info, None
    elif is_caregiver_free and is_ward_free:
        info = "Pomyslnie dodano karte pracy na dzień " + new_worksheet.date.__str__() + " w  godzinach " + new_worksheet.hour_from.__str__() + " - " + new_worksheet.hour_to.__str__() + '.' + '\n'
        return info, new_worksheet
    elif not is_caregiver_free:
        info = "Dnia " + new_worksheet.date.__str__() + " w  godzinach " + new_worksheet.hour_from.__str__() + " - " + new_worksheet.hour_to.__str__() + " pracownik " + new_worksheet.caregiver.__str__() + " wykonuje inne obowiazki." + '\n'
        return info, None
    elif not is_ward_free:
        info = "Dnia " + new_worksheet.date.__str__() + " w godzinach " + new_worksheet.hour_from.__str__() + " - " + new_worksheet.hour_to.__str__() + " podopieczny " + new_worksheet.ward.__str__() + " ma inna wizyte." + '\n'
        return info, None


import os

from visual_attention.preprocessing import preprocess_dir

def run(path, cropped, features):
    sets = ['val', 'train', 'test']
    postfix = '2017'
    for s in sets:
        preprocess_dir(os.path.join(path, s + postfix),
                       os.path.join(cropped, s),
                       os.path.join(features, s))

def main():
    input_dir = os.environ['MSCOCO_PATH']
    run(input_dir, 'output/cropped', 'output/features')

if __name__ == '__main__':
    main()


import argparse
import os
import random
from secrets import choice
import numpy as np
import torch
from dataloader import get_dataloader
from trainer import BaseTrainer, SimTrainer, ClfTrainer

def set_seed(args):
    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    if args.n_gpu > 0:
        torch.cuda.manual_seed_all(args.seed)

def main():
    parser = argparse.ArgumentParser()
    # customized the dataset and labeld size
    parser.add_argument('--dataset', type=str, default='yahoo')
    parser.add_argument('--num_labeled', type=int, default=200)

    # customize the model
    parser.add_argument('--n_gpu', type=int, default=1, help='the number of gpus')
    parser.add_argument('--num_augs', type=int, default=2, help='the number of augmentation methods used in a single run')
    parser.add_argument('--hidden_size', type=int, default=128, help='the linear hidden dimension in the classifier on the top of bert')
    parser.add_argument('--scorer_hidden_size', type=int, default=768, help='the linear hidden dimension in the classifier on the top of bert')

    # task
    parser.add_argument('--task', type=str, default='semi')
    parser.add_argument('--aug_metric', type=str, default='base', choices=['base', 'sim'])
    parser.add_argument('--seed', type=int, default=2022)

    # customize the trainer
    parser.add_argument('--num_epoch', type=int, default=20, help='num epoches to train')
    parser.add_argument('--warmup_epoch', type=int, default=0, help='num epoches to train')
    parser.add_argument('--optimizer', type=str, default='AdamW', help='the optimizer chosen to train the model')
    parser.add_argument('--thr', type=float, default=0.9, help='the threshold chosen to filter "truths" of low probabilities')
    parser.add_argument('--mu', type=int, default=4, help='the batchsize ratio between unlabeled set and labeled set')
    parser.add_argument('--lbd', type=float, default=0.1, help='the coefficient that controls the strength of the backpropagation of unlabled loss')
    parser.add_argument('--patience', type=int, default=5, help='patience in the training process')
    parser.add_argument('--aux_metric', type=str, default='CE', help='the metric for strength comparison of two augmentation predictions (default: cross entropy)')
    parser.add_argument('--method', type=str, default='aaa', help='the metric for strength comparison of two augmentation predictions (default: cross entropy)')
    parser.add_argument('--lr_main', type=float, default=1e-3, help='learning rate for the main task')
    parser.add_argument('--lr_bert', type=float, default=1e-5, help='learning rate for the bert model')
    parser.add_argument('--lr_aux', type=float, default=1e-4, help='learning rate for the auxiliary task')

    config = parser.parse_args()

    train_loader_l, train_loader_u, dev_loader, test_loader, num_class = get_dataloader(os.path.join('../data', config.dataset), config.num_labeled, config.mu, config.task)
    loaders = {
        'train_loader_l': train_loader_l,
        'train_loader_u': None if config.task == 'baseline' else train_loader_u,
        'dev_loader': dev_loader,
        'test_loader': test_loader
    }
    if config.dataset == 'imdb':
        config.num_classes = 2
    else:
        config.num_classes = num_class
    set_seed(config)

    if config.aug_metric == 'base':
        trainer = ClfTrainer(config, loaders)
    elif config.aug_metric == 'sim':
        trainer = SimTrainer(config, loaders)

    if config.task == 'baseline':
        trainer.run_base()
    elif config.task == 'semi':
        trainer.run()

if __name__ == '__main__':
    main()


import shutil
import time

import pygame

from .. import logger
from .info import Info
from .preview import Preview
from .timeline import Timeline
from .utils import *
from .video import Video

pygame.init()

def view_video(path: str) -> None:
    logger.warn("Viewer is not complete yet.")

    video = Video(path)
    timeline = Timeline(video)
    info = Info(video, timeline)
    preview = Preview(video, timeline)

    logger.info(f"Extracting frames to {video.tmpdir}")

    resized = False  # Redraw if resized
    display = pygame.display.set_mode((1280, 720), pygame.RESIZABLE)
    pygame.display.set_caption("PianoRay Viewer")

    try:
        run = True
        while run:
            time.sleep(1/15)
            resized = False

            pygame.display.update()
            events = pygame.event.get()
            for event in events:
                if event.type == pygame.QUIT:
                    run = False

                elif event.type == pygame.VIDEORESIZE:
                    resized = True

                elif event.type == pygame.KEYDOWN:
                    if event.key in (pygame.K_RIGHT, pygame.K_l):
                        timeline.next_frame()
                    elif event.key in (pygame.K_LEFT, pygame.K_h):
                        timeline.prev_frame()

            width, height = display.get_size()
            v_split = int(height * 0.9)
            h_split = int(width * 0.8)

            display.fill(BLACK)
            timeline.draw(display, events, (0, v_split, width, height-v_split))
            info.draw(display, events, (h_split, 0, width-h_split, v_split))
            preview.draw(display, events, (0, 0, h_split, v_split))
            pygame.draw.line(display, WHITE, (0, v_split), (width, v_split))
            pygame.draw.line(display, WHITE, (h_split, 0), (h_split, v_split))

    finally:
        video.run = False
        time.sleep(0.05)  # Wait for thread to stop

        pygame.quit()
        shutil.rmtree(video.tmpdir)


from math import *
import ERRCODE
from G_Function import G_Function, fgl
import common as comm
import numpy as np
import logging

def ipf():

    th1 = th2 = ph = 0.0
    gmr = gmt = 0.0

    rfile = ["", "../data/gmr_uni.txt", "../data/gmr_plano.txt", "../data/gmr_erect.txt"]
    tfile = ["", "../data/gmt_uni.txt", "../data/gmt_plano.txt", "../data/gmt_erect.txt"]

    # leaf angle distribution
    # mc = 1
    # mb = 1
    # mf = 1
    # op = 1  kernel calculation, else read from txt file
    op = 2

    # generate by itself
    if (op == 1):
        for i in range(1, 19):
            # logging.debug("i = ", i)
            th1 = radians(float(i - 1) * 10.0)

            for j in range(1, 19):
                # logging.debug("j = ", j)
                th2 = radians(float(j - 1) * 10.0)

                for k in range(1, 37):
                    # logging.debug("k = ", k)
                    ph = radians(float(k - 1) * 10.0)

                    # canopy
                    gmkernel(gmr, gmt, th1, th2, ph, comm.M_C)
                    comm.G_MRC[i, j, k] = gmr
                    comm.G_MTC[i, j, k] = gmt

                    # branch
                    gmkernel(gmr, gmt, th1, th2, ph, comm.M_B)
                    comm.G_MRB[i, j, k] = gmr
                    comm.G_MTB[i, j, k] = gmt

                    # forest floor
                    gmkernel(gmr, gmt, th1, th2, ph, comm.M_F)
                    comm.G_MRF[i, j, k] = gmr
                    comm.G_MTF[i, j, k] = gmt

        # for reflection
        # write rfiles
        f = open(rfile[0], "w")
        f.write(comm.G_MRC)
        f.close()

        f = open(rfile[1], "w")
        f.write(comm.G_MRB)
        f.close()

        f = open(rfile[2], "w")
        f.write(comm.G_MRF)
        f.close()

        # for transmission
        # write tfiles
        f = open(tfile[0], "w")
        f.write(comm.G_MTC)
        f.close()

        f = open(tfile[1], "w")
        f.write(comm.G_MTB)
        f.close()

        f = open(tfile[2], "w")
        f.write(comm.G_MTF)
        f.close()
    # read from files
    else:
        # for reflection
        contentFile = np.loadtxt(rfile[comm.M_C])
        comm.G_MRC = transferToMatrix(contentFile)

        contentFile = np.loadtxt(rfile[comm.M_B])
        comm.G_MRB = transferToMatrix(contentFile)

        contentFile = np.loadtxt(rfile[comm.M_F])
        comm.G_MRF = transferToMatrix(contentFile)

        # for transmission
        contentFile = np.loadtxt(tfile[comm.M_C])
        comm.G_MTC = transferToMatrix(contentFile)

        contentFile = np.loadtxt(tfile[comm.M_B])
        comm.G_MTB = transferToMatrix(contentFile)

        contentFile = np.loadtxt(tfile[comm.M_F])
        comm.G_MTF = transferToMatrix(contentFile)

    return ERRCODE.SUCCESS

# Mathmatics is summarized in
# Shultis and Myneni (1988)
# J. Q. Spec. Radi. Trans., 39(2), p. 115-129
def gmkernel(gmr, gmt, th1, th2, ph, m):

    gmr = 0.0
    gmt = 0.0
    phl = 0.0   # phl is radian

    gFunction = G_Function()

    gmrp = [0.0] * 362
    gmtp = [0.0] * 362
    gmrt = [0.0] * 182
    gmtt = [0.0] * 182

    for i in range(1, 361):
        phl = radians(float(i) - 1.0)

        for j in range(1, 91):
            thl1 = radians(float(j) - 1.0)
            af1 = faf(th1, thl1, phl)
            af2 = faf(th2, thl1, abs(phl - ph))
            cosf = cos(af1) * cos(af2)

            if (cosf < 0.0):
                gmrt[j] = abs(cosf)
                gmtt[j] = 0.0
            else:
                gmrt[j] = 0.0
                gmtt[j] = cosf

        # integration over theta
        for j in range(1, 90):
            thl1 = radians(float(j) - 1)
            gl1 = fgl(thl1, m) / sin(max(thl1, 1.0e-8))
            thl2 = thl1 + pi / 180
            gl2 = fgl(thl2, m) / sin(max(thl2, 1.0e-8))

            gmrp[i] += (gl2 * gmrt[j + 1] * sin(thl2) + gl1 * gmrt[j] * sin(thl1)) * pi / (2.0 * 2.0 * 90.0)
            gmtp[i] += (gl2 * gmtt[j + 1] * sin(thl2) + gl1 * gmtt[j] * sin(thl1)) * pi / (2.0 * 2.0 * 90.0)

    for i in range(1, 360):
        gmr += (gmrp[i + 1] + gmrp[i]) * 2.0 * pi / (2.0 * 360.0)
        gmr += (gmtp[i + 1] + gmtp[i]) * 2.0 * pi / (2.0 * 360.0)

    gmr /= (2.0 * pi)
    gmt /= (2.0 * pi)

    return ERRCODE.SUCCESS

# calculation of alpha
def faf(th1, th2, ph):

    data = sin(th1) * cos(th2) + sin(th1) * sin(th2) * cos(ph)
    data = copysign(min(abs(data), 1.0 - 1.0e-10), data)
    data = acos(data)

    return data

def transferToMatrix(origin):

    destin = np.zeros(20 * 20 * 38, dtype=float).reshape(20, 20, 38)
    for i in range(0, 19):
        for j in range(0, 19):
            for k in range(0, 37):
                destin[i + 1][j + 1][k + 1] = origin[i * 19 + j][k]

    return destin


import torch
import torch.nn as nn
from src.models_config import get_model_config

# some complex blocks from https://github.com/litcoderr/ComplexCNN

class ComplexConv2d(nn.Module):
    def __init__(self, in_channel, out_channel, kernel_size, stride=1, padding=0, **kwargs):
        super().__init__()

        self.conv_re = nn.Conv2d(in_channel,
                                 out_channel,
                                 kernel_size,
                                 stride=stride,
                                 padding=padding,
                                 **kwargs)
        self.conv_im = nn.Conv2d(in_channel,
                                 out_channel,
                                 kernel_size,
                                 stride=stride,
                                 padding=padding,
                                 **kwargs)

    def forward(self, x):
        real = self.conv_re(x[..., 0]) - self.conv_im(x[..., 1])
        imaginary = self.conv_re(x[..., 1]) + self.conv_im(x[..., 0])
        return torch.stack((real, imaginary), dim=-1)

class ComplexConvTranspose2d(nn.Module):
    def __init__(self, in_channel, out_channel, kernel_size, stride=1,
                 padding=0, **kwargs):
        super().__init__()

        self.tconv_re = nn.ConvTranspose2d(in_channel, out_channel,
                                           kernel_size=kernel_size,
                                           stride=stride,
                                           padding=padding,
                                           **kwargs)
        self.tconv_im = nn.ConvTranspose2d(in_channel, out_channel,
                                           kernel_size=kernel_size,
                                           stride=stride,
                                           padding=padding,
                                           **kwargs)

    def forward(self, x):
        real = self.tconv_re(x[..., 0]) - self.tconv_im(x[..., 1])
        imaginary = self.tconv_re(x[..., 1]) + self.tconv_im(x[..., 0])
        return torch.stack((real, imaginary), dim=-1)

class ComplexBatchNorm2d(nn.Module):
    def __init__(self, num_features, **kwargs):
        super().__init__()
        self.bn_re = nn.BatchNorm2d(num_features=num_features, **kwargs)
        self.bn_im = nn.BatchNorm2d(num_features=num_features, **kwargs)

    def forward(self, x):
        real = self.bn_re(x[..., 0])
        imag = self.bn_im(x[..., 1])
        output = torch.stack((real, imag), dim=-1)
        return output

class Encoder(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size, stride, padding=None, padding_mode="zeros"):
        super().__init__()
        if padding is None:
            padding = [(i - 1) // 2 for i in kernel_size]

        self.conv = ComplexConv2d(in_channels, out_channels,
                                  kernel_size=kernel_size, stride=stride,
                                  padding=padding,
                                  padding_mode=padding_mode)
        self.bn = ComplexBatchNorm2d(out_channels)
        self.relu = nn.LeakyReLU(inplace=True)

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

class Decoder(nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size, stride, padding=(0, 0)):
        super().__init__()

        self.transconv = ComplexConvTranspose2d(in_channels, out_channels,
                                                kernel_size=kernel_size,
                                                stride=stride, padding=padding)
        self.bn = ComplexBatchNorm2d(out_channels)
        self.relu = nn.LeakyReLU(inplace=True)

    def forward(self, x):
        x = self.transconv(x)
        x = self.bn(x)
        return self.relu(x)

class UNet(nn.Module):
    def __init__(self,
                 model_features=32,
                 encoder_depth=5,
                 padding_mode="zeros"):
        super().__init__()

        model_config = get_model_config(model_features=model_features,
                                        encoder_depth=encoder_depth)
        self.encoder_depth = encoder_depth
        self.encoder_list, self.decoder_list = [], []
        self.encoder_config = model_config['encoder']
        self.decoder_config = model_config['decoder']

        for i in range(encoder_depth):
            encoder_prop = self.encoder_config[f'encoder_{i}']

            encoder = Encoder(in_channels=encoder_prop.in_channels,
                              out_channels=encoder_prop.out_channels,
                              kernel_size=encoder_prop.kernel_size,
                              stride=encoder_prop.stride,
                              padding_mode=padding_mode)
            self.encoder_list.append(encoder)

        decoder_depth = encoder_depth
        for i in range(decoder_depth - 1):
            decoder_prop = self.decoder_config[f'decoder_{i}']

            decoder = Decoder(in_channels=decoder_prop.in_channels,
                              out_channels=decoder_prop.out_channels,
                              kernel_size=decoder_prop.kernel_size,
                              stride=decoder_prop.stride,
                              padding=decoder_prop.padding)
            self.decoder_list.append(decoder)

        decoder_last = self.decoder_config[f'decoder_{decoder_depth - 1}']
        self.last_decoder = ComplexConvTranspose2d(in_channel=decoder_last.in_channels,
                                                   out_channel=decoder_last.out_channels,
                                                   kernel_size=decoder_last.kernel_size,
                                                   stride=decoder_last.stride,
                                                   padding=decoder_last.padding)
        self.decoder_list = nn.ModuleList(self.decoder_list)
        self.encoder_list = nn.ModuleList(self.encoder_list)

    def forward(self, x):
        encoder_out_list = []
        for ind, encoder in enumerate(self.encoder_list):
            x = encoder(x)
            encoder_out_list.append(x)
        encoded_x = x
        for ind, decoder in enumerate(self.decoder_list):
            encoded_x = decoder(encoded_x)
            encoded_x = torch.cat([encoded_x, encoder_out_list[- ind - 2]], dim=1)

        return self.last_decoder(encoded_x)


import os

from lino.projects.std.settings import *
import lino_patrols
from lino_patrols import SETUP_INFO as setup_info

class Site(Site):

    version = setup_info['version']
    url = setup_info['url'] # "http://code.google.com/p/lino-welfare/"
    verbose_name = "Lino Patrols"

    demo_fixtures = 'std demo demo2'.split()

    auto_configure_logger_names = 'atelier lino lino_patrols'

    userdocs_prefix = 'patrols.'

    #~ project_model = 'contacts.Person'
    #~ project_model = 'pcsw.Client'

    #~ accounts_ref_length = 5

    #~ languages = ('de', 'fr', 'nl', 'en')
    languages = "de fr en"

    #~ index_view_action = "pcsw.Home"

    def setup_quicklinks(self, user, tb):
        tb.add_action('patrols.Patrols')
        self.on_each_app('setup_quicklinks', user, tb)

    def get_installed_apps(self):
        yield super(Site, self).get_installed_apps()

        yield 'lino.modlib.gfks'
        yield 'lino.modlib.users'
        yield 'lino.modlib.changes'
        yield 'lino_xl.lib.countries'
        yield 'lino_xl.lib.contacts'

        yield 'lino_patrols.patrols'

#~ SITE = Site(globals())

#~ LOGGING['logger_names'] = 'djangosite lino lino_patrols'
#~ LOGGING.update(loggers='djangosite lino lino_welfare')
#~ print 20130409, __file__, LOGGING

#~ TIME_ZONE = 'Europe/Brussels'
#~ TIME_ZONE = None
#~ print 20130613, __file__