from math import floor, gcd, isqrt, log2, sqrt

def gauss_sum(n: int) -> int:
    """ Calculates the sum of the first n natural numbers, based on the formula:

    {n}Sigma{k=1} k = n * (n + 1) / 2

    Conversion of very large floats to integers in this formula can lead to large
    rounding losses, so division by 2 & int cast is replaced with a single bitwise
    right shift, as n >> 1 = n / 2^1.
    """

    return n * (n + 1) >> 1

def is_coprime(x: int, y: int) -> bool:
    """
    Two integers are co-prime (relatively/mutually prime) if the only positive
    integer that is a divisor of both of them is 1.
    """

    return gcd(x, y) == 1

def is_hexagonal_number(h_n: int) -> int | None:
    """
    Derivation solution is based on the formula:

    n(2n - 1) = h_n, in quadratic form becomes:

    0 = 2n^2 - n - h_n, with a, b, c = 2, -1, -h_n

    putting these values in the quadratic formula becomes:

    n = (1 +/- sqrt(1 + 8h_n)) / 4

    so the inverse function, positive solution becomes:

    n = (1 + sqrt(1 + 8h_n)) / 4

    :returns: h_n's corresponding term if hexagonal, or None.
    """

    n = 0.25 * (1 + sqrt(1 + 8 * h_n))
    return int(n) if n == floor(n) else None

def is_pentagonal_number(p_n: int) -> int | None:
    """
    Derivation solution is based on the formula:

    n(3n - 1) / 2 = p_n, in quadratic form becomes:

    0 = 3n^2 - n - 2p_n, with a, b, c = 3, -1, -2p_n

    putting these values in the quadratic formula becomes:

    n = (1 +/- sqrt(1 + 24p_n)) / 6

    so the inverse function, positive solution becomes:

    n = (1 + sqrt(1 + 24p_n)) / 6

    :returns: p_n's corresponding term if pentagonal, or None.
    """

    n = (1 + sqrt(1 + 24 * p_n)) / 6
    return int(n) if n == floor(n) else None

def is_prime(n: int) -> bool:
    """ Checks if n is prime.

    This version will be used preferentially, unless the argument is expected to
    frequently exceed 1e5.

    SPEED (WORSE for N > 1e15)
        1.86s for a 15-digit prime
    SPEED (WORSE for N > 1e10)
        5.01ms for a 10-digit prime
    SPEED (WORSE for N > 1e5)
        6.6e4ns for a 6-digit prime
    SPEED (BETTER for N < 1e5)
        1.7e4ns for a 5-digit prime
    SPEED (BETTER for N < 1e3)
        7700ns for a 3-digit prime
    """

    if n < 2:
        return False
    elif n < 4:  # 2 and 3 are primes
        return True
    elif not n % 2:  # 2 is the only even prime
        return False
    elif n < 9:  # 4, 6, and 8 already excluded
        return True
    elif not n % 3:
        # primes > 3 are of the form 6k(+/-1)
        # i.e. they are never multiples of 3
        return False
    else:
        # n can only have 1 prime factor > sqrt(n): n itself!
        max_p = isqrt(n)
        step = 5  # as multiples of prime 5 not yet assessed
        # 11, 13, 17, 19, and 23 will all bypass this loop
        while step <= max_p:
            if not n % step or not n % (step + 2):
                return False
            step += 6
        return True

def is_prime_mr(num: int, k_rounds: list[int] | None = None) -> bool:
    """ Miller-Rabin probabilistic algorithm determines if a large number is
    likely to be prime.

    This version will only be used if the argument is expected to frequently
    exceed 1e5.

    -   The number received, once determined to be odd, is expressed as
        n = (2^r)s + 1, with s being odd.
    -   A random integer, a, is chosen k times (higher k means higher accuracy),
        with 0 < a < num.
    -   Calculate a^s % n. If this equals 1 or this plus 1 equals n while s has
        the powers of 2 previously factored out returned, then n passes as a
        strong probable prime.
    -   n should pass for all generated a.

    The algorithm's complexity is O(k*log^3*n). This algorithm uses a list of
    the first 5 primes instead of randomly generated a, as this has been proven
    valid for numbers up to 2.1e12. Providing a list of the first 7 primes gives
    test validity for numbers up to 3.4e14.

    SPEED (BETTER for N > 1e15)
        1.5e5ns for a 15-digit prime
    SPEED (BETTER for N > 1e10)
        7.6e4ns for a 10-digit prime
    SPEED (BETTER for N > 1e5)
        5.6e4ns for a 6-digit prime
    SPEED (WORSE for N < 1e5)
        4.2e4ns for a 5-digit prime
    SPEED (WORSE for N < 1e3)
        3.9e4ns for a 3-digit prime
    """

    if k_rounds is None:
        k_rounds = [2, 3, 5, 7, 11]
    if 2 <= num <= 3:
        return True
    if num < 2 or num % 2 == 0:
        return False

    def miller_rabin(a: int, s: int, r: int, n: int) -> bool:
        # calculate a^s % n
        x = pow(a, s, n)
        if x == 1 or x == n - 1:
            return True
        for _ in range(r):
            x = pow(x, 2, n)
            if x == 1:
                return False
            if x == n - 1:
                return True
        return False

    # write num as 2^r * s + 1 by first getting r, the largest power of 2
    # that divides (num - 1), by getting the index of the right-most one bit
    n_r = int(log2((num - 1) & -(num - 1)))
    # x * 2^y == x << y
    n_s = (num - 1) // (2 << (n_r - 1))
    for k in k_rounds:
        if k > num - 2:
            break
        if not miller_rabin(k, n_s, n_r, num):
            return False
    return True

def is_triangular_number(t_n: int) -> int | None:
    """
    Derivation solution is based on the formula:

    n(n + 1) / 2 = t_n, in quadratic form becomes:

    0 = n^2 + n - 2t_n, with a, b, c = 1, 1, -2t_n

    putting these values in the quadratic formula becomes:

    n = (-1 +/- sqrt(1 + 8t_n)) / 2

    so the inverse function, positive solution becomes:

    n = (sqrt(1 + 8t_n) - 1) / 2

    :returns: t_n's corresponding term if triangular, or None.
    """

    n = 0.5 * (sqrt(1 + 8 * t_n) - 1)
    return int(n) if n == floor(n) else None

def power_digit_sum(base: int, exponent: int) -> int:
    """ Calculates the sum of the digits of the number, base^exponent. """

    return sum(map(int, str(pow(base, exponent))))

def prime_factors_og(n: int) -> dict[int, int]:
    """ Prime decomposition repeatedly divides out all prime factors using an
    optimised Direct Search Factorisation algorithm.

    Every prime number after 2 will be odd and there can be at most 1 prime factor
    greater than sqrt(n), which would be n itself if n is a prime. This is based
    on all cofactors having been already tested following the formula:

    n / floor(sqrt(n) + 1) < sqrt(n)

    e.g. N = 12 returns {2=2, 3=1} -> 2^2 * 3^1 = 12

    SPEED (WORSE for N with large factors)
        55.88s for N = 600_851_475_143
    SPEED (WORSE for N with small factors)
        74.70ms for N = 1e12

    :returns: Dict of prime factors (keys) and their exponents (values).
    :raises ValueError: If argument is not greater than 1.
    """

    if n <= 1:
        raise ValueError("Must provide a natural number greater than 1")
    primes = dict()
    factors = [2]
    factors.extend(range(3, isqrt(n) + 1, 2))
    for factor in factors:
        while n % factor == 0:
            if factor in primes:
                primes[factor] += 1
            else:
                primes[factor] = 1
            n //= factor
    if n > 2:
        primes[n] = primes[n] + 1 if n in primes else 1
    return primes

def prime_factors(n: int) -> dict[int, int]:
    """ Prime decomposition repeatedly divides out all prime factors using a
    Direct Search Factorisation algorithm without any optimisation.

    e.g. N = 12 returns {2=2, 3=1} -> 2^2 * 3^1 = 12

    This version will be used in future solutions.

    SPEED (BETTER for N with large factors)
        2.9e+05ns for N = 600_851_475_143
    SPEED (BETTER for N with small factors)
        8590ns for N = 1e12

    :returns: Dict of prime factors (keys) and their exponents (values).
    :raises ValueError: If argument is not greater than 1.
    """

    if n <= 1:
        raise ValueError("Must provide a natural number greater than 1")
    primes = dict()
    factor = 2
    while factor * factor <= n:
        while n % factor == 0 and n != factor:
            if factor in primes:
                primes[factor] += 1
            else:
                primes[factor] = 1
            n //= factor
        factor += 1
    if n > 1:
        primes[n] = primes[n] + 1 if n in primes else 1
    return primes

def prime_numbers_og(n: int) -> list[int]:
    """
    Sieve of Eratosthenes algorithm outputs all prime numbers less than or equal
    to the upper bound provided.

    SPEED (WORSE)
        23.04ms for N = 1e5
    """

    # create mask representing [2, max], with all even numbers except 2 (index 0)
    # marked false
    boolean_mask = [not (i != 0 and i % 2 == 0) for i in range(n - 1)]
    for p in range(3, isqrt(n) + 1, 2):
        if boolean_mask[p - 2]:
            if p * p > n:
                break
            # mark all multiples (composites of the divisors) that are >= p squared
            # as false
            for m in range(p * p, n + 1, 2 * p):
                boolean_mask[m - 2] = False
    primes = []
    for i, isPrime in enumerate(boolean_mask):
        if isPrime:
            primes.append(i + 2)
    return primes

def prime_numbers(n: int) -> list[int]:
    """
    Still uses Sieve of Eratosthenes method to output all prime numbers less than
    or equal to the upper bound provided, but cuts processing time in half by only
    allocating mask memory to odd numbers and by only looping through multiples of
    odd numbers.

    This version will be used in future solutions.

    SPEED (BETTER)
        14.99ms for N = 1e5
    """

    if n < 2:
        return []
    odd_sieve = (n - 1) // 2
    upper_limit = isqrt(n) // 2
    # create mask representing [2, 3..n step 2]
    boolean_mask = [True] * (odd_sieve + 1)
    # boolean_mask[0] corresponds to prime 2 & is skipped
    for i in range(1, upper_limit + 1):
        if boolean_mask[i]:
            # j = next index at which multiple of odd prime exists
            j = i * 2 * (i + 1)
            while j <= odd_sieve:
                boolean_mask[j] = False
                j += 2 * i + 1
    primes = []
    for i, isPrime in enumerate(boolean_mask):
        if i == 0:
            primes.append(2)
            continue
        if isPrime:
            primes.append(2 * i + 1)
    return primes

def pythagorean_triplet(m: int, n: int, d: int) -> tuple[int, int, int]:
    """
    Euclid's formula generates all Pythagorean triplets from 2 numbers, m and n.

    All triplets originate from a primitive one by multiplying them by
    d = gcd(a, b, c).

    :raises ValueError: If arguments do not follow m > n > 0, or if not exactly
        one is even, or if they are not co-prime, i.e. gcd(m, n) != 1.
    """

    if n < 1 or m < n:
        raise ValueError("Positive integers assumed to be m > n > 0")
    if not ((m % 2 == 0) ^ (n % 2 == 0)):
        raise ValueError("Integers must be opposite parity")
    if not is_coprime(m, n):
        raise ValueError("Positive integers must be co-prime")
    a = (m * m - n * n) * d
    b = 2 * m * n * d
    c = (m * m + n * n) * d
    return min(a, b), max(a, b), c

def sum_proper_divisors_og(n: int) -> int:
    """ Calculates the sum of all divisors of n, not inclusive of n.

    Solution optimised based on the following:

    -   N == 1 has no proper divisor but 1 is a proper divisor of all other naturals.

    -   A perfect square would duplicate divisors if included in the loop range.

    -   Loop range differs for odd numbers as they cannot have even divisors.

    SPEED (WORSE)
        8.8e4ns for N = 1e6 - 1
    """

    if n < 2:
        return 0
    total = 1
    max_divisor = isqrt(n)
    if max_divisor * max_divisor == n:
        total += max_divisor
        max_divisor -= 1
    divisor_range = range(3, max_divisor + 1, 2) if n % 2 != 0 \
        else range(2, max_divisor + 1)
    for d in divisor_range:
        if n % d == 0:
            total += d + n // d
    return total

