#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
###############################################################################
# app.py
#
# Revision:     1.00
# Date:         6/8/2021
# Author:       Alex
#
# Purpose:      Displays a webpage using Flask.  Loads the GAN generator
#               PyTorch model and displays a random generated image.
#
# Notes:
# 1. If you've trained another generator change the GEN_FN variable to point
#    to its location.
#
###############################################################################
"""

import math
import os
from datetime import datetime
from flask import Flask
from flask import render_template
import torch
import torch.nn as nn
from PIL import Image
import numpy as np

# %% Classes
class Generator(nn.Module):
    """Generator class defining the neural network architecture."""
    def __init__(self, ngpu):
        super().__init__()
        self.ngpu = ngpu
        assert math.log(NGF, 2).is_integer(), \
            "Ensure image dimensions are a power of two!"
        self.num_blocks = int(math.log(NGF, 2) - 1)
        self.main = nn.Sequential(
            self._build_body(),
            nn.ConvTranspose2d(NGF, NC, 4, 2, 1, bias=False),
            nn.Tanh()
        )

    def _build_body(self):
        """Create all layers of the Generator excluding the output layers."""
        # Powers of two in reverse order
        channels = [NGF*(2**x) for x in range(self.num_blocks-2,-1,-1)]
        input_layer = self._convtrans_block(NZ, channels[0], kernel_size=4,
                                            stride=1, padding=0, bias=False)
        body_layers = [self._convtrans_block(inp_chan, out_chan, kernel_size=4,
                                             stride=2, padding=1, bias=False)
                       for inp_chan, out_chan in zip(channels, channels[1:])]
        return nn.Sequential(input_layer, *body_layers)

    def _convtrans_block(self, in_chan, out_chan, *args, **kwargs):
        """Returns a unit block of layers used in the body of the Generator neural network."""
        return nn.Sequential(
            nn.ConvTranspose2d(in_chan, out_chan, *args, **kwargs),
            nn.BatchNorm2d(out_chan),
            nn.ReLU(True)
    )

    def forward(self, input_data):
        """Called during forward pass through neural network."""
        return self.main(input_data)

# %% Functions
def generate_new_image():
    """Generates a new image and saves it to disk with a timestamp so that the
    filename is unique.  This prevents browser caching of images.  Returns the
    generated image's filename so that it can be passed to the HTML template.
    """
    timestamp = datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
    noise = torch.randn(1, NZ, 1, 1, device=device) # Latent Z vector
    with torch.no_grad():
        generated_img = model(noise).detach().cpu().numpy()
    # Rearrange axes so channels are last, and scale values from 0 to 255
    rearranged_arr = np.moveaxis(generated_img.squeeze(), (0,1,2), (2,0,1))
    scaled_arr = (rearranged_arr * 255 / np.max(rearranged_arr)).astype('uint8')
    # Create RGB image from Numpy array and save to disk with unique filename.
    pil_img = Image.fromarray(scaled_arr, "RGB")
    filename = f'static/img/pokegan_{timestamp}.png' # Avoid browser caching
    pil_img.convert("RGB").save(filename)
    return filename

# %% Define Parameters
PATH = 'static/img/'  # Path to folder containing website images

# PyTorch parameters
NC = 3     # Number of channels in the training images. For color images this is 3
NZ = 100   # Size of z latent vector (i.e. size of generator input)
NGF = 128  # Size of feature maps in generator
NGPU = 1   # Number of GPUs available. Use 0 for CPU mode.

# %% Load Generator Model
GEN_FN = '../models/Generator_2021-06-09_16:28:18.pth'
model = Generator(NGPU)
model.load_state_dict(torch.load(GEN_FN))
model.eval()
device = torch.device("cuda:0" if (torch.cuda.is_available() and NGPU > 0) \
                      else "cpu")
model.to(device)

# %% Run Flask Application
app = Flask(__name__)

@app.route("/")
def pokegan():
    """Generates a new image and refreshes the webpage whenever user
    queries server.  Old generated images are deleted, and the new image's
    filename is passed to the HTML template.
    """
    for file in os.listdir(PATH):
        if file.startswith("pokegan_20"): # Delete old generated images
            os.remove(PATH + file)        # to prevent clutter
    filename = generate_new_image()
    return render_template('index.html', filename=filename)

if __name__ == '__main__':
    generate_new_image() # For debugging


# -*- coding: utf-8 -*-
"""
Created on Sun Apr  8 19:21:00 2018

@author: IJACH
"""
import csv
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
from pylab import *
import numpy as np
import scipy.signal as sc
import pandas as pd

print("Fast Fourier Transform (FFT) Algorithm")
print("................................")
print("This program uses the FFT algorithm to study cyclical movements \
      in stock price.")

# ------------ Let us check for existence of the file path -------------------------
check_filepath=True
while check_filepath:
    filepath=input('enter the path of the csv file with the stock price data \
                   WITHOUT any  quotations and press Enter: ')
# Example of a file path :  \Users\IJACH\Desktop\MSFE\PROGRAMMING IN PYTHON\FINAL PROJECT\MSFTDATA.csv

# the following try -except-else block catches the error in file path and allows for repeated attempt
    try:
        f=csv.reader(filepath)
        print("Here is the filepath:"+ filepath)
    except FileNotFoundError:
        print("The filepath doesn't exist or there are some missing directories , please check and try again")
    else:
        print("Great! the file path is correct. Now, you can carry on!")
        break
# ------------ Let us Open our data file -------------------------
columns = defaultdict(list) # each value in each column is appended to a list

file_handle=open('{}'.format(filepath),'r')
reader=csv.reader(file_handle,delimiter=",")
next(reader,None) # Skips the header of the file which is Time_Index and Adj_Close_Price

for row in reader :
    for (i,v) in enumerate(row):
        columns[i].append(v)

columns[0] = list(map(int, columns[0])) # This list corresponds to the time index
columns[1] = list(map(float, columns[1]))  # This list corresponds to the Adjusted closing price
time,price=columns[0],columns[1] # assigning the above values to a more intuitive name time for time and price for price
#print("Time index is {}".format(time))
#print("Adjusted closing prices are {} ".format(price))

file_handle.close()

np.count_nonzero(price)
plt.plot(price)
plt.title("Stock price movement")

#Python code
detrend=sc.detrend(price)
#plt.plot(detrend)
#plt.title("Stock detrended prices")

#Python code
w=np.blackman(20) #we selected 20 the parameter of the blackman window function
y=np.convolve(w/w.sum(),detrend,mode='same')
plt.plot(y)
plt.title("Blackman window function for detrended Stock price")

#Python code
fft=abs(rfft(y))
plt.plot(fft)
plt.title("FFT Algorithm applied to Stock price")
print (fft)

Fast Fourier Transform (FFT) Algorithm.py


from time import time, sleep
from fd import *
from gendata import *

data_size = [100, 200, 500, 1000, 5000, 10000, 25000, 50000, 100000]
key_name = "Консервированный горошек"

for size in data_size:
    data = []
    hash_table = HashTable()

    generator(size)  # создаем файл с данными
    with open(f'./data_{size}.txt', mode='r', encoding='UTF-8') as database:
        for one_data in database:
            data.append(Product(one_data.strip()))  # переносим данные из файла в массив
            cp = Product(one_data.strip())
            data.append(cp)
            hash_table.insert(cp)

    start = time()
    value = hash_table.find_simple(key_name)
    sleep(0.01)
    end = time()
    print("Простое хэширование: " + "Размер: " + str(size) + ' ' + "Время: " + str(
        end - start - 0.01) + ' ' + "Число коллизий: " + str(hash_table.collisions_simple) + ' ' + str(value.name))

    start = time()
    value = hash_table.find_hard(key_name)
    sleep(0.01)
    end = time()
    print("Сложное хэширование: " + "Размер: " + str(size) + ' ' + "Время: " + str(
        end - start - 0.01) + ' ' + "Число коллизий: " + str(hash_table.collisions_hard) + ' ' + str(value.name) + '\n')


from PIL import Image, ImageDraw, ImageFont

def create_meme(image_path, top_text, bottom_text, output_path):
    with Image.open(image_path) as img:
        width, height = img.size

        # Load a font for the meme text
        font = ImageFont.load_default()

        # Create a drawing context
        draw = ImageDraw.Draw(img)

        # Calculate bounding boxes for top and bottom text
        top_text_bbox = draw.textbbox((0, 0), top_text, font=font)
        bottom_text_bbox = draw.textbbox((0, 0), bottom_text, font=font)

        # Calculate positions for top and bottom text
        top_text_x = (width - (top_text_bbox[2] - top_text_bbox[0])) // 2
        top_text_y = 10
        bottom_text_x = (width - (bottom_text_bbox[2] - bottom_text_bbox[0])) // 2
        bottom_text_y = height - (bottom_text_bbox[3] - bottom_text_bbox[1]) - 10

        # Draw top and bottom text on the image
        draw.text((top_text_x, top_text_y), top_text, font=font, fill="white")
        draw.text((bottom_text_x, bottom_text_y), bottom_text, font=font, fill="white")

        # Save the modified image
        img.save(output_path)

# Example usage
input_image_path = "4253978046.png"
output_image_path = "output_meme.png"
top_text = "The Fickle World of Flaky Friends"
bottom_text = "Event Planning Woes"
create_meme(input_image_path, top_text, bottom_text, output_image_path)
print(f"Meme created. Output image saved as: {output_image_path}")


from time import time
from numba import jit , prange , cuda
import asyncio

start = time()
@jit(parallel=True,fastmath=True,inline='always')
def primes_py(range_start , range_end):
    count_of_primes = 0
    range_start = range_start if range_start >=2 else 2
    for num in prange(range_start , range_end +1):
        for div_num in prange(2, num):
            if ((num % div_num) == 0 ):
                break
            else :
                count_of_primes += 1
    return count_of_primes

primes_py(0,2*10**7)

end = time()
print(f'it take {end - start} S')

# cpu 10**6 : it take 24.364680290222168 S
# cpu 10**6 : it take 23.455172777175903 S


"""
Given an array of distinct positive ints representing coin denominations and a single
non-negative int representing a target amount of money, write a function that returns
the number of ways to make change for that target amount using the given coinage.

Input:
    n = 6
    denoms = [1, 5]
Output:
    2 # 1x1 + 1x5 and 6x1

