import sympy as sym
import mpmath
import numpy
import pylab
import time

def lagrange_series(N):
  psi = []
#  h = Rational(1, N)
  h = 1.0/N
  points = [i*h for i in range(N+1)]
  for i in range(len(points)):
    p = 1
    for k in range(len(points)):
      if k != i:
        p *= (x - points[k])/(points[i] - points[k])
    psi.append(p)
  psi = psi[1:-1]
  return psi

def bernstein_series(N):
  # FIXME: check if a normalization constant is common in the definition
  # advantage is that the basis is always positive
  psi = []
#  for k in range(0,N+1):
  for k in range(1,N):  # bc elsewhere
    psi_k = x**k*(1-x)**(N-k)
    psi.append(psi_k)
  return psi

def sin_series(N):
  # FIXME: do not satisfy bc
  psi = []
  for k in range(1,N):
    psi_k = sin(pi*k*x)
    psi.append(psi_k)
  return psi

def taylor_series(N):
  # FIXME: do not satisfy bc
  print("Cannot with current BC implementation")
  return
  psi = []
  for k in range(1,N):
    psi_k = x**k
    psi.append(psi_k)
  return psi

def series(series_type, N):
  if series_type=="Taylor" : return taylor_series(N) # cannot do with current implementation of bc
  elif series_type=="sin"  : return sin_series(N)
  elif series_type=="Bernstein"  : return bernstein_series(N)
  elif series_type=="Lagrange"  : return lagrange_series(N)
  else: print("series type unknown ") # sys.exit(0)

x = sym.Symbol("x")
integrand_type = "stiffness"

bstime = []
lstime = []

bqtime = []
lqtime = []

Ns = [2, 4, 8, 16, 32]

for N in Ns:
  t0 = time.time()
  bpsi = series("Bernstein", N)
  A = sym.zeros((N-1), (N-1))
  for i in range(0, N-1):
    for j in range(0, N-1):
      integrand = 0
      if integrand_type == "mass": integrand = bpsi[i]*bpsi[j]
      if integrand_type == "stiffness": integrand = sym.diff(bpsi[i],x)*sym.diff(bpsi[j],x)
      integrand = sym.lambdify([x], integrand)
      A[i,j] = mpmath.quad(integrand, [0, 1])
  t1 = time.time()
  bqtime.append(t1-t0)

for N in Ns:
  t0 = time.time()
  lpsi = series("Lagrange", N)
  A = sym.zeros((N-1), (N-1))
  for i in range(0, N-1):
    for j in range(0, N-1):
      integrand = 0
      if integrand_type == "mass": integrand = lpsi[i]*lpsi[j]
      if integrand_type == "stiffness" : integrand = sym.diff(lpsi[i],x)*sym.diff(lpsi[j],x)
      integrand = sym.lambdify([x], integrand)
      A[i,j] = mpmath.quad(integrand, [0,1])
  t1 = time.time()
  lqtime.append(t1-t0)

for N in Ns:
  t0 = time.time()
  bpsi = series("Bernstein", N)
  A = sym.zeros((N-1), (N-1))
  for i in range(0, N-1):
    for j in range(0, N-1):
      integrand = 0
      if integrand_type == "mass": integrand = bpsi[i]*bpsi[j]
      if integrand_type == "stiffness": integrand = sym.diff(bpsi[i],x)*sym.diff(bpsi[j],x)
      A[i,j] = sym.integrate(integrand, (x, [0, 1]))
  t1 = time.time()
  bstime.append(t1-t0)

for N in Ns:
  t0 = time.time()
  lpsi = series("Lagrange", N)
  A = sym.zeros((N-1), (N-1))
  for i in range(0, N-1):
    for j in range(0, N-1):
      integrand = 0
      if integrand_type == "mass": integrand = lpsi[i]*lpsi[j]
      if integrand_type == "stiffness" : integrand = sym.diff(lpsi[i],x)*sym.diff(lpsi[j],x)
      A[i,j] = sym.integrate(integrand, (x, [0, 1]))
  t1 = time.time()
  lstime.append(t1-t0)

print("Berstein quadrature ", bqtime)
print("Lagrange quadrature ", lqtime)
print("Bernstein symbolic ", bstime)
print("Lagrange symbolic ", lstime)

import pylab
pylab.loglog(Ns, bqtime)
pylab.loglog(Ns, lqtime)
pylab.loglog(Ns, bstime)
pylab.loglog(Ns, lstime)
pylab.loglog(Ns, [4*10**-4*N**2 for N in Ns])
pylab.loglog(Ns, [10**-4*N**4 for N in Ns])
pylab.legend(["Bernstein quad", "Lagrange quad", "Berstein symb", "Lagrange symb", "N**2", "N**4"], loc="upper left")
pylab.show()


# 나이트의 이동 https://www.acmicpc.net/problem/7562
"""
나이트가 한 번에 이동할 수 있는 칸
dx = [-1, 1, -2, 2, -2, -1, 1, 2]
dy = [2, 2, 1, 1, -1, -2, -2, -1]
나이트가 이동하려고 하는 칸이 주어진다.
나이트는 몇 번 움직이면 이 칸으로 이동할 수 있을까?
"""
import sys
from collections import deque

dx = [-1, 1, -2, 2, -2, -1, 1, 2]
dy = [2, 2, 1, 1, -1, -2, -2, -1]

for _ in range(int(sys.stdin.readline())):
    length = int(sys.stdin.readline()) # 체스판 한 변의 길이
    curr = tuple(map(int, sys.stdin.readline().split())) # 현재 위치
    goal = tuple(map(int, sys.stdin.readline().split())) # 목표 위치

    count = 0 # 최소 몇 번만에 이동할 수 있는지
    visited = [[-1 for _ in range(length)] for _ in range(length)]
    queue = deque([curr])
    visited[curr[0]][curr[1]] = 0 # 시작 위치는 0으로 둠

    while queue:
        x, y = queue.popleft()

        if x == goal[0] and y == goal[1]:
            count = visited[x][y]
            break

        for i in range(8):
            nx, ny = x + dx[i], y + dy[i]
            if 0 <= nx < length and 0 <= ny < length:
                if visited[nx][ny] == -1:
                    queue.append((nx, ny))
                    visited[nx][ny] = visited[x][y] + 1

    print(count)


import cv2
import numpy as np
import matplotlib.pyplot as plt
import json
import multiprocessing as mp

from src.process.dataloader import *

from pytesseract import Output
import pytesseract

def string_to_bag_of_chars(string):

    base = [0 for _ in range(256)]
    for l in string: base[ord(l)] += 1

    return base

def ad_contours_mp(boxes_bbx, contours, hierarchy, thread, num_threads):

    for n in range(thread, len(contours), num_threads):
        c = contours[n]
        if hierarchy[0][n][-2] == -1: continue
        rect = cv2.boundingRect(c)
        if rect[2] < 100 or rect[3] < 100: continue
        x,y,w,h = rect
        # cv2.rectangle(copied,(x,y),(x+w,y+h),(255, 0, 0),2)
        boxes_bbx[n] = (x, y, w, h)

    return None