def sum_proper_divisors(num: int) -> int:
    """ Calculates the sum of all divisors of num, not inclusive of num.

    Solution above is further optimised by using prime factorisation to
    out-perform the original method.

    This version will be used in future solutions.

    SPEED (BETTER)
        1.5e4ns for N = 1e6 - 1
    """

    if num < 2:
        return 0
    n = num
    total = 1
    p = 2
    while p * p <= num and n > 1:
        if n % p == 0:
            j = p * p
            n //= p
            while n % p == 0:
                j *= p
                n //= p
            total *= (j - 1)
            total //= (p - 1)
        if p == 2:
            p += 1
        else:
            p += 2
    if n > 1:
        total *= (n + 1)
    return total - num


import csv
import numpy as np
import os
import pydicom
from segmentation_models.backbones import get_preprocessing
import tensorflow as tf

from pneumothorax_segmentation.constants import image_size, folder_path
from pneumothorax_segmentation.data_augment import apply_random_data_augment
from pneumothorax_segmentation.params import tf_image_size

# Documentation for reading dicom files at https://pydicom.github.io/pydicom/stable/viewing_images.html#using-pydicom-with-matplotlib

preprocess_input = get_preprocessing("resnet34")

def get_all_images_list(folder):
    "Load all images filenames in folder. Returns a list of (filepath, filename)"
    all_images_in_folder = []

    for dirName, _, fileList in os.walk(folder_path + "/data/dicom-images-%s" % folder):
        for filename in fileList:
            if ".dcm" in filename.lower():
                all_images_in_folder.append((os.path.join(dirName,filename), filename.replace(".dcm", "")))

    return all_images_in_folder

def get_dicom_data(file_path):
    "Return the dicom raw data of a given file"
    return pydicom.dcmread(file_path)

cached_csv = []
def get_raw_masks(name):
    """
        Returns a list of the masks as they appear in train-rle.csv. Masks '-1' are filtered out\n
        Note side-effect: loads the csv on the first run and caches it
    """
    global cached_csv

    # The csv data is stored in a cache. This way, the csv is read only once
    if (len(cached_csv) == 0):
        with open(folder_path + '/data/train-rle.csv') as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')
            for row in csv_reader:
                cached_csv.append(row)

    # Retrieve masks as they are in the csv
    raw_masks = []
    for row in cached_csv:
        if row[0] == name:
            raw_masks.append(row[1])

    # Remove the -1 from images with no mask
    if (raw_masks[0] == " -1"):
        raw_masks = []

    return raw_masks

def get_image_label(name):
    "Returns 1 if there is a pneumothorax, 0 otherwise. Based on data in train-rle.csv"
    raw_masks = get_raw_masks(name)
    if len(raw_masks) == 0:
        return 0
    return 1

def get_true_mask(name):
    "Takes the name of the image as input and returns the mask mapping as a numpy matrix of shape (image_size, image_size) and values 0-1"

    raw_masks = get_raw_masks(name)

    # Format the masks to an exploitable format
    masks = []
    for raw_mask in raw_masks:
        mask = raw_mask.split(" ")
        mask = mask[1:] # raw_mask starts with a space
        mask = [int(m) for m in mask]
        masks.append(mask)

    # Use the masks to create the actual mapping of image_size * image_size
    mask_mapping = np.zeros(image_size ** 2, dtype=np.int)
    for mask in masks:
        is_it_a_mask = False
        current_pixel = 0
        for pixel_long_movement in mask:
            if is_it_a_mask:
                for i in range(pixel_long_movement):
                    mask_mapping[current_pixel + i] = 1
            current_pixel += pixel_long_movement
            is_it_a_mask = not is_it_a_mask
    mask_mapping = np.reshape(mask_mapping, (image_size, image_size))
    mask_mapping = np.transpose(mask_mapping, (1, 0))

    return mask_mapping

def format_pixel_array_for_tf(pixel_array, apply_data_augment_technique=None):
    """
        Inputs pixel_array as they are stroed in the dicom file. Outputs a tensor ready to go through the models\n
        apply_data_augment_technique can be used to apply data augmentation. See apply_random_data_augment for values
    """
    image = tf.convert_to_tensor(pixel_array, dtype=tf.float32)
    image = tf.reshape(image, (1, image_size, image_size, 1))
    if (apply_data_augment_technique != None):
        image = apply_random_data_augment(image, apply_data_augment_technique)
    # tf.image.resize behaves weirdly with the default method when reducing size. AREA method makes more sense in our case, thought the default bilinear method makes more sense when making an image bigger
    image = tf.image.resize(image, (tf_image_size, tf_image_size), align_corners=True, method=tf.image.ResizeMethod.AREA)
    image = tf.image.grayscale_to_rgb(image)
    image = preprocess_input(image)
    return image


from sys import stdin
def minimum_swaps(arr,n):
    grafo = {}
    solucion = [i+1 for i in range(n)]
    ans = 0
    i = 0
    while solucion != arr:
        #print(solucion,arr)
        #Si no es necesario acomodar el elemento en su lugar
        if arr[i] != solucion[i]:

            aux = arr[i] #4
            arr[i] = arr[aux-1]
            arr[aux-1]=aux
            ans += 1
        else:
            i+=1
    return ans

def main():
    n = int(stdin.readline().strip())
    array = [int(_) for _ in stdin.readline().strip().split()]
    print(minimum_swaps(array,n))

main()


import numpy as np
import matplotlib.pyplot as plt
import os
import torch
import torchvision
import numpy as np
from torchvision import transforms
from sklearn.metrics import precision_recall_curve, average_precision_score, auc, roc_auc_score, roc_curve
import matplotlib.pyplot as plt
from config import *
import random

maha_dists = np.load('maha_dists.npy',allow_pickle=True)
input_data = np.load('/network/tmp1/bhattdha/detectron2_kitti/embeddings_storage/final_data.npy', allow_pickle=True)[()]
input_data_OOD = np.load('/network/tmp1/bhattdha/detectron2_kitti/embeddings_storage/final_data_OOD.npy', allow_pickle=True)[()]

## the dataset
X_org = input_data['features']
y_org = input_data['labels']
# X_ood = input_data_OOD['features']
# y_ood = input_data_OOD['labels']

# y_ood[y_ood == 6] = 5
# y_ood[y_ood == 7] = 5
# ood_class = [5, 6, 7]
X =  X_org
y =  y_org
## total reprodicibility
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)

X_ood = input_data_OOD['features']
y_ood = input_data_OOD['labels']
val_data_all_classes = {}

means = {}
covars = {}

# train_fraction = 0.7
num_classes = max(y)+1

class_labels = np.arange(num_classes)
# class_labels = np.random.permutation(num_classes)
# class_labels = np.random.permutation(class_labels)

for class_label in class_labels:
	print('Training Class# {}'.format(class_label))

	indices = np.where(y==class_label)[0]
	# indices = np.random.permutation(indices)
	data = X[indices,:]
	# class_label_fake = (class_label + 5)%len(class_labels)
	# indices_fake = np.where(y==class_label_fake)[0]
	# val_other_class_data = X[indices_fake,:]
	# data = np.random.permutation(data)

	train_data_samples = int(len(data)*train_fraction)
	val_data_samples = int(len(data) - train_data_samples)

	train_data = 1e2*data[:train_data_samples,:]
	val_data = 1e2*data[train_data_samples:, :]

	# data = {'train_data': train_data, 'val_data': val_data}

	val_data_all_classes[str(class_label)] = val_data

	mean = np.mean(train_data, axis = 0)
	cov = np.cov(train_data.T)
	means[str(class_label)] = mean
	## may be wrong!
	covars[str(class_label)] = np.linalg.inv(cov + 1e-10*np.identity(1024))

maha_class = maha_dists[:,5].astype(int)
maha_true_dist = []
maha_false_dist = []

# for ind, m in enumerate(maha_dists):
# 	maha_true_dist.append(m[maha_class[ind]])
# 	m[maha_class[ind]] = np.inf
# 	m[5] = np.inf
# 	maha_false_dist.append(m.min())

## loading the results
# maha_true_dist = np.array(maha_true_dist)
# maha_false_dist = np.array(maha_false_dist)
# input_data_OOD = np.load('/network/tmp1/bhattdha/detectron2_kitti/embeddings_storage/final_data_OOD.npy', allow_pickle=True)[()]
# X_ood = input_data_OOD['features']
# y_ood = input_data_OOD['labels']

acc_threshs = [60.0, 70.0, 80.0, 85.0, 90.0, 95.0]
ood_stats = {}
for acc_thresh in acc_threshs:
	print("For accuracy: ", acc_thresh)
	mahathresh = {}
	class_dist = {}
	for i in range(num_classes):
		class_dist[i] = maha_dists[maha_dists[:,5]==i][:,i]
		class_dist[i].sort()
		class_dist[i] = class_dist[i][::-1]
		index = int(len(class_dist[i]) - len(class_dist[i])*acc_thresh/100.0)
		mahathresh[i] = class_dist[i][index]

	# mahathresh = {0: 3093.944707607109, 1: 5710.413855647991, 2: 28235.425795092746, 3: 79163.39452332728, 4: 2313.9860080440644}
	tp = 0
	fp = 0

	for x in X_ood:
		data_point = 1e2*x
		flag = True
		mds = [] ## has mahalanobis distances
		for mean_label in means.keys():
			diff = (data_point - means[mean_label]).reshape(len(data_point), 1)

			mahalanobis_distance = np.dot(diff.T, np.dot(covars[mean_label], diff))[0][0]

			# maha_all.append(mahalanobis_distance)
			mds.append(mahalanobis_distance)

		for i in mahathresh.keys():

			if mahathresh[i] > mds[i]:
				fp += 1
				flag = False
				break
			else:
				continue

		if flag:
			tp += 1

	ood_stats[acc_thresh] = {'tp':tp, 'fp':fp, 'accuracy': tp/(tp+fp)}

import ipdb; ipdb.set_trace()

colors = ['C'+str(i+1) for i in range(5)]

for i in range(4):
	plt.plot(class_dist[i], '-o', alpha=0.7, color=colors[i], label="class maha dists"+str(i).zfill(5))
	# plt.plot(maha_false_dist, '-o', alpha=0.7, color=colors[1], label="maha_false_dist")

# [1e3, 1e4,  1e3]
plt.legend()
plt.legend(loc='upper right')
plt.xlabel('datapoint ->')
plt.ylabel('mahalanobis distance -> ')
plt.title('Mahalanobis distance plot')
plt.savefig('maha_dists.png')

import ipdb; ipdb.set_trace()


#!/usr/bin/env python
# encoding: utf-8
# @Time : 2019-07-31 10:24

__author__ = 'Ted'

from PIL import Image, ImageFont, ImageDraw

content={
    "back_img":"pre/paper.jpg",
    "001":{
        "ad":'老板，买10盒月饼呗',
        "head":'001.jpg'
    },
    "002": {
        "ad": '老板，买20盒月饼呗',
        "head": '002.jpg'
    },
    "003": {
        "ad": '老板，生活不易，买50盒月饼呗',
        "head": '003.jpg'
    },
    "004": {
        "ad": '老板，买个80盒月饼，不多',
        "head": '004.jpg'
    },
    "005": {
        "ad": '老板，看面相，你应该买100盒月饼',
        "head": '005.jpg'
    },
    "006": {
        "ad": '老板，恭喜你中奖了，奖品是150盒月饼',
        "head": '006.jpg'
    },
    "007": {
        "ad": '老板，你的员工让我告诉你，他们想吃月饼了',
        "head": '007.jpg'
    },
    "008": {
        "ad": '老板，我卖月饼，买200盒呗',
        "head": '008.jpg'
    },
    "009": {
        "ad": '老板，不整500盒月饼送礼啊',
        "head": '009.jpg'
    }
}
def get_pic(background,head,adcontent,mark,pic_name):
    im = Image.open(background)

    head_img = Image.open(f"head/{head}").resize((150,150),Image.ANTIALIAS)
    im.paste(head_img,(75,20))
    draw = ImageDraw.Draw(im)
    fnt = ImageFont.truetype("pre/SimSun.ttf",20)

    ad_parts = adcontent.split("，")
    y_pos = 180
    for ad_part in ad_parts:
        if ad_part!=ad_parts[-1]:
            ad_w,ad_h = draw.textsize(ad_part+"，", font=fnt)
            draw.text(((300-ad_w)/2,y_pos),ad_part+"，",font=fnt,fill=(0,0,0))
            y_pos+=ad_h+10
        else:
            ad_w, ad_h = draw.textsize(ad_part, font=fnt)
            draw.text(((300 - ad_w) / 2, y_pos), ad_part, font=fnt, fill=(0, 0, 0))
            y_pos += ad_h + 10

    mark_font = ImageFont.truetype("pre/arial.ttf",100)
    draw.text((125,400),mark,font=mark_font,fill=(0,0,0))

    haha = Image.open("pre/haha.jpg")
    im.paste(haha,(0,650))

    qrcode = Image.open("pre/tedxpy.jpg").resize((80,80),Image.ANTIALIAS)
    im.paste(qrcode,(180,810))
    sign_font = ImageFont.truetype("pre/SimSun.ttf",10)
    draw.text((60,875),"自定义制作图片，请扫码",font=sign_font,fill=(0,0,0))
    im.save(pic_name)