* you have an unlimited amount of coins
* Dynamic Programming
answer - O(N)T O(d)S --N=nodes, d=depth
"""

def numberOfWaysToMakeChange(array, money):

    units_in_money = [ 0 for x in range(money+1)]
    # [0, 0, 0, 0...]

    # Initialize zero dollar to one
    units_in_money[0] = 1
    for denomination in array:
        # Is my change within the unit?
        # The INDEX is my amount
        for unit in range(len(units_in_money)):
            if denomination <= unit:
                # If so, add the remaining denomination count to mine to get another change combo
                #units_in_money[unit] = units_in_money[unit] + units_in_money[unit-denomination]
                units_in_money[unit] += units_in_money[unit-denomination]

    return units_in_money[-1]

if __name__ == "__main__":

    array = [1, 5]
    money = 6
    array = [2, 3, 7]
    money = 0

    print(numberOfWaysToMakeChange(array, money))


from django.urls import path
from . import views

#Note: views.index is a  function in the views module
app_name = 'polls' #Useful for namespacing in the templates!
urlpatterns = [
    #ex /polls/
    path('', views.IndexView.as_view(), name='index'),
    #ex /polls/4/
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    #ex /polls/4/results/
    path('<int:pk>/results/', views.ResultsView.as_view(), name = 'results'),
    #ex /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),

    path('<int:comment_id>/upvote_me/', views.upvote_me, name='upvote_me'),

    path('user_submit_question/', views.user_submit_question, name='user_submit_question')

]


from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from selenium.webdriver.common.keys import Keys

meeting_1 = ""
#meeting_2 = input("Enter url of 2nd meeting:")
#meeting_3 = input("Enter url of 3rd meeting:")
#meeting_4 = input("Enter url of 4th meeting:")
#meeting_5 = input("Enter url of 5th meeting:")

def page_open_wait_Xpath(Xpath):
    try:
      element = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH, Xpath ))
    )
    except:
        print("page_open_wait_xpath error")

def page_open_wait(id):
    try:
     element = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.ID, id))
    )
    except:
        print("page_open_wait error")
chromedriver =  "/home/kavyansh/Desktop/cisco automation/chromedriver"
brave_path = "/usr/bin/brave-browser"
option  = webdriver.ChromeOptions()
option.binary_location = brave_path
driver = webdriver.Chrome(executable_path=chromedriver , options = option)
driver.get('https://meetingsapac40.webex.com/webappng/sites/meetingsapac40/meeting/download/22fa8f64ec31aeae23ae7f9d63d41576?launchApp=true')
time.sleep(10)

meeting_number = driver.find_element_by_xpath('//*[@id="meetingSimpleContainer"]/div[2]/div[2]/div/input')
send  = ActionChains(driver)

send.move_to_element(meeting_number).click().send_keys("166 990 7158").perform()


import numpy as np

def euclidean_distance(x, y):
    return abs(x - y)

def update_centroids(points, assignments, k):
    new_centroids = []
    for i in range(k):
        cluster_points = [points[j] for j in range(len(points)) if assignments[j] == i]
        if cluster_points:
            new_centroids.append(np.mean(cluster_points))
        else:
            new_centroids.append(None)
    return new_centroids

# Given points, initial means, and k value
points = [2, 3, 4, 10, 11, 12, 20, 25, 30]
k = 3
initial_means = [2, 4, 6]

# Initialize centroids and assignments
centroids = initial_means
assignments = [None] * len(points)

iteration = 0
while True:
    # Assign points to the closest centroid
    new_assignments = []
    for point in points:
        distances = [euclidean_distance(point, centroid) for centroid in centroids if centroid is not None]
        closest_centroid_idx = np.argmin(distances)
        new_assignments.append(closest_centroid_idx)

    # Update centroids based on new assignments
    new_centroids = update_centroids(points, new_assignments, k)

    # Check if the assignments have changed or not
    if new_assignments == assignments:
        break
    else:
        assignments = new_assignments
        centroids = new_centroids
        iteration += 1

    # Print results for each iteration
    print(f"Iteration {iteration}:")
    for i in range(k):
        cluster_points = [points[j] for j in range(len(points)) if assignments[j] == i]
        print(f"C{i + 1} = {cluster_points}")
    print(f"New centroids: {centroids}")

Scripts (kun testet på 2022 sættet)/kmeans 1 dimensional.py


"""
    Collect and prepare the CMC data for dataset
    (similar to create_tiny_datastet.py but only for CMC)
"""

path_manual_annotations = r"./annotations/shot-annotations_manual"
path_camera_annotations = r"./eval_cmc/all_annotations_per_vid_09032022"
path_cmc_output = r"./annotations/camera_annotations_manual"

import os
import json
import glob
import csv

def main():
    if not os.path.isdir(path_cmc_output):
        os.mkdir(path_cmc_output)

    annotations = glob.glob(os.path.join(path_manual_annotations, "*-shot_annotations.json"))
    for path in annotations:
        vid = os.path.split(path)[-1].split('-')[0]

        with open(path) as f:
            manual_annotations = json.load(f)

        path_cam_ann = os.path.join(path_camera_annotations, f"{vid}.csv")

        # Only continue if a camera movement exists
        if not os.path.isfile(path_cam_ann):
            continue

        with open(path_cam_ann) as f:
            csv_reader = csv.DictReader(f, delimiter=';')
            all_camera_annotations = [dict(row) for row in csv_reader]

        # Collect camera annotations
        camera_annotations = []
        for annotation in all_camera_annotations:
            corresponding_shot = list(filter(lambda shot: shot["inPoint"] <= int(annotation["start"]) - 1 and shot["outPoint"] >= int(annotation["stop"]) - 1, manual_annotations))
            # print(annotation)
            # print(corresponding_shot)
            if not len(corresponding_shot) == 1:
                print("VID: ", vid, "Start:", annotation["start"], "Stop:", annotation["stop"])
                continue

            camera_annotations.append({
            "shotId": corresponding_shot[0]["shotId"],
            # Note that SID in the CMCs is actually cmId (see below)
            "cmId": int(annotation["sid"]),
            "Start": int(annotation["start"]) - 1,
            "Stop": int(annotation["stop"]) - 1,
            "class_name": annotation["class_name"]})

        with open(os.path.join(path_cmc_output, f"{vid}-sequence_annotations.json"), 'w') as outfile:
            json.dump(camera_annotations, outfile, indent=4)

if __name__ == "__main__":
    main()


from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import math
import time

def calc(x):
  return str(math.log(abs(12*math.sin(int(x)))))

from selenium.webdriver.chrome.options import Options
chrome_options = Options()

webdriver.ChromeOptions().add_argument("--browser.chrome.path=F:/chrome-win64/chrome.exe")

webdriver.ChromeOptions().add_argument("--browser.chrome.driver=C:/chromedriver/chromedriver.exe")

try:
    browser = webdriver.Chrome()
    # говорим WebDriver ждать все элементы в течение 5 секунд
    browser.implicitly_wait(5)

    browser.get("http://suninjuly.github.io/explicit_wait2.html")

    # говорим Selenium проверять в течение 5 секунд, пока кнопка не станет кликабельной
    Money = WebDriverWait(browser, 12).until(
            EC.text_to_be_present_in_element((By.ID, "price"), "100")
        )
    button = browser.find_element(By.CSS_SELECTOR, "#book")
    button.click()

    input1 = browser.find_element(By.CSS_SELECTOR, "#input_value")
    answer_button = browser.find_element(By.CSS_SELECTOR, "#answer")
    x_value = input1.text
    answer = calc(x_value)
    answer_button.send_keys(answer)

    button2 = browser.find_element(By.CSS_SELECTOR, "#solve")
    button2.click()

    alert = browser.switch_to.alert
    print(alert.text)
    alert.accept()

finally:
    time.sleep(3)
    browser.quit()


import os
import json
import numpy as np
import argparse

pp = argparse.ArgumentParser(description='Format PASCAL 2012 metadata.')
pp.add_argument('--load-path', type=str, default='/home/julioarroyo/research_Eli_and_Julio/single-positive-multi-label-julio/data/pascal/', help='Path to a directory containing a copy of the PASCAL dataset.')
pp.add_argument('--save-path', type=str, default='/home/julioarroyo/research_Eli_and_Julio/single-positive-multi-label-julio/data/pascal/', help='Path to output directory.')
args = pp.parse_args()

catName_to_catID = {
    'person': 0,
    'bird': 1,
    'cat': 2,
    'cow': 3,
    'dog': 4,
    'horse': 5,
    'sheep': 6,
    'aeroplane': 7,
    'bicycle': 8,
    'boat': 9,
    'bus': 10,
    'car': 11,
    'motorbike': 12,
    'train': 13,
    'bottle': 14,
    'chair': 15,
    'diningtable': 16,
    'pottedplant': 17,
    'sofa': 18,
    'tvmonitor': 19
}

catID_to_catName = {catName_to_catID[k]: k for k in catName_to_catID}

ann_dict = {}
image_list = {'train': [], 'val': []}

for phase in ['train', 'val']:
    for cat in catName_to_catID:
        # this file tells you in what images does cat occurr
        with open(os.path.join(args.load_path, 'VOCdevkit', 'VOC2012', 'ImageSets', 'Main', cat + '_' + phase + '.txt'), 'r') as f:
            for line in f:
                cur_line = line.rstrip().split(' ')
                image_id = cur_line[0]
                label = cur_line[-1]
                image_fname = image_id + '.jpg'
                # if cat occurs, save it in ann_dict, which maps from image to catID that occur in the image
                # image_list holds all images with annotated objects in them, classified by train or val
                if int(label) == 1:
                    if image_fname not in ann_dict:
                        ann_dict[image_fname] = []
                        image_list[phase].append(image_fname)
                    ann_dict[image_fname].append(catName_to_catID[cat])
    # create label matrix:
    image_list[phase].sort()
    num_images = len(image_list[phase])
    label_matrix = np.zeros((num_images, len(catName_to_catID)))
    for i in range(num_images):
        cur_image = image_list[phase][i]
        label_indices = np.array(ann_dict[cur_image])
        label_matrix[i, label_indices] = 1.0 # puts a 1.0 at (i, j) where i is the i-th image and j is the index of the category
    np.save(os.path.join(args.save_path, 'formatted_' + phase + '_labels.npy'), label_matrix)
    np.save(os.path.join(args.save_path, 'formatted_' + phase + '_images.npy'), np.array(image_list[phase]))


import tkinter as tk
from tkinter import font
import requests
from PIL import Image
from PIL import ImageTk

root = tk.Tk()
root.title("Get Weather")

HEIGHT = 500
WIDTH = 600

#api weather 5 day: api.openweathermap.org/data/2.5/forecast?q={city name}&appid={your api key}
#api key: {your api key}

def format_response(weather):
    try:
        name = weather['name']
        desc = weather['weather'][0]['description']
        temp = weather['main']['temp']
        temp_min = weather['main']['temp_min']
        temp_max = weather['main']['temp_max']
        humidity = weather['main']['humidity']
        wind = weather['wind']['speed']
        sunrise = weather['sys']['sunrise']
        sunset = weather['sys']['sunset']

        weather_output = 'City: %s \nConditions: %s \nTemperature (°F): %s \n Low: %s \n High: %s \n Humidity: %s \n Wind Velocity: %s' % (name, desc, temp, temp_min, temp_max, humidity, wind)
    except:
        weather_output = "There was a problem retrieving that information."

    return weather_output

def get_weather(city):
    weather_key = '{your api key}'
    url = 'http://api.openweathermap.org/data/2.5/weather'
    params = {'APPID': weather_key, 'q': city, 'units': 'imperial'}
    response = requests.get(url, params=params)
    weather = response.json()
    #print(weather)

    label['text'] = format_response(weather)

    icon_name = weather['weather'][0]['icon']
    open_image(icon_name)

def open_image(icon):
    size = int(lower_frame.winfo_height()*0.25)
    img = ImageTk.PhotoImage(Image.open('./img/'+icon+'.png').resize((size, size)))
    weather_icon.delete("all")
    weather_icon.create_image(0,0, anchor='nw', image=img)
    weather_icon.image = img

canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

background_image = tk. PhotoImage(file="bitday_wallpaper_clock_1_0.png")
background_label = tk.Label(root, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

frame = tk.Frame(root, bg="#D9FCBC", bd=5)
frame.place(relx=0.5, rely=0.1, relwidth=0.75, relheight=0.1, anchor='n')

lower_frame = tk.Frame(root, bg="#FFFFD0", bd=10)
lower_frame.place(relx=0.5, rely=0.25, relwidth=0.75, relheight=0.6, anchor='n')

entry = tk.Entry(frame, font=("Calibri", 14))
entry.place(relwidth=0.65, relheight=1)

button = tk.Button(frame, text="Get Weather", command=lambda: get_weather(entry.get()))
button.place(relx=0.7, rely=0, relwidth=0.3, relheight=1)

label = tk.Label(lower_frame, font=("Calibri", 14))
label.place(relwidth=1, relheight=1)

weather_icon = tk.Canvas(label, bd=0, highlightthickness=0)
weather_icon.place(relx=.75, rely=0, relwidth=1, relheight=0.5)

root.mainloop()


#  Cost= income1 / (1 + r) + income 2/ (1 + r)2 + ...

t = int(input())

def calculator(r, income):
    ans = 0.0
    power = 1
    for i in range(len(income)-1):
        ans += income[i+1] / pow((1+r), power)
        power += 1
    return ans

for i in range(t):
    input()
    income = list(map(int, input().split()))

    cost = income[0]

    left = -1.0
    right = 1.0
    for _ in range(1000):
        mid = left + (right-left) / 2
        if (calculator(mid, income) > cost):
            left = mid
        else:
            right = mid

    print("Case #" + str(i+1) + ": " + str(mid))


"""
Graphene is based on an octree data structure. We mesh at
the lowest agglomerated level of the octree (L2) and then
create stitched meshes at each higher level of the tree
recursively starting from those L2 meshes. This scheme allows
use to rapidly reconfigure small regions that change while
proofreading.

The goal of meshing is to render each L2 label into a distinct
mesh. However, in order for the stitching to work, as in a flat
segmentation, we need to extend one voxel into the neighboring
chunk.