def ad_detector(img):

    # copied = cv2.cvtColor(img.copy(), cv2.COLOR_GRAY2BGR)

    # Processing operations
    ret, thresh = cv2.threshold(img, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY_INV) # Letters (1) Background (0)
    dst = cv2.cornerHarris(thresh,10,3,0.04)
    dst = (dst - dst.min()) / (dst.max() - dst.min()) * 255
    ret, thresh = cv2.threshold(dst.astype(np.uint8), 0, 255, cv2.THRESH_OTSU)

    horizontalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (10, 1))
    blops = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10))

    horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, blops)
    horizontal = cv2.morphologyEx(thresh, cv2.MORPH_DILATE, horizontalStructure.T)

    contours, hierarchy = cv2.findContours(horizontal, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    boxes_bbx = [0 for i in range(len(contours))]
    threads = 8

    L = mp.Manager().list(boxes_bbx)
    processes = [mp.Process(target = ad_contours_mp, args=(L, contours, hierarchy, i, threads)) for i in range(threads)]
    [p.start() for p in processes]
    [p.join() for p in processes]

    return list(L)

def crop_words(bbx):

    d = pytesseract.image_to_data(bbx, lang = 'spa', nice = 5, output_type=Output.DICT)
    n_boxes = len(d['level'])
    text = []

    for i in range(n_boxes):

        detection = d['text'][i]
        if len(detection)!=0: text.append(detection)

    return text

def ad_to_json(bbx):

    words = crop_words(bbx)

    return words

def file_to_json(doc):

    bbxs = ad_detector(doc)

    res = {}
    for n, bbx in enumerate(bbxs):
        if not bbx: continue
        x, y, h, w = bbx
        res[n] = {"ocr": ad_to_json(doc[y:y+h, x:x+w]), 'bbx': bbx}

    return res

def all_files_json(dataloader):

    json_collection = {"files": {}}

    for num_document in range(len(dataloader)):

        print(f"Processant {num_document}\t",)

        document = dataloader[num_document][0]
        name = dataloader.files[num_document].strip()

        json_collection['files'][num_document] = {'filename': name, 'ads': file_to_json(document)}

    return json_collection

def compute(filenames):
    files = DataAnuncis(filenames)
    json_all = all_files_json(files)
    with open("./src/jsons/results.json", "wb") as outfile:
        string = json.dumps(json_all)
        outfile.write(string.encode('utf-8'))


class Solution:
    def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int:
        graph = defaultdict(list)

        for i in range(len(times)):
            start, end , time = times[i]
            graph[start].append((time,end))

        dis = [float("inf")] * (n+1)
        dis[0]= 0
        queue = []
        heapq.heappush(queue, (0,k))
        visited = set()

        while queue:
            n = len(queue)
            for i in range(n):
                time, cur = heapq.heappop(queue)
                if cur in visited: continue
                visited.add(cur)
                dis[cur] = time
                for i, node in graph[cur]:
                    heapq.heappush(queue, (time + i, node))

        if max(dis) == float("inf"): return -1
        else:
            return max(dis)


import torch
import torch.nn as nn
import torch.nn.functional as F

class FocalLoss(nn.Module):
    'Focal Loss - https://arxiv.org/abs/1708.02002'

    def __init__(self, alpha=0.25, gamma=2):
        super().__init__()
        self.alpha = alpha
        self.gamma = gamma

    def forward(self, pred_logits, target):
        pred = pred_logits.sigmoid()
        ce = F.binary_cross_entropy_with_logits(pred_logits, target, reduction='none')
        alpha = target * self.alpha + (1. - target) * (1. - self.alpha)
        pt = torch.where(target == 1, pred, 1 - pred)
        return alpha * (1. - pt) ** self.gamma * ce

class SmoothL1Loss(nn.Module):
    'Smooth L1 Loss'

    def __init__(self, beta=0.11):
        super().__init__()
        self.beta = beta

    def forward(self, pred, target):
        x = (pred - target).abs()
        l1 = x - 0.5 * self.beta
        l2 = 0.5 * x ** 2 / self.beta
        return torch.where(x >= self.beta, l1, l2)

class LossBinary(nn.Module):
    """
    Loss defined as \alpha BCE - (1 - \alpha) SoftJaccard
    """

    def __init__(self, jaccard_weight=0.3):
        super().__init__()
        self.nll_loss = nn.BCEWithLogitsLoss()
        self.jaccard_weight = jaccard_weight

    def forward(self, outputs, targets):
        loss = (1 - self.jaccard_weight) * self.nll_loss(outputs, targets)

        if self.jaccard_weight:
            eps = 1e-15
            jaccard_target = (targets == 1).float()
            jaccard_output = F.sigmoid(outputs)

            intersection = (jaccard_output * jaccard_target).sum()
            union = jaccard_output.sum() + jaccard_target.sum()

            loss -= self.jaccard_weight * torch.log((intersection + eps) / (union - intersection + eps))
        return loss


from typing import Sequence, Tuple

import numpy as np
import torch
from scipy.signal import resample
from torch import Tensor
from wfdb import Record

class Resample:
  def __init__(self, fs: int):
    assert fs > 0
    self.fs = fs

  def __call__(self, record: Record) -> Record:
    if record.fs != self.fs:
      size, _ = record.p_signal.shape
      resampled_length = int(size * self.fs / record.fs)
      p_signal = resample(record.p_signal, num=resampled_length)
      return Record(
        p_signal=p_signal,
        record_name=record.record_name,
        fs=self.fs,
        sig_name=record.sig_name,
        comments=record.comments)
    return record

class CenterCrop:
  def __init__(self, size: int):
    assert size > 0
    self.size = size

  def __call__(self, record: Record) -> Record:
    size, _ = record.p_signal.shape
    if size > self.size:
      offset = (size - self.size) // 2
      p_signal = record.p_signal[offset:offset + self.size]
      return Record(
        p_signal=p_signal,
        record_name=record.record_name,
        fs=record.fs,
        sig_name=record.sig_name,
        comments=record.comments)
    return record

class MaskedPad:
  def __init__(self, size):
    assert size > 0
    self.size = size

  def __call__(self, record: Record) -> Tuple[Record, Tensor]:
    size, num_channels = record.p_signal.shape
    if size < self.size:
      sig_start = self.size - size
      p_signal = np.zeros_like(record.p_signal, shape=(self.size, num_channels))
      p_signal[sig_start:] = record.p_signal
      mask = torch.zeros(self.size)
      mask[sig_start:] = 1.
    else:
      p_signal = record.p_signal
      mask = torch.ones(size)
    record = Record(
      p_signal=p_signal,
      record_name=record.record_name,
      fs=record.fs,
      sig_name=record.sig_name,
      comments=record.comments)
    return record, mask

class Normalize:
  def __call__(self, record: Record) -> Record:
    mean = record.p_signal.mean(axis=0)
    std = record.p_signal.std(axis=0)
    p_signal = (record.p_signal - mean) / (std + 1e-9)
    return Record(
      p_signal=p_signal,
      record_name=record.record_name,
      fs=record.fs,
      sig_name=record.sig_name,
      comments=record.comments)

class SelectLeads:
  def __init__(self, leads: Sequence[str]):
    assert len(set(leads)) == len(leads)  # all leads are unique
    self.leads = leads

  def __call__(self, record: Record) -> Record:
    lead_indices = []
    for selected_lead in self.leads:
      lead_indices.append(record.sig_name.index(selected_lead))
    p_signal = record.p_signal[:, lead_indices]
    sig_name = list(self.leads)
    return Record(
      p_signal=p_signal,
      record_name=record.record_name,
      fs=record.fs,
      sig_name=sig_name,
      comments=record.comments)

class ReplaceNaN:
  """Replace nan with the mean computed over an entire lead."""
  def __call__(self, record: Record) -> Record:
    if np.isnan(record.p_signal).any():
      _, num_channels = record.p_signal.shape
      mean = np.nanmean(record.p_signal, axis=0)
      p_signal = record.p_signal.copy()
      for i in range(num_channels):
        np.nan_to_num(p_signal[:, i], copy=False, nan=mean[i])
      return Record(
        p_signal=p_signal,
        record_name=record.record_name,
        fs=record.fs,
        sig_name=record.sig_name,
        comments=record.comments)
    return record

class ToTensor:
  def __init__(self, channels_first: bool = False):
    self.channels_first = channels_first

  def __call__(self, record: Record) -> Tensor:
    p_signal = torch.from_numpy(record.p_signal).float()
    if self.channels_first:
      p_signal = p_signal.transpose(0, 1)
    return p_signal


import numpy as np
from scipy import stats, linalg

class StatFunctions():
    def false_discovery_rate(p_values, q = 0.05):
        if q < 0:
            q = 0
        elif q > 1:
            q = 1

        x = np.arange(len(p_values))/len(p_values)
        p_values = np.sort(p_values)

        index = np.sum(p_values <= q*x)
        if index > 0:
            r = p_values[index]
        else:
            r = 0
        return r

    def quantiles(values, P = 100):
        assert len(values) > 0, 'No elements in values'
        if len(values.shape) == 1:
            return StatFunctions.quantiles_1d(values, P)
        elif len(values.shape) == 2:
            return StatFunctions.quantiles_2d(values, P)
        elif len(values.shape) == 3:
            return StatFunctions.quantiles_3d(values, P)

    def quantiles_1d(values, P = 100):
        # NOTE the implementation of percentile in python might differ from quantile in matlab
        percentiles = []
        for k in range(P):
            percentiles.append(np.percentile(values, k*100/(P-1)))
        Q = np.array(percentiles)
        return Q

    def quantiles_2d(values, P = 100):
        Q = []
        for i in range(values.shape[1]):
            current_values = values[:,i].copy()
            # NOTE the implementation of percentile in python might differ from quantile in matlab
            percentiles = []
            for k in range(P):
                percentiles.append(np.percentile(current_values, k*100/(P-1)))
            Q.append(percentiles)
        Q = np.array(Q).T
        return Q

    def quantiles_3d(values, P = 100):
        Q = np.zeros([P, values.shape[1], values.shape[2]])
        for i in range(values.shape[1]):
            for j in range(values.shape[2]):
                current_values = values[:,i,j].copy().T
                # NOTE the implementation of percentile in python might differ from quantile in matlab
                percentiles = []
                for k in range(P):
                    percentiles.append(np.percentile(current_values, k*100/(P-1)))
                Q[:,i,j] = np.array(percentiles)
        Q = np.squeeze(Q)
        return Q

    def p_value(observed_difference, random_differences, single = True):
        assert len(np.shape(observed_difference)) == len(np.shape(random_differences)) - 1
        if isinstance(random_differences, list):
            random_differences = np.array(random_differences)
        M = random_differences.size
        if len(np.shape(observed_difference)) == 0:
            return StatFunctions.p_value_scalar(observed_difference, random_differences, single)
        elif len(np.shape(observed_difference)) == 1:
            return StatFunctions.p_value_vector(observed_difference, random_differences, single)
        elif len(np.shape(observed_difference)) == 2:
            return StatFunctions.p_value_matrix(observed_difference, random_differences, single)

    def p_value_scalar(observed_difference, random_differences, single):
        M = len(random_differences) + 1
        normalized_observed_difference = observed_difference - np.mean(random_differences)
        normalized_random_differences = random_differences - np.mean(random_differences)
        if single:
            if normalized_observed_difference > 0:
                p_value = (np.sum(normalized_random_differences > normalized_observed_difference) + 1) / M
            else:
                p_value = (np.sum(normalized_random_differences < normalized_observed_difference) + 1) / M
        else:
            p_value = (np.sum(np.abs(normalized_random_differences) > np.abs(normalized_observed_difference)) + 1) / M
        return p_value

    def p_value_vector(observed_difference, random_differences, single):
        N = np.shape(random_differences)[-1]
        p_value = np.ones(N)
        for n in range(N):
            p_value[n] = StatFunctions.p_value_scalar(observed_difference[n], random_differences[:,n], single)
        return p_value

    def p_value_matrix(observed_difference, random_differences, single):
        N = np.shape(random_differences)[-1]
        p_value = np.ones([N, N])
        for n in range(N):
            p_value[n,:] = StatFunctions.p_value_vector(observed_difference[:,n], random_differences[:,:,n], single)
        return p_value

    def bonferroni(p_values, p):
        # calculates the Bonferroni correction for p-values. p is the starting p-value.
        r = p / len(p_values)
        return r

    def correlation(data, correlation_type):
        correlation_type = correlation_type.replace(' ', '_')
        corr = np.zeros((data.shape[1], data.shape[1]), dtype=np.float)
        try:
            correlation_function = eval('StatFunctions.correlation_{}'.format(correlation_type))
            corr = correlation_function(data)
        except Exception as e:
            print('Correlation function {} not implemented'.format(correlation_type))
            print(e)
        return corr

    def correlation_pearson(data):
        return np.corrcoef(data)

    def correlation_spearman(data):
        rank = np.argsort(data)
        return np.corrcoef(rank)

    def correlation_kendall(data):
        correlation = np.zeros((data.shape[0], data.shape[0]))
        for i in range(data.shape[0]):
            for j in range(data.shape[0]):
                correlation[i, j] = stats.kendalltau(data[i], data[j])[0]
        return correlation

    def correlation_partial_pearson(data):
        data = data.T
        data = np.asarray(data)
        nodes = data.shape[1]
        correlation = np.zeros((nodes, nodes), dtype=np.float)
        for i in range(nodes):
            correlation[i, i] = 1
            for j in range(i+1, nodes):
                idx = np.ones(nodes, dtype=np.bool)
                idx[i] = False
                idx[j] = False
                beta_i = linalg.lstsq(data[:, idx], data[:, j])[0]
                beta_j = linalg.lstsq(data[:, idx], data[:, i])[0]
                res_j = data[:, j] - data[:, idx].dot(beta_i)
                res_i = data[:, i] - data[:, idx].dot(beta_j)
                corr = stats.pearsonr(res_i, res_j)[0]
                correlation[i, j] = corr
                correlation[j, i] = corr
        return correlation

    def correlation_partial_spearman(data):
        data = data.T
        data = np.asarray(data)
        nodes = data.shape[1]
        correlation = np.zeros((nodes, nodes), dtype=np.float)
        for i in range(nodes):
            correlation[i, i] = 1
            for j in range(i+1, nodes):
                idx = np.ones(nodes, dtype=np.bool)
                idx[i] = False
                idx[j] = False
                beta_i = linalg.lstsq(data[:, idx], data[:, j])[0]
                beta_j = linalg.lstsq(data[:, idx], data[:, i])[0]
                res_j = data[:, j] - data[:, idx].dot(beta_i)
                res_i = data[:, i] - data[:, idx].dot(beta_j)
                corr = stats.spearmanr(res_i, res_j)[0]
                correlation[i, j] = corr
                correlation[j, i] = corr
        return correlation


def lengthOfLongestSubstring(s):
        if s == "":
            return 0
        def longestStartingAt(st):
            seen = set()
            j = 0
            while j < len(st):
                if st[j] in seen:
                    return len(seen)
                else:
                    seen.add(st[j])
                j+=1
            return len(seen)

        return max([longestStartingAt(s[i:]) for i in range(len(s))])

print(lengthOfLongestSubstring("abcabcbb"))
print(lengthOfLongestSubstring("bb"))


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from compas.utilities import pairwise

from compas.datastructures import mesh_flip_cycles
from compas.datastructures import Mesh
from compas_rhino.artists import MeshArtist

mesh = Mesh.from_json('cablenet.json')

# make lookup dicts for vertex normals of the cablenet
key_normal = {key: mesh.vertex_normal(key) for key in mesh.vertices()}

# ==============================================================================
# Intrados and extrados
# ==============================================================================

idos = mesh.copy()
edos = idos.copy()

# offset the intrados from the cablenet
# by 2cm in the direction of the corresponding cablenet vertex normal
for key, attr in idos.vertices(True):
    nx, ny, nz = key_normal[key]

    attr['x'] += 0.02 * nx
    attr['y'] += 0.02 * ny
    attr['z'] += 0.02 * nz

# offset the intrados from the intrados
# by 2cm in the direction of the corresponding cablenet vertex normal
for key, attr in edos.vertices(True):
    nx, ny, nz = key_normal[key]

    attr['x'] += 0.06 * nx
    attr['y'] += 0.06 * ny
    attr['z'] += 0.06 * nz

# ==============================================================================
# Concrete volume
# ==============================================================================

volume = idos.copy()
volume.name = 'concrete1'

# flip its cycles to make the bottom normals point downwards
mesh_flip_cycles(volume)

# set the key offset
dkey = volume._max_int_key + 1

# add the vertices of the extrados
for key, attr in edos.vertices(True):
    volume.add_vertex(key=key + dkey, **attr)

# add the faces of the extrados
for fkey in edos.faces():
    vertices = edos.face_vertices(fkey)
    vertices = [key + dkey for key in vertices]

    volume.add_face(vertices)

# construct a polygon of boundary vertices
boundary = edos.vertices_on_boundary(ordered=True)
boundary.append(boundary[0])

# add the "side" faces
for a, b in pairwise(boundary):
    volume.add_face([b, a, a + dkey, b + dkey])

# ==============================================================================
# Export and visualisation
# ==============================================================================

# export
volume.to_json('concrete1.json')

# visualize
artist = MeshArtist(volume, layer="Concrete1")
artist.clear_layer()
artist.draw_mesh(color=(0, 0, 255))


import random

from discord import Message
from discord.ext import commands

class Alea(commands.Cog, name="Juste Prix", description="Juste Prix le jeux"):
    def __init__(self, bot: commands.Bot) -> None:
        super().__init__()
        self.bot = bot
        self.juste_prix = -1

    #      ██╗██╗   ██╗███████╗████████╗███████╗    ██████╗ ██████╗ ██╗██╗  ██╗
    #      ██║██║   ██║██╔════╝╚══██╔══╝██╔════╝    ██╔══██╗██╔══██╗██║╚██╗██╔╝
    #      ██║██║   ██║███████╗   ██║   █████╗      ██████╔╝██████╔╝██║ ╚███╔╝
    # ██   ██║██║   ██║╚════██║   ██║   ██╔══╝      ██╔═══╝ ██╔══██╗██║ ██╔██╗
    # ╚█████╔╝╚██████╔╝███████║   ██║   ███████╗    ██║     ██║  ██║██║██╔╝ ██╗
    #  ╚════╝  ╚═════╝ ╚══════╝   ╚═╝   ╚══════╝    ╚═╝     ╚═╝  ╚═╝╚═╝╚═╝  ╚═╝
    @commands.command()
    async def alea(self, ctx: commands.Context, stop=""):
        """Pick a random number between 0 and 1000,
        i will tell to the next message if they are close to it.
        if you specify any argument after this command, it will stop the alea
        """
        if stop != "":
            self.juste_prix = -1
        else:
            self.juste_prix = random.randint(0, 1000)
        await ctx.channel.send("Just Prix started")

    @commands.Cog.listener("on_message")
    async def wait_message_juste_prix(self, message: Message):
        if self.juste_prix != -1:
            if int(message.content) < self.juste_prix:
                await message.channel.send("plus haut")
            if int(message.content) > self.juste_prix:
                await message.channel.send("plus bas")
            if int(message.content) == self.juste_prix:
                await message.channel.send("c'est ça !")
                self.juste_prix = -1

async def setup(bot: commands.Bot):
    await bot.add_cog(Alea(bot))
    print(f"cog loaded: {__file__}")

async def teardown(bot: commands.Bot):
    print(f"cog unloaded: {bot}{__file__}")


# -*- coding: UTF-8 -*-
"""
title: 可互换矩形的组数
You are given n rectangles represented by a 0-indexed 2D integer array rectangles, where rectangles[i] = [widthi, heighti] denotes the width and height of the ith rectangle.
Two rectangles i and j (i < j) are considered interchangeable if they have the same width-to-height ratio. More formally, two rectangles are interchangeable if widthi/heighti == widthj/heightj (using decimal division, not integer division).
Return the number of pairs of interchangeable rectangles in rectangles.

Example 1:
Input: rectangles = [[4,8],[3,6],[10,20],[15,30]]
Output: 6
Explanation: The following are the interchangeable pairs of rectangles by index (0-indexed):
- Rectangle 0 with rectangle 1: 4/8 == 3/6.
- Rectangle 0 with rectangle 2: 4/8 == 10/20.
- Rectangle 0 with rectangle 3: 4/8 == 15/30.
- Rectangle 1 with rectangle 2: 3/6 == 10/20.
- Rectangle 1 with rectangle 3: 3/6 == 15/30.
- Rectangle 2 with rectangle 3: 10/20 == 15/30.

Example 2:
Input: rectangles = [[4,5],[7,8]]
Output: 0
Explanation: There are no interchangeable pairs of rectangles.

Constraints:
n == rectangles.length
1 <= n <= 10^5
rectangles[i].length == 2
1 <= widthi, heighti <= 10^5
"""
from collections import defaultdict
from typing import List

class Solution:
    def interchangeableRectangles(self, rectangles: List[List[int]]) -> int:
        def gcd(a: int, b: int) -> int:
            while b:
                a, b = b, a % b
            return a

        ratio2cnt = defaultdict(int)
        for w, h in rectangles:
            g = gcd(w, h)
            ratio2cnt[(w // g, h // g)] += 1
        res = 0
        for cnt in ratio2cnt.values():
            # 组合数 cnt个矩形中任选2个进行互换
            res += cnt * (cnt - 1) // 2
        return res

    def interchangeableRectangles_2(self, rectangles: List[List[int]]) -> int:
        def gcd(a: int, b: int) -> int:
            while b:
                a, b = b, a % b
            return a

        ratio2cnt = defaultdict(int)
        res = 0
        for w, h in rectangles:
            g = gcd(w, h)
            # cnt * (cnt - 1) // 2 = 0 + 1 + 2 + …… + cnt-1 = sum(range(cnt))
            res += ratio2cnt[(w // g, h // g)]
            ratio2cnt[(w // g, h // g)] += 1
        return res

if __name__ == '__main__':
    print(Solution().interchangeableRectangles_2(rectangles=[[4, 8], [3, 6], [10, 20], [15, 30]]))


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

import json

data = {
	"operator": "ct",
	"vendor" : "xx",
	"timestamp" : "20190705",
	"data" : {
		"id" : 1,
		"age" : 18,
		"city" : "shanghai",
		"top" : ["com","cn"]
	}
}

print(type(data))
print(data)

with open('data.json', 'w') as f:
	json.dump(data, f, sort_keys=True, indent=4, separators=(',', ': '))

with open("data.json",'r') as f:
	d = json.load(f)
	print(type(d),type(d['data']['age']))
	print(d)


from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',

	url(r'^$', 'band.views.home', name='home'),
	url(r'^bio/', 'band.views.bio', name='bio'),
    url(r'^disc/', 'band.views.disc', name='disc'),
    url(r'^tour/', 'band.views.tour', name='tour'),
    # Examples:
    # url(r'^$', 'helloworld.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
)


import pygame

class GameScreen():
    """游戏屏幕类"""
    def __init__(self, screen):
        """加载图片所在屏幕属性
        screen-Surface为图片所在屏幕Surface对象"""
        self.screen = screen  # 图片的所在屏幕->Surface
        self.screen_rect = screen.get_rect()  # 图片所在屏幕的外接矩形->Rect
        # screen为Surface对象而screen_rect为Rect对象

class Ship(GameScreen):
    """飞船"""
    def __init__(self, screen, settings):
        """初始化飞船并设置初始位置"""
        GameScreen.__init__(self, screen)
        self.image = pygame.image.load('images/ship.png')  # 获取飞船图像->Surface
        self.rect = self.image.get_rect()  # 获取飞船图片外接矩形外接
        self.rect.centerx = self.screen_rect.centerx  # 将每艘新飞船放在屏幕底部中央
        self.rect.bottom = self.screen_rect.bottom
        self.moving_right = False  # 飞船移动标志-右
        self.moving_left = False  # 飞船移动标志-左
        self.speed = settings.ship_speed  # 飞船速度
        self.centerx = float(self.rect.centerx)  # 记录飞船的中心横坐标值

    def update(self):
        """更新飞船位置"""
        if self.moving_right == 1 and \
                self.rect.right < self.screen_rect.right:  # 飞船右移
            self.centerx += self.speed
        elif self.moving_left == 1 and \
                self.rect.x > self.screen_rect.x:  # 飞船左移
            self.centerx -= self.speed
        self.rect.centerx = self.centerx  # 将飞船中心坐标值（float）赋值给飞船横坐标

    def center_ship(self):
        """将飞船位置居中"""
        self.centerx = self.screen_rect.centerx
        self.rect.centerx = self.centerx

    def paint(self):
        """在指定位置绘制飞船到Surface"""
        self.screen.blit(self.image, self.rect)

class Sky(GameScreen):
    """天空背景"""
    def __init__(self, screen):
        super().__init__(screen)
        self.images = pygame.image.load('images/sky.png')
        self.rect = self.images.get_rect()
        self.rect.x = self.screen_rect.x
        self.rect.y = self.screen_rect.y

    def paint(self):
        """绘制天空背景到Surface"""
        self.screen.blit(self.images, self.rect)

class Bullet(pygame.sprite.Sprite):
    """飞船发射的子弹"""
    def __init__(self, screen, ship, settings, bullet_shift):
        """初始化子弹及其初始位置
        screen-Surface为所在屏幕，ship-class为飞船类，
        setting-class为设置类，bullet_shift-int为子弹偏移量"""
        super().__init__()
        self.screen = screen
        self.rect = pygame.Rect(0, 0,  # 获取矩形对象
                                settings.bullet_width, settings.bullet_height)
        self.rect.centerx = ship.rect.centerx + bullet_shift  # 子弹初始横坐标
        self.rect.y = ship.rect.y  # 子弹初始纵坐标
        self.y = float(self.rect.y)  # 记录子弹纵坐标小数值
        self.color = settings.bullet_color  # 子弹颜色
        self.speed = settings.bullet_speed  # 子弹速度

    def update(self):
        """更新子弹位置"""
        self.y -= self.speed
        self.rect.y = self.y

    def paint(self):
        """绘制子弹到Surface"""
        pygame.draw.rect(self.screen, self.color, self.rect)

class Alien(pygame.sprite.Sprite, GameScreen):
    """外星人"""
    direction = 1  # 外星飞船移动方向：1为右，-1为左

    # 注：此处飞船移动方向即可作为Alien类的类属性，也可以按照书本教程作为Settings类的实例属性，
    #   但不可作为Alien类的实例属性。
    # 原因：Alien类的类属性和Settings类的实例属性，在外星飞船边缘确定时，由一个aline实例改变，
    #   则所有alien的direction值都会发生改变，而Alien的实例属性则只会改变当前alien实例自身的
    #   direction值，不能使整个外星飞船阵列统一换向。

    def __init__(self, settings, screen):
        pygame.sprite.Sprite.__init__(self)
        GameScreen.__init__(self, screen)
        # 重点！！！： 继承父类构造函数的写法：
        # 正解：（1）super().__init(...) ——括号中无self，仅包括需要传递的形参！
        #      （2）Base.__init__(self,...) ——Base表示父类，括号中既有self，又有需传递的
        #      形参，此种写法适合多继承时使用
        self.y = None   # 初始化外星飞船的位置，先为空（None），之后会赋值
        self.x = None
        self.settings = settings
        self.image = pygame.image.load('images/alien.png')
        self.rect = self.image.get_rect()  # alien图片大小：100*70

    def check_edges(self):
        """检测外星飞船是否到达屏幕边缘"""
        if self.rect.right >= self.screen_rect.right \
                or self.rect.x <= self.screen_rect.x:
            return True

    def update(self):
        """更新外星飞船位置"""
        self.x += self.settings.alien_xspeed * self.direction
        self.y += self.settings.alien_yspeed
        self.rect.x = self.x
        self.rect.y = self.y

class Button(GameScreen):
    """play按钮"""
    def __init__(self, screen, text):
        # 按钮属性
        super().__init__(screen)    # 继承游戏屏幕属性
        self.button_color = (0, 255, 0)     # 设置按钮颜色
        self.width, self.height = 150, 50   # 设置按钮宽度和高度
        self.rect = pygame.Rect(0, 0, self.width, self.height)      # 设置按钮的矩形对象
        self.rect.centerx = self.screen_rect.centerx  # 按钮位置
        self.rect.centery = self.screen_rect.centery + 100
        # 文本属性
        self.text_color = (255, 255, 255)   # 设置文本颜色
        self.font = pygame.font.SysFont('Arial', 40)    # 从系统获取字体（打包成exe时，字体不能为None）
        self.text_image = self.font.render(text, True,
                                           self.text_color,
                                           self.button_color)   # 将字体文本装换为Surface对象
        self.text_rect = self.text_image.get_rect()     # 获取文本的矩形对象
        self.text_rect.center = self.rect.center    # 设置文本矩形对象位置

    def paint(self):
        """绘制按钮到Surface"""
        self.screen.fill(self.button_color, self.rect)      # 绘制按钮背景颜色
        self.screen.blit(self.text_image, self.text_rect)   # 绘制文本的Surface对象

class Scoreboard(GameScreen):
    """计分板"""
    def __init__(self, stats, screen):
        super().__init__(screen)    # 继承游戏屏幕属性
        self.color = (100, 100, 100)    # 设置计分板文本颜色
        self.stats = stats  # 初始化游戏状态
        self.font = pygame.font.SysFont('Arial', 25)    # 设置计分板文本字体
        self.score_init()    # 实时分数计分板
        self.highest_score_init()   # 最高分计分板
        self.level_init()   # 玩家等级
        self.shipsign_init()    # 飞船标识

    def score_init(self):
        """实时分数计分板"""
        self.score = "{:,}".format(self.stats.score)    # 实时分数（并用format使数字千分位格式化）
        self.score_image = self.font.render(self.score,
                                            True, self.color)   # 获取文本Surface对象
        self.score_rect = self.score_image.get_rect()   # 获取文本Rect对象
        self.score_rect.topright = (self.screen_rect.right - 65,
                                    5)  # 设置文本位置（right，top）

    def highest_score_init(self):
        """最高分计分板"""
        self.highest_score = "{:,}".format(
            self.stats.highest_score)
        self.highest_image = self.font.render(self.highest_score,
                                              True, self.color)
        self.highest_rect = self.highest_image.get_rect()
        self.highest_rect.centerx = self.screen_rect.centerx
        self.highest_rect.y = 5

    def level_init(self):
        """玩家等级"""
        self.level = 'Lev.' + str(self.stats.level)
        self.level_image = self.font.render(self.level, True,
                                            self.color)
        self.level_rect = self.level_image.get_rect()
        self.level_rect.right = self.screen_rect.right - 18
        self.level_rect.y = self.score_rect.bottom + 5

    def shipsign_init(self):
        """剩余飞船标识"""
        self.ships = pygame.sprite.Group()      # 创建飞船标识组
        for i in range(self.stats.ships_left):  # 创建飞船标识
            shipsign = ShipSign(self.screen)
            shipsign.rect.y = 0     # 设置飞船标识位置
            shipsign.rect.x = shipsign.rect.width * i
            self.ships.add(shipsign)    # 将飞船标识添加到组中

    def update_score(self):
        """更新实时分数"""
        self.score_image = self.font.render("{:,}".format(self.stats.score),
                                            True, self.color)
    def update_highest_score(self):
        """更新最高分"""
        self.highest_score = "{:,}".format(
            self.stats.highest_score)
        self.highest_image = self.font.render(self.highest_score,
                                              True, self.color)

    def update_level(self):
        """更新玩家等级"""
        self.level = 'Lev.' + str(self.stats.level)
        self.level_image = self.font.render(self.level, True,
                                            self.color)

    def update_shipsign(self):
        """更新飞船标识"""
        self.ships.empty()  # 清空原本飞船标识
        for i in range(self.stats.ships_left):  # 根据声音飞船数创建标识
            shipsign = ShipSign(self.screen)    #创建一个飞船标识
            shipsign.rect.y = 0     # 设置飞船标识位置
            shipsign.rect.x = shipsign.rect.width * i
            self.ships.add(shipsign)    # 将飞船标识添加到组中

    def paint(self):
        """绘制计分板到Surface对象"""
        self.screen.blit(self.highest_image, self.highest_rect)
        self.screen.blit(self.score_image, self.score_rect)
        self.screen.blit(self.level_image, self.level_rect)
        self.ships.draw(self.screen)

class ShipSign(pygame.sprite.Sprite, GameScreen):
    """飞船标识"""
    def __init__(self, screen):
        pygame.sprite.Sprite.__init__(self)     # 继承精灵类
        GameScreen.__init__(self, screen)
        self.image = pygame.image.load('images/ship_sign.png')      # 加载飞船标识图片
        self.rect = self.image.get_rect()   # 获取飞船标识的矩形对象


"""
This script allows testing the back-end API by allowing data to be sent as JSON and pretty-print the JSON response
"""
import argparse
import json
import os.path

import requests

URL = 'http://localhost:8080'

METHOD_CHOICES = ('GET', 'POST', 'PUT', 'DELETE')

parser = argparse.ArgumentParser(description='Sends API requests to the back-end API to visualise the JSON response '
                                             'data')
parser.add_argument('-u', '--url', default=URL, required=False, help='The base URL where the API is hosted at')
parser.add_argument('-f', '--file', default=None, required=False, help='A request JSON file')
parser.add_argument('-e', '--endpoint', default=None, required=False, help='The endpoint to send the request to')
parser.add_argument('-d', '--data', default=None, help='The JSON data to send to the API. Can be a JSON String or a JSON file')
parser.add_argument('-H', '--headers', default=None,
                    help='Headers as a JSON-like String {"Content-Type": "application/json"}')
parser.add_argument('-m', '--method', default='GET', help='The method to send the request with',
                    choices=METHOD_CHOICES)

methods = {
    'GET': requests.get,
    'POST': requests.post,
    'PUT': requests.put,
    'DELETE': requests.delete
}

args = parser.parse_args()

FILE = args.file
ENDPOINT = args.endpoint
DATA = None
HEADERS = None

if FILE and ENDPOINT:
    parser.error('You can only provide a request file using -f or an endpoint using -e. Note that the arguments other'
                 ' than -h or -f are only valid when -e is used')
elif not FILE and not ENDPOINT:
    parser.error('You must specify either -f or -e')
elif FILE:
    if os.path.exists(FILE):
        with open(FILE, 'r') as f:
            request: dict = json.load(f)

        URL = request.get('url', URL)

        if 'endpoint' not in request:
            print('endpoint must be specified in the request file')
            exit(1)
        else:
            ENDPOINT = request.get('endpoint')

        DATA = request.get('data', None)
        HEADERS = request.get('headers', None)
        METHOD = request.get('method', 'GET')

        if METHOD not in METHOD_CHOICES:
            print(f'{METHOD} not a recognized method from {METHOD_CHOICES}')
            exit(1)
    else:
        print(f'The file {FILE} does not exist')
        exit(1)
else:
    DATA = args.data
    HEADERS = args.headers
    METHOD = args.method
    URL = args.url

if not ENDPOINT.startswith('/'):
    ENDPOINT = f'/{ENDPOINT}'

if DATA and isinstance(DATA, str):
    try:
        DATA = json.loads(DATA)
    except ValueError:
        with open(DATA, 'r') as f:
            DATA = json.load(f)

if HEADERS and isinstance(HEADERS, str):
    HEADERS = json.loads(args.headers)

def parse_response(response):
    if response.status_code >= 400:
        print(f'An error occurred: Status Code {response.status_code}')
        print(f'Response Body: {response.content.decode()}')
    else:
        print(f'Response {response.status_code}')
        print(f'JSON:')
        response_json = response.json()
        response_json = json.dumps(response_json, indent=2)
        print(response_json)

def main():
    url = f'{URL}{ENDPOINT}'

    default_headers = {'Content-Type': 'application/json'}

    if HEADERS:
        headers = {**default_headers, **HEADERS}
    else:
        headers = default_headers

    method = methods.get(METHOD, methods['GET'])
    response = method(url, json=DATA, headers=headers)

    parse_response(response)

if __name__ == '__main__':
    main()


# coding: utf-8

"""
    ExaVault API

    See our API reference documentation at https://www.exavault.com/developer/api-docs/  # noqa: E501

    OpenAPI spec version: 2.0
    Contact: support@exavault.com
    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

from __future__ import absolute_import

import re  # noqa: F401

# python 2 and python 3 compatibility library
import six

from exavault.api_client import ApiClient

class RecipientsApi(object):
    """NOTE: This class is auto generated by the swagger code generator program.

    Do not edit the class manually.
    Ref: https://github.com/swagger-api/swagger-codegen
    """

    def __init__(self, api_client=None):
        if api_client is None:
            api_client = ApiClient()
        self.api_client = api_client

    def resend_invitations_for_share(self, ev_api_key, ev_access_token, share_id, **kwargs):  # noqa: E501
        """Resend invitations to share recipients  # noqa: E501

        Resend invitations to one or all recipients attached to specified share. The most recent message that was sent for the share will be re-used for this email.  You can use [GET /shares/{id}](#operation/getShareById) to view the recipient list and message history for a share. Use [PATCH /shares/{id}](#operation/updateShareById) to add or remove recipients.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.resend_invitations_for_share(ev_api_key, ev_access_token, share_id, async_req=True)
        >>> result = thread.get()

        :param async_req bool
        :param str ev_api_key: API Key required to make the API call. (required)
        :param str ev_access_token: Access token required to make the API call. (required)
        :param int share_id: ID of the share to resend invites for. (required)
        :param ResendInvitationsRequestBody body:
        :return: ShareRecipientsResponse
                 If the method is called asynchronously,
                 returns the request thread.
        """
        kwargs['_return_http_data_only'] = True
        if kwargs.get('async_req'):
            return self.resend_invitations_for_share_with_http_info(ev_api_key, ev_access_token, share_id, **kwargs)  # noqa: E501
        else:
            (data) = self.resend_invitations_for_share_with_http_info(ev_api_key, ev_access_token, share_id, **kwargs)  # noqa: E501
            return data

    def resend_invitations_for_share_with_http_info(self, ev_api_key, ev_access_token, share_id, **kwargs):  # noqa: E501
        """Resend invitations to share recipients  # noqa: E501

        Resend invitations to one or all recipients attached to specified share. The most recent message that was sent for the share will be re-used for this email.  You can use [GET /shares/{id}](#operation/getShareById) to view the recipient list and message history for a share. Use [PATCH /shares/{id}](#operation/updateShareById) to add or remove recipients.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True
        >>> thread = api.resend_invitations_for_share_with_http_info(ev_api_key, ev_access_token, share_id, async_req=True)
        >>> result = thread.get()

        :param async_req bool
        :param str ev_api_key: API Key required to make the API call. (required)
        :param str ev_access_token: Access token required to make the API call. (required)
        :param int share_id: ID of the share to resend invites for. (required)
        :param ResendInvitationsRequestBody body:
        :return: ShareRecipientsResponse
                 If the method is called asynchronously,
                 returns the request thread.
        """

        all_params = ['ev_api_key', 'ev_access_token', 'share_id', 'body']  # noqa: E501
        all_params.append('async_req')
        all_params.append('_return_http_data_only')
        all_params.append('_preload_content')
        all_params.append('_request_timeout')

        params = locals()
        for key, val in six.iteritems(params['kwargs']):
            if key not in all_params:
                raise TypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method resend_invitations_for_share" % key
                )
            params[key] = val
        del params['kwargs']
        # verify the required parameter 'ev_api_key' is set
        if ('ev_api_key' not in params or
                params['ev_api_key'] is None):
            raise ValueError("Missing the required parameter `ev_api_key` when calling `resend_invitations_for_share`")  # noqa: E501
        # verify the required parameter 'ev_access_token' is set
        if ('ev_access_token' not in params or
                params['ev_access_token'] is None):
            raise ValueError("Missing the required parameter `ev_access_token` when calling `resend_invitations_for_share`")  # noqa: E501
        # verify the required parameter 'share_id' is set
        if ('share_id' not in params or
                params['share_id'] is None):
            raise ValueError("Missing the required parameter `share_id` when calling `resend_invitations_for_share`")  # noqa: E501

        collection_formats = {}

        path_params = {}
        if 'share_id' in params:
            path_params['shareId'] = params['share_id']  # noqa: E501

        query_params = []

        header_params = {}
        if 'ev_api_key' in params:
            header_params['ev-api-key'] = params['ev_api_key']  # noqa: E501
        if 'ev_access_token' in params:
            header_params['ev-access-token'] = params['ev_access_token']  # noqa: E501

        form_params = []
        local_var_files = {}

        body_params = None
        if 'body' in params:
            body_params = params['body']
        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.select_header_accept(
            ['application/json'])  # noqa: E501

        # HTTP header `Content-Type`
        header_params['Content-Type'] = self.api_client.select_header_content_type(  # noqa: E501
            ['application/json'])  # noqa: E501

        # Authentication setting
        auth_settings = []  # noqa: E501

        return self.api_client.call_api(
            '/recipients/shares/invites/{shareId}', 'POST',
            path_params,
            query_params,
            header_params,
            body=body_params,
            post_params=form_params,
            files=local_var_files,
            response_type='ShareRecipientsResponse',  # noqa: E501
            auth_settings=auth_settings,
            async_req=params.get('async_req'),
            _return_http_data_only=params.get('_return_http_data_only'),
            _preload_content=params.get('_preload_content', True),
            _request_timeout=params.get('_request_timeout'),
            collection_formats=collection_formats)


"""
Kirjoita ohjelma, joka muuntaa tuumia senttimetreiksi niin kauan kunnes käyttäjä antaa negatiivisen tuumamäärän.
 Sen jälkeen ohjelma lopettaa toimintansa. 1 tuuma = 2,54 cm
"""
while True:
    tuuma = float(input('Syötä mitta tuumana niin muutan ne senttimetreiksi '))
    if tuuma < 0:
        break
    cm = tuuma * 2.54
    print(f'{tuuma} tuumaa on {cm} senttimetriä')


from xcp2k.inputsection import InputSection
from xcp2k.classes._each368 import _each368

class _e_density_bqb1(InputSection):
    def __init__(self):
        InputSection.__init__(self)
        self.Section_parameters = None
        self.Add_last = None
        self.Common_iteration_levels = None
        self.Filename = None
        self.Log_print_key = None
        self.Skip_first = None
        self.Store_step_number = None
        self.Check = None
        self.Overwrite = None
        self.History = None
        self.Parameter_key = None
        self.Optimize = None
        self.EACH = _each368()
        self._name = "E_DENSITY_BQB"
        self._keywords = {'Add_last': 'ADD_LAST', 'Common_iteration_levels': 'COMMON_ITERATION_LEVELS', 'Filename': 'FILENAME', 'Log_print_key': 'LOG_PRINT_KEY', 'Skip_first': 'SKIP_FIRST', 'Store_step_number': 'STORE_STEP_NUMBER', 'Check': 'CHECK', 'Overwrite': 'OVERWRITE', 'History': 'HISTORY', 'Parameter_key': 'PARAMETER_KEY', 'Optimize': 'OPTIMIZE'}
        self._subsections = {'EACH': 'EACH'}
        self._attributes = ['Section_parameters']


from threading import Lock

from logger import log

class TreeNode:

    def __init__(self, ip_addr, parent_node = None):
        self.nodes = []          # Child nodes
        self.ip_addr = ip_addr   # IP address of the node
        self.parent_node = None  # Reference to the parent node

    def has_free_child_spot(self):
        # We are considering a binary tree - max 2 children.
        children_count = len(self.nodes)
        return children_count < 2

    def assign_child(self, child_node):
        # The caller needs to make sure that the node
        # has not exceeded the maximum number of children (2).
        self.nodes.append(child_node)

class BinaryTree:

    def __init__(self, root_node):
        self._lock = Lock()         # For mutual exclusion
        self._root_node = root_node # Root node of the tree structure

    def add_node(self, node_ip_addr):
        # It performs a BFS algorithm to find
        # the next free spot in the tree structure.
        with self._lock:
            nodes = [self._root_node] # Treated as a queue

            while len(nodes) > 0:
                # Retrieve the current node
                curr_node = nodes.pop(0)

                # Expand its children (add them to the queue as well)
                for node in curr_node.nodes:
                    # If the node is already in the tree structure,
                    # do not add it again, just return the parent node.
                    if node.ip_addr == node_ip_addr:
                        return curr_node
                    nodes.append(node)

                # If the current node has a free spot (has either 0 or 1 child),
                # assign it the node as its new child and return the parent (current node).
                if curr_node.has_free_child_spot():
                    curr_node.assign_child(TreeNode(node_ip_addr, parent_node=curr_node))
                    return curr_node

        return None


import time
from typing import Callable, Tuple, Union

import numpy as np

def function(x: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
    """Function for which we find the root: $f(x) = x^3 - 2x - 5$.

    Args:
        x: Value(s) at which to evaluate the function.

    Returns:
        Numpy array or float with function evaluations for the provided `x`.

    """
    return (x - 2) ** 3

def check_strict_monotonicity(
    function: Callable, a: float = 0.0, b: float = 1.0
) -> bool:
    """Check whether `function` is strictly monotonically increasing or
    decreasing over the interval `[a, b]`.

    Args:
        function: Function to check for strict monotonicity.
        a: Left endpoint of the interval.
        b: Right endpoint of the interval.

    Returns:
        Boolean indicating whether `function` is strictly monotonically
        increasing or decreasing
    """
    if function(x=a) > function(x=b):
        print(
            f"Function `f` is strictly monotonically decreasing over the "
            f"interval {[a, b]}."
        )
        is_increasing = False
    elif function(x=a) < function(x=b):
        print(
            f"Function `f` is strictly monotonically increasing over the "
            f"interval {[a, b]}."
        )
        is_increasing = True
    else:
        raise ValueError(
            f"Function `f` is not strictly monotonic over the "
            f"interval {[a, b]}."
        )

    return is_increasing

def find_root(
    function: Callable,
    a: float = 0.0,
    b: float = 1.0,
    tolerance: float = 1e-6,
    is_increasing: bool = True,
    y: float = 0.0,
    run_time_limit: float = 60.0,
) -> Tuple[float, float, float]:
    """Find the root of the function using bisection method.

    Args:
        a: Left endpoint of the interval.
        b: Right endpoint of the interval.
        tolerance: Tolerance level for the root.
        is_increasing: Boolean indicating whether the function is strictly
            monotonically increasing or decreasing over the interval `[a, b]`.
        y: If we want to find the inverse value of `function` for `y`, we can
            do this by finding the root of the function `y - f(x)`.
        run_time_limit: If the algorithm runs for longer than this time limit,
            it will stop and return the current best estimate.

    Returns:
        Float with the root of the function, the required time to find the root
        and the function evaluation at the root.

    Raises:
        AssertionError: If the interval is not defined as `[a, b]` with
            `a < b`.
        AssertionError: If the tolerance is not a positive number.
    """
    start_time = time.perf_counter()

    assert a < b, "The interval must be defined as `[a, b]` with `a < b`."
    assert tolerance > 0, "The tolerance must be a positive number."

    is_increasing = check_strict_monotonicity(a=a, b=b, function=function)
    if y != 0.0:
        # We are searching for root of `y - function(x)`, so if `function(x)`
        # is strictly monotonically increasing, then `y - function(x)` is
        # strictly monotonically decreasing and vice versa.
        is_increasing = not is_increasing

    converged = False
    while not converged:
        # 1. Find the midpoint `c = (a + b) / 2`.
        c = (a + b) / 2
        # 2. Evaluate the function at the midpoint.
        if y == 0.0:
            # We are finding the root of `function`.
            func_midpoint = function(x=c)
        else:
            # We are finding the inverse value of `function` for `y`.
            func_midpoint = y - function(x=c)
        # 3. If the function value at the midpoint is close enough to zero, we
        # are done. Otherwise, if the function value at the midpoint is
        # positive, the root is in the left half of the interval, otherwise it
        # is in the right half of the interval.
        if abs(func_midpoint) <= tolerance:
            return c, time.perf_counter() - start_time, func_midpoint
        else:
            if is_increasing:
                if func_midpoint > 0:
                    b = c
                else:
                    a = c
            else:
                if func_midpoint > 0:
                    a = c
                else:
                    b = c
            converged = False

        if time.perf_counter() - start_time > run_time_limit:
            print(
                f"Time limit of {run_time_limit} s reached. "
                f"Returning current best estimate, which is {c}."
                f"\nFunction evaluation: {func_midpoint}."
            )

            return c, time.perf_counter() - start_time, func_midpoint

def find_inverse_value(
    function: Callable,
    y: float,
    a: float = 0.0,
    b: float = 1.0,
    tolerance: float = 1e-6,
    is_increasing: bool = True,
) -> Tuple[float, float]:
    """Find the inverse value of `function` using bisection method.
    This is done as described in
    https://math.stackexchange.com/questions/1440818/finding-the-inverse-of-a-function-using-bisection-method

    Args:
        y: Value for which to find the inverse value of `function`, i.e.
            `function^{-1}(y)`.
        --for the rest of the arguments, see `find_root`--

    Returns:
        Float with the inverse value of `function` for `y` and the required
        time to find the inverse value.
    """
    start_time = time.perf_counter()

    assert a <= y <= b, "The value `y` must be in the interval `[a, b]`."

    inverse_value, _, _ = find_root(
        function=function,
        a=a,
        b=b,
        tolerance=tolerance,
        is_increasing=is_increasing,
        y=y,
        run_time_limit=180.0,  # 3 minutes
    )

    return inverse_value, time.perf_counter() - start_time

def main() -> None:
    root, time_req_root, func_eval = find_root(
        function=function, a=-5.0, b=5.0, tolerance=1e-10
    )
    print(
        f"Found root at `x = {root}` in {round(time_req_root, 6)} s."
        f"\nFunction evaluation: {func_eval}.\n\n"
    )

    y = 3.0
    inverse, time_req_inverse = find_inverse_value(
        function=function, y=y, a=0.0, b=5.0, tolerance=1e-10
    )
    print(
        f"Found inverse value `f^(-1)(y={y}) = {round(inverse, 6)}` in "
        f"{round(time_req_inverse, 6)} s."
    )

if __name__ == "__main__":
    main()


#!/usr/bin/env python

import sys
import os
import signal
import json
from pathlib import Path
import requests
import threading, queue
import time
from tqdm import tqdm

package_q = queue.Queue(maxsize=500)
results_q = queue.Queue(maxsize=500)

base_url = "https://api.npmjs.org/downloads/point/last-year/"

to_get = []

def get_worker():
    # We can't do bulk requests for scoped packages, but we can for
    # everything else

    while True:

        package = package_q.get()

        url = base_url + package
        try:
            resp = requests.get(url=url, timeout=10)
        except:
            # Lots of weird things happen when this times out in a thread,
            # this is the lazy solution
            os.kill(os.getpid(), signal.SIGINT)

        dl_data = resp.json()

        if "error" in dl_data:
            dl_data = {
                "downloads": -1,
                "package": package
            }

        results_q.put(dl_data)
        package_q.task_done()

def put_worker():

    while True:
        result = results_q.get()

        package = result["package"]

        the_file = "downloads/%s" % package

        with open(the_file, "w") as fh:
            fh.write(json.dumps(result))

        #print(the_file)

        results_q.task_done()

# Main
#

threading.Thread(target=put_worker, daemon=True).start()
threading.Thread(target=get_worker, daemon=True).start()
threading.Thread(target=get_worker, daemon=True).start()
threading.Thread(target=get_worker, daemon=True).start()
threading.Thread(target=get_worker, daemon=True).start()
threading.Thread(target=get_worker, daemon=True).start()
threading.Thread(target=get_worker, daemon=True).start()
threading.Thread(target=get_worker, daemon=True).start()
threading.Thread(target=get_worker, daemon=True).start()

with open("all_packages.json") as fh:
    data = json.load(fh)

    all_packages = data['rows']

#for filename in tqdm(all_packages, miniters=1):
for filename in all_packages:

    one_id = filename["id"]
    the_file = "downloads/%s" % one_id

    # We only want scoped things
    if not one_id.startswith('@'):
        continue

    # Things that start with a @ are special in npm
    if one_id.startswith('@'):
        (the_dir, the_package) = one_id.split('/')
        if os.path.exists("downloads/%s" % the_dir):
            # We're fine
            pass
        else:
            os.mkdir("downloads/%s" % the_dir)

    if os.path.exists(the_file):
        continue

    print(one_id)
    package_q.put(one_id)

while not package_q.empty():
    print("Waiting on package queue")
    time.sleep(1)

while not results_q.empty():
    print("Waiting on results queue")
    time.sleep(1)


T = int(input())

for t in range(1, T + 1):
	N = int(input())
	X = input().strip().split()
	res = 0
	curr = list(X[0])

	for i in range(1, len(X)):
		prev = curr
		curr = list(X[i])

		if len(curr) > len(prev):
			continue

		digit_diff = len(prev) - len(curr)
		min_len = len(curr)
		res += digit_diff

		if curr[:min_len] < prev[:min_len]:
			curr.append([0] * (digit_diff + 1))
		elif curr[:min_len] > prev[:min_len]:
			curr.append([0] * (digit_diff))
		else:
			if digit_diff != 0 and int("".join(prev[len(curr):])) + 1 < 10**(digit_diff):
				print(str(int("".join(prev[len(curr):])) + 1))
				curr.extend(list(str(int("".join(prev[len(curr):])) + 1)))
			else:
				curr.extend([0]*digit_diff)
				res += 1

	print("Case #{}: {}".format(t, res))


field = []
with open("input.txt") as inp:
    field = [line.strip() for line in inp.readlines()]

trees = 0
x = 0
y = 0
while y < len(field):
    if field[y][x] == '#':
        trees += 1
    x = (x + 3) % len(field[0])
    y = y + 1

print(trees)


import ast
import argparse
import pathlib
import sys

from typing import TypedDict, Optional

import find_py_imports.visitor as v
import find_py_imports.formatter as fmt

class _Err(TypedDict):
        filename: Optional[str]
        error: Exception

def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('-n', '--line-number', action='store_true', dest='show_line_number',
        help='show line number')
    parser.add_argument('--hide-syntax-error', action='store_true',dest='hide_syntax_err',
        help='do not print syntax error print to stderr')
    parser.add_argument('--print-file-not-found-error', action='store_true', dest='print_file_not_found_err',
        help='print not founded files to stderr')
    parser.add_argument('file', nargs='*', type=str, help='filename(s)')

    args = parser.parse_args()
    show_line_number: bool = args.show_line_number
    print_syntax_err: bool = not args.hide_syntax_err
    print_file_not_found_err: bool = args.print_file_not_found_err
    files: list[str] = args.file
    filenames_are_provided = True

    formatter = None
    pred = (1 < len(files), show_line_number)  # test [multiple_file?, show line_number?]
    if pred == (False, False):
        formatter = fmt.SimpleFormatter()
    elif pred == (False, True):
        formatter = fmt.LinenoFormatter()
    elif pred == (True, False):
        formatter = fmt.FilenameFormatter()
    elif pred == (True, True):
        formatter = fmt.FilenameLinenoFormatter()
    else:
        raise Exception

    # if no filename is provided then use input chars from stdin as content of a file
    if len(files) < 1:
        filenames_are_provided = False

    result: list[fmt.Record] = []
    def save_result(fn: str, stmt: v.ImportStatement):
        result.append(fmt.Record(fn, stmt))

    errs: list[_Err] = []
    if filenames_are_provided:
        # interpret input as filename
        for fn in files:
            try:
                if not pathlib.Path(fn).exists():
                    raise FileNotFoundError(fn)
                with open(fn) as fp:
                    tree = ast.parse(fp.read())
                    visitor = v.MyNodeVisitor(fn, save_result)
                    visitor.visit(tree)
            except (FileNotFoundError, SyntaxError) as e:
                errs.append({
                    'filename': fn,
                    'error': e,
                })
    else:
        # interpret input as code string
        try:
            tree = ast.parse(sys.stdin.read())
            visitor = v.MyNodeVisitor(None, save_result)
            visitor.visit(tree)
        except (FileNotFoundError, SyntaxError) as e:
            errs.append({
                'filename': None,
                'error': e,
            })

    for r in result:
        print(formatter.format(r))

    for e in errs:
        if print_syntax_err:
            s = ''
            if 1 < len(files):
                s = f' at {e["filename"]}'
            sys.stderr.write(f'syntax error{s}: {e["error"]}\n')
        if print_file_not_found_err:
            sys.stderr.write(f'no such file: {e["error"]}\n')

if __name__ == '__main__':
    main()


import json

from ryu.ofproto.ofproto_v1_3_parser import OFPMatch
from webob import Response

from ryu.lib.addrconv import mac
from ryu.ofproto import ether
from ryu.ofproto import inet

REST_ALL = 'all'

REST_MATCH = 'match'
REST_IN_PORT = 'in_port'
REST_SRC_MAC = 'dl_src'
REST_DST_MAC = 'dl_dst'
REST_DL_TYPE = 'dl_type'
REST_DL_TYPE_ARP = 'ARP'
REST_DL_TYPE_IPV4 = 'IPv4'
REST_DL_TYPE_IPV6 = 'IPv6'
REST_DL_VLAN = 'dl_vlan'
REST_SRC_IP = 'nw_src'
REST_DST_IP = 'nw_dst'
REST_SRC_IPV6 = 'ipv6_src'
REST_DST_IPV6 = 'ipv6_dst'
REST_NW_PROTO = 'nw_proto'
REST_NW_PROTO_TCP = 'TCP'
REST_NW_PROTO_UDP = 'UDP'
REST_NW_PROTO_ICMP = 'ICMP'
REST_NW_PROTO_ICMPV6 = 'ICMPv6'
REST_TP_SRC = 'tp_src'
REST_TP_DST = 'tp_dst'
REST_DSCP = 'ip_dscp'

# Utility functions
def to_int(i):
    return int(str(i), 0)

def to_match(m):
    return OFPMatch(**m)

def to_str_list(l):
    return [str(e) for e in l] if l else []

def to_int_list(l):
    return [int(e) for e in l] if l else []

def keep(o):
    return o

def post_method(keywords=None):
    keywords = keywords or {}

    def _wrapper(method):
        def __wrapper(self, req, **kwargs):
            try:
                try:
                    body = req.json if req.body else {}
                except ValueError:
                    raise ValueError('Invalid syntax %s', req.body)
                kwargs.update(body)
                for key, converter in keywords.items():
                    new_key = key.startswith('[') and key[1:-1] or key  # check for optional [key]
                    optional = key != new_key
                    key = new_key
                    value = kwargs.get(key, None)
                    if value is None and not optional:
                        raise ValueError('%s not specified' % key)
                    kwargs[key] = converter(value)
            except ValueError as e:
                return Response(content_type='application/json',
                                body=json.dumps({"error": str(e)}), status=400)
            try:
                return method(self, **kwargs)
            except Exception as e:
                status = 500
                body = {
                    "error": str(e),
                    "status": status,
                }
                return Response(content_type='application/json',
                                body=json.dumps(body), status=status)
        __wrapper.__doc__ = method.__doc__
        return __wrapper
    return _wrapper

def get_method(keywords=None):
    keywords = keywords or {}

    def _wrapper(method):
        def __wrapper(self, _, **kwargs):
            try:
                for key, converter in keywords.items():
                    value = kwargs.get(key, None)
                    if value is None:
                        continue
                    kwargs[key] = converter(value)
            except ValueError as e:
                return Response(content_type='application/json',
                                body=json.dumps({"error": str(e)}), status=400)
            try:
                return method(self, **kwargs)
            except Exception as e:
                status = 500
                body = {
                    "error": str(e),
                    "status": status,
                }
                return Response(content_type='application/json',
                                body=json.dumps(body), status=status)
        __wrapper.__doc__ = method.__doc__
        return __wrapper
    return _wrapper

delete_method = get_method


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from absl.testing import parameterized

from tensorflow.python.data.experimental.ops import testing
from tensorflow.python.data.kernel_tests import test_base
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.framework import combinations
from tensorflow.python.platform import test

class MapFusionTest(test_base.DatasetTestBase, parameterized.TestCase):

  def _testMapFusion(self, functions):
    dataset = dataset_ops.Dataset.range(5).apply(
        testing.assert_next(["Map", "MemoryCacheImpl"]))
    for function in functions:
      dataset = dataset.map(function)

    dataset = dataset.cache()
    options = dataset_ops.Options()
    options.experimental_optimization.apply_default_optimizations = False
    options.experimental_optimization.map_fusion = True
    dataset = dataset.with_options(options)
    expected_output = []
    for x in range(5):
      r = x
      for function in functions:
        if isinstance(r, tuple):
          r = function(*r)  # Pass tuple as multiple arguments.
        else:
          r = function(r)
      expected_output.append(r)
    self.assertDatasetProduces(dataset, expected_output=expected_output)

  @combinations.generate(test_base.default_test_combinations())
  def testMapFusionScalar(self):
    identity = lambda x: x
    increment = lambda x: x + 1

    def increment_and_square(x):
      y = x + 1
      return y * y

    functions = [identity, increment, increment_and_square]

    for x in functions:
      for y in functions:
        self._testMapFusion([x, y])
        for z in functions:
          self._testMapFusion([x, y, z])

  @combinations.generate(test_base.default_test_combinations())
  def testMapAndFilterFusionTuple(self):
    with_42 = lambda x: (x, 42)
    swap = lambda x, y: (y, x)

    self._testMapFusion([with_42, swap])
    self._testMapFusion([with_42, swap, swap])

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


#! /usr/bin/env python
#################################################################
###  This program is part of PyINT  v1.0                      ###
###  Copy Right (c): 2017, Yunmeng Cao                        ###
###  Author: Yunmeng Cao                                      ###
###  Email : ymcmrs@gmail.com                                 ###
###  Univ. : Central South University & University of Miami   ###
#################################################################

import os
import sys
import glob
import time
import argparse

import h5py
import numpy as np

def check_variable_name(path):
    s=path.split("/")[0]
    if len(s)>0 and s[0]=="$":
        p0=os.getenv(s[1:])
        path=path.replace(path.split("/")[0],p0)
    return path

def read_template(File, delimiter='='):
    '''Reads the template file into a python dictionary structure.
    Input : string, full path to the template file
    Output: dictionary, pysar template content
    Example:
        tmpl = read_template(KyushuT424F610_640AlosA.template)
        tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
    '''
    template_dict = {}
    for line in open(File):
        line = line.strip()
        c = [i.strip() for i in line.split(delimiter, 1)]  #split on the 1st occurrence of delimiter
        if len(c) < 2 or line.startswith('%') or line.startswith('#'):
            next #ignore commented lines or those without variables
        else:
            atrName  = c[0]
            atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
            atrValue = check_variable_name(atrValue)
            template_dict[atrName] = atrValue
    return template_dict

def UseGamma(inFile, task, keyword):
    if task == "read":
        f = open(inFile, "r")
        while 1:
            line = f.readline()
            if not line: break
            if line.count(keyword) == 1:
                strtemp = line.split(":")
                value = strtemp[1].strip()
                return value
        print("Keyword " + keyword + " doesn't exist in " + inFile)
        f.close()

def UseGamma2(inFile, task, keyword):
    if task == "read":
        f = open(inFile, "r")
        while 1:
            line = f.readline()
            if not line: break
            if line.count(keyword) == 1:
                strtemp = line.split(":")
                value = strtemp[2].strip()
                return value
        print("Keyword " + keyword + " doesn't exist in " + inFile)
        f.close()

def usage():
    print('''
******************************************************************************************************

          Get co-registration standard deviation of SLCs for one project

   usage:

            GenerateRSC_Gamma.py projectName

      e.g.  Get_off_std.py GalapagosT061EnvA

*******************************************************************************************************
    ''')

def main(argv):

    if len(sys.argv)==2:
        if argv[0] in ['-h','--help']: usage(); sys.exit(1)
        else: projectName=sys.argv[1]
    else:
        usage();sys.exit(1)

    scratchDir = os.getenv('SCRATCHDIR')
    OFFDir = scratchDir + '/' + projectName + '/RSLC'
    OFFSTR = OFFDir + '/*.off_std'
    OFFFile = glob.glob(OFFSTR)
    STD_TXT ='COREG_STD_ALL'
    os.chdir(OFFDir)
    if os.path.isfile(STD_TXT):
        os.remove(STD_TXT)

    for ff in OFFFile:
        OFF_STD = ff
        NM = os.path.basename(ff).split('.')[0]
        RR = UseGamma(OFF_STD,'read','final range offset poly. coeff.:')
        cor_rg = RR.split(' ')[0]

        AA = UseGamma(OFF_STD,'read','final azimuth offset poly. coeff.:')
        cor_az = AA.split(' ')[0]

        STDRR = UseGamma(OFF_STD,'read','final model fit std. dev. (samples) range:')
        std_rg=STDRR.split(' ')[0]

        std_az = UseGamma2(OFF_STD,'read','final model fit std. dev. (samples) range:')

        STR = NM + ' ' + cor_rg + ' ' + cor_az + ' ' + std_rg + ' ' + std_az
        call_str ='echo ' + STR + ' >> ' + STD_TXT
        os.system(call_str)

    sys.exit(1)

if __name__ == '__main__':
    main(sys.argv[1:])


import os
import os.path
import sys

from umlfri2.plugin.starters import BaseProgramStarter

ADDON_ROOT_PATH = os.path.dirname(os.path.dirname(__file__))

class PythonStarter(BaseProgramStarter):
    if hasattr(sys, 'frozen'):
        program = (sys.executable, '--plugin')
    else:
        program = (sys.executable, os.path.join(ADDON_ROOT_PATH, 'starter', 'python_runner.py'))

    environment = {
        'LIB': os.path.join(ADDON_ROOT_PATH, 'library'),
        'PATH': '{path}'
    }


try:

    import RPi.GPIO as GPIO
    from lib_nrf24 import NRF24
    import time
    import spidev

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(23, GPIO.OUT, initial=GPIO.LOW)
    GPIO.setup(22, GPIO.OUT, initial=GPIO.LOW)

    print("Transmitter")
    pipes = [0xe7, 0xe7, 0xe7, 0xe7, 0xe7]

    radio = NRF24(GPIO, spidev.SpiDev())
    radio.begin(0, 22)
    radio.setPayloadSize(1)
    radio.setChannel(30)

    radio.setDataRate(NRF24.BR_250KBPS)
    radio.setPALevel(NRF24.PA_MAX)
    radio.setAutoAck(False)
    radio.enableDynamicPayloads()

    radio.openWritingPipe(pipes)
    radio.printDetails()
    print("///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////")

    i = 0

    while True:
        #print("Transmitting Ping")
        message = 0xFF
        radio.write(str(message))
        #time.sleep(1)
        i += 1

except KeyboardInterrupt:

    radio.write("HE XAPAT")
    GPIO.output(22,0)
    GPIO.output(23,0)
    #GPIO.output(24,0)
    GPIO.cleanup()


from selenium import webdriver
from tkinter import Tk
from time import sleep
r=Tk()
r.withdraw()
browser = webdriver.Firefox(executable_path='C:/Users/ASUS/Downloads/geckodriver-v0.26.0-win64/geckodriver.exe')
browser.get('https://www.google.com/search?q=google+translate&oq=goo&aqs=chrome.0.69i59j69i57j35i39j0l2j69i60l3.2202j0j7&sourceid=chrome&ie=UTF-8')
sleep(1)
browser.find_element_by_xpath('//*[@id="tw-tl"]').click()
sleep(1)
browser.find_element_by_xpath('//*[@id="tw-container"]/g-expandable-container/div/div/div[6]/g-expandable-container/div/g-expandable-content/span/div/div[2]/div[1]/div/div[2]/div[38]').click()
#browser.find_element_by_xpath('//*[@id="tw-container"]/g-expandable-container/div/div/div[6]/g-expandable-container/div/g-expandable-content/span/div/div[2]/div[1]/div/div[2]/div[89]').click();
sleep(1)
searchbox= browser.find_element_by_xpath('//*[@id="tw-source-text-ta"]')
with open('hindi.txt','w',encoding='utf-8') as file:
    with open('english.txt','r') as f:
        for x in f:
            searchbox.send_keys(x);
            sleep(5)
            #getdata=browser.find_element_by_xpath('//*[@id="tw-target-text"]/span');
            browser.find_element_by_xpath('//*[@id="tw-cpy-btn"]/span').click()
            result=r.clipboard_get()
            file.write(result+'\n');
            browser.find_element_by_xpath('//*[@id="tw-cst"]/span').click()
        f.close();
    file.close()


import pexpect

robot = pexpect.spawn('ssh student@172.27.26.188')
robot.expect('student@172.27.26.188\'s password:')
robot.sendline('cs641')
robot.expect('Enter your group name: ')
robot.sendline("team_9")

robot.expect('Enter password: ')
robot.sendline("team9")

#robot.expect('\r\n\r\n\r\nYou have solved 4 levels so far.\r\nLevel you want to start at: ', timeout=50)

robot.expect('at: ', timeout=50)

robot.sendline("5")
robot.expect('.*')
robot.sendline("go")
robot.expect('.*')
robot.sendline("wave")
robot.expect('.*')
robot.sendline("dive")
robot.expect('.*')
robot.sendline("go")
robot.expect('.*')
robot.sendline("read")
robot.expect('.*')

f = open("plaintexts.txt", 'r')
f1= open("ciphertexts.txt",'w')

text = []

for i in f.readlines():
	s = list(i.split())
	text = text + s

c = 0
for line in text:
	robot.sendline(line)
	robot.expect("Slowly, a new text starts.*")
	#print(robot.before)
	#print('=======================================')
	#print(robot.after)
	dummy = str(robot.after)[73:89]
	print(str(c) + " " + dummy)
	c+=1
	f1.writelines(dummy +"\n")
	robot.sendline("c")
	robot.expect('The text in the screen vanishes!')

robot.close()
f.close()
f1.close()


import numpy as np
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, Flatten, Reshape
from models.our_loss import *

class AudioModel(tf.keras.Model):
    def __init__(self, with_loss, without_tempo):
        super(AudioModel, self).__init__()

        self.optimizer = tf.keras.optimizers.Adam(learning_rate=0.0001)
        self.batch_size = 128
        self.num_epochs = 30
        self.num_classes = 4
        self.with_loss = with_loss
        self.without_tempo =without_tempo
        input_shape = (60,300,6)
        if(without_tempo==True):
            input_shape = (60,300,5)

        self.cnn = Sequential()

        self.cnn.add(tf.keras.layers.Conv2D(20, kernel_size =(6, 6),input_shape=input_shape ,kernel_regularizer=tf.keras.regularizers.L2(l2=0.0000001)))
        #self.cnn.add(tf.keras.layers.BatchNormalization())
        self.cnn.add(tf.keras.layers.ReLU())
        self.cnn.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))

        self.cnn.add(tf.keras.layers.Conv2D(40, kernel_size =(5, 5), padding ='same',kernel_regularizer=tf.keras.regularizers.L2(l2=0.0000001)))
    #    self.cnn.add(tf.keras.layers.BatchNormalization())
        self.cnn.add(tf.keras.layers.ReLU())
        self.cnn.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))

        self.cnn.add(tf.keras.layers.Conv2D(80, kernel_size =(4, 4), padding ='same',kernel_regularizer=tf.keras.regularizers.L2(l2=0.0000001)))
        self.cnn.add(tf.keras.layers.BatchNormalization())
        self.cnn.add(tf.keras.layers.ReLU())
        self.cnn.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))

        self.cnn.add(Flatten())
        self.cnn.add(tf.keras.layers.Dense(64 ,kernel_regularizer=tf.keras.regularizers.L2(l2=0.0000001)))
        self.cnn.add(tf.keras.layers.BatchNormalization())
        self.cnn.add(tf.keras.layers.ReLU())
        self.cnn.add(tf.keras.layers.Dropout(.6))
        self.cnn.add(tf.keras.layers.Dense(16 ,kernel_regularizer=tf.keras.regularizers.L2(l2=0.000001)))
        self.cnn.add(tf.keras.layers.BatchNormalization())
        self.cnn.add(tf.keras.layers.ReLU())
        self.cnn.add(tf.keras.layers.Dropout(.6))
        self.softmax_layer = tf.keras.layers.Dense(4, activation="softmax")

        print(self.cnn.summary())

        if(self.with_loss==True):
            self.vec2veclayer = tf.keras.layers.Dense(2, activation="tanh")

    def call(self, input):

        if(self.without_tempo == True):
            input =input[:,:,:,1:]

        out = self.cnn(input)
        if(self.with_loss==True):

            vec2vec = self.vec2veclayer (out)
            probs = self.softmax_layer(out)
            return probs, vec2vec

        probs = self.softmax_layer(out)
        return probs, probs

    def loss(self, logits, labels,two_d_vectorspace):

        C = our_loss( labels,two_d_vectorspace, self.batch_size)
        my_loss = tf.keras.losses.CategoricalCrossentropy()
        loss =my_loss(labels,logits)
        if(self.with_loss==True):
            loss = loss +C

        return loss

        #return tf.math.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels,logits))

    def accuracy( self,labels, logits ):

        correct_predictions = tf.equal(tf.argmax(logits, 1), tf.argmax(labels, 1))

        return tf.reduce_mean(tf.cast(correct_predictions, tf.float32))

    def train(self, labels,inputs, test_inputs,test_labels):

        num_examples = len(inputs)
        num_batches = int(num_examples/self.batch_size)
        train_acc =[]
        test_acc =[]
        epoch = []

        for epochs in range(self.num_epochs):
            print(epochs)

            indices = np.arange(num_examples)
            indices=tf.random.shuffle(indices)
            shuffled_inputs=  tf.gather(inputs,indices)
            shuffled_labels=  tf.gather(labels,indices)

            for k in range(num_batches):
                step_size=self.batch_size
                batch_inputs =shuffled_inputs[ k*step_size :k*step_size+step_size]
                batch_labels = shuffled_labels[k*step_size :k*step_size+step_size]

                with tf.GradientTape() as tape:
                    logits,two_d_vectorspace= self.call( batch_inputs)
                    loss = self.loss(logits,batch_labels,two_d_vectorspace)
                    print(loss)

                gradients = tape.gradient(loss,self.trainable_variables)
                self.optimizer.apply_gradients(zip(gradients,self.trainable_variables))
            train_acc.append(self.test(labels, inputs))
            test_acc.append(self.test(test_labels, test_inputs))
            epoch.append(epochs)
        return train_acc,test_acc,epoch

    def test(self,labels,inputs):

        num_examples = len(inputs)
        num_batches = int(num_examples/self.batch_size)
        acc=0
        for k in range(num_batches):
            step_size=self.batch_size
            batch_inputs =inputs[ k*step_size :k*step_size+step_size]
            batch_labels = labels[k*step_size :k*step_size+step_size]
            logits,two_d_vectorspace= self.call(batch_inputs)
            acc= acc+self.accuracy(logits,batch_labels)

        return acc/num_batches


import torch
import torch.nn as nn
import torch.nn.functional as F
from src.base.model import BaseModel

from src.layers.cell import *
from src.layers.cst_cell import *
from numpy.fft import fft, ifft
from scipy.fftpack import fftfreq
from math import sqrt

class FourierDecomp(nn.Module):
    def __init__(self, hist_len, in_dim, hid_dim, out_dim, n_nodes, freq_type, freq_threshold, device):
        super(FourierDecomp, self).__init__()
        '''
        input time series: [b, n, l, d]
        output c/e time seires: [b, n, l, d]
        '''
        self.fourier_layer = FourierCell(in_dim * n_nodes, out_dim* n_nodes, hist_len, freq_type, freq_threshold, device)
        self.mlp = nn.Sequential(nn.Conv1d(in_dim* n_nodes, hid_dim *2, 1),
                                        nn.GELU(),
                                        nn.Conv1d(hid_dim *2, out_dim* n_nodes, 1)
                                        ).to(device)

    def forward(self, ts_in):
        b, n, l, d = ts_in.shape
        ts_in = ts_in.permute(0,1,3,2).reshape(b, n*d, l)
        x1 = self.fourier_layer(ts_in)
        x2 = self.mlp(ts_in)
        x = x1 + x2
        ts_out = F.relu(x)
        return ts_out.reshape(b, n, d, l).permute(0,1,3,2)

class FourierCell(nn.Module):
    def __init__(self, in_channels, out_channels, t_len, freq_type, freq_threshold, device):
        super(FourierCell, self).__init__()
        """
        FFT -> linear transform -> Inverse FFT
        """
        self.in_channels = in_channels # n * in_d
        self.out_channels = out_channels # n * out_d
        self.freq_type = freq_type
        self.freq_threshold = int(freq_threshold)
        self.scale = (1 / (in_channels*out_channels))
        if freq_type == 'high':
            self.weights = nn.Parameter(self.scale * torch.rand(in_channels, out_channels, t_len//2 + 1 - self.freq_threshold, dtype=torch.cfloat)).to(device)
        elif freq_type == 'low':
            self.weights = nn.Parameter(self.scale * torch.rand(in_channels, out_channels, self.freq_threshold, dtype=torch.cfloat)).to(device)
    def compl_mul(self, input, weights):
        # (batch, in_channel, x ), (in_channel, out_channel, x) -> (batch, out_channel, x)
        return torch.einsum("bix,iox->box", input, weights)

    def forward(self, ts_in):
        x_ft = torch.fft.rfft(ts_in) # [1024, 34, 13]
        ts_out = torch.zeros(ts_in.shape[0], self.out_channels, ts_in.size(-1)//2 + 1, device=ts_in.device, dtype=torch.cfloat)
        if self.freq_type == 'low':
            ts_out[:, :, :self.freq_threshold] = self.compl_mul(x_ft[:, :, :self.freq_threshold], self.weights)
        elif self.freq_type == 'high':
            ts_out[:, :, self.freq_threshold:] = self.compl_mul(x_ft[:, :, self.freq_threshold:], self.weights)
        ts_out = torch.fft.irfft(ts_out, n=ts_in.shape[-1])
        return ts_out

#################### tcn
class TemporalEnc(nn.Module):
    '''
    input (b, n, t, d)
    output (b, n, l-2, hid_dim)
    '''
    def __init__(self, in_dim, hid_dim, kernel_size=3):
        super(TemporalEnc, self).__init__()
        self.c_in = in_dim
        self.c_out = hid_dim
        self.res_conv = nn.Conv2d(in_dim, hid_dim, 1)
        self.kernel_size = kernel_size
        self.conv1 = nn.Conv2d(in_dim, hid_dim, (1, kernel_size))
        self.conv2 = nn.Conv2d(in_dim, hid_dim, (1, kernel_size))

    def forward(self, x):
        # x [b, n, t, d]
        x = x.permute(0, 3, 1, 2)  # [b, c, num_nodes, t]
        x_input = self.res_conv(x)
        x_input = x_input[:, :, :, self.kernel_size - 1:]
        out = self.conv1(x) + x_input
        out = out * torch.sigmoid(self.conv2(x))
        out = out.permute(0, 2, 3, 1) #[b, n, l-2, d]
        return out

class SpatialAtten(nn.Module):
    '''
    input (b, n, l, d)
    output: a_c, a_e (b, n, n) *2
    '''
    def __init__(self, hid_dim, embed_dim, wo_causal_s, attn_threshold, block_num, seq_len, input_dim):
        super(SpatialAtten, self).__init__()
        self.attn_threshold = attn_threshold
        self.wo_causal_s = wo_causal_s
        self.embed_dim = embed_dim
        # layer
        l_t = seq_len - (block_num+1) * 2
        self.ts_proj = nn.Linear(l_t * hid_dim, embed_dim)

    def get_norm_attn(self, attn):
        '''
        attn: (b, n, n)
        '''
        # np.save('/home/yutong/STCausal/notebook/attn_0.npy', attn.cpu().detach().numpy())
        mask_c_bool = torch.ge(attn, self.attn_threshold)
        mask_c = mask_c_bool.int() * -np.inf
        mask_c = torch.where(torch.isnan(mask_c), torch.full_like(mask_c,1),mask_c).requires_grad_(False)
        maske_attn_c = attn * mask_c
        a_c = F.softmax(maske_attn_c, -1).detach()
        a_c = torch.where(torch.isnan(a_c), torch.full_like(a_c,0),a_c).requires_grad_(False)

        if not self.wo_causal_s:
            mask_e_bool = ~mask_c_bool
            mask_e = mask_e_bool.int() * -np.inf
            mask_e = torch.where(torch.isnan(mask_e), torch.full_like(mask_e,1),mask_e).requires_grad_(False)
            neg_attn = (torch.ones(attn.shape).to(attn.device) / attn)
            maske_attn_e = neg_attn * mask_e
            a_e = F.softmax(maske_attn_e, -1).detach()
            a_e = torch.where(torch.isnan(a_e), torch.full_like(a_e,0),a_e).requires_grad_(False)
        else: a_e = None

        return a_c, a_e

    def attention(self, queries, keys):
        scale = 1. / sqrt(self.embed_dim)
        scores = torch.einsum("ble,bse->bls", queries, keys)
        A = torch.softmax(scale * scores, dim=-1)
        return A

    def forward(self, ts_enc):
        # ts_enc #[b, n, l_, d]
        b, n, l_, d = ts_enc.shape
        # print(ts_enc.shape)
        # input()
        ts_enc = self.ts_proj(ts_enc.reshape(b * n, -1)).reshape(b, n, self.embed_dim) # [b, n, 512]
        attn = self.attention(ts_enc, ts_enc) # [b, n, n]
        a_c, a_e = self.get_norm_attn(attn)
        return a_c, a_e
        # return attn, a_e

# class Prediction(nn.Module):
#     def __init__(self, pred_len, hid_dim, n_nodes, hid_dim_pred, output_dim):
#         super(Prediction, self).__init__()
#         self.output_dim = output_dim
#         self.pred_len = pred_len
#         self.hid_dim_pred = hid_dim_pred
#         self.fc_in = nn.Linear(hid_dim, hid_dim_pred)
#         self.fc_out = nn.Linear(hid_dim_pred, pred_len * output_dim)
#         self.ln = nn.LayerNorm([n_nodes ,hid_dim_pred])

#     def forward(self, hn):
#         # h: (b, n, hid_dim)
#         b, n, d = hn.shape
#         h = F.relu(self.fc_in(hn.reshape(b * n, d)))
#         h = self.ln(h.reshape(b, n, self.hid_dim_pred))
#         pred = self.fc_out(h.reshape(b * n, self.hid_dim_pred))
#         return pred.reshape(b, n, self.pred_len, self.output_dim).permute(0,2,1,3)

class CSTBlock(nn.Module):
    def __init__(self, seq_len, pred_len, hid_dim, n_nodes, input_dim, output_dim, pred_block, device, wo_causal_s, attn_threshold, spatial_embed_dim, block_num):
        super(CSTBlock, self).__init__()
        self.pred_block = pred_block
        self.output_dim = output_dim
        self.pred_len = pred_len
        self.block_num = block_num
        self.wo_causal_s = wo_causal_s

        # layer
        if block_num == 0:
            self.temporal= TemporalEnc(input_dim, hid_dim, kernel_size=3)
        else:
            self.temporal= TemporalEnc(hid_dim, hid_dim, kernel_size=3)
        self.get_attention = SpatialAtten(hid_dim, spatial_embed_dim, wo_causal_s, attn_threshold, block_num, seq_len, input_dim)
        self.ln = nn.LayerNorm([n_nodes ,hid_dim])

    def spatial_agg(self, att, v):
        return torch.einsum("bln,bnsd->blsd", att, v)

    def forward(self, h):
        # h: [b, n, s, d]
        # b, n, s, d = h.shape
        h_ = self.temporal(h) # [512, n, l, d?]
        a_c, a_e = self.get_attention(h_)
        c = self.spatial_agg(a_c , h_)
        c = c + h_
        c = self.ln(c.permute(0, 2, 1, 3))# [b, l_, n, d]
        c = c.permute(0, 2, 1, 3)

        if not self.wo_causal_s:
            e = self.spatial_agg(a_e, h_)
            e = e.reshape(-1, e.shape[-1])
        else: e = None
        return c, e, a_c


#!/usr/bin/python

import os
import sys

fn = sys.argv[1]

fh = open(fn, "r")
T = int(fh.readline().strip())
cases = []

for i in range(T):
    case = []
    for j in range(4):
        case.append([k for k in fh.readline().strip()])
    dummy = fh.readline().strip()
    cases.append(case)

fh.close()

d_X={"X":"X", "O":".", ".":".", "T":"X"}
d_O={"X":".", "O":"O", ".":".", "T":"O"}

def determine_win(case):
    for r in range(4):
        if map(lambda z: d_X[z], case[r]) == ['X', 'X', 'X', 'X']:
            return "X won"
        elif map(lambda z: d_O[z], case[r]) == ['O', 'O', 'O', 'O']:
            return "O won"
    for c in range(4):
        if map(lambda z: d_X[z], map(lambda j: case[j][c], range(4))) == ['X', 'X', 'X', 'X']:
            return "X won"
        elif map(lambda z: d_O[z], map(lambda j: case[j][c], range(4))) == ['O', 'O', 'O', 'O']:
            return "O won"
    if map(lambda z: d_X[z], map(lambda j: case[j][j], range(4))) == ['X', 'X', 'X', 'X']:
        return "X won"
    if map(lambda z: d_O[z], map(lambda j: case[j][j], range(4))) == ['O', 'O', 'O', 'O']:
        return "O won"
    if map(lambda z: d_X[z], map(lambda j: case[j][3-j], range(4))) == ['X', 'X', 'X', 'X']:
        return "X won"
    if map(lambda z: d_O[z], map(lambda j: case[j][3-j], range(4))) == ['O', 'O', 'O', 'O']:
        return "O won"
    if "." not in sum(case, []):
        return "Draw"
    return "Game has not completed"

fh_o = open("out.txt","w")
for i, case in enumerate(cases):

    print >> fh_o, "Case #"+str(i+1)+": "+ determine_win(case)

fh_o.close()


#!/usr/bin/env python
# coding: utf-8

# In[58]:

import numpy as np
import pandas as pd

# In[59]:

file_path = "WSJ_final_training_set.pos"
test_corpora = "WSJ_23.words"

# In[60]:

emission = {}
transmission = {}

count = 0
with open(file_path,'r') as lines:
    tag_list = []
    for l in lines:
        count += 1
        word_pos = l.split('\t')
#         if count == 26:
#             print(type(word_pos[0].strip('\n')))
        if len(word_pos) == 1: # if it is an empty line, treat as a word with tag ''
            tag = str(word_pos[0].strip('\n'))
        else:
            word = word_pos[0]#.lower() #regardless of capital
            tag = word_pos[1].strip('\n')
        tag_list.append(tag)
        if tag not in emission:
            emission[tag] = {}
        if word not in emission[tag]:
            emission[tag][word] = 1
        else:
            emission[tag][word] += 1

# In[61]:

for i in range(len(tag_list)-1):
	if tag_list[i] not in transmission:
		transmission[tag_list[i]]={}
	if tag_list[i+1] not in transmission[tag_list[i]]:
		transmission[tag_list[i]][tag_list[i+1]] = 1
	else:
		transmission[tag_list[i]][tag_list[i+1]] += 1

# In[62]:

def transmission_probability(cur_tag,prev_tag):
	denominator = sum(transmission[prev_tag].values())
	if cur_tag in transmission[prev_tag]:
		numerator = transmission[prev_tag][cur_tag]
	else:
		numerator = 0
	return numerator/denominator

tag_list_unique = list(set(tag_list)) #delete replicates
tags_matrix = np.zeros((len(tag_list_unique), len(tag_list_unique)), dtype='float32')

print("the length of the unique tag list: ", len(tag_list_unique))

# In[63]:

def get_emission(word,tag):
    if tag == '':
        return 0
    denominator = sum(emission[tag].values())
    if word in emission[tag]:
        numerator = emission[tag][word]
    else:
        #use hard coded probability
        if any(c.isdigit() for c in word) and tag == "CD": #contains digits
            return 1 / sum(emission["CD"].values())
        elif word.endswith('s') and tag == "NNS": #ends with s
            return  0.5 / sum(emission["NNS"].values())
        elif word[0].isupper() and tag == "NNP": #first letter capitalized
            return  0.5 / sum(emission["NNP"].values())
        elif not any(c.isalnum() for c in word) and tag == ".": #has neither digits nor letter
            return 0.5 / sum(emission["."].values())
        #elif word #punctuation?
        else:
            numerator = 0.00001
    return numerator/denominator

# In[64]:

for i,prev_tag in enumerate(tag_list_unique):
    for j,cur_tag in enumerate(tag_list_unique):
        tags_matrix[i, j] = transmission_probability(cur_tag,prev_tag) # row is the current tag, column is the previous tag

# In[65]:

tags_matrix

# In[66]:

tags_df = pd.DataFrame(tags_matrix, columns = tag_list_unique, index=tag_list_unique)

# In[67]:

# if '' in tag_list:
#     print(True)
# else:
#     print(False)
tags_df

# In[68]:

def Viterbi(words):
    state = [] #to record state that contribute to the maximum
    for index, word in enumerate(words):
        if word == '':
            state.append('')
        else:
            prob = []

            for tag in tag_list_unique:

                transmission_prob = tags_df.loc['',tag] if (index == 0) else tags_df.loc[state[-1],tag]
                emission_prob = get_emission(word, tag)
                state_prob = emission_prob * transmission_prob
                prob.append(state_prob)
            state.append(tag_list_unique[prob.index(max(prob))]) #record the state with max prob

    return list(zip(words,state))

# In[69]:

with open(test_corpora) as f:
    lines = [line.rstrip() for line in f]
answer = Viterbi(lines)

# In[70]:

file = open('submission.pos','w')
for each in answer:
    if each[0] == '':
        file.write("\n")
    else:
        file.write(each[0]+"\t"+each[1]+"\n")

file.close()

# In[ ]:

# In[ ]:


def is_sorted(arr):
    for i in range(len(arr) - 1):
        if arr[i] > arr[i + 1]:
            return False
    return True

def bubble_sort(arr):
    while not is_sorted(arr):
        for i in range(len(arr) - 1):
            # print(i)
            if arr[i] > arr[i + 1]:
                arr[i], arr[i + 1] = arr[i + 1], arr[i]
    return arr

# print(is_sorted([1, 3, 10, 2]))
# print(is_sorted([1, 3, 10, 11]))

print(bubble_sort([19, 3, 10, 2]))