if __name__== "__main__":
    for i in range(1,10):
        background = "pre/paper.jpg"
        head = content[f'00{i}']['head']
        adcontent = content[f'00{i}']['ad']
        get_pic(background,head,adcontent,f"{i}",f"{i}.jpg")
    print("九宫格图片生成完毕！")


from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework import serializers
from rest_framework import generics
from rest_framework import viewsets
from rest_framework.decorators import detail_route, list_route
from rest_framework.views import APIView
from core.models import *
from django.forms import widgets
from django.conf.urls import patterns, url
from services.cord.models import VOLTTenant, VBNGTenant, CordSubscriberRoot
from core.xoslib.objects.cordsubscriber import CordSubscriber
from plus import PlusSerializerMixin, XOSViewSet
from django.shortcuts import get_object_or_404
from xos.apibase import XOSListCreateAPIView, XOSRetrieveUpdateDestroyAPIView, XOSPermissionDenied
from xos.exceptions import *
import json
import subprocess

if hasattr(serializers, "ReadOnlyField"):
    # rest_framework 3.x
    ReadOnlyField = serializers.ReadOnlyField
else:
    # rest_framework 2.x
    ReadOnlyField = serializers.Field

class CordSubscriberIdSerializer(serializers.ModelSerializer, PlusSerializerMixin):
        id = ReadOnlyField()
        service_specific_id = ReadOnlyField()
        vlan_id = ReadOnlyField()      # XXX remove this
        c_tag = ReadOnlyField()
        s_tag = ReadOnlyField()
        vcpe_id = ReadOnlyField()
        instance = ReadOnlyField()
        image = ReadOnlyField()
        vbng_id = ReadOnlyField()
        firewall_enable = serializers.BooleanField()
        firewall_rules = serializers.CharField()
        url_filter_enable = serializers.BooleanField()
        url_filter_rules = serializers.CharField()
        url_filter_level = serializers.CharField(required=False)
        cdn_enable = serializers.BooleanField()
        instance_name = ReadOnlyField()
        image_name = ReadOnlyField()
        routeable_subnet = serializers.CharField(required=False)
        ssh_command = ReadOnlyField()
        bbs_account = ReadOnlyField()

        wan_container_ip = ReadOnlyField()
        uplink_speed = serializers.CharField(required=False)
        downlink_speed = serializers.CharField(required=False)
        status = serializers.CharField()
        enable_uverse = serializers.BooleanField()

        lan_ip = ReadOnlyField()
        wan_ip = ReadOnlyField()
        nat_ip = ReadOnlyField()
        private_ip = ReadOnlyField()

        wan_mac = ReadOnlyField()

        vcpe_synced = serializers.BooleanField()

        humanReadableName = serializers.SerializerMethodField("getHumanReadableName")

        class Meta:
            model = CordSubscriber
            fields = ('humanReadableName', 'id',
                      'service_specific_id', 'vlan_id', 's_tag', 'c_tag',
                      'vcpe_id', 'instance', 'instance_name', 'image', 'image_name',
                      'firewall_enable', 'firewall_rules',
                      'url_filter_enable', 'url_filter_rules', 'url_filter_level',
                      'bbs_account',
                      'ssh_command',
                      'vcpe_synced',
                      'cdn_enable', 'vbng_id', 'routeable_subnet', 'nat_ip', 'lan_ip', 'wan_ip', 'private_ip', 'wan_mac',
                      'wan_container_ip',
                      'uplink_speed', 'downlink_speed', 'status', 'enable_uverse')

        def getHumanReadableName(self, obj):
            return obj.__unicode__()

#------------------------------------------------------------------------------
# The "old" API
# This is used by the xoslib-based GUI
#------------------------------------------------------------------------------

class CordSubscriberList(XOSListCreateAPIView):
    queryset = CordSubscriber.get_tenant_objects().select_related().all()
    serializer_class = CordSubscriberIdSerializer

    method_kind = "list"
    method_name = "cordsubscriber"

class CordSubscriberDetail(XOSRetrieveUpdateDestroyAPIView):
    queryset = CordSubscriber.get_tenant_objects().select_related().all()
    serializer_class = CordSubscriberIdSerializer

    method_kind = "detail"
    method_name = "cordsubscriber"

# We fake a user object by pulling the user data struct out of the
# subscriber object...

def serialize_user(subscriber, user):
    return {"id": "%d-%d" % (subscriber.id, user["id"]),
            "name": user["name"],
            "level": user.get("level",""),
            "mac": user.get("mac", ""),
            "subscriber": subscriber.id }

class CordUserList(APIView):
    method_kind = "list"
    method_name = "corduser"

    def get(self, request, format=None):
        instances=[]
        for subscriber in CordSubscriber.get_tenant_objects().all():
            for user in subscriber.users:
                instances.append( serialize_user(subscriber, user) )

        return Response(instances)

    def post(self, request, format=None):
        data = request.DATA
        subscriber = CordSubscriber.get_tenant_objects().get(id=int(data["subscriber"]))
        user = subscriber.create_user(name=data["name"],
                                    level=data["level"],
                                    mac=data["mac"])
        subscriber.save()

        return Response(serialize_user(subscriber,user))

class CordUserDetail(APIView):
    method_kind = "detail"
    method_name = "corduser"

    def get(self, request, format=None, pk=0):
        parts = pk.split("-")
        subscriber = CordSubscriber.get_tenant_objects().filter(id=parts[0])
        for user in subscriber.users:
            return Response( [ serialize_user(subscriber, user) ] )
        raise XOSNotFound("Failed to find user %s" % pk)

    def delete(self, request, pk):
        parts = pk.split("-")
        subscriber = CordSubscriber.get_tenant_objects().get(id=int(parts[0]))
        subscriber.delete_user(parts[1])
        subscriber.save()
        return Response("okay")

    def put(self, request, pk):
        kwargs={}
        if "name" in request.DATA:
             kwargs["name"] = request.DATA["name"]
        if "level" in request.DATA:
             kwargs["level"] = request.DATA["level"]
        if "mac" in request.DATA:
             kwargs["mac"] = request.DATA["mac"]

        parts = pk.split("-")
        subscriber = CordSubscriber.get_tenant_objects().get(id=int(parts[0]))
        user = subscriber.update_user(parts[1], **kwargs)
        subscriber.save()
        return Response(serialize_user(subscriber,user))

#------------------------------------------------------------------------------
# The "new" API with many more REST endpoints.
# This is for integration with with the subscriber GUI
#------------------------------------------------------------------------------

class CordSubscriberViewSet(XOSViewSet):
    base_name = "subscriber"
    method_name = "rs/subscriber"
    method_kind = "viewset"
    queryset = CordSubscriber.get_tenant_objects().select_related().all()
    serializer_class = CordSubscriberIdSerializer

    def get_vcpe(self):
        subscriber = self.get_object()
        if not subscriber.vcpe:
            raise XOSMissingField("vCPE object is not present for subscriber")
        return subscriber.vcpe

    @classmethod
    def get_urlpatterns(self):
        patterns = super(CordSubscriberViewSet, self).get_urlpatterns()
        patterns.append( self.detail_url("vcpe_synced/$", {"get": "get_vcpe_synced"}, "vcpe_synced") )
        patterns.append( self.detail_url("url_filter/$", {"get": "get_url_filter"}, "url_filter") )
        patterns.append( self.detail_url("url_filter/(?P<level>[a-zA-Z0-9\-_]+)/$", {"put": "set_url_filter"}, "url_filter") )
        patterns.append( self.detail_url("services/$", {"get": "get_services"}, "services") )
        patterns.append( self.detail_url("services/(?P<service>[a-zA-Z0-9\-_]+)/$", {"get": "get_service"}, "get_service") )
        patterns.append( self.detail_url("services/(?P<service>[a-zA-Z0-9\-_]+)/true/$", {"put": "enable_service"}, "enable_service") )
        patterns.append( self.detail_url("services/(?P<service>[a-zA-Z0-9\-_]+)/false/$", {"put": "disable_service"}, "disable_service") )

        patterns.append( self.detail_url("users/$", {"get": "get_users", "post": "create_user"}, "users") )
        patterns.append( self.detail_url("users/clearusers/$", {"get": "clear_users", "put": "clear_users", "post": "clear_users"}, "clearusers") )
        patterns.append( self.detail_url("users/newuser/$", {"put": "create_user", "post": "create_user"}, "newuser") )
        patterns.append( self.detail_url("users/(?P<uid>[0-9\-]+)/$", {"delete": "delete_user"}, "user") )
        patterns.append( self.detail_url("users/(?P<uid>[0-9\-]+)/url_filter/$", {"get": "get_user_level"}, "user_level") )
        patterns.append( self.detail_url("users/(?P<uid>[0-9\-]+)/url_filter/(?P<level>[a-zA-Z0-9\-_]+)/$", {"put": "set_user_level"}, "set_user_level") )

        patterns.append( self.detail_url("bbsdump/$", {"get": "get_bbsdump"}, "bbsdump") )

        patterns.append( url("^rs/initdemo/$", self.as_view({"put": "initdemo", "get": "initdemo"}), name="initdemo") )

        patterns.append( url("^rs/subidlookup/(?P<ssid>[0-9\-]+)/$", self.as_view({"get": "ssiddetail"}), name="ssiddetail") )
        patterns.append( url("^rs/subidlookup/$", self.as_view({"get": "ssidlist"}), name="ssidlist") )

        patterns.append( url("^rs/vbng_mapping/$", self.as_view({"get": "get_vbng_mapping"}), name="vbng_mapping") )

        return patterns

    def list(self, request):
        object_list = self.filter_queryset(self.get_queryset())

        serializer = self.get_serializer(object_list, many=True)

        return Response({"subscribers": serializer.data})

    def get_vcpe_synced(self, request, pk=None):
        subscriber = self.get_object()
        return Response({"vcpe_synced": subscriber.vcpe_synced})

    def get_url_filter(self, request, pk=None):
        subscriber = self.get_object()
        return Response({"level": subscriber.url_filter_level})

    def set_url_filter(self, request, pk=None, level=None):
        subscriber = self.get_object()
        subscriber.url_filter_level = level
        subscriber.save()
        return Response({"level": subscriber.url_filter_level})

    def get_users(self, request, pk=None):
        subscriber = self.get_object()
        return Response(subscriber.users)

    def get_user_level(self, request, pk=None, uid=None):
        subscriber = self.get_object()
        user = subscriber.find_user(uid)
        if user and user.get("level", None):
            level = user["level"]
        else:
            level = self.get_object().url_filter_level

        return Response( {"id": uid, "level": level} )

    def set_user_level(self, request, pk=None, uid=None, level=None):
        subscriber = self.get_object()
        subscriber.update_user(uid, level=level)
        subscriber.save()
        return self.get_user_level(request, pk, uid)

    def create_user(self, request, pk=None):
        data = request.DATA
        name = data.get("name",None)
        mac = data.get("mac",None)
        if (not name):
             raise XOSMissingField("name must be specified when creating user")
        if (not mac):
             raise XOSMissingField("mac must be specified when creating user")

        subscriber = self.get_object()
        newuser = subscriber.create_user(name=name, mac=mac)
        subscriber.save()

        return Response(newuser)

    def delete_user(self, request, pk=None, uid=None):
        subscriber = self.get_object()
        subscriber.delete_user(uid)
        subscriber.save()

        return Response( {"id": uid, "deleted": True} )

    def clear_users(self, request, pk=None):
        subscriber = self.get_object()
        subscriber.users = []
        subscriber.save()

        return Response( "Okay" )

    def get_services(self, request, pk=None):
        subscriber = self.get_object()
        return Response(subscriber.services)

    def get_service(self, request, pk=None, service=None):
        service_attr = service+"_enable"
        subscriber = self.get_object()
        return Response({service: getattr(subscriber, service_attr)})

    def enable_service(self, request, pk=None, service=None):
        service_attr = service+"_enable"
        subscriber = self.get_object()
        setattr(subscriber, service_attr, True)
        subscriber.save()
        return Response({service: getattr(subscriber, service_attr)})

    def disable_service(self, request, pk=None, service=None):
        service_attr = service+"_enable"
        subscriber = self.get_object()
        setattr(subscriber, service_attr, False)
        subscriber.save()
        return Response({service: getattr(subscriber, service_attr)})

    def get_bbsdump(self, request, pk=None):
        subscriber = self.get_object()
        if not subsciber.volt or not subscriber.volt.vcpe:
            raise XOSMissingField("subscriber has no vCPE")
        if not subscriber.volt.vcpe.bbs_account:
            raise XOSMissingField("subscriber has no bbs_account")

        result=subprocess.check_output(["python", "/opt/xos/observers/vcpe/broadbandshield.py", "dump", subscriber.volt.vcpe.bbs_account, "123"])
        if request.GET.get("theformat",None)=="text":
            from django.http import HttpResponse
            return HttpResponse(result, content_type="text/plain")
        else:
            return Response( {"bbs_dump": result } )

    def setup_demo_subscriber(self, subscriber):
        # nuke the users and start over
        subscriber.users = []
        subscriber.create_user(name="Mom's PC",      mac="010203040506", level="PG_13")
        subscriber.create_user(name="Dad's PC",      mac="90E2Ba82F975", level="PG_13")
        subscriber.create_user(name="Jack's Laptop", mac="685B359D91D5", level="PG_13")
        subscriber.create_user(name="Jill's Laptop", mac="34363BC9B6A6", level="PG_13")
        subscriber.save()

    def initdemo(self, request):
        object_list = CordSubscriber.get_tenant_objects().all()

        # reset the parental controls in any existing demo vCPEs
        for o in object_list:
            if str(o.service_specific_id) in ["0", "1"]:
                self.setup_demo_subscriber(o)

        demo_subscribers = [o for o in object_list if o.is_demo_user]

        if demo_subscribers:
            return Response({"id": demo_subscribers[0].id})

        subscriber = CordSubscriberRoot(service_specific_id=1234,
                                        name="demo-subscriber",)
        subscriber.is_demo_user = True
        subscriber.save()

        self.setup_demo_subscriber(subscriber)

        return Response({"id": subscriber.id})

    def ssidlist(self, request):
        object_list = CordSubscriber.get_tenant_objects().all()

        ssidmap = [ {"service_specific_id": x.service_specific_id, "subscriber_id": x.id} for x in object_list ]

        return Response({"ssidmap": ssidmap})

    def ssiddetail(self, pk=None, ssid=None):
        object_list = CordSubscriber.get_tenant_objects().all()

        ssidmap = [ {"service_specific_id": x.service_specific_id, "subscriber_id": x.id} for x in object_list if str(x.service_specific_id)==str(ssid) ]

        if len(ssidmap)==0:
            raise XOSNotFound("didn't find ssid %s" % str(ssid))

        return Response( ssidmap[0] )

    def get_vbng_mapping(self, request):
        object_list = VBNGTenant.get_tenant_objects().all()

        mappings = []
        for vbng in object_list:
            if vbng.mapped_ip and vbng.routeable_subnet:
                mappings.append( {"private_ip": vbng.mapped_ip, "routeable_subnet": vbng.routeable_subnet, "mac": vbng.mapped_mac, "hostname": vbng.mapped_hostname} )

        return Response( {"vbng_mapping": mappings} )