Each L2 chunk represents a self contained proofread agglomeration
of the L1 watershed regions over an area of typically 256x256x512
voxels. Actual proofreading extends across L2 chunks, but this is
represented by higher levels of the octree. Therefore, adjacent
L2 chunks have completely different labels.

In order to create accurate merging between chunks, we'll need to
relabel the overlap region using the lowest parent chunk ids between
the primary chunk and each individual overlap region (therefore each
overlap region may require a different chunk graph level). The reason
we can't just label them all with the root ID and mesh is that levels
higher than the lowest level may introduce non-local information. For
instance, a self touch on the boundary that would have been kept apart
at L3 would be unified at the root. The chunk position determines what
the lowest root is. For example, a chunk located at the origin will
require an L3 overlap merge. A chunk located one unit from the origin
will require an L4 merge. A chunk located three units from the origin
will require an L5 merge, and so on according to the fan-out of the octree.

Once the chunk is relabeled using the correct parent, some odd cases
crop up.  For example, due to information in the overlap region, L2
labels that were formerly independent connected components may be
merged via a chain of one or more L3+ relabeled overlap labels. Therefore,
we apply the following rules:

1. If the L2 label does not touch the overlap region, use that label.
2. Each overlap supervoxel is merged with neighboring labels that share
  a parent. Each resulting connected component is remapped using the minimum
  covered L2 label from the primary chunk. If no such label exists it
  is mapped to 0.

"""
from typing import Sequence
import numpy as np
import time
import collections
from functools import lru_cache
import datetime
import pytz

import networkx as nx

import cc3d

from tqdm import tqdm

import cloudvolume
from cloudvolume.lib import Bbox, Vec, xyzrange
from cloudvolume import CloudVolume
import fastremap

UTC = pytz.UTC

def remap_segmentation(
  cv, chunk_x, chunk_y, chunk_z, mip=2,
  overlap_vx=1, time_stamp=None, progress=False
):
  ws_cv = CloudVolume(
    cv.meta.cloudpath, mip=mip,
    progress=progress, fill_missing=cv.fill_missing
  )
  mip_diff = mip - cv.meta.watershed_mip

  mip_chunk_size = np.array(
    cv.meta.graph_chunk_size, dtype=np.int
  ) / np.array([2 ** mip_diff, 2 ** mip_diff, 1])
  mip_chunk_size = mip_chunk_size.astype(np.int)

  offset = Vec(chunk_x, chunk_y, chunk_z) * mip_chunk_size
  bbx = Bbox(offset, offset + mip_chunk_size + overlap_vx)
  if cv.meta.chunks_start_at_voxel_offset:
    bbx += ws_cv.voxel_offset
  bbx = Bbox.clamp(bbx, ws_cv.bounds)

  seg = ws_cv[bbx][..., 0]

  if not np.any(seg):
    return seg

  sv_remapping, unsafe_dict = get_lx_overlapping_remappings(
    cv, chunk_x, chunk_y, chunk_z,
    time_stamp=time_stamp, progress=progress
  )

  seg = fastremap.mask_except(seg, list(sv_remapping.keys()), in_place=True)
  fastremap.remap(seg, sv_remapping, preserve_missing_labels=True, in_place=True)

  for unsafe_root_id in tqdm(unsafe_dict.keys(), desc="Unsafe Relabel", disable=(not progress)):
    bin_seg = seg == unsafe_root_id

    if np.sum(bin_seg) == 0:
        continue

    cc_seg = cc3d.connected_components(bin_seg)
    for i_cc in range(1, np.max(cc_seg) + 1):
      bin_cc_seg = cc_seg == i_cc

      overlaps = []
      overlaps.extend(np.unique(seg[-2, :, :][bin_cc_seg[-1, :, :]]))
      overlaps.extend(np.unique(seg[:, -2, :][bin_cc_seg[:, -1, :]]))
      overlaps.extend(np.unique(seg[:, :, -2][bin_cc_seg[:, :, -1]]))
      overlaps = np.unique(overlaps)

      linked_l2_ids = overlaps[np.in1d(overlaps, unsafe_dict[unsafe_root_id])]

      if len(linked_l2_ids) == 0:
        seg[bin_cc_seg] = 0
      else:
        seg[bin_cc_seg] = linked_l2_ids[0]

  return seg

@lru_cache(maxsize=200)
def get_higher_to_lower_remapping(cv, chunk_id, time_stamp):
  """
  Retrieves lx node id to sv id mappping

  :param cv: CloudVolumeGraphene object
  :param chunk_id: np.uint64
  :param time_stamp: datetime object
  :return: dictionary
  """
  rr_chunk = cv.get_chunk_mappings(chunk_id=chunk_id, timestamp=time_stamp)

  # This for-loop ensures that only the latest lx_ids are considered
  # The order by id guarantees the time order (only true for same neurons
  # but that is the case here).
  lx_remapping = {}
  all_lower_ids = set()
  for k in sorted(rr_chunk.keys(), reverse=True):
    this_child_ids = rr_chunk[k]

    if this_child_ids[0] in all_lower_ids:
      continue

    all_lower_ids.update(list(this_child_ids))
    lx_remapping[k] = this_child_ids

  return lx_remapping

@lru_cache(maxsize=None)
def get_root_lx_remapping(cv, chunk_id, stop_layer, time_stamp):
  """
  Retrieves root to l2 node id mapping

  :param cv: CloudVolumeGraphene object
  :param chunk_id: np.uint64
  :param stop_layer: int
  :param time_stamp: datetime object
  :return: multiples
  """
  lx_id_remap = get_higher_to_lower_remapping(
    cv, chunk_id, time_stamp=time_stamp
  )

  lx_ids = np.array(list(lx_id_remap.keys()))
  root_ids = cv.get_roots(lx_ids, stop_layer=stop_layer)

  return lx_ids, np.array(root_ids), lx_id_remap

# @lru_cache(maxsize=None)
def get_lx_overlapping_remappings(
  cv, chunk_x, chunk_y, chunk_z,
  time_stamp=None, progress=False
):
  """
  Retrieves sv id to layer mapping for chunk with overlap in positive
    direction (one chunk)

  :param cv: CloudVolumeGraphene object
  :param chunk_x: np.uint64
  :param chunk_y: np.uint64
  :param chunk_z: np.uint64
  :param time_stamp: datetime object
  :return: multiples
  """
  if time_stamp is None:
    time_stamp = datetime.datetime.utcnow()

  if isinstance(time_stamp, datetime.datetime) and time_stamp.tzinfo is None:
    time_stamp = UTC.localize(time_stamp)

  chunk_layer = 2
  chunk_id = cv.meta.encode_label(chunk_layer, chunk_x, chunk_y, chunk_z, 0)

  neigh_chunk_ids = []
  neigh_parent_chunk_ids = []

  # Collect neighboring chunks and their parent chunk ids
  # We only need to know about the parent chunk ids to figure the lowest
  # common chunk
  # Notice that the first neigh_chunk_id is equal to `chunk_id`.
  for x in range(chunk_x, chunk_x + 2):
    for y in range(chunk_y, chunk_y + 2):
      for z in range(chunk_z, chunk_z + 2):

        neigh_chunk_id = cv.meta.encode_label(layer=2, x=x, y=y, z=z, segid=0)
        neigh_chunk_ids.append(neigh_chunk_id)
        neigh_parent_chunk_ids.append(
          get_parent_chunk_ids(cv, neigh_chunk_id)
        )

  # Find lowest common chunk
  # finding the layer that has the lowest common parent of
  # these 8 neighboring chunks
  # Layer agreement will equal 0 if that is layer 3, 1 if
  # that is layer 4, etc
  neigh_parent_chunk_ids = np.array(neigh_parent_chunk_ids)
  layer_agreement = np.all(
    (neigh_parent_chunk_ids - neigh_parent_chunk_ids[0]) == 0, axis=0
  )
  stop_layer = np.where(layer_agreement)[0][0] + chunk_layer

  # Find the parent in the lowest common chunk for each l2 id. These parent
  # ids are referred to as root ids even though they are not necessarily the
  # root id.
  neigh_lx_ids = []
  neigh_lx_id_remap = {}
  neigh_root_ids = []

  safe_lx_ids = []
  unsafe_lx_ids = []
  unsafe_root_ids = []

  # This loop is the main bottleneck
  for neigh_chunk_id in tqdm(neigh_chunk_ids, disable=(not progress), desc="Neighbor"):
    # print(f"Neigh: {neigh_chunk_id} --------------")

    lx_ids, root_ids, lx_id_remap = get_root_lx_remapping(
      cv, neigh_chunk_id, stop_layer, time_stamp=time_stamp
    )
    neigh_lx_ids.extend(lx_ids)
    neigh_lx_id_remap.update(lx_id_remap)
    neigh_root_ids.extend(root_ids)

    if neigh_chunk_id == chunk_id:
      # The first neigh_chunk_id is the one we are interested in. All lx
      # ids that share no root id with any other lx id are "safe", meaning
      # that we can easily obtain the complete remapping (including
      # overlap) for these. All other ones have to be resolved using the
      # segmentation.
      _, u_idx, c_root_ids = np.unique(
        neigh_root_ids, return_counts=True, return_index=True
      )

      safe_lx_ids = lx_ids[u_idx[c_root_ids == 1]]
      unsafe_lx_ids = lx_ids[~np.in1d(lx_ids, safe_lx_ids)]
      unsafe_root_ids = np.unique(root_ids[u_idx[c_root_ids != 1]])

  lx_root_dict = dict(zip(neigh_lx_ids, neigh_root_ids))
  root_lx_dict = collections.defaultdict(list)

  # Future sv id -> lx mapping
  sv_ids = []
  lx_ids_flat = []

  # Do safe ones first
  for i_root_id in range(len(neigh_root_ids)):
    root_lx_dict[neigh_root_ids[i_root_id]].append(neigh_lx_ids[i_root_id])

  for lx_id in safe_lx_ids:
    root_id = lx_root_dict[lx_id]
    for neigh_lx_id in root_lx_dict[root_id]:
      lx_sv_ids = neigh_lx_id_remap[neigh_lx_id]
      sv_ids.extend(lx_sv_ids)
      lx_ids_flat.extend([lx_id] * len(neigh_lx_id_remap[neigh_lx_id]))

  # For the unsafe ones we can only do the in chunk svs
  # But we will map the out of chunk svs to the root id and store the
  # hierarchical information in a dictionary
  for lx_id in unsafe_lx_ids:
    sv_ids.extend(neigh_lx_id_remap[lx_id])
    lx_ids_flat.extend([lx_id] * len(neigh_lx_id_remap[lx_id]))

  unsafe_dict = collections.defaultdict(list)
  for root_id in unsafe_root_ids:
    if np.sum(~np.in1d(root_lx_dict[root_id], unsafe_lx_ids)) == 0:
      continue

    for neigh_lx_id in root_lx_dict[root_id]:
      unsafe_dict[root_id].append(neigh_lx_id)

      if neigh_lx_id in unsafe_lx_ids:
        continue

      sv_ids.extend(neigh_lx_id_remap[neigh_lx_id])
      lx_ids_flat.extend([root_id] * len(neigh_lx_id_remap[neigh_lx_id]))

  # Combine the lists for a (chunk-) global remapping
  sv_remapping = dict(zip(sv_ids, lx_ids_flat))

  return sv_remapping, unsafe_dict

def get_parent_chunk_ids(cv, label):
  """
  Creates list of chunk parent ids

  :param label: np.uint64
  :return: np.ndarray
  """
  parent_chunk_layers = range(
    int(cv.meta.decode_layer_id(label)) + 1, int(cv.meta.n_layers) + 1
  )

  chunk_coord = Vec(*cv.meta.decode_chunk_position(label))

  parent_chunk_ids = [ cv.meta.decode_chunk_id(label) ]
  for layer in parent_chunk_layers:
    chunk_coord = chunk_coord // cv.meta.fan_out
    chunk_id = cv.meta.encode_label(
      layer, chunk_coord[0], chunk_coord[1], chunk_coord[2], segid=0
    )
    parent_chunk_ids.append(chunk_id)

  return np.array(parent_chunk_ids, dtype=np.uint64)


import pandas as pd
import maboss

class Cellline:
    def __init__(self, name, mutations, transition_rates_up, initial_states, dict_gene_nodes, dict_strict_gene_nodes):
        self.name = name
        self.mutations = mutations
        self.transition_rates_up = transition_rates_up
        self.initial_states = initial_states
        self.dict_gene_nodes = dict_gene_nodes
        self.dict_strict_gene_nodes = dict_strict_gene_nodes
    def __repr__(self):
        try :
            self.model
            try:
                self.results
                return self.name+', simu'
            except:
                return self.name+', compu'
        except:
            return self.name

    def personalize_model(self, model):
        personalized_model = model.copy()
        nodes = model.network.names

        for node in nodes:
            to_inverse=False
            if node in self.dict_gene_nodes:
                for gene in self.dict_gene_nodes[node]:
                    if gene[0]=='!':
                        to_inverse = True
                        gene = gene[1:]
                    if gene in self.mutations.keys():
                        val_mut = self.mutations[gene]
                        if to_inverse:
                            if val_mut=='ON':
                                val_mut ='OFF'
                            else:
                                val_mut = 'ON'
                        personalized_model.mutate(node, val_mut)
            if node in self.dict_strict_gene_nodes:
                for gene in self.dict_strict_gene_nodes[node]:
                    if gene in self.transition_rates_up.keys():
                        personalized_model.param['$u_'+node] = self.transition_rates_up[gene]
                        personalized_model.param['$d_'+node] = 1/self.transition_rates_up[gene]
            if len(self.initial_states)!=0:
                for node in self.initial_states:
                    personalized_model.network.set_istate(node, self.initial_states[node])
        self.model = personalized_model
        return personalized_model

    def run_simulation(self):
        self.results = self.model.run()
        print('done')

class CellEnsemble:
    def __init__(self, celllines, general_model):
        self.model = general_model
        self.data = celllines
        self.simu = {'base':{cellname:Cellline(**celllines[cellname])
                             for cellname in celllines}}
        self.update()
    def __repr__(self):
        return 'conditions : '+str(list(self.simu.keys()))+'\ncell lines : '+str(list(self.simu['base'].keys()))
    def resume(self):
        """Plot the names of the personalized models stored, under a pandas.DataFrame format."""
        return pd.DataFrame(self.simu)

    def add_condition(self, conditions, condition_name):
        """Add a condition (new version of each cell line personalized model with mutations) to the CellEnsembl object
        conditions : mutations in the MaBoSS format : (Node_name, effect). The effect can be 'ON' or 'OFF'. For mutliple mutation, a list or tuple can be given.
        condition_name : name of the condition to call them and to define title of the output graphs.
        """
        self.simu[condition_name] = {cellname:Cellline(**celllines[cellname])
                                     for cellname in celllines}
        self.update()
        if type(conditions[0]) is not str:
            print('{} mutations for the condition {}'.format(len(conditions), condition_name))
            for condition in conditions:
                for k in self.simu[condition_name]:
                    self.simu[condition_name][k].model.mutate(*condition)
        else:
            for k in self.simu[condition_name]:
                self.simu[condition_name][k].model.mutate(*conditions)

    def update(self, new_model=None):
        """By default, the method recreates personalized versions of the model which is stored as an attribute : self.model.
        new model : You can also give the new version of the general model directly as an argument in this method with this argument.
        It allow to keep the format of the CellEnsembl object (conditions and celllines) but to change the general model used.
        """
        if new_model is not None:
            self.model = new_model

        for k1 in self.simu:
            for k2 in self.simu[k1]:
                self.simu[k1][k2].personalize_model(self.model)

    def run_simulation(self, celllines='all', conditions='all', redo=True, mute=False):

        if celllines == 'all':
            celllines = list(self.simu['base'].keys())
        elif type(celllines) not in [list, tuple]:
            celllines = [celllines]
        if conditions == 'all':
            conditions = list(self.simu.keys())
        elif type(conditions) not in [list, tuple]:
            conditions = [conditions]

        for condition in conditions:
            for cellline in celllines:
                if redo==False:
                    try:
                        self.simu[condition][cellline].results
                        if mute==False:
                            print('the simulation {}|{} will not be re-computed'.format(cellline, condition))
                        continue
                    except:
                        pass
                if mute==False:
                    print('Simulating', cellline, 'in the condition', condition)
                self.simu[condition][cellline].run_simulation()

    def plot_piechart(self, celllines='all', conditions='all'):
        if celllines == 'all':
            celllines = list(self.simu['base'].keys())
        elif type(celllines) not in [list, tuple]:
            celllines = [celllines]
        if conditions == 'all':
            conditions = list(self.simu.keys())
        elif type(conditions) not in [list, tuple]:
            conditions = [conditions]

        if len(conditions)>1:
            for cellline in celllines:
                fig, axs = plt.subplots(1, len(conditions), figsize=(8*len(conditions),5), constrained_layout=True)
                for condition in conditions:
                    try:
                        self.simu[condition][cellline].results.plot_piechart(axes = axs[conditions.index(condition)])
                        axs[conditions.index(condition)].set_title(cellline + ' | ' + condition)
                    except:
                        print('the simulation {}|{} seems not having been computed'.format(cellline, condition))
        else:
            for condition in conditions:
                for cellline in celllines:
                    try:
                        self.simu[condition][cellline].results.plot_piechart()
                        plt.title(cellline + ' | ' + condition)
                    except:
                        print('the simulation {}|{} seems not having been computed'.format(cellline, condition))
    def plot_trajectory(self, celllines='all', conditions='all'):
        if celllines == 'all':
            celllines = list(self.simu['base'].keys())
        elif type(celllines) not in [list, tuple]:
            celllines = [celllines]
        if conditions == 'all':
            conditions = list(self.simu.keys())
        elif type(conditions) not in [list, tuple]:
            conditions = [conditions]

        if len(conditions)>1:
            for cellline in celllines:
                fig, axs = plt.subplots(1, len(conditions), figsize=(8*len(conditions),5), constrained_layout=True)
                for condition in conditions:
                    try:
                        self.simu[condition][cellline].results.plot_trajectory(axes = axs[conditions.index(condition)])
                        axs[conditions.index(condition)].set_title(cellline + ' | ' + condition)
                    except:
                        print('the simulation {}|{} seems not having been computed'.format(cellline, condition))
        else:
            for condition in conditions:
                for cellline in celllines:
                    try:
                        self.simu[condition][cellline].results.plot_trajectory()
                        plt.title(cellline + ' | ' + condition)
                    except:
                        print('the simulation {}|{} seems not having been computed'.format(cellline, condition))

    def compare_survival(self, celllines='all', conditions='all'):

        outputs_df = pd.DataFrame(index=[], columns=['proliferation_rates', 'survival_rates'])

        if celllines == 'all':
            celllines = list(self.simu['base'].keys())
        elif type(celllines) not in [list, tuple]:
            celllines = [celllines]
        if conditions == 'all':
            conditions = list(self.simu.keys())
        elif type(conditions) not in [list, tuple]:
            conditions = [conditions]

        for condition in conditions:
            for cellline in celllines:
                outputs_dict = {'survival_rates' : {}, 'proliferation_rates' : {}}

                st = self.simu[condition][cellline].results.last_states_probtraj
                death_rate = float(sum(st[s] for s in st if 'Apoptosis' in s or 'Mitotic' in s))
                proliferation = float(sum(st[s] for s in st if 'Apoptosis' not in s and 'Mitotic' not in s and 'Prolif' in s))

                outputs_dict['survival_rates'][condition+'_'+cellline] =  1-death_rate
                outputs_dict['proliferation_rates'][condition+'_'+cellline] = proliferation
                outputs_df = pd.concat([pd.DataFrame(outputs_dict), outputs_df])
        return outputs_df


import collections
import multiprocessing

def calculate_price_in_rupees(DishName):
    return {
        'dish': DishName.dish,
        'price': round(DishName.price * 77.85, 2)
    }

DishName = collections.namedtuple('DishName', [
    'dish',
    'price',
])
if __name__ == "__main__":
    DishNames = (
        DishName(dish='Shrimp Carbonara', price=1815),
        DishName(dish='Lobster Bisque', price=1882),
        DishName(dish='Spaghetti with Meatballs', price=1867),
        DishName(dish='Tom Kha Ghai', price=1930),
        DishName(dish='Cordon Bleu', price=1939),
        DishName(dish='Coq au Vin', price=1928),
        DishName(dish='Pomme Frites', price=1951),
    )

pool = multiprocessing.Pool()
result = pool.map(calculate_price_in_rupees, DishNames)
print(result)
'''
[{'dish': 'Shrimp Carbonara', 'price': 141297.75},
{'dish': 'Lobster Bisque', 'price': 146513.7},
{'dish': 'Spaghetti with Meatballs', 'price': 145345.95},
{'dish': 'Tom Kha Ghai', 'price': 150250.5},
{'dish': 'Cordon Bleu', 'price': 150951.15},
{'dish': 'Coq au Vin', 'price': 150094.8},
{'dish': 'Pomme Frites', 'price': 151885.35}]
'''


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr  2 09:50:07 2019

@author: pickering
"""

import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import matplotlib.lines as lines
import matplotlib.gridspec as gs
import matplotlib.patches as patch
plt.rc('text', usetex=True)
plt.rc('font', family='sans-serif',size='12')

plt.close('all')
fig = plt.figure()
fig.set_size_inches(4,5)
ax = plt.gca()
plt.plot([0,1],[0.2,0.2], color='k')
plt.plot([0,1],[0.8,0.8], color='k')
plt.xlim(-0.5,1.5)
plt.ylim(0,1)
plt.xticks([])
plt.yticks([0.2,0.8],[r'$E_1$',r'$E_2'])
arrow = patch.FancyArrowPatch((0.1,0.2),(0.1,0.8),arrowstyle='simple',mutation_scale=20,color='b')
ax.add_artist(arrow)

arrow2 = patch.FancyArrowPatch((0.9,0.8),(0.9,0.2),arrowstyle='simple',mutation_scale=20,color='r')
ax.add_artist(arrow2)

plt.text(-0.2,0.25,r'Absorption',color='b',ha='center',va='center')
plt.text(1.2,0.25,r'Emission',color='r',ha='center',va='center')
plt.text(0.5,0.1,r'$h\nu = \Delta E = E_2-E_1$',color='k',ha='center',va='center')

arrow3 = patch.FancyArrowPatch((0.4,0.2),(0.4,0.8),arrowstyle='|-|',mutation_scale=5,color='k',ls='-',alpha=0.5)
ax.add_artist(arrow3)
plt.text(0.5,0.5,r'$h\nu$',color='k',ha='center',va='center')
plt.savefig('../final_figures/energy_gap.png', bbox_inches='tight', dpi=400)


import torch
import numpy as np

def createDictLabels(labels):

    """
    Creates dictionaries that fits data with non-sequential labels into a
    sequential order label from [0...nClasses].
    :param labels: all the non-sequential labels
    :return: dict that converts from non-sequential to sequential,
             dict that converts from sequential to non-sequential
    """

    # Re-arange the Target vectors between [0..nClasses_train]
    labels = labels.numpy()
    unique_labels = np.unique(labels)
    dictLabels = {val: i for i, val in enumerate(unique_labels)}
    dictLabelsInverse = {i: val for i, val in enumerate(unique_labels)}
    return dictLabels,dictLabelsInverse

def fitLabelsToRange(dictLabels,labels):

    """
    Converts Tensor values to the values contained in the dictionary
    :param dictLabels: dictionary with the conversion values
    :param labels: Tensor to convert
    :return: Tensor with the converted labels.
    """
    labels = labels.numpy()
    unique_labels = np.unique(labels)
    labels_temp = np.array(labels)
    for i in dictLabels.keys():
        labels_temp[labels == i] = dictLabels[i]
    labels = labels_temp
    return torch.from_numpy(labels)

def unflattenParams(model,flatParams):
    flatParams = flatParams.squeeze()
    indx = 0
    for param in model.net.parameters():
        lengthParam = param.view(-1).size()[0]
        param.data = flatParams[indx:indx+lengthParam].view_as(param).data
        indx = indx + lengthParam
    a = 0


# tutorial based on this YT video: https://www.youtube.com/watch?v=lLPdRRy7dfE&list=PL3JVwFmb_BnRKqcbtl2hHL5GIQOHX-sC5&index=1
import os
from google.cloud import bigquery