class CordDebugIdSerializer(serializers.ModelSerializer, PlusSerializerMixin):
    # Swagger is failing because CordDebugViewSet has neither a model nor
    # a serializer_class. Stuck this in here as a placeholder for now.
    id = ReadOnlyField()
    class Meta:
        model = CordSubscriber

class CordDebugViewSet(XOSViewSet):
    base_name = "cord_debug"
    method_name = "rs/cord_debug"
    method_kind = "viewset"
    serializer_class = CordDebugIdSerializer

    @classmethod
    def get_urlpatterns(self):
        patterns = []
        patterns.append( url("^rs/cord_debug/vbng_dump/$", self.as_view({"get": "get_vbng_dump"}), name="vbng_dump"))
        return patterns

    # contact vBNG service and dump current list of mappings
    def get_vbng_dump(self, request, pk=None):
        result=subprocess.check_output(["curl", "http://10.0.3.136:8181/onos/virtualbng/privateip/map"])
        if request.GET.get("theformat",None)=="text":
            from django.http import HttpResponse
            result = json.loads(result)["map"]

            lines = []
            for row in result:
                for k in row.keys():
                     lines.append( "%s %s" % (k, row[k]) )

            return HttpResponse("\n".join(lines), content_type="text/plain")
        else:
            return Response( {"vbng_dump": json.loads(result)["map"] } )


from __future__ import annotations

from dataclasses import fields
from typing import Tuple

import numpy as np
from napari.layers import Image

def update_layer_contrast_limits(
    layer: Image,
    contrast_limits_quantiles: Tuple[float, float] = (0.01, 0.98),
    contrast_limits_range_quantiles: Tuple[float, float] = (0.0, 1.0),
) -> None:
    nonzero_mask = layer.data > 0
    if (~nonzero_mask).all():
        return

    limit_0, limit_1, limit_range_0, limit_range_1 = np.quantile(
        layer.data[nonzero_mask],
        (*contrast_limits_quantiles, *contrast_limits_range_quantiles),
    )
    layer.contrast_limits = (limit_0, limit_1 + 1e-8)
    layer.contrast_limits_range = (limit_range_0, limit_range_1 + 1e-8)

def array_safe_eq(a, b) -> bool:
    """Check if a and b are equal, even if they are numpy arrays"""
    if a is b:
        return True
    if isinstance(a, np.ndarray) and isinstance(b, np.ndarray):
        return a.shape == b.shape and (a == b).all()
    try:
        return a == b
    except TypeError:
        return NotImplemented

def dataclass_eq(dc1, dc2) -> bool:
    """checks if two dataclasses which hold numpy arrays are equal"""
    if dc1 is dc2:
        return True
    if dc1.__class__ is not dc2.__class__:
        return NotImplemented
    fields_names = [f.name for f in fields(dc1)]
    return all(
        array_safe_eq(getattr(dc1, field_name), getattr(dc2, field_name))
        for field_name in fields_names
    )


import argparse
import yaml
from pyspark.sql.functions import udf, when, year

class CreateSqlInput:
    def __init__(self):
        self.name = 'CalculateStats'

    @staticmethod
    @udf
    def extract_production(dict_string):
        try:
            production_array = yaml.load(dict_string, Loader=yaml.FullLoader)
            parsed_production = []
            for production in production_array:
                parsed_production.append(production['name'])
        except ValueError:
            parsed_production = []
        return parsed_production

    @staticmethod
    def main(spark, config):
        joined_parquet_path = config.get('PATHS', 'joined_parquet_path')
        sql_input_path = config.get('PATHS', 'sql_input_path')
        joined_df = spark.read.parquet(joined_parquet_path)

        joined_df = joined_df.withColumn('production_companies',
                                         CreateSqlInput.extract_production('production_companies'))

        joined_df = joined_df.withColumn('ratio',
                                         when(joined_df['revenue'] != 0, joined_df['budget']/joined_df['revenue'])
                                         .otherwise(0.0))

        joined_df = joined_df.withColumn('year', year('release_date'))

        joined_df = joined_df.orderBy('ratio', ascending=False)
        joined_df.select('title', 'production_companies', 'budget', 'revenue', 'ratio', 'year').show(5, False)

        joined_df.select(['title',
                          'budget',
                          'year',
                          'revenue',
                          'vote_average',
                          'ratio',
                          'production_companies',
                          'url',
                          'abstract']).write.mode('overwrite').parquet(sql_input_path)

if __name__ == '__main__':
    import sys
    from os import path
    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
    from tfi_etl.sparkscript import SparkScriptRunner

    parser = argparse.ArgumentParser()
    parser.add_argument('-config')

    args = parser.parse_args()
    config_path = str(args.config)

    calculate_stats = CreateSqlInput()
    script_runner = SparkScriptRunner(config_path, calculate_stats)
    script_runner.run()


from playsound import playsound
import os
import pandas as pd

path = "audio/" # path to the dataset
files = os.listdir(path)

df = pd.DataFrame([], columns = ["file_name", "label"])

for file, i in zip(files, range(len(files))):
	print("Currently playing " + file)
	playsound(path + file)
	label = input("Please, provide the label(n for noisy and c for clean audio files): ")
	while(label != "c" and label != "n"):
		label = input("Provided label is neither n nor c. Try again... ")
	df.loc[i] = [file, label]

df.to_json("data.json", orient = "records")


# Sinw wave plot tool
import numpy as np
import matplotlib.pyplot as plt
f =0.5 #frequency of sine wave
# f =2
A =5# maximum amplitude of sine wave
# A = 1
x = np.arange(-6.28, 6.28, 0.01)# array arranged from -pi to +pi and with small increment of 0.01
# x = np.arange(-3.14, 3.14, 0.01)
#y = A*np.sin(f*x)
y = A*np.tan(f*x)
plt.plot(x,y)
plt.xlabel('angle')
plt.ylabel('amplitude')
plt.show()


import matplotlib.pyplot as plt
import numpy as np
import os, tkinter, tkinter.filedialog, tkinter.messagebox

# show the file selection filedialog
root = tkinter.Tk()
root.withdraw()
fTyp = [('','*')]
iDir = os.path.abspath(os.path.dirname(__file__))
# tkinter.messagebox.showinfo('簡易プロットプログラムです','どのフォルダのcsvでグラフを作る？')

# output the processing file name
file = tkinter.filedialog.askopenfilename(filetypes = fTyp,initialdir = iDir)
# tkinter.messagebox.showinfo('oxプログラム',file)

df = np.loadtxt(file, skiprows=5, delimiter=',', encoding='utf-8')

rows = len(df[:,0])
x = np.arange(rows)

# 横軸の単位をsecondにしてグラフを見たいときはこちら↓を使う。
# plt.plot(df[:,0], df[:,1])
# 横軸を「1～csvファイルの行数」としてグラフを見たいときはこちら↓を使う。
plt.plot(x, df[:,1])

# plt.vlines(np.arange(24800,26400,200), -0.05, 0.05, color='k', linestyle=':', lw=0.5)
# plt.fill_between([24800,26400], -0.05, 0.05, color='skyblue')

plt.show()


import cv2
from cv2 import dnn_superres

# Create an SR object
sr = dnn_superres.DnnSuperResImpl_create()

# Read image
image = cv2.imread('2.jpg')

# ##########Read the desired model
#path = "./models/EDSR_x3.pb"
path = "./models/LapSRN_x2.pb"
sr.readModel(path)

# Set the desired model and scale to get correct pre- and post-processing
sr.setModel("edsr", 3)

# Upscale the image
result = sr.upsample(image)

cv2.imshow("Original Image", image)
cv2.imshow("Super Resolution by bicubic", cv2.resize(image,None, fx=3, fy=3, interpolation=cv2.INTER_CUBIC))
cv2.imshow("Super Resolution by DL", result)
key = cv2.waitKey(20000)
cv2.destroyAllWindows()

# Save the image
cv2.imwrite("./upscaled.png", result)