os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'CloudDemo_AS_Service.json'

client = bigquery.Client()

sql_query = """
SELECT station_id, name, dockcount
FROM `bigquery-public-data.san_francisco.bikeshare_stations`
LIMIT 50
"""

query_job = client.query(sql_query)

for row in query_job.result():
    print(row)

print(query_job.to_dataframe())


#!/usr/bin/env python
"""
:Created: 2015-06-29

"""
from __future__ import print_function

__description__ = 'host -'
__version__ = '0.0.4-dev' # script-mpe
__db__ = '~/.taxus-code.sqlite'
__rc__ = '~/.domain.rc'
__usage__ = """

Usage:
  host.py [options] ( find <ref>...
                       | info [ <ref>... ]
                       | init [ -p... ]
                       | list
                       | new -p...
                       | update -p... <ref> )
  host.py [options] test init

Options:
    -c RC --config=RC
                  Use config file to load settings [default: %s]
    -d REF --dbref=REF
                  SQLAlchemy DB URL [default: %s].

Other flags:
    -h --help     Show this usage description.
                  For a command and argument description use the command 'help'.
    --version     Show version (%s).

""" % ( __rc__, __db__, __version__ )
__doc__ += __usage__

import os
from datetime import datetime

from script_mpe import log
from script_mpe import libcmd_docopt
from script_mpe.libcmd_docopt import cmd_help
from script_mpe.taxus import core, net, ScriptMixin
from script_mpe.domain2 import init_host

def cmd_init(settings):
    sa = net.Host.get_session('default', settings.dbref)
    host_dict = init_host(settings)
    name = host_dict['name']
    record = net.Host.fetch(filters=(net.Host.name == name,), sa=sa, exists=False)
    if not record:
        host = net.Host(name=name, date_added=datetime.now(),
                date_updated=datetime.now())
        sa.add(host)
        sa.commit()
        log.std('{bwhite}Added host %s record{default}', name)
    else:
        host = record
    print('host at', host_dict.path(), ':', host)

def cmd_list(settings):
    sa = net.Host.get_session('default', settings.dbref)
    for h in sa.query(net.Host).all():
        print(h)

def cmd_test_init(settings):
    sa = net.Host.get_session('default', settings.dbref)
    host_dict = init_host(settings)
    name = host_dict['name']
    print(net.Host.fetch(filters=(net.Host.name == name,), sa=sa, exists=False))
    #print net.Host.init(sa=sa)

### Transform cmd_ function names to nested dict

commands = libcmd_docopt.get_cmd_handlers(globals(), 'cmd_')
commands['help'] = libcmd_docopt.cmd_help

### Util functions to run above functions from cmdline

def main(opts):

    """
    Execute command.
    """

    #settings = opts.flags
    opts.flags.configPath = os.path.expanduser(opts.flags.config)
    settings = libcmd_docopt.init_config(opts.flags.configPath, dict(
            nodes = {}, interfaces = {}, domain = {}
        ), opts.flags)
    opts.default = 'info'
    return libcmd_docopt.run_commands(commands, settings, opts)

def get_version():
    return 'taxus-host-py.mpe/%s' % __version__

if __name__ == '__main__':
    import sys
    opts = libcmd_docopt.get_opts(__doc__, version=get_version())
    opts.flags.dbref = ScriptMixin.assert_dbref(opts.flags.dbref)
    sys.exit(main(opts))


#!usr/bin/python
# -*- coding: utf-8 -*-
import time
while True:
    try:
        date=input('请输入日期：')
        struct_time=time.strptime(date,'%Y-%m-%d')
    except ValueError as e:
        print("输入日期有误:{e}\n请重新输入".format(e=e))
        continue
    else:
        print(struct_time.tm_yday)
        break


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import MetaData
from sqlalchemy import String
from sqlalchemy import Table
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker

# 初始化数据连接,create_engine()用来初始化数据库连接
# SQLAlchemy用一个字符串表示连接信息：'数据库类型+数据库驱动名称://用户名:口令@机器地址:端口号/数据库名'
engine = create_engine('mysql+mysqlconnector://root:root@localhost:3306/test_python')

# 创建元数据
metadata = MetaData(engine)

# 创建表
c = Table('classroom', metadata,
      Column('id', String(20), primary_key=True),
      Column('name', String(20)),
      mysql_engine='InnoDB',
      mysql_charset='utf8',
      mysql_key_block_size="1024"
     )
t = Table('teacher', metadata,
      Column('id', String(20), primary_key=True),
      Column('name', String(20)),
      Column('subject', String(20)),
      Column('class_id', String(20)),
      mysql_engine='InnoDB',
      mysql_charset='utf8',
      mysql_key_block_size="1024"
     )
metadata.create_all()

# 创建对象基类
Base = declarative_base()

# 班级
class Classroom(Base):
    __tablename__ = 'classroom'

    id = Column(String(20), primary_key=True)
    name = Column(String(20))
    # 一对多
    teacher = relationship('Teacher')

    def __repr__(self):
        return '<User: (id: %s, name: %s, teacher: %s)>' % (self.id, self.name, self.teacher)

class Teacher(Base):
    __tablename__ = 'teacher'

    id = Column(String(20), primary_key=True)
    name = Column(String(20))
    subject = Column(String(20))

    # "多"的一方teacher表是通过外键关联到class表
    class_id = Column(String(20), ForeignKey('classroom.id'))

    def __repr__(self):
        return '<Teacher: (id: %s, name: %s, subject: %s, class_id: %s)>' % (self.id, self.name, self.subject, self.class_id)

# 多次插入方式
def insert_multiple():
    new_class = Classroom(id='1', name='三年二班')
    session.add(new_class)
    session.commit()

    math_teacher = Teacher(id='1', name='李志', class_id='1', subject='数学')
    chiese_teacher = Teacher(id='2', name='赵雷', class_id='1', subject='语文')
    session.add_all([math_teacher, chiese_teacher])
    session.commit()

# 一次插入方式
def insert_once():
    math_teacher = Teacher(id='1', name='李志', class_id='1', subject='数学')
    chiese_teacher = Teacher(id='2', name='赵雷', class_id='1', subject='语文')
    new_class = Classroom(id='1', name='三年二班', teacher=[math_teacher, chiese_teacher])
    session.add(new_class)
    session.commit()

DBsession = sessionmaker(bind=engine)
session = DBsession()

insert_once()

result = session.query(Classroom).filter(Classroom.id == '1').all()
print(result)

session.close()


import random
import torch
from utils import print_rank_0
from SwissArmyTransformer.model import GLMModel, EncoderDecoderModel
from SwissArmyTransformer.model.mixins import BaseMixin
from SwissArmyTransformer.model.base_model import non_conflict
from SwissArmyTransformer.mpu.transformer import standard_attention, split_tensor_along_last_dim

def get_prefix_model(model_cls):
    def new_model_cls(args):
        model = model_cls(args)
        if args.freeze_transformer:
            print_rank_0("Freeze transformer parameters")
            model.requires_grad_(False)
        prefix_mixin = PrefixPromptMixin(prefix_length=args.prefix_prompt, num_layers=args.num_layers,
                                         hidden_size=args.hidden_size, prompt_func=args.prompt_func)
        if isinstance(model, GLMModel):
            model.add_mixin(
                "prefix_prompt",
                prefix_mixin
            )
        elif isinstance(model, EncoderDecoderModel):
            model.encoder.add_mixin(
                "prefix_prompt",
                prefix_mixin
            )
        else:
            raise NotImplementedError(model_cls)
        return model

    return new_model_cls

class PrefixPromptMixin(BaseMixin):
    def __init__(self, prefix_length, num_layers, hidden_size, prompt_func='none'):
        super().__init__()
        self.prefix_length = prefix_length
        self.num_layers = num_layers
        self.hidden_size = hidden_size
        self.embeddings = torch.nn.ModuleList(
            [torch.nn.Embedding(prefix_length, hidden_size) for _ in range(self.num_layers)]
        )
        for embedding in self.embeddings:
            torch.nn.init.normal_(embedding.weight, mean=0, std=0.1)
        self.prompt_func = prompt_func
        if prompt_func != 'none':
            raise NotImplementedError(prompt_func)

    def get_prompt(self, batch_size, layer_id):
        prefix_hidden_states = self.embeddings[layer_id].weight
        prefix_hidden_states = prefix_hidden_states.unsqueeze(0).expand(batch_size, -1, -1)
        return prefix_hidden_states

    @non_conflict
    def attention_fn(self, q, k, v, mask, dropout_fn, old_impl=standard_attention, layer_id=None, cross_attention=False,
                     **kw_args):
        if not cross_attention:
            attn_module = self.transformer.layers[layer_id].attention
            prefix = self.get_prompt(q.size(0), layer_id)
            mixed_raw_layer = attn_module.query_key_value(prefix)
            (_,
             mixed_key_prefix,
             mixed_value_prefix) = split_tensor_along_last_dim(mixed_raw_layer, 3)
            key_prefix = attn_module._transpose_for_scores(mixed_key_prefix)
            value_prefix = attn_module._transpose_for_scores(mixed_value_prefix)
            k, v = torch.cat((key_prefix, k), dim=2), torch.cat((value_prefix, v), dim=2)
            if mask.numel() > 1:
                mask_prefix = torch.ones(self.prefix_length, device=mask.device, dtype=mask.dtype)
                mask_prefix = mask_prefix.expand(*(mask.size()[:-1]), -1)
                mask = torch.cat((mask_prefix, mask), dim=-1)
        return old_impl(q, k, v, mask, dropout_fn, layer_id=layer_id, cross_attention=cross_attention,
                        **kw_args)


# tests programmatic config of template system
import os

import pytest

BASE_DIR = os.path.dirname(__file__)

@pytest.fixture
def voila_config():
    def config(app):
        pass

    os.environ["JUPYTER_CONFIG_DIR"] = os.path.join(BASE_DIR, "../configs/general")
    yield config
    del os.environ["JUPYTER_CONFIG_DIR"]

@pytest.fixture
def voila_config_file_paths_arg():
    # we don't want the tests to use any configuration on the system
    path = os.path.abspath(os.path.join(BASE_DIR, "../configs/general"))
    return "--VoilaTest.config_file_paths=[%r]" % path

@pytest.mark.skip(reason="TODO: update for JupyterLab extensions")
async def test_lists_extension(http_server_client, base_url):
    response = await http_server_client.fetch(base_url)
    assert response.code == 200
    html_text = response.body.decode("utf-8")
    assert "Hi Voilà" in html_text
    assert "ipytest/extension.js" in html_text


# This Python file uses the following encoding: utf-8

from pyrevit import revit, DB
from rpw.ui.forms import Alert

kolektor = DB.FilteredElementCollector(revit.doc).WhereElementIsNotElementType().WhereElementIsViewIndependent().OfCategory(DB.BuiltInCategory.OST_Walls).ToElements()
curtainWalls = []
n = 0

for e in kolektor:
	try:
		elementType = revit.doc.GetElement(e.GetTypeId())
		if elementType.Kind == DB.WallKind.Curtain:
			curtainWalls.append(e)
			n = n + 1
	except:
		print("not curtain wall")

text = "Broj obrađenih zidova je : " + str(n)
tits = "Allow Joints for Curtain Walls"

Alert(text, title=tits, header="Trolovi su uspešno obavili posao!")

with revit.Transaction(tits, revit.doc):
	for e in curtainWalls:
		try:
			DB.WallUtils.AllowWallJoinAtEnd(e, 0)
			DB.WallUtils.AllowWallJoinAtEnd(e, 1)
		except:
			print("Fail")
	# End Transaction

Workflow321.tab/Automation.panel/Wall Join At End.pulldown/Allow.pushbutton/script.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# By Allex Lima <allexlima@unn.edu.br> | www.allexlima.com

from ui_manager import *

if __name__ == "__main__":
    app = QtGui.QApplication(['BestFit Algorithm'])
    window = BestfitApp()
    window.show()
    app.exec_()


import asyncio
import time

import aiohttp

from data import config
from handlers.users.image import servers

async def check_real():
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(url=f'{servers["real"]}') as response:
                r = await response.json()
                real = 'ðŸŸ¢'
    except:
        real = 'ðŸ”´'
    return real

async def check_dream():
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(url=f'{servers["dream"]}') as response:
                r = await response.json()
                dream = 'ðŸŸ¢'
    except:
        dream = 'ðŸ”´'
    return dream

async def check_weather():
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(f'https://api.openweathermap.org/data/2.5/weather?q=baku&appid={config.OPEN_WEATHER}&units=metric') as r:
                data = await r.json()
                weather = 'ðŸŸ¢'
    except:
        weather = 'ðŸ”´'
    return weather

async def check_currency():
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get(f"https://v6.exchangerate-api.com/v6/{config.CURRENCY_API}/latest/AZ") as response:
                data = await response.json()
                weather = 'ðŸŸ¢'
    except:
        weather = 'ðŸ”´'
    return weather

async def check_openai():
    try:
        headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + config.OPENAI_API_KEY,
        }
        json_data = {
            'model': 'gpt-3.5-turbo',
            'messages': [
                {
                    'role': 'user',
                    'content': '5+5',
                },
            ],
            'temperature': 0.7
        }
        timeout = aiohttp.ClientTimeout(total=60)
        async with aiohttp.ClientSession(headers=headers, timeout=timeout) as session:
            start_time = time.time()
            async with session.post('https://api.openai.com/v1/chat/completions', json=json_data) as response:
                end_time = time.time()
                response_time = int(end_time - start_time)
    except:
        response_time = 0
    if not (0 < response_time < 60):
        open_ai = 'ðŸ”´'
    elif response_time > 20:
        open_ai = 'ðŸŸ '
    elif response_time > 10:
        open_ai = 'ðŸŸ¡'
    else:
        open_ai = 'ðŸŸ¢'
    return open_ai


import matplotlib.pyplot as plt

import pathlib

text = pathlib.Path("test.txt").read_text()

rows = []
for line in text.splitlines():
    rows.append([float(val) for val in line.split()])

import numpy as np

data = np.array(rows)
print(data.shape)
plt.matshow(data)
plt.show()


def match_iterator_pattern(pattern, iterator, default=None):
    """
    Iterates through the iterator and attempts to match each item with the given pattern. If a match is found, it returns
    the first group of the match. If no match is found in the iterator, it returns the default value.
    """
    for item in iterator:
        match = pattern.match(item)
        if match:
            return match.group(1)
    return default


#Lists exercise 9
matrix1 = [[1, 3], [2, 4]]
matrix2 = [[5, 2], [1, 0]]
# Created an empty matrix in order to append (add) the calculated elements
matrix3 = []

# I want mResults = [[6, 5], [3, 4]]]
# mResults.append([6, 5])
# mResults.append([3, 4])

# This is going to locate the element each time it loops
element1 = [0, 1]
# This is going to locate the index each time it loops
index1 = [0, 1]

# Range(2) limits the loop to 2 elements from list
for element1 in range(2):
    # Created an empty element to append to final list (matrix3).
    tempList = []
    # Range(2) limits the loop to 2 indices from matrix1 and matrix2
    for index1 in range(2):
        # Appending the calculated indices to tempList[]
        tempList.append((matrix1[element1][index1]) + (matrix2[element1][index1]))
    # Appending the calculated elements of tempList to empty list of matrix3
    matrix3.append(tempList)

print(matrix3)


# tf.idf Sequential Search in Python

import string, math, sys, os, time, glob, errno

startTime = time.process_time()
assert sys.version_info >= (3,0)

# TF IDF ALGORITHM:
# TF(t) = (Number of times term t appears in a document) / (Total number of terms in the document)
# IDF(t) = log_e(Total number of documents / Number of documents with term t in it).
# Score = TF * IDF

# Return number of times term t appears in a document

termFrequencies = []
IDF = 0

def calculateTF(t):
  # TF(t) = (Number of times term t appears in a document) / (Total number of terms in the document)

  timesInDoc = 0
  counter = 0
  for doc in tokens:
    timesInDoc = 0
    for word in tokens[counter]:
      if word == t:
        timesInDoc += 1

    #termFrequencies.append(timesInDoc)

    totalTerms = len(set(doc))
    termFrequencies.append(timesInDoc / totalTerms)
    counter += 1

  print("TF is ", timesInDoc, "\nTotal terms is ", totalTerms)
  print(termFrequencies)
  #return tf/totalTerms

def calculateIDF():
  # IDF(t) = log_e(Total number of documents / Number of documents with term t in it).
  numDocs = len(allDocuments)
  numDocsWithT = 0
  for i in termFrequencies:
    if i > 0:
      numDocsWithT += 1
  if numDocsWithT != 0:
    return math.log(numDocs / numDocsWithT)
  else:
    return 0

def calculateScore():
  IDFScores = []
  print("IDF in ccalc is : ", IDF)
  for tf in termFrequencies:
    #print(tf)
    score = round(tf * IDF, 6)
    IDFScores.append(score)
  print(IDFScores)

# Returns the tokens of a document.

def createTokens(doc):
  return doc.lower().split(" ")

# Move this section of pre declarations to the top

#with open("./bigTextTest.txt", 'r') as file:
#    data = file.read().replace('\n', '')
#print(data)

#tokenisedData = [createTokens(data)]

#print(tokenisedData)

# Read documents from files

path = './corpus/*.txt'
files = glob.glob(path)
allDocuments = []
for name in files:
  with open(name) as f:
    allDocuments.append(f.read().replace('\n', ''))

tokens = [createTokens(d) for d in allDocuments]

print("Hey! What do you want to search?")
query = input().lower()

queryTokens = query.lower().split(" ")
#print(queryTokens)

print("---------------------------------------------")

calculateTF(query)
IDF = calculateIDF()
calculateScore()

#print(TF(query, tokens))

# for i in tokens:
#   for j in i:
#     print(j)

endTime = time.process_time()

print("Execution time: ", round((endTime-startTime), 4), "seconds")


from psycopg_pool import ConnectionPool
import os

try:
    pool = ConnectionPool(conninfo=os.environ["DATABASE_URL"])
except KeyError:
    pool = None

class CurrencyQueries:
    def structure_countries(self, country: list):
        try:
            return {
                "id": country[0],
                "currency_code": country[1],
                "country": country[2],
            }
        except IndexError:
            return {"warning": "impropertly formatted country."}

    def get_list_from_db(self):
        """
        Arguments: N/A
        Returns: a list containing data about each country, received
        from the database
        """
        with pool.connection() as conn:
            with conn.cursor() as cur:
                cur.execute(
                    """
                        SELECT id
                        , currency_code
                        , country
                        FROM currency;
                    """
                )
                results = []
                countries = cur.fetchall()
                for country in countries:
                    formatted_country = self.structure_countries(country)
                    if "warning" in formatted_country:
                        return []
                    results.append(formatted_country)
                return results

    def get_currency_code_pair(self, origin_country, destination_country):
        with pool.connection() as conn:
            with conn.cursor() as cur:
                cur.execute(
                    """
                        SELECT currency_code
                        FROM currency
                        WHERE %s = country
                    """,
                    [origin_country],
                )
                origin_code = cur.fetchall()[0][0]
                cur.execute(
                    """
                        SELECT currency_code
                        FROM currency
                        WHERE %s = country
                    """,
                    [destination_country],
                )
                destination_code = cur.fetchall()[0][0]
                return [origin_code, destination_code]


#first, I had to do this in the console $ python3 -m pip install boto3
#also make sure amazon CLI is set up.
import boto3

#ec2 stuff
print("*****Printing describe instances of EC2 Instances\n")
ec2 = boto3.client('ec2')

response = ec2.describe_instances()
for reservation in response['Reservations']:
    for instance in reservation['Instances']:
        print(instance, '\n')
# write an output file with entire response.  This will overwrite anything previous.
f=open("./Results/ec2_descriptions.json", "w+")
f.write("{'Results of ec2.describe_instances in boto3': %s}" % (response))
f.close()
print("File ec2_descriptions.json was created or updated in the Results folder.")

print("Open ec2_descriptions.json in Results folder to see")


#!/usr/bin/env python3
"""
    CANReverse CAN Bus Reverse-Engineering-Software as part of my bachelors thesis
    "Conception of a prototypical realization of selected attacks on the CAN bus via OBD-II".

    (c) Jannik Schmied, 2023
"""
import sys

from argparse import ArgumentParser, Namespace
from datetime import datetime
from shlex import split
from subprocess import Popen, DEVNULL, PIPE
from time import sleep

from pyfiglet import figlet_format

# Show extended error messages
DEBUG: bool = False

# Constants
VERSION: str = "1.0.0rc1"
FILE: str
SANITIZE: bool = False
SILENT: bool = False
INTERFACE: str = "vcan0"

def parse_args() -> Namespace:
    parser: ArgumentParser = ArgumentParser()
    parser.add_argument("--file", "-f", help="Specify candump logfile (needs to be sanitized, use --sanitize/-s else)", type=str, required=True)
    parser.add_argument("--sanitize", "-s", help="Sanitizes file for usage", action='store_true')
    parser.add_argument("--silent", help="Suppress unnecessary output", action='store_true')
    parser.add_argument("--interface", "-i", help="Specify CAN interface (default: vcan0)", type=str, default="vcan0")

    return parser.parse_args()

def sanitize(file: str) -> str:
    new_file: str = f"candump_logfile_{datetime.now().strftime('%Y_%m_%d-%H_%M_%S')}_sanitized.log"
    command: str = f"cat {file}" + " | awk '{print $3}' | sort | uniq" + f" > {new_file}"

    try:
        sanitize_file_process = Popen(split(command), stdout=DEVNULL, stderr=PIPE)
        sanitize_file_process.terminate()
    except Exception as e:
        print("[!] An error occurred:", e)
        sys.exit(1)

    return new_file

def main():
    args = parse_args()

    global FILE
    FILE = args.file

    if args.sanitize:
        global SANITIZE
        SANITIZE = args.sanitize
    if args.silent:
        global SILENT
        SILENT = args.silent
    if args.interface:
        global INTERFACE
        INTERFACE = args.interface

    file: str = FILE

    if not SILENT:
        print("\n", figlet_format("CANREVERSE"))
        print(f"(c) Jannik Schmied, 2022. Version {VERSION}")
        print("-" * 56)

    if SANITIZE:
        print(f"[*] Sanitizing file for further usage...")
        file = sanitize(file)

    try:
        print("[*] Reading file...")
        with open(file, "r") as logfile:
            lines = logfile.readlines()
            packet_counter: int = 0
            for line in lines:
                packet_counter += 1
            send_counter: int = 0

            print("[*] Start reverse engineering process")
            print(f"[i] Total packets: {packet_counter}")
            for line in lines:
                can_message = line
                command = f"cansend {INTERFACE} {can_message}"

                can_message = can_message.replace('\n', '').replace('\r', '')
                print(f"[*] Sending packet {can_message} ({send_counter}/{packet_counter})")
                for counter in range(1):
                    try:
                        send_can_message_process = Popen(split(command), stdout=PIPE, stderr=PIPE)
                        send_counter += 1
                        send_can_message_process.terminate()
                    except Exception as e:
                        print(f"[!] Error: {e}")
                        exit(1)
                sleep(3)
    except FileExistsError:
        print("[!] File not found!")
        sys.exit(1)
    except FileNotFoundError:
        print("[!] File not found!")
        sys.exit(1)
    except KeyboardInterrupt:
        print("\n[i] Stopped. (Interrupted by user)")
    except Exception as e:
        print(f"[!] Error: {e}")
    finally:
        print(f"[i] Finished! Sent {send_counter} of {packet_counter} packets.")

if __name__ == '__main__':
    main()


from __future__ import print_function, division

from thinkbayes2 import Pmf

class Monty(Pmf):
    """Map from string location of car to probability"""

    def __init__(self, hypos):
        """Initialize the distribution.

        hypos: sequence of hypotheses
        """
        Pmf.__init__(self)
        for hypo in hypos:
            self.Set(hypo, 1)
        self.Normalize()

    def Update(self, data):
        """Updates each hypothesis based on the data.

        data: any representation of the data
        """
        for hypo in self.Values():
            like = self.Likelihood(data, hypo)
            self.Mult(hypo, like)
        self.Normalize()

    def Likelihood(self, data, hypo):
        """Compute the likelihood of the data under the hypothesis.

        hypo: string name of the door where the prize is
        data: string name of the door Monty opened
        """
        if hypo == data:
            return 0
        elif hypo == 'A':
            return 0.5
        else:
            return 1