#OK
###############################################   if you want to use GPU
# Read the desired model
"""
path = "EDSR_x3.pb"
sr.readModel(path)

# Set CUDA backend and target to enable GPU inference
sr.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)
sr.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
"""


# -*- coding: utf-8 -*-
#
# File: BPDOrganizacion.py
#
# Copyright (c) 2011 by Conselleria de Infraestructuras y Transporte de la
# Generalidad Valenciana
#
# GNU General Public License (GPL)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
#
#

__author__ = """Conselleria de Infraestructuras y Transporte de la Generalidad Valenciana
<gvSIGbpd@gvSIG.org>, Model Driven Development sl <gvSIGbpd@ModelDD.org>,
Antonio Carrasco Valero <carrasco@ModelDD.org>"""
__docformat__ = 'plaintext'

from AccessControl import ClassSecurityInfo
from Products.Archetypes.atapi import *
from Products.gvSIGbpd.BPDUnidadOrganizacional import BPDUnidadOrganizacional
from Products.gvSIGbpd.config import *

# additional imports from tagged value 'import'
from Acquisition  import aq_inner, aq_parent

##code-section module-header #fill in your manual code here
##/code-section module-header

schema = Schema((

    BooleanField(
        name='permiteLeer',
        widget=BooleanField._properties['widget'](
            label="Permite ver Organizacion",
            label2="Allow to see Organization",
            description="Si Verdadero, entonces los usuarios pueden ver la Organizacion. Puede ser Falso durante  procesos de importacion largos, o por indicacion del administrador.",
            description2="If True, then the users may see  the Organization. It may be False during long import processes or by manager request.",
            label_msgid='gvSIGbpd_BPDOrganizacion_attr_permiteLeer_label',
            description_msgid='gvSIGbpd_BPDOrganizacion_attr_permiteLeer_help',
            i18n_domain='gvSIGbpd',
        ),
        description="Si Verdadero, entonces los usuarios pueden ver la Organizacion. Puede ser Falso durante  procesos de importacion largos, o por indicacion del administrador.",
        duplicates="0",
        label2="Allow to see Organization",
        ea_localid="344",
        derived="0",
        collection="false",
        styleex="volatile=0;",
        description2="If True, then the users may see  the Organization. It may be False during long import processes or by manager request.",
        ea_guid="{4AB95A00-7009-4f7d-8E86-E26666E1849C}",
        read_only="True",
        default="True",
        label="Permite ver Organizacion",
        containment="Not Specified",
        position="0",
        owner_class_name="BPDOrganizacion",
        exclude_from_exportconfig="True",
        exclude_from_copyconfig="True"
    ),

    BooleanField(
        name='permiteModificar',
        widget=BooleanField._properties['widget'](
            label="Permite modificar Organizacion",
            label2="Allow to change Organization",
            description="Si Verdadero, entonces los usuarios pueden cambiar la Organizacion. Puede ser Falso durante  procesos de importacion largos, o por indicacion del administrador.",
            description2="If True, then the users may change the Organization. It may be False during long import processes or by manager request.",
            label_msgid='gvSIGbpd_BPDOrganizacion_attr_permiteModificar_label',
            description_msgid='gvSIGbpd_BPDOrganizacion_attr_permiteModificar_help',
            i18n_domain='gvSIGbpd',
        ),
        description="Si Verdadero, entonces los usuarios pueden cambiar la Organizacion. Puede ser Falso durante  procesos de importacion largos, o por indicacion del administrador.",
        duplicates="0",
        label2="Allow to change Organization",
        ea_localid="345",
        derived="0",
        collection="false",
        styleex="volatile=0;",
        description2="If True, then the users may change the Organization. It may be False during long import processes or by manager request.",
        ea_guid="{159316D0-39EF-4c8d-8CF7-FF2DBFE4C49D}",
        read_only="True",
        default="True",
        label="Permite modificar Organizacion",
        containment="Not Specified",
        position="2",
        owner_class_name="BPDOrganizacion",
        exclude_from_exportconfig="True",
        exclude_from_copyconfig="True"
    ),

    ComputedField(
        name='coleccionesPoliticasDeNegocio',
        widget=ComputedWidget(
            label="Politicas de Negocio (colecciones)",
            label2="Business Policies (collections)",
            description="Colecciones de Politicas de Negocio que gobiernan la Organizacion y sus Procesos de Negocio, y constituyen la base de las Reglas de Negocio.",
            description2="Collections of Business Policies  governing the Organisation and its Business Processes, and constitute the basis for the Business Rules.",
            label_msgid='gvSIGbpd_BPDOrganizacion_contents_coleccionesPoliticasDeNegocio_label',
            description_msgid='gvSIGbpd_BPDOrganizacion_contents_coleccionesPoliticasDeNegocio_help',
            i18n_domain='gvSIGbpd',
        ),
        contains_collections=True,
        label2='Business Policies (collections)',
        label='Politicas de Negocio (colecciones)',
        represents_aggregation=True,
        description2='Collections of Business Policies  governing the Organisation and its Business Processes, and constitute the basis for the Business Rules.',
        multiValued=1,
        owner_class_name="BPDOrganizacion",
        expression="context.objectValues(['BPDColeccionPoliticasDeNegocio'])",
        computed_types=['BPDColeccionPoliticasDeNegocio'],
        non_framework_elements=False,
        description='Colecciones de Politicas de Negocio que gobiernan la Organizacion y sus Procesos de Negocio, y constituyen la base de las Reglas de Negocio.'
    ),

    ComputedField(
        name='coleccionesReglasDeNegocio',
        widget=ComputedWidget(
            label="Reglas de Negocio (colecciones)",
            label2="Business Rules (collections)",
            description="Colecciones de Reglas deNegocio que se derivan de las politicas de Negocio, y dirigen los Procesos de Negocio de la Organizacion.",
            description2="Collections of Business Rules derived from Business Policies, and driving the Business Process in the Organisation.",
            label_msgid='gvSIGbpd_BPDOrganizacion_contents_coleccionesReglasDeNegocio_label',
            description_msgid='gvSIGbpd_BPDOrganizacion_contents_coleccionesReglasDeNegocio_help',
            i18n_domain='gvSIGbpd',
        ),
        contains_collections=True,
        label2='Business Rules (collections)',
        label='Reglas de Negocio (colecciones)',
        represents_aggregation=True,
        description2='Collections of Business Rules derived from Business Policies, and driving the Business Process in the Organisation.',
        multiValued=1,
        owner_class_name="BPDOrganizacion",
        expression="context.objectValues(['BPDColeccionReglasDeNegocio'])",
        computed_types=['BPDColeccionReglasDeNegocio'],
        non_framework_elements=False,
        description='Colecciones de Reglas deNegocio que se derivan de las politicas de Negocio, y dirigen los Procesos de Negocio de la Organizacion.'
    ),

    ComputedField(
        name='coleccionesProcesosDeNegocio',
        widget=ComputedWidget(
            label="Procesos de Negocio (colecciones)",
            label2="Business Processes (collections)",
            description="Colecciones de Procesos de Negocio realizando cursos de accion con los que la Organizacion persigue propositos especificos.",
            description2="Collections of Business Processes realising courses of action through which the Organisation pursues specific goals.",
            label_msgid='gvSIGbpd_BPDOrganizacion_contents_coleccionesProcesosDeNegocio_label',
            description_msgid='gvSIGbpd_BPDOrganizacion_contents_coleccionesProcesosDeNegocio_help',
            i18n_domain='gvSIGbpd',
        ),
        contains_collections=True,
        label2='Business Processes (collections)',
        label='Procesos de Negocio (colecciones)',
        represents_aggregation=True,
        description2='Collections of Business Processes realising courses of action through which the Organisation pursues specific goals.',
        multiValued=1,
        owner_class_name="BPDOrganizacion",
        expression="context.objectValues(['BPDColeccionProcesosDeNegocio'])",
        computed_types=['BPDColeccionProcesosDeNegocio'],
        non_framework_elements=False,
        description='Colecciones de Procesos de Negocio realizando cursos de accion con los que la Organizacion persigue propositos especificos.'
    ),

    ComputedField(
        name='coleccionesArtefactos',
        widget=ComputedWidget(
            label="Artefactos (colecciones)",
            label2="Artefacts (collections)",
            description="Colecciones de Artefactos que se producen, consumen, consultan, editan, y en general son el objeto del esfuerzo de la Organizacion.",
            description2="Collections of Artefacts produced, consumed, consulted, edited, or otherwise object of the Organisation effort.",
            label_msgid='gvSIGbpd_BPDOrganizacion_contents_coleccionesArtefactos_label',
            description_msgid='gvSIGbpd_BPDOrganizacion_contents_coleccionesArtefactos_help',
            i18n_domain='gvSIGbpd',
        ),
        contains_collections=True,
        label2='Artefacts (collections)',
        label='Artefactos (colecciones)',
        represents_aggregation=True,
        description2='Collections of Artefacts produced, consumed, consulted, edited, or otherwise object of the Organisation effort.',
        multiValued=1,
        owner_class_name="BPDOrganizacion",
        expression="context.objectValues(['BPDColeccionArtefactos'])",
        computed_types=['BPDColeccionArtefactos'],
        non_framework_elements=False,
        description='Colecciones de Artefactos que se producen, consumen, consultan, editan, y en general son el objeto del esfuerzo de la Organizacion.'
    ),

    ComputedField(
        name='coleccionesHerramientas',
        widget=ComputedWidget(
            label="Herramientas (colecciones)",
            label2="Tools (collections)",
            description="Colecciones de Herramientas que la Organizacion aplica para manejar ciertos Artefactos y asistir en la ejecucion de Pasos de Procesos de Negocio.",
            description2="Collections of Tools applied in the Organisation to handle certain Artefacts, and assist in the execution of Business Process Steps.",
            label_msgid='gvSIGbpd_BPDOrganizacion_contents_coleccionesHerramientas_label',
            description_msgid='gvSIGbpd_BPDOrganizacion_contents_coleccionesHerramientas_help',
            i18n_domain='gvSIGbpd',
        ),
        contains_collections=True,
        label2='Tools (collections)',
        label='Herramientas (colecciones)',
        represents_aggregation=True,
        description2='Collections of Tools applied in the Organisation to handle certain Artefacts, and assist in the execution of Business Process Steps.',
        multiValued=1,
        owner_class_name="BPDOrganizacion",
        expression="context.objectValues(['BPDColeccionHerramientas'])",
        computed_types=['BPDColeccionHerramientas'],
        non_framework_elements=False,
        description='Colecciones de Herramientas que la Organizacion aplica para manejar ciertos Artefactos y asistir en la ejecucion de Pasos de Procesos de Negocio.'
    ),

),
)

##code-section after-local-schema #fill in your manual code here
##/code-section after-local-schema

BPDOrganizacion_schema = OrderedBaseFolderSchema.copy() + \
    getattr(BPDUnidadOrganizacional, 'schema', Schema(())).copy() + \
    schema.copy()

##code-section after-schema #fill in your manual code here
##/code-section after-schema