def main():
    hypos = 'ABC'
    pmf = Monty(hypos)

    data = 'B'
    pmf.Update(data)

    for hypo, prob in sorted(pmf.Items()):
        print(hypo, prob)

if __name__ == '__main__':
    main()


# TITLE
# Remove duplicates from a list

# DESCRIPTION
# Write a Python program that removes duplicate elements from a list, only keeping one occurrence of each element in the list.
# The original list should be mutated (modified).
# The program must print the final version of the list.

# EXPECTED OUTPUT
# LIST                  | OUTPUT
# [1, 1, 2, 3, 4, 4]    | [1, 2, 3, 4]
# ["a", "a", "b", "a"]  | ["a", "b"]
# [1, 2, 3]             | [1, 2, 3]
# []                    | []

input_list = [1, 1, 2, 3, 4, 4]
# input_list = ["a", "a", "b", "a"]
# input_list = [1, 2, 3]
# input_list = []

if len(input_list) == 0:
    print(input_list)
else:
    new_set = set(input_list)
    input_list = sorted(list(new_set))
    print(input_list)


import os
from setuptools import setup

def read(fname):
    return

setup(
    name = 'Nosferatu',
    version = '0.4.4',
    author = 'Daniel Cardin',
    author_email = 'ddcardin@gmail.com',
    description = (
        'A webapp to remotely control your home lights and wall sockets'
    ),
    license = 'Apache 2.0',
    keywords = 'nosferatu webapp home automation lights lightswitch',
    packages=['nosferatu', 'tests'],
    long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Topic :: Internet :: WWW/HTTP :: WSGI :: Application',
        'License :: OSI Approved :: Apache Software License',
        'Programming Language :: Python :: 3',
    ],
    install_requires=[
        'APScheduler',
        'alembic',
        'cssmin',
        'Flask',
        'Flask-Assets',
        'Flask-User',
        'Flask-Cache',
        'Flask-Login',
        'Flask-Migrate',
        'Flask-SQLAlchemy',
        'SQLAlchemy',
        'gunicorn',
        'jsmin',
        'psycopg2',
        'redis',
        'webassets',
    ],
)


import numpy as np
import math
import sys

def mult(a, b, k):
    if (k == 1):
        return a * b
    c = np.zeros((k, k), dtype=np.int)
    k //= 2
    a11 = a[:k, :k]
    a12 = a[:k, k:]
    a21 = a[k:, :k]
    a22 = a[k:, k:]
    b11 = b[:k, :k]
    b12 = b[:k, k:]
    b21 = b[k:, :k]
    b22 = b[k:, k:]
    p1 = mult(a11 + a22, b11 + b22, k)
    p2 = mult(a21 + a22, b11, k)
    p3 = mult(a11, b12 - b22, k)
    p4 = mult(a22, b21 - b11, k)
    p5 = mult(a11 + a12, b22, k)
    p6 = mult(a21 - a11, b11 + b12, k)
    p7 = mult(a12 - a22, b21 + b22, k)
    c[:k, :k] = p1 + p4 - p5 + p7
    c[:k, k:] = p3 + p5
    c[k:, :k] = p2 + p4
    c[k:, k:] = p1 - p2 + p3 + p6
    return c

def read_matrix(n, k, f=sys.stdin):
    a = np.loadtxt(f, dtype=np.int, ndmin=2)
    b = list(map(list, a[n:]))
    a = list(map(list, a[:n]))
    for i in range(n):
        a[i] += [0] * (k - n)
    for i in range(n, k):
        a.append([0] * k)
    a = np.array(a)
    for i in range(n):
        b[i] += [0] * (k - n)
    for i in range(n, k):
        b.append([0] * k)
    b = np.array(b)
    return a, b

def output(c, n):
    print()
    for i in range(n):
        for j in range(n):
            print(c[i][j], end=' ')
        print()

def test(filename):
    f = open(filename)
    n = int(f.readline())
    k = 2 ** math.ceil(math.log2(n))
    a, b = read_matrix(n, k, f)
    c = mult(a, b, k)
    c1 = np.dot(a, b)
    if c.all() == c1.all():
        print("correct")

if __name__ == "__main__":
    n = int(input())
    k = 2 ** math.ceil(math.log2(n))
    a, b = read_matrix(n, k)
    c = mult(a, b, k)
    output(c, n)


import warnings
from enum import IntFlag
from typing import Optional, Union

from .. import xdr as stellar_xdr
from ..asset import Asset
from ..keypair import Keypair
from ..muxed_account import MuxedAccount
from ..strkey import StrKey
from ..utils import raise_if_not_valid_ed25519_public_key
from .operation import Operation

__all__ = ["TrustLineEntryFlag", "AllowTrust"]

class TrustLineEntryFlag(IntFlag):
    """Indicates which flags to set. For details about the flags,
    please refer to the `CAP-0018 <https://github.com/stellar/stellar-protocol/blob/master/core/cap-0018.md>`_.

    - **UNAUTHORIZED_FLAG**: The account can hold a balance but cannot receive payments, send payments, maintain offers or manage offers

    - **AUTHORIZED_FLAG**: The account can hold a balance, receive payments, send payments, maintain offers or manage offers

    - **AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG**: The account can hold a balance and maintain offers but cannot receive payments, send payments or manage offers
    """

    UNAUTHORIZED_FLAG = 0
    AUTHORIZED_FLAG = 1
    AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG = 2

class AllowTrust(Operation):
    """The :class:`AllowTrust` object, which represents a AllowTrust operation
    on Stellar's network.

    Updates the authorized flag of an existing trustline. This can only be
    called by the issuer of a trustline's `asset
    <https://developers.stellar.org/docs/glossary/assets/>`_.

    The issuer can only clear the authorized flag if the issuer has the
    ``AUTH_REVOCABLE_FLAG`` set. Otherwise, the issuer can only set the authorized
    flag.

    Threshold: Low

    See `Allow Trust <https://developers.stellar.org/docs/start/list-of-operations/#allow-trust>`_ for more information.

    :param trustor: The trusting account (the one being authorized).
    :param asset_code: The asset code being authorized.
    :param authorize: `True` to authorize the line, `False` to deauthorize，if you need further control,
        you can also use :class:`stellar_sdk.operation.allow_trust.TrustLineEntryFlag`.
    :param source: The source account for the operation. Defaults to the transaction's source account.

    """

    _XDR_OPERATION_TYPE: stellar_xdr.OperationType = (
        stellar_xdr.OperationType.ALLOW_TRUST
    )

    def __init__(
        self,
        trustor: str,
        asset_code: str,
        authorize: Union[TrustLineEntryFlag, bool],
        source: Optional[Union[MuxedAccount, str]] = None,
    ) -> None:
        # We keep this class to ensure that the SDK can correctly parse historical transactions.
        warnings.warn(
            "Use `stellar_sdk.operation.set_trust_line_flags.SetTrustLineFlags` instead.",
            DeprecationWarning,
        )
        super().__init__(source)

        self.trustor: str = trustor
        self.asset_code: str = asset_code

        if isinstance(authorize, bool):
            if authorize is True:
                self.authorize: TrustLineEntryFlag = TrustLineEntryFlag.AUTHORIZED_FLAG
            else:
                self.authorize = TrustLineEntryFlag.UNAUTHORIZED_FLAG
        else:
            self.authorize = authorize
        raise_if_not_valid_ed25519_public_key(self.trustor, "trustor")
        Asset.check_if_asset_code_is_valid(self.asset_code)

    def _to_operation_body(self) -> stellar_xdr.OperationBody:
        trustor = Keypair.from_public_key(self.trustor).xdr_account_id()
        length = len(self.asset_code)
        pad_length = 4 - length if length <= 4 else 12 - length
        asset_code = bytearray(self.asset_code, "ascii") + b"\x00" * pad_length
        authorize = stellar_xdr.Uint32(self.authorize.value)
        if len(asset_code) == 4:
            asset_type = stellar_xdr.AssetType.ASSET_TYPE_CREDIT_ALPHANUM4
            asset_code4 = stellar_xdr.AssetCode4(asset_code)
            asset = stellar_xdr.AssetCode(type=asset_type, asset_code4=asset_code4)
        else:
            asset_type = stellar_xdr.AssetType.ASSET_TYPE_CREDIT_ALPHANUM12
            asset_code12 = stellar_xdr.AssetCode12(asset_code)
            asset = stellar_xdr.AssetCode(type=asset_type, asset_code12=asset_code12)
        allow_trust_op = stellar_xdr.AllowTrustOp(trustor, asset, authorize)
        body = stellar_xdr.OperationBody(
            type=self._XDR_OPERATION_TYPE, allow_trust_op=allow_trust_op
        )
        return body

    @classmethod
    def from_xdr_object(cls, xdr_object: stellar_xdr.Operation) -> "AllowTrust":
        """Creates a :class:`AllowTrust` object from an XDR Operation
        object.

        """
        source = Operation.get_source_from_xdr_obj(xdr_object)
        assert xdr_object.body.allow_trust_op is not None
        assert xdr_object.body.allow_trust_op.trustor.account_id.ed25519 is not None
        trustor = StrKey.encode_ed25519_public_key(
            xdr_object.body.allow_trust_op.trustor.account_id.ed25519.uint256
        )
        authorize = xdr_object.body.allow_trust_op.authorize.uint32
        authorize = TrustLineEntryFlag(authorize)
        asset_type = xdr_object.body.allow_trust_op.asset.type
        if asset_type == stellar_xdr.AssetType.ASSET_TYPE_CREDIT_ALPHANUM4:
            assert xdr_object.body.allow_trust_op.asset.asset_code4 is not None
            asset_code = (
                xdr_object.body.allow_trust_op.asset.asset_code4.asset_code4.decode()
            )
        elif asset_type == stellar_xdr.AssetType.ASSET_TYPE_CREDIT_ALPHANUM12:
            assert xdr_object.body.allow_trust_op.asset.asset_code12 is not None
            asset_code = (
                xdr_object.body.allow_trust_op.asset.asset_code12.asset_code12.decode()
            )
        else:
            raise NotImplementedError(
                "Operation of asset_type={} is not implemented" ".".format(asset_type)
            )

        asset_code = asset_code.rstrip("\x00")
        op = cls(
            source=source, trustor=trustor, authorize=authorize, asset_code=asset_code
        )
        return op

    def __str__(self):
        return (
            f"<AllowTrust [trustor={self.trustor}, "
            f"asset_code={self.asset_code}, "
            f"authorize={self.authorize}, "
            f"source={self.source}]>"
        )


def maximumToys(prices, k):
    count = 0
    total = 0
    prices.sort()
    for price in prices:
        if k - (total + price) >= 0:
            count += 1
            total += price
    return count

arr = [10,20,50,30,40]

print (maximumToys(arr, 30))


class Calculator:
    def power(self, i, j):
        if i < 0 or j < 0:
            return 'n and p should be non-negative'
        return i ** j

if __name__ == '__main__':
    myCalculator = Calculator()
    T = int(input())
    for _ in range(T):
        i, j = map(int, input().rstrip().split())

        try:
            ans = myCalculator.power(i,j)
            print(ans)
        except Exception as e:
            print(e)


# -*- coding: utf-8 -*-
"""
UNIVERSIDADE FEDERAL RURAL DE PERNAMBUCO - UFRPE
UNIDADE ACADÊMICA DO CABO DE SANTO AGOSTINHO - UACSA

@author(s):
    Rogério Soares (rogerio.soaress@ufrpe.br)

Created on Wed Apr 29 00:03:47 2020
"""

import tkinter
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import numpy as np

def on_key_press(event):
    print("you pressed {}".format(event.key))
    key_press_handler(event, canvas, toolbar)

canvas.mpl_connect("key_press_event", on_key_press)

def _quit():
    root.quit()     # stops mainloop
    root.destroy()  # this is necessary on Windows to prevent
                    # Fatal Python Error: PyEval_RestoreThread: NULL tstate

def plot_stat(window):

    global root
    root = tkinter.Toplevel(window)
    root.wm_title("Embedding in Tk")

    fig = Figure(figsize=(5, 4), dpi=100)
    t = np.arange(0, 3, .01)
    fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))

    global canvas
    canvas = FigureCanvasTkAgg(fig, master=root)  # A tk.DrawingArea.
    canvas.draw()
    canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

    global toolbar
    toolbar = NavigationToolbar2Tk(canvas, root)
    toolbar.update()
    canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

    button = tkinter.Button(master=root, text="Quit", command=_quit)
    button.pack(side=tkinter.BOTTOM)


def display_road():
    print("|" + " " * 28 + "|")
    for i in range(10):
        print("|" + " " * 28 + "|")
    print("|" + " " * 28 + "|")

def display_car(position):
    road = ["|" + " " * 28 + "|"]
    for i in range(10):
        if i == 5:
            road.append("|" + " " * (position - 1) + "*" + " " * (27 - position) + "|")
        else:
            road.append("|" + " " * 28 + "|")
    road.append("|" + " " * 28 + "|")
    for line in road:
        print(line)

def update_position(position, direction):
    if direction == "right":
        return min(position + 1, 27)
    elif direction == "left":
        return max(position - 1, 1)
    else:
        return position

def play_game():
    position = 14
    while True:
        display_road()
        display_car(position)
        direction = input("Enter direction (left, right, or quit): ")
        if direction == "quit":
            break
        position = update_position(position, direction)

play_game()


##############################################################################################
## Course   : Linked Data and Python: Introduction                                          ##
## Section  : Querying/Navigation - Excercise                                               ##
## Authors  : Christian Fleiner, Andreas Harth                                              ##
## See more : https://github.com/wintechis/SMART-vhb-Linked-Data-and-Python-Introduction    ##
##                                                                                ##
## Exercises:                                                                               ##
## - 6.1 Retrieve triple range from triple list                                             ##
## - 6.2 Use transitive methods                                                             ##
##############################################################################################

from typing import Iterator
from rdflib import Graph, URIRef

###################################################
##  6.1 Return the 2. and 3. triple of the graph ##
###################################################

def get_slices() -> list[dict]:
    #Nobel Peace Prize 2020
    g = Graph().parse('https://data.nobelprize.org/store/6/metadata/3886?recursive=nobelprize&format=text/turtle', format='turtle')
    l = sorted(list(g))
    # ↓↓↓ START TO CODE BELOW ↓↓↓
    return

###################################################################################################################################
##  6.2 Return all documents that were cited by d directly or indirectly (make use of the transitive_objects method of a graph)  ##
###################################################################################################################################
citations = '''
PREFIX ex: <http://example.org/>

ex:a ex:cites ex:b , ex:c .
ex:b ex:cites ex:c .
ex:d ex:cites ex:a, ex:f .
ex:e ex:cites ex:d, ex:c .

'''
def get_all_citations() -> Iterator[URIRef]:
    g = Graph().parse(data=citations, format='turtle')
    # Use g.transitive_objects()
     # ↓↓↓ START TO CODE BELOW ↓↓↓
    return

if __name__ == '__main__':
    print(list(map(lambda triple: [term.n3() for term in triple], get_slices())))
    #print([x.n3() for x in get_all_citations()])


#!/usr/bin/env python3

# Author: Samer A. Mohamed ()

import rospy
from std_msgs.msg import Float32MultiArray
from nav_msgs.msg import Odometry
from math import atan2

#Define global variables
FSM = 0 #Finite state machine variable "Like pointer to current mission"
com_msg = Float32MultiArray() #Command message "Go to target pose [x, y, z]"
Pose = [0.0,0.0,0.0] #Current pose variable
lin_thres = rospy.get_param('/lin_thres') #Intermediate goal error threshold

#Callbacks
def pose_callback(msg):
  #Associated global variables
  global Pose

  #update instantaneous pose
  Pose = [msg.pose.pose.position.x, msg.pose.pose.position.y, 2*atan2(msg.pose.pose.orientation.z,msg.pose.pose.orientation.w)]

#Initialize the mission planning node
rospy.init_node('mp_debi')
fsm_pub = rospy.Publisher('/targ',Float32MultiArray,queue_size=1) #Target command publisher
rospy.Subscriber('/odom',Odometry,pose_callback)

#Looping
while not rospy.is_shutdown():
  #First state: Go to the first X sign
  if FSM==0:
    com_msg.data = [1.6,2.8,1.5708]
    if abs(Pose[0]-com_msg.data[0]) <= lin_thres and abs(Pose[1]-com_msg.data[1]) <= lin_thres:
      #Increment FSM variable
      FSM = FSM + 1

  #Second state: Go to the second X sign
  elif FSM==1:
    com_msg.data = [-0.9,2.2,-1.5708]
    if abs(Pose[0]-com_msg.data[0]) <= lin_thres and abs(Pose[1]-com_msg.data[1]) <= lin_thres:
      #Increment FSM variable
      FSM = FSM + 1

  #Third state: Go to the third X sign
  elif FSM==2:
    com_msg.data = [1.6,-0.95,1.5708]
    if abs(Pose[0]-com_msg.data[0]) <= lin_thres and abs(Pose[1]-com_msg.data[1]) <= lin_thres:
      #Increment FSM variable
      FSM = FSM + 1

  #Fourth state: Go to the fourth X sign
  elif FSM==3:
    com_msg.data = [-2.0,0.6,0.0]
    if abs(Pose[0]-com_msg.data[0]) <= lin_thres and abs(Pose[1]-com_msg.data[1]) <= lin_thres:
      #Increment FSM variable
      FSM = FSM + 1

  #Fifth state: Go back to the starting position
  elif FSM==4:
    com_msg.data = [0.0,0.0,0.0]

  #Publish mission planner command
  fsm_pub.publish(com_msg)
  rospy.sleep(0.5)


T = int(input())
for test_case in range(0, T+1):
    K, N, M = map(int, input().split()) # 몇칸 식 간다 / 총 정류장 / 충전기 수
    arr = list(map(int, input().split()))

    station_list = [0] * (N + 1)
    for i in range(len(arr)):
         station_list[arr[i]] += 1

    start = 0
    end = K
    cnt = 0

    while True:
        zero = 0
        for i in range(start+1, end+1):
            if station_list[i] == 1:
                start = i
            else:
                zero += 1

        if zero == K:
            cnt = 0
            break

        cnt += 1
        end = start + K

        if end >= N:
            break
    print(f'#{test_case} {cnt}')

"""
T = int(input())
for test_case in range(0, T+1):
    K, N, M = map(int, input().split()) # 몇칸 식 간다 / 총 정류장 / 충전기 수
    charger = list(map(int, input().split()))
    #충전위치 표를 만드는 경우

    stop = [0] * (N+1)
    for i in charger:
    stop[i] = 1

    cnt = 0
    last = 0 #마지막 충전 위치
    while last+K < N: # 마지막 충전 이후 종점을 통과하지 않으면
        if stop[last+K] == 1: #최대 이동 후 충전기가 있으면
            last = last + K #마지막 충전 위치 갱신
            cnt += 1

"""
"""
T = int(input())
for test_case in range(0, T+1):
    K, N, M = map(int, input().split()) # 몇칸 식 간다 / 총 정류장 / 충전기 수
    charger = list(map(int, input().split()))

    last = 0
    cnt = 0
    for i in range(1, M+2): #마지막 충전위치로부터 도착할 수 있는 충전기인지 확인
    if charger[i]-charger[i-1] > K: #두 충전기 사이 거리가 이동 가능 거리 초과
        cnt = 0
        break # 운행 불가
    elif charger[i] - charger[last] > K: #마지막 충전기로부터 도착할 수 없으면
        last = i-1 # 이전 충전기에서 충전
        cnt += 1

    print(f'{test_case} {cnt}')

"""
"""
T = int(input())
for tc in range(1, T+1):
    K, N, M = map(int, intput().split())

    stop = [0] * N ...
    last = 0
    cnt = 0
    while last + K < N: # 종점에 도착하지 않은 경우
        if stop[last+K} == 1: #최대 이동후 충전기가 있으면
            last =last + K #마지막 충전 위치 갱신
            cnt += 1
        else: #최대 이동후 충전기가 없으면
        pre = last #last+1부터 last + K 사이 충전기 중 가장 먼 충전기 찾기
        for i in range(last+K, last, -1):
        if stop[i] == 1 :
            last = i #충전기 번호 기록
            cnt += 1 #충전횟수 추가
            break
        if pre == last: #마지막 충전위치 갱신되지 않으면
            cnt = 0 #운행 실패, 중단
            break
    print(f'#{tc} {cnt}'
"""


"""
Программа: Сохранение моделей и их параметров
Версия: 1.0
"""

import joblib
import pandas as pd
import yaml
from lightgbm import LGBMClassifier
from catboost import CatBoostClassifier

def load_recommend_model(model: LGBMClassifier, supplier_id: int, **kwargs) -> None:
    """
    Cораняет обученную рекомендательную модель и ее параметры для конкретного поставщика.

    Аргументы:
        model (LGBMClassifier): обученная модель
        supplier_id (int): идентификатор поставщика.
        kwargs (dict):
            models (str): путь к файлу конфигурации, содержащему модели.
            params (str): путь к файлу конфигурации, содержащему параметы моделей.
    """
    # загрузка моделей и их параметров
    with open(kwargs['params']) as file:
        params = yaml.load(file, Loader=yaml.FullLoader)
    models = joblib.load(kwargs['models'])

    # загружаем модель и параметры в словарь по индексу supplier_id
    models[supplier_id] = model
    params[supplier_id] = model.get_params()

    # сохраняем словарь моделей и параметров
    joblib.dump(models, kwargs['models'])
    with open(kwargs['params'], 'w') as f:
        yaml.dump(params, f)

def load_model(model: CatBoostClassifier, **kwargs) -> None:
    """
    Cохраняет обученную модель, предсказывающую победителя, и ее параметры.

    Аргументы:
        model (СatBoostClassifier): обученная модель
        kwargs (dict):
            models (str): путь к файлу конфигурации, содержащему модели.
            params (str): путь к файлу конфигурации, содержащему параметы моделей.
    """
    # загрузка моделей и их параметров
    with open(kwargs['params']) as file:
        params = yaml.load(file, Loader=yaml.FullLoader)
    models = joblib.load(kwargs['models'])

    # загружаем модель catboost и ее параметры
    models['catboost'] = model
    params['catboost'] = model.get_params()

    # сохраняем словарь моделей и параметров
    joblib.dump(models, kwargs['models'])
    with open(kwargs['params'], 'w') as f:
        yaml.dump(params, f)

def load_data(df_train: pd.DataFrame, df_test: pd.DataFrame, df_recommend_submission: pd.DataFrame,
              df_evaluate: pd.DataFrame, **kwargs) -> None:
    """
    Загрузка данных из файла конфигурации и сохранение обработанных данных в CSV-файлы.

    Аргументы:
        df_train: DataFrame с тренировочными данными.
        df_test: DataFrame с тестовыми данными.
        df_recommend_submission: DataFrame с данными для получения предсказаний.
        df_evaluate: DataFrame с данными для оценки модели.
        kwargs: Аргументы для функции. Содержит:
            train_data (str): Путь тренировочных предобработанных данных.
            test_data (str): Путь тестовых предобработанных данных.
            recommend_sub_path (str): Путь файла, содержащего поставщиков и их закупке из тестовых данных
            evaluate_data (str): Путь данных для получения предсказаний
    """

    # Сохранение данных в CSV-файлы
    df_train.to_csv(kwargs['train_data'], index_label='index')
    df_test.to_csv(kwargs['test_data'], index_label='index')
    df_recommend_submission.to_csv(kwargs['recommend_sub_path'], index_label='index')
    df_evaluate.to_csv(kwargs['evaluate_data'], index_label='index')


# Uses python3
# @author: Junzhong Loo
# Date: 13/6/2021

import sys

def get_change(m):
    """
    Find minimum number of coins needed to change the
    input value into coins with denominations 1, 5, 10
    """
    coin_denomination = [1, 5, 10]

    # largest to smallest
    coin_denomination.reverse()

    min_coins_needed = 0

    for coin_value in coin_denomination:
        number_of_coins = m // coin_value
        m -= number_of_coins * coin_value
        min_coins_needed += number_of_coins

    return min_coins_needed

if __name__ == '__main__':
    m = int(input())
    print(get_change(m))