class BPDOrganizacion(OrderedBaseFolder, BPDUnidadOrganizacional):
    """
    """
    security = ClassSecurityInfo()
    __implements__ = (getattr(OrderedBaseFolder,'__implements__',()),) + (getattr(BPDUnidadOrganizacional,'__implements__',()),)

    # This name appears in the 'add' box
    archetype_name = 'Organizacion'

    meta_type = 'BPDOrganizacion'
    portal_type = 'BPDOrganizacion'

    # Change Audit fields

    creation_date_field = 'fechaCreacion'
    creation_user_field = 'usuarioCreador'
    modification_date_field = 'fechaModificacion'
    modification_user_field = 'usuarioModificador'
    deletion_date_field = 'fechaEliminacion'
    deletion_user_field = 'usuarioEliminador'
    is_inactive_field = 'estaInactivo'
    change_counter_field = 'contadorCambios'
    sources_counters_field = 'contadoresDeFuentes'
    change_log_field = 'registroDeCambios'

    # Versioning and Translation fields

    inter_version_field = 'uidInterVersionesInterno'
    version_field = 'versionInterna'
    version_storage_field = 'versionInternaAlmacenada'
    version_comment_field = 'comentarioVersionInterna'
    version_comment_storage_field = 'comentarioVersionInternaAlmacenada'
    inter_translation_field = 'uidInterTraduccionesInterno'
    language_field = 'codigoIdiomaInterno'
    fields_pending_translation_field = 'camposPendientesTraduccionInterna'
    fields_pending_revision_field = 'camposPendientesRevisionInterna'

    allowed_content_types = ['BPDColeccionPoliticasDeNegocio', 'BPDColeccionHerramientas', 'BPDColeccionProcesosDeNegocio', 'BPDColeccionReglasDeNegocio', 'BPDColeccionArtefactos'] + list(getattr(BPDUnidadOrganizacional, 'allowed_content_types', []))
    filter_content_types             = 1
    global_allow                     = 1
    content_icon = 'bpdorganizacion.gif'
    immediate_view                   = 'Textual'
    default_view                     = 'Textual'
    suppl_views                      = ('Textual', 'Tabular', )
    typeDescription                  = "Raiz de contenidos para definicion y publicacion de procedimientos de gestion."
    typeDescMsgId                    =  'gvSIGbpd_BPDOrganizacion_help'
    archetype_name2                  = 'Organisation'
    typeDescription2                 = '''Root of all definition and publicacion content.'''
    archetype_name_msgid             = 'gvSIGbpd_BPDOrganizacion_label'
    factory_methods                  = None
    factory_enablers                 = None
    propagate_delete_impact_to       = None

    actions =  (

       {'action': "string:$object_url/base_edit",
        'category': "object",
        'id': 'edit',
        'name': 'Edit',
        'permissions': ("ModifyPortalContent",),
        'condition': """python:('portal_factory' in object.getPhysicalPath())"""
       },

       {'action': "string:$object_url/Editar",
        'category': "object",
        'id': 'editar',
        'name': 'Edit',
        'permissions': ("ModifyPortalContent",),
        'condition': """python:( not ('portal_factory' in object.getPhysicalPath())) and object.fAllowWrite()"""
       },

       {'action': "string:${object_url}/MDDNewVersion",
        'category': "object_buttons",
        'id': 'mddnewversion',
        'name': 'New Version',
        'permissions': ("Modify portal content",),
        'condition': """python:object.fAllowVersion() and object.getEsRaiz()"""
       },

       {'action': "string:${object_url}/MDDNewTranslation",
        'category': "object_buttons",
        'id': 'mddnewtranslation',
        'name': 'New Translation',
        'permissions': ("Modify portal content",),
        'condition': """python:0 and object.fAllowTranslation() and object.getEsRaiz()"""
       },

       {'action': "string:$object_url/content_status_history",
        'category': "object",
        'id': 'content_status_history',
        'name': 'State',
        'permissions': ("View",),
        'condition': """python:0"""
       },

       {'action': "string:${object_url}/MDDInspectClipboard",
        'category': "object_buttons",
        'id': 'inspectclipboard',
        'name': 'Clipboard',
        'permissions': ("View",),
        'condition': """python:object.fAllowRead()"""
       },

       {'action': "string:${object_url}/MDDOrdenar",
        'category': "object_buttons",
        'id': 'reorder',
        'name': 'Reorder',
        'permissions': ("Modify portal content",),
        'condition': """python:object.fAllowWrite()"""
       },

       {'action': "string:${object_url}/MDDExport",
        'category': "object_buttons",
        'id': 'mddexport',
        'name': 'Export',
        'permissions': ("View",),
        'condition': """python:object.fAllowExport()"""
       },

       {'action': "string:${object_url}/MDDImport",
        'category': "object_buttons",
        'id': 'mddimport',
        'name': 'Import',
        'permissions': ("Modify portal content",),
        'condition': """python:object.fAllowImport()"""
       },

       {'action': "string:${object_url}/sharing",
        'category': "object",
        'id': 'local_roles',
        'name': 'Sharing',
        'permissions': ("Manage properties",),
        'condition': """python:1"""
       },

       {'action': "string:${object_url}/",
        'category': "object",
        'id': 'view',
        'name': 'View',
        'permissions': ("View",),
        'condition': """python:1"""
       },

       {'action': "string:${object_url}/MDDChanges",
        'category': "object_buttons",
        'id': 'mddchanges',
        'name': 'Changes',
        'permissions': ("View",),
        'condition': """python:1"""
       },

       {'action': "string:${object_url}/MDDVersions",
        'category': "object_buttons",
        'id': 'mddversions',
        'name': 'Versions',
        'permissions': ("View",),
        'condition': """python:1"""
       },

       {'action': "string:${object_url}/MDDCacheStatus/",
        'category': "object_buttons",
        'id': 'mddcachestatus',
        'name': 'Cache',
        'permissions': ("View",),
        'condition': """python:1"""
       },

       {'action': "string:${object_url}/TextualRest",
        'category': "object_buttons",
        'id': 'textual_rest',
        'name': 'TextualRest',
        'permissions': ("View",),
        'condition': """python:1"""
       },

    )

    _at_rename_after_creation = True

    schema = BPDOrganizacion_schema

    ##code-section class-header #fill in your manual code here
    ##/code-section class-header

    # Methods

    security.declarePublic('manage_afterAdd')
    def manage_afterAdd(self,item,container):
        """
        """

        return self.pHandle_manage_afterAdd(  item, container)

    security.declarePublic('manage_pasteObjects')
    def manage_pasteObjects(self,cb_copy_data=None,REQUEST=None):
        """
        """

        return self.pHandle_manage_pasteObjects( cb_copy_data, REQUEST)

    security.declarePublic('cb_isMoveable')
    def cb_isMoveable(self):
        """
        """

        return self._at_rename_after_creation or  ('portal_factory' in self.getPhysicalPath()) or ((  not self.getEsRaiz()) and self.fAllowWrite())

    security.declarePublic('fAllowRead')
    def fAllowRead(self):
        """
        """

        return self.getPermiteLeer() and ( self.getEsRaiz() or self.getRaiz().fAllowRead())

    security.declarePublic('fAllowWrite')
    def fAllowWrite(self):
        """
        """

        return self.fAllowRead() and self.getPermiteModificar() and ( self.getEsRaiz() or self.getRaiz().fAllowWrite())

    security.declarePublic('moveObjectsByDelta')
    def moveObjectsByDelta(self,ids,delta,subset_ids=None):
        """
        """

        return self.pHandle_moveObjectsByDelta( ids, delta, subset_ids=subset_ids)

registerType(BPDOrganizacion, PROJECTNAME)
# end of class BPDOrganizacion

##code-section module-footer #fill in your manual code here
##/code-section module-footer


from django.shortcuts import render, get_object_or_404, redirect, HttpResponse
from django.contrib.auth.decorators import login_required
from account.models import User
from product.models import Product
from .models import Message, MessageRoom

@login_required
def check_message_room(request, product_id):
    product = get_object_or_404(Product, id=product_id)
    receiver = product.creator
    sender = request.user
    message_room = MessageRoom.objects.filter(product=product,sender=sender)
    if not message_room.exists():
        message_room =MessageRoom.objects.create(product=product,sender=sender, receiver=receiver)
    else:
        message_room = MessageRoom.objects.get(product=product,sender=sender)

    # if request.method == 'POST':
    #     content = request.POST.get('content')
    #     sender = request.user

    #     message = Message.objects.create(
    #         sender=sender,
    #         receiver=receiver,
    #         product=product,
    #         content=content
    #     )

        # Perform any additional actions, notifications, or redirects

    return redirect('messaging:message-room',id=message_room.id)

@login_required
def message_room(request,id):

    message_room = get_object_or_404(MessageRoom, id=id)
    if request.user == message_room.sender or request.user == message_room.receiver:
        return render(request, 'messaging/messageroom.html', {'message_room':message_room})

    else:
        return HttpResponse('Unauthorized access. Sorry')

def view_messages(request):
    # messages = MessageRoom.objects.filter(receiver=user).order_by('-id') | MessageRoom.objects.filter(sender=user).order_by('-id')
    messages = MessageRoom.with_messages(request.user)
    return render(request, 'messaging/view_messages.html', {'messages': messages})

@login_required
def send_messages(request):
    if request.method == "POST":
        message = request.POST.get('message')
        room_id = request.POST.get("roomid")
        room = MessageRoom.objects.get(id=room_id)
        Message.objects.create(room=room,content=message, sender=request.user)
        return redirect('messaging:message-room',id=room.id)

    return HttpResponse('Something went wrong.')


from tkinter import *
from tkinter import messagebox as mbox
import socket

win=Tk()
win.title('               CLIENT         ')
win.configure(bg='#BC8F8F')
win.geometry('320x500')

typemsg=Listbox(win,height=25,width=45)
typemsg.place(x=10,y=15)
udpsocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

udpsocket.sendto(str.encode("Client is connected!"), ("localhost", 5555))

mbox.showinfo('info',"Client Connected")
req = udpsocket.recvfrom(1024)
typemsg.insert(0,"Server : "+req[0].decode())

def sent():
    message = matter_name.get()
    typemsg.insert(END,"Client : "+message)
    udpsocket.sendto(str.encode(message),("localhost",5555))
    req = udpsocket.recvfrom(1024)
    typemsg.insert(END,"Server : "+req[0].decode())
    matter_entrybox.delete(0,END)

matter_name=StringVar()
matter_entrybox=Entry(win,width=35,textvariable=matter_name,border=4,font=('arial','10'))
matter_entrybox.place(x=10,y=440)

send_button=Button(win,text='Send',command=sent,borderwidth=0,bg="#20B2AA",fg="gold" ,font=("times new roman",13) )
send_button.place(x=275,y=440)

win.mainloop()


# python 3.6.6

# 0 0 0 ------> no elements selected (0)
# 0 0 1 ------> only "c" element has been selected (1)
# 0 1 0 ------> only "b" element has been selected (2)
# 0 1 1 ------> only "b" and "c" element has been selected (3)
# 1 0 0 ------> similarly (4)
# 1 0 1 ------> (5)
# 1 1 0 ------> (6)
# 1 1 1 ------> (7)

def power_set(items):
    N = len(items) # 3 items
    combo = []
    for i in range(2**N):  # create all combinations count => 8
        temp_combo = []

        # 2 1 0 - index j
        # 0 0 0 - binary representation
        for j in range(N):

            # iterate by index over binary number, from right-> left. ex: 001 - take 1, then 0, then 0.
            # to understand if it's 1 or 0 used modulo operator %.
            # 0 % 2 = 0
            # 1 % 2 = 1
            if(i >> j) % 2 == 1:
                temp_combo.append(items[j])
        if temp_combo:
            combo.append(temp_combo)
    return combo
# Output:
# 0:['a']
# 1:['b']
# 2:['a', 'b']
# 3:['c']
# 4:['a', 'c']
# 5:['b', 'c']
# 6:['a', 'b', 'c']

if __name__ == '__main__':
    items = ['a','b','c']
    power_set = power_set(items)


def pomekons_battle(bonus: int, player1_pokemons_attack: list[int], player2_pokemons_attack: list[int]) -> str:
    [player1_ai, player1_di, player1_li] = player1_pokemons_attack
    [player2_ai, player2_di, player2_li] = player2_pokemons_attack
    player1_attack: float = (player1_ai + player1_di) / 2.0
    player2_attack: float = (player2_ai + player2_di) / 2.0

    if player1_li % 2 == 0:
        player1_attack += bonus

    if player2_li % 2 == 0:
        player2_attack += bonus

    if player1_attack > player2_attack:
        return 'Dabriel'

    if player2_attack > player1_attack:
        return 'Guarte'

    return 'Empate'

def main() -> None:
    game: int = int(input())
    while game > 0:
        bonus: int = int(input())
        player1_pokemons_attack: list[int] = list(map(int, input().split()))
        player2_pokemons_attack: list[int] = list(map(int, input().split()))
        print(pomekons_battle(bonus, player1_pokemons_attack, player2_pokemons_attack))
        game -= 1

if __name__ == '__main__':
    main()


import numpy as np
from PyQt5.QtCore import QSize
from PyQt5.QtGui import QIcon, QColor
from PyQt5.QtWidgets import QListWidgetItem, QPushButton
from LGEprocess.flags_LGE import *
from skimage import exposure, img_as_float
import torch.utils.data as Datas
from LGEprocess import Network as Network
import nibabel as nib
import os
import torch
def Seg(img):
    print(img.shape)
    os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
    device = torch.device("cuda:0")
    print(torch.__version__)
    data=img
    dataloder = Datas.DataLoader(dataset=data, batch_size=1, shuffle=False)
    Segnet = Network.DenseBiasNet(n_channels=1, n_classes=4).to(device)

    pretrained_dict = torch.load('./model/net_epoch_source-Seg-Network.pkl', map_location='cpu')
    model_dict = Segnet.state_dict()
    pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
    model_dict.update(pretrained_dict)
    Segnet.load_state_dict(model_dict)

    with torch.no_grad():
        for epoch in range(1):
            for step, (img) in enumerate(dataloder):
                print(img.shape)
                img=img.to(device).float()
                print(img.shape)
                img=Segnet(img)
    img= img[0, 1, :, :, :] * 1 + img[0, 2, :, :, :] * 2 + img[0, 3, :, :, :] * 3
    img = img.data.cpu().numpy()
    print(img.shape)
    return img

def Reg(mov,fix):
    print(mov.shape)
    print(fix.shape)
    os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"

    device = torch.device("cuda:0")
    print(torch.__version__)
    data = mov,fix
    dataloder = Datas.DataLoader(dataset=data, batch_size=2, shuffle=False)
    Flownet = Network.VXm(2).to(device)
    ##
    pretrained_dict = torch.load('./model/net_epoch_source-Flow-Network.pkl')
    model_dict = Flownet.state_dict()
    pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
    model_dict.update(pretrained_dict)
    Flownet.load_state_dict(model_dict)

    with torch.no_grad():
        for epoch in range(1):
            for step, (mov,fix) in enumerate(dataloder):
                print(mov.shape)
                print(fix.shape)
                mov = mov.to(device).float()
                fix = fix.to(device).float()
                print(mov.shape)
                print(fix.shape)
                flow_field_x1, mov_fix, flow_field_x2, es_source = Flownet(fix, mov, fix)
                mov_fix = mov_fix[0, 0, :, :, :].data.cpu().numpy()
                print(mov_fix.shape)
                return mov_fix

def load_nii(path):
    image = nib.load(path)
    affine = image.affine
    image = np.asarray(image.dataobj)
    return image, affine

def normor(image):
    image -=image.mean()
    image /=image.std()
    return image

def crop_img(label_es, img, box_height=128, box_width=128):
    a = label_es.nonzero()
    a_x = a[0]
    a_x_middle = np.median(a[0])
    a_height = max((a_x)) - min((a_x)) + 1

    assert a_height < box_height, 'height小了'
    a_x_start = max(0,int(a_x_middle - box_height / 2))
    if(int(a_x_middle - box_height / 2)>=0):
        a_x_end = int(a_x_middle + box_height / 2)
    else:
        a_x_end=box_height
    print('axs',a_x_start)
    print('axe',a_x_end)
    print('x:',a_x_end-a_x_start)

    a_y = a[1]
    a_y_middle = np.median(a_y)
    a_width = max(a_y) - min(a_y) + 1
    # print(a_width,a_height)
    assert a_width < box_width, 'width小了'
    a_y_start = max(0,int(a_y_middle - box_width / 2))
    if(int(a_y_middle - box_width / 2)>=0):
        a_y_end = int(a_y_middle + box_width / 2)
    else:
        a_y_end=box_width

    img_1 = img[a_x_start:a_x_end, a_y_start:a_y_end, :]
    print('img1',img_1.shape)
    #plt.imshow(img_1[:,:,5], cmap='gray')
    return img_1

class MyItem_LGE(QListWidgetItem):
    def __init__(self, name=None, parent=None):
        super(MyItem_LGE, self).__init__(name, parent=parent)
        self.setIcon(QIcon('icons/color.png'))
        self.setSizeHint(QSize(60, 60))  # size
        print('MyItem_LGE')

    def get_params(self):
        protected = [v for v in dir(self) if v.startswith('_') and not v.startswith('__')]
        param = {}
        for v in protected:
            param[v.replace('_', '', 1)] = self.__getattribute__(v)
        return param

    def update_params(self, param):
        for k, v in param.items():
            if '_' + k in dir(self):
                self.__setattr__('_' + k, v)

class LabelItem(MyItem_LGE):
    def __init__(self, parent=None):
        super(LabelItem, self).__init__('添加GT', parent=parent)

    def __call__(self, label):
        # blank = np.zeros(img.shape, img.dtype)
        # img = cv2.addWeighted(img, self._alpha, blank, 1 - self._alpha, self._beta)
        return label

class NormItem(MyItem_LGE):
    def __init__(self, parent=None):
        super(NormItem, self).__init__('归一化', parent=parent)

    def __call__(self, img):
        max = img.max()
        min = img.min()
        img = (img - min) / (max - min)
        return img

class LightItem(MyItem_LGE):
    def __init__(self, parent=None):
        super(LightItem, self).__init__('亮度', parent=parent)
        self.alpha = 1

    def __call__(self, img):
        img = img_as_float(img)
        if (self.alpha <=1 & self.alpha >0):
            img = exposure.adjust_gamma(img, self.alpha)  # 图片调暗
        elif (self.alpha > 1):
            img = exposure.adjust_gamma(img, 0.5)  # 图片调亮
        else:
            print('请输入大于0的数字！')
        return img

class ROIItem(MyItem_LGE):
    def __init__(self, parent=None):
        super(ROIItem, self).__init__('ROI提取', parent=parent)

    def __call__(self, img):
        print(img.shape)
        label_path='./image/patient081_frame01_gt.nii.gz'
        label=nib.load(label_path).get_data()
        print(label.shape)
        img=crop_img(label_es=label,img=img,box_height=128,box_width=128)
        print(img.shape)

        return img

class RegItem(MyItem_LGE):
    def __init__(self, parent=None):
        super(RegItem, self).__init__('配准', parent=parent)

    def __call__(self, img):
        path='./image/_es.nii.gz'
        fix=nib.load(path).get_data()
        img = np.transpose(img, (2, 1, 0))  # xyz-zyx
        img = normor(img)
        img = img[np.newaxis, np.newaxis, :, :, :]
        fix = np.transpose(fix, (2, 1, 0))  # xyz-zyx
        fix = normor(fix)
        fix = fix[np.newaxis, np.newaxis, :, :, :]
        mov=img

        img=Reg(mov,fix)
        img = np.transpose(img, (2, 1, 0))  # zyx-xyz
        return img

class SegItem(MyItem_LGE):
    def __init__(self, parent=None):
        super(SegItem, self).__init__('分割', parent=parent)
    def __call__(self, img):
        img = np.transpose(img, (2, 1, 0))  # xyz-zyx
        img=normor(img)
        img = img[np.newaxis,np.newaxis, :, :, :]
        # print(img.shape)
        img=Seg(img)
        img=np.transpose(img,(2,1,0))#zyx-xyz
        print(img.shape)

        return img


import cv2
import numpy as np
import glob
import uuid
import caffe
import skimage.io
from util import histogram_equalization
from scipy.ndimage import zoom
from skimage.transform import resize
import random
import cv2
import numpy as np
from matplotlib import pyplot as plt
import dlib
from project_face import frontalizer

IMAGE_WIDTH = 32
IMAGE_HEIGHT = 32

class mouth_detector():
    def __init__(self):
        self.PATH_face_model = '../lib/shape_predictor_68_face_landmarks.dat'
        self.face_cascade = cv2.CascadeClassifier('../lib/haarcascade/haarcascade_frontalface_default.xml')
        self.eye_cascade = cv2.CascadeClassifier('../lib/haarcascade/haarcascade_eye.xml')
        self.mouth_cascade = cv2.CascadeClassifier('../lib/haarcascade/mouth.xml')
        self.md_face = dlib.shape_predictor(self.PATH_face_model)
        self.fronter = frontalizer('../lib/ref3d.pkl')

    def mouth_detect_single(self,image,isPath):

        if isPath == True:
            img = cv2.imread(image, cv2.IMREAD_UNCHANGED)
        else:
            img = image

        img = histogram_equalization(img)
        gray_img1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = self.face_cascade.detectMultiScale(gray_img1, 1.3, 5)

        for (x,y,w,h) in faces:
            roi_gray = gray_img1[y:y+h, x:x+w]
            eyes = self.eye_cascade.detectMultiScale(roi_gray)
            if(len(eyes)>0):
                p = x
                q = y
                r = w
                s = h
                face_region = gray_img1[q:q+s, p:p+r]
                face_region_rect = dlib.rectangle(long(q),long(p),long(q+s),long(p+r))
                rectan = dlib.rectangle(long(x),long(y),long(x+w),long(y+h))
                shape = self.md_face(img,rectan)
                p2d = np.asarray([(shape.part(n).x, shape.part(n).y,) for n in range(shape.num_parts)], np.float32)
                rawfront, symfront = self.fronter.frontalization(img,face_region_rect,p2d)
                face_hog_mouth = symfront[165:220, 130:190]
                gray_img = cv2.cvtColor(face_hog_mouth, cv2.COLOR_BGR2GRAY)
                crop_img_resized = cv2.resize(gray_img, (IMAGE_WIDTH, IMAGE_HEIGHT), interpolation = cv2.INTER_CUBIC)
                #cv2.imwrite("../img/output_test_img/mouthdetectsingle_crop_rezized.jpg",gray_img)
                return crop_img_resized,rectan.left(),rectan.top(),rectan.right(),rectan.bottom()
        else:
            return None,-1,-1,-1,-1

    def mouth_detect_bulk(self,input_folder,output_folder):

        transformed_data_set = [img for img in glob.glob(input_folder+"/*jpg")]

        for in_idx, img_path in enumerate(transformed_data_set):
            mouth,x,y,w,h = self.mouth_detect_single(img_path,True)
            if 'showingteeth' in img_path:
                guid = uuid.uuid4()
                uid_str = guid.urn
                str_guid = uid_str[9:]
                path = output_folder+"/"+str_guid+"_showingteeth.jpg"
                cv2.imwrite(path,mouth)
            else:
                guid = uuid.uuid4()
                uid_str = guid.urn
                str_guid = uid_str[9:]
                path = output_folder+"/"+str_guid+".jpg"
                cv2.imwrite(path,mouth)

    def negative_image(self,imagem):
        imagem = (255-imagem)
        return imagem

    def adaptative_threashold(self,input_img_path):
        img = cv2.imread(input_img_path,0)
        img = cv2.medianBlur(img,3)
        ret,th1 = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
        th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
                    cv2.THRESH_BINARY,11,2)
        th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,\
                    cv2.THRESH_BINARY,11,2)
        #cv2.imwrite("../img/output_test_img/hmouthdetectsingle_adaptative.jpg",th3)
        return th3


from fastapi import APIRouter, Depends, HTTPException

from ...celery.tasks import ExcelParser
from ..crud.dishes_crud import DishesCrud
from ..crud.menu_crud import MenuCrud
from ..crud.submenu_crud import SubmenuCrud

parser_router = APIRouter(prefix='/parser', tags=['Parser'])

@parser_router.post('/parse-excel')
async def parse_excel(
    menu_service: MenuCrud = Depends(),
    submenu_service: SubmenuCrud = Depends(),
    dish_service: DishesCrud = Depends()
):
    try:
        excel_parser = ExcelParser(menu_service, submenu_service, dish_service)
        await excel_parser.parser()
        return {'message': 'Excel data parsed and loaded successfully'}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


import pandas as pd
from datetime import datetime
import os

def get_csv(source):
    try:
        df = pd.read_csv('data/' + source + '.csv')
    except (OSError, IOError) as e:
        df = pd.DataFrame()
        print(e)
    return df;

def get_status(source_name):
    return '';

def set_status(source_name, status):
    return;

def get_data(source_name, meta_filter):
    df = get_csv(source_name)
    df = df[df['meta'].str.contains(meta_filter)]
    return df

def put_all_data(source_name, descr, df):
    local = get_csv(source_name)
    result = pd.concat([local, df]).drop_duplicates(['ref', 'date'])
    result = result.sort_values(by=['ref', 'date'])
    if not os.path.exists('data'):
        os.makedirs('data')
    result.to_csv('data/'+source_name+'.csv', columns=['ref', 'date', 'meta', 'value', 'file_date'], quoting=1, index=False)
    df['file_date'] = pd.to_datetime(df['file_date'])
    date = df['file_date'].max()
    date = date.today().replace(microsecond=0)
    lu = pd.DataFrame(data=[[source_name, date, 'None']], columns=['Name', 'Date', 'Status'])
    try:
        lu_new = pd.read_csv('data/last-update.csv')
    except (OSError, IOError) as e:
        lu_new = lu
    result = pd.concat([lu, lu_new]).drop_duplicates(['Name'])
    result.to_csv('data/last-update.csv', quoting=1, index=False)
    print(result)

def get_last_update(source_name, alternative_date):
    try:
        df = pd.read_csv('data/last-update.csv', index_col='Name')
    except (OSError, IOError) as e:
        return None
    if df.empty or source_name not in df.index:
        return alternative_date;
    date = df.get_value(source_name, "Date", takeable=False)
    return datetime.strptime(date, '%Y-%m-%d %H:%M:%S')


'''
Created on 22 Jul 2018

@author: Paulo
'''
from random import sample
import pprint

class MinesweeperLogic(object):
    """classdocs"""

    def __init__(self, rowSize, columnSize, numberMines):
        '''
        Constructor
        '''
        self.NewGame(rowSize, columnSize, numberMines)

    def GenerateMines(self):
        mineCoordinates=[]
        mines = sample(range(0, (self.columnSize*self.rowSize)-1) , self.numberMines)

        #print (mines)

        for mine in mines:
            mineCoordinates.append(self.IntToCoordinates(mine))

        #print(mineCoordinates)
        return ((mines, mineCoordinates))

    def GenerateGameMatrix(self, mines):

        matrix = [[Cell() for _ in range(self.columnSize)] for _ in range(self.rowSize)]

        for mine in mines:
            mineRow, mineColumn = (mine)
            matrix[mineRow][mineColumn].value = -1

            rowRange = range (mineRow-1, mineRow + 2)
            columnRange = range (mineColumn -1, mineColumn + 2)

            for i in rowRange:
                for j in columnRange:
                    if ( 0 <= i < self.rowSize and 0 <= j < self.columnSize and matrix[i][j].value!= -1):
                        matrix[i][j].value+=1

        #self.PrintGameMatrix(matrix)

        return matrix

    def NewGame(self, rowSize, columnSize, numberMines):
        self.rowSize = rowSize
        self.columnSize = columnSize
        self.numberMines = numberMines

        self.numberMoves = self.rowSize * self.columnSize

        self.minesInt, self.minesLocations = self.GenerateMines()
        self.gameMatrix = self.GenerateGameMatrix(self.minesLocations)

    def ClickMove(self, buttonNumber):
        result={
            "finish":False,
            "mine":False,
            "tile_info" : []
            }

        #Translates the int to Coordinates
        row , column = self.IntToCoordinates(buttonNumber)

        #Sets the specific cell as clicked
        self.gameMatrix[row][column].SetClicked()
        #Decreases the number of plays (used to know if game is won)
        self.numberMoves -= 1
        result['tile_info'].append((self.CoordinatesToInt(row, column) ,self.gameMatrix[row][column].value))

        if self.gameMatrix[row][column].value == -1:
            result['finish'] = result['mine']= True

        if self.gameMatrix[row][column].value == 0:
            #Runs the propagation calculation
            propagateList = self.PropagateZeros(row, column)
            #Updates the number of moves
            self.numberMoves -= len(propagateList)
            for cell in propagateList:
                row, column = cell
                self.gameMatrix[row][column].SetClicked()
                result['tile_info'].append((self.CoordinatesToInt(row, column) ,self.gameMatrix[row][column].value))

        if self.numberMoves <= self.numberMines:
            result['finish'] = True

        return result

    def FlagMove(self, buttonNumber):
        #Translates the int to Coordinates
        row , column = self.IntToCoordinates(buttonNumber)
        self.gameMatrix[row][column].ToggleFlag()

    def IntToCoordinates(self, i):
        if i < 0 :
            raise ValueError
        row = int(i / self.columnSize)
        column = i % self.columnSize
        return (row, column)

    def CoordinatesToInt(self, row, column):
        return column + row * self.columnSize

    def PropagateZeros(self, row, column):
        propagateList=[]
        def FloodFill(row, column):
            rowRange = range (row-1, row + 2)
            columnRange = range (column -1, column + 2)

            for i in rowRange:
                for j in columnRange:
                    #Inside row boundaries and Column boundaries and not flagged cell and not the initial cell (row column)
                    if ( 0 <= i < self.rowSize and 0 <= j < self.columnSize and self.gameMatrix[i][j].flag == False and self.gameMatrix[i][j].clicked == False and not (i==row and j==column)):
                        if (i,j) in propagateList:
                            continue
                        else:
                            propagateList.append((i,j))
                            if (self.gameMatrix[i][j].value == 0):
                                FloodFill(i, j)
        FloodFill(row, column)

        return propagateList

    def ShowMines(self):
        return self.minesInt

    def PrintGameMatrix(self, matrix):
        aux_matrix = [[matrix[p][o].value for o in range(self.columnSize)] for p in range(self.rowSize)]
        pprint.pprint(aux_matrix, indent=4, width=200)
        return aux_matrix

class Cell():

    def __init__(self):
        self.flag = False
        self.clicked = False
        #-1 means mine
        self.value = 0

    def ToggleFlag(self):
        if self.flag == True:
            self.flag = False
        else:
            self.flag = True

    def SetClicked(self):
        self.clicked=True


# 5. 2520 - самое маленькое число, которое делится без остатка на все числа от 1 до 10.
# Какое самое маленькое число делится нацело на все числа от 1 до 20?

from Python_introduction.HWSem2.AddTask4 import get_primes  # import of the method from another task solved

def min_number(n):
    """
    :param n: max_number
    :return: the min_number for which: min_number % i = 0, i from 1 to max_number
    """
    primes = get_primes(int(n ** 0.5) + 1)

    def get_factors(number):
        """
        :param number: number to be factorized
        :return: factorization dictionary
        """
        factor_dict = {1: 1}  # factor dictionary initialization
        for prime in primes:
            if prime * prime > number:  # get prime factors before sqrt(number)
                break
            while number != 1 and number % prime == 0:
                number /= prime
                if prime in factor_dict:
                    factor_dict[prime] += 1  # increases a power (value) of this prime factor
                else:
                    factor_dict[prime] = 1  # adds a new prime factor to the dict
            if number == 1:  # if a number is equal to one -> factorization is over
                break
        if number != 1:  # the last factor that is bigger than sqrt(number) is the prime factor (like in 2*3*17: 17 is the one)
            factor_dict[number] = 1
        return factor_dict

    res_factor_dict = {1: 1}
    product = 1

    for i in range(2, n + 1):  # for all elements from 2 to n we build a unique factors dictionary
        curr_f_dict = get_factors(i)
        for item in curr_f_dict:
            if item in res_factor_dict:  # if the factor is already in the res_factor_dict
                res_factor_dict[item] = max(res_factor_dict[item], curr_f_dict[item])  # if the power is larger -> extends the factors dictionary
            else:
                res_factor_dict[item] = curr_f_dict[item]  # if the factors' dictionary does not contain the current factor -> adds it with its power

    for i in res_factor_dict:  # here we're building the product
        product *= int(i ** res_factor_dict[i])

    print(res_factor_dict)

    # print(res_factor_dict) # dictionary checking

    return product

print(min_number(10))
print(min_number(20))
print(min_number(100))

print(min_number(100000))  # optimization checking


class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.

        """
        if len(nums) in [0, 1]:
            return nums

        nonzeroCount = 0

        for element in nums:
            if element != 0:
                nonzeroCount += 1

        insertPtr = 0
        currPtr = 0

        while nonzeroCount > 0 and currPtr < len(nums):
            print("currPtr {} , insertPtr {}, nonzeroCount {}".format(currPtr, insertPtr, nonzeroCount))

            if currPtr != insertPtr and nums[currPtr] != 0:
                nums[insertPtr] = nums[currPtr]
                nums[currPtr] = 0
                insertPtr += 1
                nonzeroCount -= 1
                print("Index {}, NewVal {}".format(insertPtr, nums[insertPtr]))

            if currPtr == insertPtr and nums[currPtr] != 0:
                insertPtr += 1

            currPtr += 1


from stevedore import extension

class Extensions:
    """Lazy singleton container for stevedore extensions.

    Loads each namespace when requested for the first time.
    """

    _managers = {}

    def __init__(self):
        raise NotImplementedError()

    @classmethod
    def get(cls, namespace, name):
        manager = cls._managers.get(namespace)
        if manager is None:
            manager = cls._load_namespace(namespace)
        return manager[name].plugin

    @classmethod
    def _load_namespace(cls, namespace):
        manager = extension.ExtensionManager(namespace)
        cls._managers[namespace] = manager
        return manager


# https://www.codewars.com/kata/58ad388555bf4c80e800001e

def cut_the_ropes(arr):
    res = [len(arr)]
    for i in arr:
        m = min(arr)
        arr = [x - m for x in arr if x > m]
        rem = len(arr) - arr.count(0)
        if rem == 0:
            return res
        res.append(rem)


#program to verify mobile number using regex
import re

# \w [a-zA-Z0-9]
#\W  [^a-zA-Z0-9]

phn = "412-555a-1212"

if(re.search("\d{3}-\d{3}-d{4}", phn)):
    print("It is a phone number")
else:
    print("Invalid phone number")


import re
import requests
from selenium import webdriver
from xvfbwrapper import Xvfb
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.common import exceptions

class YTGrabber:
    '''
    Класс принимает Youtube URL страниц, все плейлисты, плейлист и все видео,
    и возваращает все видеоматериалы данной страницы.
    '''
    driver = None
    vdisplay = None

    def _check_valid_url(self, url):

        if type(url) is int:
            raise TypeError("URL is not to be int type!")

        self.url = url.strip()

        if re.match(r"https://www\.youtube\.com/(playlist\?list=|channel/)[\w]+(/playlists|/videos)", self.url):
            return True

        if re.match(r"https://www\.youtube\.com/(playlist\?list=|channel/)[\w]+", self.url):
            return True

        raise ValueError("URL is not correct!")

    def _get_page(self, url):
        self._check_valid_url(url)

        resp = requests.get(self.url)

        if resp.text.find("404 Not Found") >= 0:
            raise ValueError("'{}' , страница не найдена либо не существует".format(self.url))

        if resp.text.find("Произошла ошибка! - YouTube") >= 0:
            raise ValueError("'{}' , Произошла ошибка! - YouTube".format(self.url))

        self.driver.get(self.url)

        return True

    def get_content(self, url):
        self._get_page(url)

        preload = True

        html = WebDriverWait(self.driver, 3).until(EC.presence_of_element_located((By.TAG_NAME , "html")), "Содержимое не найден или его нет !")

        while preload:
            html.send_keys(Keys.END)
            try:
                WebDriverWait(self.driver, 3).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#contents #contents #continuations #spinner")))
            except:
                preload = False

        items = self.driver.find_elements(By.CSS_SELECTOR , "#contents #contents #items > *")

        if not items:
             items = self.driver.find_elements(By.CSS_SELECTOR , "#contents #contents #contents > *")

        if not items:
            raise ValueError("Содержимое не найден или его нет !")

        videos = []

        for item in items:
            videos.append({
                "title": item.find_element_by_id("video-title").get_attribute("title"),
                "href": item.find_element_by_id("video-title").get_attribute("href") or item.find_element_by_class_name("ytd-thumbnail").get_attribute("href"),
                "thumbnail": item.find_element_by_id("img").get_attribute("src"),
            })

        return videos

    def __enter__(self):
        self.vdisplay = Xvfb()
        self.vdisplay.start()

        options = webdriver.ChromeOptions()
        options.handless = False
        options.add_argument("--no-sandbox")
        options.add_argument("--disable-setuid-sandbox")

        self.driver = webdriver.Chrome(options=options, executable_path="driver/chromedriver")

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if self.driver:
            self.driver.close()

        if self.vdisplay:
            self.vdisplay.stop()