from agent import Agent
import argparse
from collections import deque
from env import Environment
import numpy as np
import torch

from model import QNetwork, Small, Large, Dropout
import matplotlib
matplotlib.use("TkAgg")
from matplotlib import pyplot as plt

def main(args):
    if args.examine:
        examine()
    if args.random:
        random()
    if args.train:
        train_multiple(summary_interval=50)
    if args.test:
        test()

def examine():
    with Environment() as env:
        # reset the environment
        env_info = env.reset()

        # number of agents in the environment
        print('Number of agents:', len(env_info.agents))

        # number of actions
        action_size = env.action_space_size
        print('Number of actions:', action_size)

        # examine the state space
        state = env_info.vector_observations[0]
        print('States look like:', state)
        state_size = len(state)
        print('States have length:', state_size)

def random():
    with Environment(no_graphics=False) as env:
        env_info = env.reset()
        action_size = env.action_space_size
        score = 0
        while True:
            action = np.random.randint(action_size)
            env_info = env.step(action)
            reward = env_info.rewards[0]
            done = env_info.local_done[0]
            score += reward
            if done:
                break
            print('\rScore: {:.2f}'.format(score), end="")
        print('\rScore: {:.2f}'.format(score))

def test():
    with Environment(no_graphics=False) as env:
        env_info = env.reset(train_mode=False)
        action_size = env.action_space_size
        state_size = len(env_info.vector_observations[0])
        state = env_info.vector_observations[0]
        agent = Agent(model=QNetwork, state_size=state_size, action_size=action_size, seed=0)
        agent.qnetwork_local.load_state_dict(torch.load('results/checkpoint.pth'))
        score = 0
        while True:
            action = agent.act(state)
            env_info = env.step(action)
            state = env_info.vector_observations[0]
            reward = env_info.rewards[0]
            done = env_info.local_done[0]
            score += reward
            if done:
                break
            print('\rScore: {:.2f}'.format(score), end="")
        print('\rScore: {:.2f}'.format(score))

def train_multiple(summary_interval):
    models = [QNetwork, Small, Large, Dropout]
    with Environment() as env:
        summary_scores = {}
        for model in models:
            summary = train(model, env, summary_interval)
            summary_scores[model.__name__] = summary
        plot_summary(summary_scores, summary_interval)

def train(model, env, summary_interval=100):
    env_info = env.reset(train_mode=True)
    action_size = env.action_space_size
    state_size = len(env_info.vector_observations[0])
    agent = Agent(model=model, state_size=state_size, action_size=action_size, seed=0)
    model_name = model.__name__
    summary_scores = _train(env, agent, model_name=model_name, summary_interval=summary_interval)
    return summary_scores

def _train(env, agent, model_name='model', summary_interval=100,
           n_episodes=2000, max_t=1000, eps_start=1.0, eps_end=0.01):
    """Deep Q-Learning.

    Params
    ======
        n_episodes (int): maximum number of training episodes
        max_t (int): maximum number of timesteps per episode
        eps_start (float): starting value of epsilon, for epsilon-greedy action selection
        eps_end (float): minimum value of epsilon
    """
    scores = []                        # list containing scores from each episode
    summary_scores = []
    scores_window = deque(maxlen=summary_interval)  # last 100 scores
    eps = eps_start                    # initialize epsilon
    eps_decay = (eps_end ** (1 / n_episodes)) / eps_start
    for i_episode in range(1, n_episodes + 1):
        env_info = env.reset(train_mode=True)
        state = env_info.vector_observations[0]
        score = 0
        for t in range(max_t):
            action = agent.act(state, eps)
            env_info = env.step(action)
            next_state = env_info.vector_observations[0]
            reward = env_info.rewards[0]
            done = env_info.local_done[0]
            agent.step(state, action, reward, next_state, done)
            state = next_state
            score += reward
            if done:
                break
        scores_window.append(score)       # save most recent score
        scores.append(score)              # save most recent score
        eps = max(eps_end, eps_decay * eps)  # decrease epsilon
        print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)), end="")
        if i_episode % summary_interval == 0:
            summary_scores.append(np.mean(scores_window))
            print('\rEpisode {}\tAverage Score: {:.2f}'.format(i_episode, np.mean(scores_window)))
            torch.save(agent.qnetwork_local.state_dict(), 'results/' + model_name + '.pth')
            plot_scores(scores, summary_scores, summary_interval, model_name)
        # if np.mean(scores_window) >= 20.0:
        #     print('\nEnvironment solved in {:d} episodes!\tAverage Score: {:.2f}'.format(
        #         i_episode - summary_interval, np.mean(scores_window)))
        #     break
    torch.save(agent.qnetwork_local.state_dict(), 'results/' + model_name + '.pth')
    plot_scores(scores, summary_scores, summary_interval, model_name)
    return summary_scores

def plot_scores(scores, summary_scores, summary_interval, file_name=''):
    plt.ylabel('Score')
    plt.xlabel('Episode #')
    plt.plot(np.arange(len(scores)), scores)
    plt.plot(np.arange(len(summary_scores) * summary_interval), summary_scores)
    if file_name:
        plt.savefig('results' + file_name + '.png', bbox_inches='tight')
    else:
        plt.show()

def plot_summary(summary_scores, summary_interval):
    plt.ylabel('Score')
    plt.xlabel('Episode #')
    for key, scores in summary_scores.items():
        plt.plot(np.arange(len(scores)) * summary_interval, scores, label=key)
    plt.legend()
    plt.savefig('results/summary.png', bbox_inches='tight')
    plt.close()

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='DeepRL - Q-learning project')
    parser.add_argument('--examine',
                        action="store_true",
                        dest="examine",
                        help='Print environment information')
    parser.add_argument('--random',
                        action="store_true",
                        dest="random",
                        help='Start a random agent')
    parser.add_argument('--train',
                        action="store_true",
                        dest="train",
                        help='Train a new network')
    parser.add_argument('--test',
                        action="store_true",
                        dest="test",
                        help='Load an existing network and test it')
    args = parser.parse_args()
    if not any(vars(args).values()):
        parser.error('No arguments provided.')
    main(args)


from bot import autocord
from bot import PERMISSIONS

def get_bots(split=True):
    guild = autocord.get_guild(437048931827056642)
    bots = guild.get_role(439587658058956811)
    bots = bots.members

    idle = []
    active = []

    for bot in bots:
        flag = str(bot.status)

        if flag == "online" or flag == "idle":
            active.append(bot)
        else:
            idle.append(bot)

    if split:
        return (active, idle)
    else:
        return active + idle

def permission_map(i: int):
    perm_map = {}

    guild = autocord.get_guild(437048931827056642)
    bot = guild.get_member(i)
    bot_perms = bot.guild_permissions

    for perm in PERMISSIONS:
        p = bot_perms.__getattribute__(perm)
        # print(f"{perm}: {p}")

        perm_map[perm] = p

    del perm_map["value"]

    return [(k, v) for k, v in perm_map.items()]

def format_cmd(cmd: str):
    r = f"```bash\n{cmd}\n```\n"

    return r


import termcolor2

x = int(input("Enter First Number: "))  # 20
y = int(input("Enter second Number: "))  # 40

if x > y:
    print(termcolor2.colored("Error! TryAgain", color="red"))
else:
    for i in range(1,x+1):
        if x % i == 0 and y % i == 0:
            bmm = i

print(f"BMM: {bmm}")


from django.shortcuts import render,redirect
from .models import *
from django.contrib import messages
from django.contrib.auth.decorators import login_required

def index(request):
    courses = Course.objects.all().order_by('-id')[:3]
    blogs = Blog.objects.all().order_by('-date_created')[:3]
    context = {'courses': courses, 'blogs': blogs}
    return render(request, 'mainsite/index.html', context)

def about(request):
    context = {}
    return render(request, 'mainsite/about.html', context)

def contact(request):
    if request.method == 'POST':
        message = request.POST['message']
        name = request.POST['name']
        email = request.POST['email']
        subject = request.POST['subject']
        messages.info(request, 'Thank you for Contacting us ' +
                      name + ", We shall get back to you very soon")

        print(message)
        print(name)
        print(email)
        print(subject)

    context = {}
    return render(request, 'mainsite/contact.html', context)

@login_required(login_url='/login/')
def blogsingle(request, blog_id):
    blogs = Blog.objects.all().order_by('-date_created')[:7]
    blog = Blog.objects.get(pk=blog_id)
    comments = BlogComments.objects.filter(post=blog).order_by('-id')
    if request.method == 'POST':
        name = request.user.username
        email = request.user.email
        comment = request.POST['comment']
        BlogComments.objects.create(
            post=blog, name=name, email=email, comment=comment)

    context = {'blog': blog, 'comments': comments, 'blogs': blogs}
    return render(request, 'mainsite/blogpost.html', context)

@login_required(login_url='/login/')
def blog(request):
    courses = Course.objects.all().order_by('-id')[:3]
    blogs = Blog.objects.all().order_by('-id')[:10]
    context = {'blogs': blogs, 'courses': courses}
    return render(request, 'mainsite/blog.html', context)

@login_required(login_url='/login/')
def courses(request):
    courses = Course.objects.all().order_by('tag')
    context = {'courses': courses}
    return render(request, 'mainsite/courses.html', context)

@login_required(login_url='/login/')
def courseDetails(request, course_id):
    course = Course.objects.get(pk=course_id)
    lesson = lessons.objects.filter(course=course).order_by('postion')
    reviews = coursefeedback.objects.filter(course=course).order_by('-id')
    if request.method == 'POST':
        name = request.user.username
        comment = request.POST['feedback']
        coursefeedback.objects.create(
            course=course, name=name, comment=comment)
    context = {'course': course, 'lesson': lesson, 'reviews': reviews}
    return render(request, 'mainsite/courseDetails.html', context)

@login_required(login_url='/login/')
def courseLesson(request, lesson_id):
    lesson = lessons.objects.get(pk=lesson_id)
    reviews = lessonfeedback.objects.filter(lesson=lesson).order_by('-id')
    if request.method == 'POST':
        name = request.user.username
        comment = request.POST['feedback']
        lessonfeedback.objects.create(
            lesson=lesson, name=name, comment=comment)

    context = {'lesson': lesson,'reviews':reviews}
    return render(request, 'mainsite/lesson.html', context)


from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import TipoActividad

class TipoActividadForm(forms.ModelForm):
    class Meta:
        model = TipoActividad
        exclude = ['']
        labels = {
            'horasRequeridas': _('Required hours for 1 credit'),
        }


import pandas as pd
import datetime
import numpy as np
import os

prices = pd.DataFrame.from_csv("data/prices.csv", index_col=False)

tmp = pd.to_datetime(prices.marketdate)
prices["date"] = [d.date() for d in tmp]

def date_filter(df, date_col, start, end):
    print(type(end))
    print(type(df[date_col][1]))
    res = df[np.logical_and(df[date_col] >= start,
                            df[date_col] < end)]
    return (res)

def sum_max(df, group_cols, value_col):
    grp = group_cols + [value_col]
    res = df[grp].groupby(group_cols).sum().max()
    return (res)

def qtile_mean(df, group_cols, value_col, qtile):
    grp = group_cols + [value_col]
    res = df[grp].groupby(group_cols).quantile(qtile).mean()
    return (res)

def gross_period_returns(df, date_col, value_col, id_col, start, end):
    cols = [date_col, value_col, id_col]

    tmp = df[cols][df[date_col] <= start]
    tmp.sort_values(by=date_col, inplace=True)
    tmp = tmp.drop_duplicates(subset=id_col, keep="last")
    tmp.set_index(id_col, inplace=True)
    start_vals = tmp[value_col]

    tmp = df[cols][df[date_col] >= end]
    tmp.sort_values(by=date_col, inplace=True)
    tmp = tmp.drop_duplicates(subset=id_col, keep="first")
    tmp.set_index(id_col, inplace=True)
    end_vals = tmp[value_col]

    res = (end_vals - start_vals) / start_vals
    return (res)

def gross_nday_returns(df, date_col, id_col, value_col, start, ndays=30):
    end = start + datetime.timedelta(days=ndays)
    res = gross_period_returns(df=df, date_col=date_col, value_col=value_col, id_col=id_col,
                               start=start, end=end)
    return (res)

def date_iterator(first, last, incr_days=20 ):
    res = first
    while res <= last:
        yield res
        res = res + datetime.timedelta(days=incr_days)

min_date = prices.date.min()
max_date = prices.date.max()
start = min_date

fulldf = pd.DataFrame()
diter = date_iterator(first=min_date, last=max_date, incr_days=30)
for date in diter:
    print (date)
    datedf = pd.DataFrame()
    for ndays in [30, 90, 180, 360]:
        ser = gross_nday_returns(df=prices,
                               id_col="gempermid",
                               date_col="date",
                               value_col="close_",
                               start=date,
                               ndays=ndays)
        df = pd.DataFrame(ser)
        df.columns = ["ret%d" % (ndays)]
        datedf = (df if (datedf.shape[0] == 0)
                else pd.merge(datedf, df, how="outer", left_index=True, right_index=True))
        print(datedf.shape)
    datedf["date"] = date
    fulldf = (datedf if fulldf.shape[0] == 0 else
               pd.concat([fulldf, datedf]))
    print (fulldf.tail())

    print('')
if (not os.path.isdir("output")):
    os.makedirs("output")
fulldf.to_csv("output/returns.csv")
print ("done")


"""Pass JSON 'data' to HMAC service"""

from binascii import hexlify
import socket
from flask import Flask, request
import os

app = Flask(__name__)

@app.route("/")
def home_page():
    """Useless home page"""
    return "
Crypto
"

@app.route("/hmac", methods=['POST'])
def build_mac():
    """Handle HMAC requests"""
    data = request.get_json()

    with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as sock:
        # Connect to server and send data
        sock.connect(os.environ['SOCKET_PATH'])
        sock.sendall(bytes(data['data'] + '\n', 'utf-8'))

        # Receive data from the server and shut down
        return {
            "hmac": hexlify(sock.recv(1024))
        }


from sklearn.feature_extraction.text import TfidfVectorizer

X = ["the cat in the hat",
     "the cat wearing a hat",
     "the cat's moving"
     "the cat is moving"
     ]
X_val = ["the cat is my hat"]
y = [1, 0]
y_val = [1]
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(X)
X_val = vectorizer.transform(X_val)

print(vectorizer.get_feature_names_out())
print(X_val)


import requests
from bs4 import BeautifulSoup, BeautifulStoneSoup
from fake_useragent import UserAgent
from openpyxl import load_workbook, workbook
from requests.api import request
from time import sleep

print("""Şehir kodları:
0-Adana
1-Antalya
2-Aydın
3-Denizli
4-Hatay
5-Isparta
6-Muğla
7-Bütün İller
""")

location_code = input("Arama yapmak istediğiniz şehir veya şehirlerin kodlarını girin: ")
location_list = ["adana", "antalya", "aydin", "denizli", "hatay", "isparta", "mugla"]
selected_locations = list(map(int, location_code.split()))

if(selected_locations[0]==7):
    selected_locations = location_list[0:11]
else:
    for i in range(len(selected_locations)):
        selected_locations[i] = location_list[selected_locations[i]]

print("Seçtiğiniz Şehirler =>", selected_locations)
workbook = load_workbook(filename="Template.xlsx")
sheet = workbook.active

def beautify(string):
    string=" ".join(string.replace("\n","").split())
    return string

for selected_location in selected_locations:
    page_index = 1
    while(True):
        user_agent = {'User-Agent':str(UserAgent().random)}
        url = f"https://www.hepsiemlak.com/{selected_location}-satilik?page={page_index}"
        page = requests.get(url,headers=user_agent)
        while(page.status_code !=200):
            print("Çok fazla istek atildi")
            sleep(60*5)
            user_agent = {'User-Agent':str(UserAgent().random)}
            url = f"https://www.hepsiemlak.com/{selected_location}-satilik?page={page_index}"
            page = requests.get(url,headers=user_agent)

        soup = BeautifulSoup(page.content,"html.parser")
        home_links = soup.find_all("a",class_="card-link")
        if(home_links == []):
            break

        for home_link in home_links:
            home_link = home_link['href']
            home_url = f"https://www.hepsiemlak.com{home_link}"
            home_page = requests.get(home_url,headers=user_agent)
            while(home_page.status_code !=200):
                print("Çok fazla istek atildi")
                sleep(60*5)
                user_agent = {'User-Agent':str(UserAgent().random)}
                home_url = f"https://www.hepsiemlak.com{home_link}"
                home_page = requests.get(home_url,headers=user_agent)

            home_soup = BeautifulSoup(home_page.content,"html.parser")

            home_title = beautify(home_soup.find("h1",class_="fontRB").text)
            home_price = beautify(home_soup.find("p",class_="fontRB fz24 price").text)
            home_properties = (home_soup.find("ul",class_="short-info-list")).find_all("li")
            home_info = home_soup.findAll("li",class_="spec-item")

            home_city = beautify(home_properties[0].text)
            home_town = beautify(home_properties[1].text)
            home_district = beautify(home_properties[2].text)
            home_type = beautify(home_properties[3].text+" "+home_properties[4].text)
            home_room = beautify(home_properties[5].text)
            home_size = beautify(home_properties[6].text)
            home_no = ""
            home_date = ""
            home_floor = ""
            home_age = ""
            home_heating = ""
            home_top_floor = ""
            home_credit = ""
            home_furniture = ""
            home_bathrooms = ""
            home_building = ""
            home_state = ""
            home_status = ""
            home_deed = ""
            home_dues = ""
            home_trade = ""
            home_front = ""
            home_rent = ""
            home_fuel = ""
            home_office = ""
            home_site = ""
            home_council = ""
            home_island = ""
            home_parcel = ""

            row_index = 2
            while True:
                if(sheet[f'A{row_index}'].value!=None):
                    row_index += 1
                else:
                    break
            sheet[f'A{row_index}'].value = home_title
            sheet[f'B{row_index}'].value = home_price
            sheet[f'C{row_index}'].value = home_city
            sheet[f'D{row_index}'].value = home_town
            sheet[f'E{row_index}'].value = home_district
            sheet[f'F{row_index}'].value = home_type
            sheet[f'G{row_index}'].value = home_room
            sheet[f'H{row_index}'].value = home_size

            print("Başlık:", home_title)
            print("Ücret:", home_price)
            print("Şehir:", home_city)
            print("İlçe:", home_town)
            print("Mahalle:", home_district)
            print("Konut Tipi:", home_type)
            print("Oda Sayısı:", home_room)
            print("Büyüklük:", home_size)

            for i in home_info:
                if "İlan no" in i.text :
                    home_no = (i.text)[8:]
                    sheet[f'I{row_index}'].value = home_no
                    print("İlan no:", home_no)
                elif "Son Güncelleme Tarihi" in i.text:
                    home_date = (i.text)[22:]
                    sheet[f'J{row_index}'].value = home_date
                    print("Son Güncelleme Tarihi:", home_date)
                elif "Bulunduğu Kat" in i.text:
                    home_floor = (i.text)[14:]
                    sheet[f'K{row_index}'].value = home_floor
                    print("Bulunduğu Kat:", home_floor)
                elif "Bina Yaşı" in i.text:
                    home_age = (i.text)[10:]
                    sheet[f'L{row_index}'].value = home_age
                    print("Bina Yaşı:", home_age)
                elif "Isınma Tipi" in i.text:
                    home_heating = (i.text)[12:]
                    sheet[f'M{row_index}'].value = home_heating
                    print("Isınma Tipi:", home_heating)
                elif "Kat Sayısı" in i.text:
                    home_top_floor = (i.text)[11:]
                    sheet[f'N{row_index}'].value = home_top_floor
                    print("Kat Sayısı:", home_top_floor)
                elif "Krediye Uygunluk" in i.text:
                    home_credit = (i.text)[17:]
                    sheet[f'O{row_index}'].value = home_credit
                    print("Krediye Uygunluk:", home_credit)
                elif "Eşya Durumu" in i.text:
                    home_furniture = (i.text)[12:]
                    sheet[f'P{row_index}'].value = home_furniture
                    print("Eşya Durumu:", home_furniture)
                elif "Banyo Sayısı" in i.text:
                    home_bathrooms = (i.text)[13:]
                    sheet[f'Q{row_index}'].value = home_bathrooms
                    print("Banyo Sayısı:", home_bathrooms)
                elif "Yapı Tipi" in i.text:
                    home_building = (i.text)[10:]
                    sheet[f'R{row_index}'].value = home_building
                    print("Yapı Tipi:", home_building)
                elif "Yapının Durumu" in i.text:
                    home_state = (i.text)[15:]
                    sheet[f'S{row_index}'].value = home_state
                    print("Yapının Durumu:", home_state)
                elif "Kullanım Durumu" in i.text:
                    home_status = (i.text)[16:]
                    sheet[f'T{row_index}'].value = home_status
                    print("Kullanım Durumu:", home_status)
                elif "Tapu Durumu" in i.text:
                    home_deed = (i.text)[12:]
                    sheet[f'U{row_index}'].value = home_deed
                    print("Tapu Durumu:", home_deed)
                elif "Takas" in i.text:
                    home_trade = (i.text)[6:]
                    sheet[f'V{row_index}'].value = home_trade
                    print("Takas:", home_trade)
                elif "Cephe" in i.text:
                    home_front = (i.text)[6:]
                    sheet[f'W{row_index}'].value = home_front
                    print("Cephe:", home_front)
                elif "Site İçerisinde" in i.text:
                    home_site = (i.text)[16:]
                    sheet[f'X{row_index}'].value = home_site
                    print("Site İçerisinde:", home_site)
                elif "Yakıt Tipi" in i.text:
                    home_fuel = (i.text)[11:]
                    sheet[f'Y{row_index}'].value = home_fuel
                    print("Yakıt Tipi:", home_fuel)
                elif "Yetkili Ofis" in i.text:
                    home_office = (i.text)[13:]
                    sheet[f'Z{row_index}'].value = home_office
                    print("Yetkili Ofis:", home_office)
                elif "Aidat" in i.text:
                    home_dues = (i.text)[6:]
                    sheet[f'AA{row_index}'].value = home_dues
                    print("Aidat:", home_dues)
                elif "Kira Getirisi" in i.text:
                    home_rent = (i.text)[14:]
                    sheet[f'AB{row_index}'].value = home_rent
                    print("Kira Getirisi:", home_rent)
                elif "Ada" in i.text:
                    home_island = (i.text)[3:]
                    sheet[f'AC{row_index}'].value = home_island
                    print("Ada:", home_island)
                elif "Parsel" in i.text:
                    home_parcel = (i.text)[6:]
                    sheet[f'AD{row_index}'].value = home_parcel
                    print("Parsel:", home_parcel)
                elif "İlgili Belediye" in i.text:
                    home_council = (i.text)[15:]
                    sheet[f'AE{row_index}'].value = home_council
                    print("İlgili Belediye:", home_council)

            print("------------------------------------------------")
        page_index +=1
        workbook.save("Sonuc.xlsx")
input("Bitti")


import sqlite3
import string
import os
import click
from flask import Flask, request, render_template, redirect, jsonify
from flask import send_from_directory
from flask.ext.cors import CORS, cross_origin
from sqlite3 import OperationalError
from urllib.parse import urlparse

__version__ = '1.1.4'
db_path = 'var/urls.db'
host = os.environ.get("SHORTENER_DOMAIN", 'localhost:5000')
protocol = os.environ.get("PROTOCOL", 'http://')

BASE = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
BASE.extend(list(string.ascii_lowercase))
BASE.extend(list(string.ascii_uppercase))
BASE_LEN = len(BASE)

# Assuming urls.db is in your app root folder
app = Flask(__name__)

cors = CORS(app, resources={r"/": {"origins": "*"}})

def get_base_next(char):
    if char == '':
        return False, '0'
    char_index = BASE.index(char)
    char_index += 1
    return (False, BASE[char_index]) if \
        char_index < BASE_LEN else (True, '0')

def next_id(id_=None):
    new_id = id_
    if id_ is None:
        new_id = '0'
    else:
        index = -1
        to_inc = new_id[index]
        final, next = get_base_next(to_inc)
        new_id = new_id[:index] + next
        index -= 1
        len_id = len(new_id)
        while index + 6 >= 0 and final:
            if index + len_id >= 0:
                to_inc = new_id[index]
                final, next = get_base_next(to_inc)
                new_id = new_id[:index] + next + new_id[index + 1:]
            else:
                to_inc = ''
                final, next = get_base_next(to_inc)
                new_id = next + new_id[index + 1:]

            index -= 1

    return new_id

def table_check():
    create_table = """
        CREATE TABLE WEB_URL(
        ID INTEGER PRIMARY KEY     AUTOINCREMENT,
        NUM TEXT NOT NULL UNIQUE,
        URL  TEXT  NOT NULL UNIQUE
        );
        """
    with sqlite3.connect(db_path) as conn:
        cursor = conn.cursor()
        try:
            cursor.execute(create_table)
        except OperationalError:
            pass

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico',
                               mimetype='image/vnd.microsoft.icon')

@app.route('/', methods=['GET', 'POST'])
@cross_origin(origin='localhost', headers=['Content-Type', 'Authorization'])
def home():
    method = request.method
    with sqlite3.connect(db_path) as conn:
        try:
            cursor = conn.cursor()
            rows_query = """
                SELECT NUM, max(ID) FROM WEB_URL"""
            result_cursor = cursor.execute(rows_query)
            result_fetch = result_cursor.fetchone()
            last_num = result_fetch[0]
            number_of_rows = result_fetch[1]
            number_of_rows = 0 if number_of_rows is None else number_of_rows
            if (method == 'GET' and request.args.get('url', None)) or \
               method == 'POST':
                original_url = request.args.get('url') if \
                    method == 'GET' else request.form.get('url')
                if original_url:
                    if urlparse(original_url).scheme == '':
                        original_url = 'http://' + original_url
                    exist_row = """
                        SELECT NUM FROM WEB_URL
                            WHERE URL='{url}'
                        """.format(url=original_url)
                    result_cursor = cursor.execute(exist_row)
                    result_fetch = result_cursor.fetchone()
                    if result_fetch:
                        new_num = result_fetch[0]
                    else:
                        new_num = next_id(last_num)
                        insert_row = """
                            INSERT INTO WEB_URL (URL, NUM)
                                VALUES ('{url}', '{num}')
                            """.format(url=original_url, num=new_num)
                        cursor.execute(insert_row)
                        number_of_rows += 1
                    encoded_string = new_num
                    short_url = '/'.join([host, encoded_string])
                    if method == 'GET':
                        return jsonify({'short_url': short_url,
                                        'code': 'SUCCESS',
                                        'original_url': original_url,
                                        'version': __version__})
                    else:
                        return render_template(
                            'home.html', short_url=short_url,
                            protocol=protocol,
                            number_of_rows=number_of_rows,
                            version=__version__)

            return render_template('home.html',
                                   protocol=protocol,
                                   number_of_rows=number_of_rows,
                                   version=__version__)
        except Exception as error:
            if method == 'GET':
                return jsonify(**{'code': 'ERROR',
                                  'error': str(error),
                                  'original_url': original_url
                                  })
            else:
                return render_template(
                    'home.html',
                    number_of_rows=number_of_rows,
                    error=True)

@app.route('/<short_url>')
def redirect_short_url(short_url):
    decoded_string = short_url
    with sqlite3.connect(db_path) as conn:
        cursor = conn.cursor()
        select_row = """
                SELECT URL FROM WEB_URL
                    WHERE NUM='{num}'
                """.format(num=decoded_string)
        result_cursor = cursor.execute(select_row)
        try:
            return redirect(result_cursor.fetchone()[0])
        except Exception:
            pass

    return render_template(
        'home.html',
        error=True)

@click.option('--version', help='Print Version and exit',
              is_flag=True)
@click.option('--debug', help='Enable debug option',
              is_flag=True)
@click.command()
def main(debug, version):
    if version:
        import sys
        sys.exit('Your Version is: %s' % __version__)
    table_check()
    app.run(host='0.0.0.0', debug=debug)

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
import random, math
from somali.data.scp import get_random_number
from somali import config

aliases=['rmap']
description = f'Vai mandar um lugar aleatorio do mapa, devido a "problemas" pode ser que caia no meio do mar então é so ir para a costa mais proxima que é a localização real.'
usage = 'digite o comando, "rmapa".'

async def command(ctx,) -> None:
    count = 0
    # lagitude = random.uniform(-90, 90)
    # longitude = random.uniform(-180, 180)
    # # r = f'https://www.google.com.br/maps/@{lagitude},{longitude},15z'
    with open('/home/pi/Botos/Oboto/somali/data/cidades.csv') as fr:
        lines = fr.readlines()
        random_line = random.choice(lines) if lines else None

    circle_x, circle_y = random_line.split(",", 1)
    circle_x = float(circle_x.replace('"',""))
    circle_y = float(circle_y.replace('"',""))
    print(circle_x, circle_y)

    if -160 < circle_x and circle_y  < 160:
        # radius of the circle
        circle_r = 20

        # random angle
        alpha = 2 * math.pi * random.random()
        # random radius
        r = circle_r * math.sqrt(random.random())
        # calculating coordinates
        x = r * math.cos(alpha) + circle_x
        y = r * math.sin(alpha) + circle_y
        ctx.response = f'FBBlock https://www.google.com.br/maps/@{x},{y},15z'

    elif -170 < circle_x and circle_y < 170:
        # radius of the circle
        circle_r = 9

        # random angle
        alpha = 2 * math.pi * random.random()
        # random radius
        r = circle_r * math.sqrt(random.random())
        # calculating coordinates
        x = r * math.cos(alpha) + circle_x
        y = r * math.sin(alpha) + circle_y
        ctx.response = f'FBBlock https://www.google.com.br/maps/@{x},{y},15z'

    elif -179 < circle_x and circle_y < 179:
        # radius of the circle
        circle_r = 0.4

        # random angle
        alpha = 2 * math.pi * random.random()
        # random radius
        r = circle_r * math.sqrt(random.random())
        # calculating coordinates
        x = r * math.cos(alpha) + circle_x
        y = r * math.sin(alpha) + circle_y
        ctx.response = f'FBBlock https://www.google.com.br/maps/@{x},{y},15z'

    elif -180 < circle_x and circle_y < 180:
        # radius of the circle
        circle_r = 0.4

        # random angle
        alpha = 2 * math.pi * random.random()
        # random radius
        r = circle_r * math.sqrt(random.random())
        # calculating coordinates
        x = r * math.cos(alpha) + circle_x
        y = r * math.sin(alpha) + circle_y
        ctx.response = f'FBBlock https://www.google.com.br/maps/@{x},{y},15z'

    else:
        # radius of the circle
        circle_r = 0.4

        # random angle
        alpha = 2 * math.pi * random.random()
        # random radius
        r = circle_r * math.sqrt(random.random())
        # calculating coordinates
        x = r * math.cos(alpha) + circle_x
        y = r * math.sin(alpha) + circle_y
        ctx.response = f'FBBlock https://www.google.com.br/maps/@{x},{y},15z'

    count += 1


'''
Created on Dec 6, 2018

@author: ashwath
'''
from coapthon.resources.resource import Resource

class TestCoapResource(Resource):

    def __init__(self, name= "TestCoapResource", coap_server = None):
        super(TestCoapResource, self).__init__(name, coap_server, visible=True, observable=True, allow_children=True)

        self.payload = "Test Coap Resource"
        self.resource_type = "rt1"
        self.content_type = "text/plain"
        self.interface_type = "if1"

    def render_GET(self, request):
        print("successfully retrieved this message from TestCoapResource. Payload: "+ str(self.payload))

        file_handler = open("/home/ashwath/Downloads/testFile", "r")

        self.payload = file_handler.read()

        file_handler.close()

        return self

    def render_POST(self, request):

        res = TestCoapResource()
#         res.location_query = request.URI_QUERY

        file_handler = open("/home/ashwath/Downloads/testFile", "w")

        res.payload = request.payload

        file_handler.write(request.payload)

        file_handler.close()

        return res

    def render_DELETE(self, request):

        self.payload = request.payload

        file_handler = open("/home/ashwath/Downloads/testFile", "w")

#         file_handler.write(self.payload)

        file_handler.close()

        return True

    def render_PUT(self, request):
        self.payload = request.payload

        file_handler = open("/home/ashwath/Downloads/testFile", "a")

        file_handler.write(self.payload)

        file_handler.close()

        return self


import pygame
from pygame import Color
from models import Spaceship, Asteroid, Bullet
from utils import load_sprite , get_random_position, print_text

class SpaceRocks:
    MIN_ASTEROID_DISTANCE = 250
    SPAWN_TIME = 120
    SHIELD_PULSE = 60

    def __init__(self):
        self._init_pygame()
        self.screen = pygame.display.set_mode((800, 600))
        self.background = load_sprite("space", False)
        self.clock = pygame.time.Clock()
        self.font = pygame.font.Font(None, 64)
        self.play_again = True
        self.setup_new_game()

    def setup_new_game(self):
        self.shield_pulse_time = 0
        self.time_to_spawn = 0
        self.destroyed_asteroids = 0
        self.message = ""
        self.asteroids = []
        self.bullets = []
        self.spaceship = Spaceship((400, 300), self.bullets.append)

        for _ in range(1):
            self.spawn_asteroid()

    def spawn_asteroid(self):
        while True:
            position = get_random_position(self.screen)
            if (
                position.distance_to(self.spaceship.position)
                > self.MIN_ASTEROID_DISTANCE
            ):
                break
        self.asteroids.append(Asteroid(position, self.asteroids.append))

    def main_loop(self):
        while self.play_again == True:
            self._handle_input()
            self._process_game_logic()
            self._draw()

    def _init_pygame(self):
        pygame.init()
        pygame.display.set_caption("Space Rocks")

    def _handle_input(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT or (
                event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE
            ):
                quit()
            elif (
                self.spaceship
                and event.type == pygame.KEYDOWN
                and event.key == pygame.K_SPACE
            ):
                self.spaceship.shoot()
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_a and self.spaceship:
                self.spawn_asteroid()

            elif event.type == pygame.KEYDOWN and event.key == pygame.K_e and not self.spaceship :
                self.spaceship = Spaceship((400, 300), self.bullets.append)
                self.message = ""

            elif event.type == pygame.KEYDOWN and event.key == pygame.K_r:
                self.setup_new_game()

        is_key_pressed = pygame.key.get_pressed()
        if self.spaceship:
            if is_key_pressed[pygame.K_RIGHT]:
                self.spaceship.rotate(clockwise=True)
            elif is_key_pressed[pygame.K_LEFT]:
                self.spaceship.rotate(clockwise=False)
            if is_key_pressed[pygame.K_UP]:
                self.spaceship.accelerate()
            elif is_key_pressed[pygame.K_DOWN]:
                self.spaceship.decelerate()
            if is_key_pressed[pygame.K_b]:
                self.spaceship.emergency_brake()

    def _process_game_logic(self):
        for game_object in self._get_game_objects():
            game_object.move(self.screen)

        if self.spaceship:
            for asteroid in self.asteroids:
                if asteroid.collides_with(self.spaceship):
                    if self.spaceship.shield == 0:
                        self.spaceship = None
                        self.message = "Przegrałeś!"
                        break
                    else:
                        self.asteroids.remove(asteroid)
                        self.spaceship.shield = 0
                        asteroid.split()
                        self.destroyed_asteroids += 1

        #self.asteroid.move()
        for bullet in self.bullets[:]:
            for asteroid in self.asteroids[:]:
                if asteroid.collides_with(bullet):
                    self.asteroids.remove(asteroid)
                    self.bullets.remove(bullet)
                    asteroid.split()
                    self.destroyed_asteroids += 1
                    break

            if not self.screen.get_rect().collidepoint(bullet.position):
                self.bullets.remove(bullet)

        if not self.asteroids and self.spaceship:
            self.message = "Wygrałeś!"

        self.time_to_spawn += 1
        if self.time_to_spawn == self.SPAWN_TIME and self.spaceship:
            self.spawn_asteroid()
            self.time_to_spawn = 0

        self.shield_pulse_time += 1
        if self.shield_pulse_time == 60:
            self.shield_pulse_time = 0

    def _draw(self):
        self.screen.blit(self.background, (0, 0))
        for game_object in self._get_game_objects():
            game_object.draw(self.screen)

        if self.spaceship and self.spaceship.shield == 1 :
            color = (255, 100 + 155 * (self.shield_pulse_time/self.SHIELD_PULSE), 0+ 255 * (self.shield_pulse_time/self.SHIELD_PULSE))
            pygame.draw.circle(self.screen, color, self.spaceship.position, self.spaceship.radius+3, 2)

        if self.message:
            print_text(self.screen, self.message, self.font)

        print_text(self.screen, str(self.destroyed_asteroids), self.font, (770,30))
        # if self.spaceship:
        #     print_text(self.screen, str(self.spaceship.shield), self.font, (570,30))

        #print_text(self.screen, str(self.SPAWN_TIME - self.time_to_spawn), self.font, (570,30))

        print_text(self.screen, str(self.shield_pulse_time), self.font, (570,30))

        pygame.display.flip()
        self.clock.tick(60)

    def _get_game_objects(self):
        game_objects = [*self.asteroids, *self.bullets]

        if self.spaceship:
            game_objects.append(self.spaceship)

        return game_objects


import colorgram
from turtle import Turtle,Screen
import random
colors=colorgram.extract('img.jpg',25)
col=colors[0]
s=Screen()
t=Turtle()
s.colormode(255)
cols=[]
for color in colors:
    r = color.rgb.r
    g = color.rgb.g
    b = color.rgb.b
    nc=(r,g,b)
    cols.append(nc)

t.pensize(20)
t.penup()
t.setx(-350)
t.sety(300)
for i in range(16):
    for j in range(18):
        t.pencolor(cols[random.randint(0,24)])
        t.pendown()
        t.forward(1)
        t.penup()
        t.forward(40)
    t.back(738)
    t.right(90)
    t.forward(40)
    t.left(90)

t.forward(1)
s.exitonclick()


import tkinter as tk
import tkinter.messagebox
import parser
from math import sqrt, factorial

button_param = {
    "relief": "flat",
    "height": 3,
    "width": 3,
    "font": "Courier 11 bold",
    "activebackground": "gray74"
}

class Calculator(tk.Frame):
    def __init__(self, master=None):
        """Create a frame widget with the parent MASTER for the class Calculator."""
        tk.Frame.__init__(self, master)
        self.grid()
        self.master.title("Calculator")
        self.master.resizable(width=False, height=False)
        self.but1 = tk.Button(
            self, text="1", command=lambda arg=1: self.clicked(arg), **button_param)
        self.but1.grid(row=1, column=1)
        self.but2 = tk.Button(
            self, text="2", command=lambda arg=2: self.clicked(arg), **button_param)
        self.but2.grid(row=1, column=2)
        self.but3 = tk.Button(
            self, text="3", command=lambda arg=3: self.clicked(arg), **button_param)
        self.but3.grid(row=1, column=3)
        self.but4 = tk.Button(
            self, text="4", command=lambda arg=4: self.clicked(arg), **button_param)
        self.but4.grid(row=2, column=1)
        self.but5 = tk.Button(
            self, text="5", command=lambda arg=5: self.clicked(arg), **button_param)
        self.but5.grid(row=2, column=2)
        self.but6 = tk.Button(
            self, text="6", command=lambda arg=6: self.clicked(arg), **button_param)
        self.but6.grid(row=2, column=3)
        self.but7 = tk.Button(
            self, text="7", command=lambda arg=7: self.clicked(arg), **button_param)
        self.but7.grid(row=3, column=1)
        self.but8 = tk.Button(
            self, text="8", command=lambda arg=8: self.clicked(arg), **button_param)
        self.but8.grid(row=3, column=2)
        self.but9 = tk.Button(
            self, text="9", command=lambda arg=9: self.clicked(arg), **button_param)
        self.but9.grid(row=3, column=3)
        self.but0 = tk.Button(
            self, text="0", command=lambda arg=0: self.clicked(arg), **button_param)
        self.but0.grid(row=4, column=1)
        self.but_C = tk.Button(
            self, text="C", command=self.reset, **button_param)
        self.but_C.grid(row=3, column=6)
        self.but_CE = tk.Button(
            self, text="CE", command=self.delete, **button_param)
        self.but_CE.grid(row=4, column=3)
        self.but_plus = tk.Button(
            self, text="+", command=lambda arg="+": self.clicked(arg), **button_param)
        self.but_plus.grid(row=1, column=4)
        self.but_minus = tk.Button(
            self, text="-", command=lambda arg="-": self.clicked(arg), **button_param)
        self.but_minus.grid(row=2, column=4)
        self.but_multi = tk.Button(
            self, text="*", command=lambda arg="*": self.clicked(arg), **button_param)
        self.but_multi.grid(row=3, column=4)
        self.but_div = tk.Button(
            self, text="÷", command=lambda arg="/": self.clicked(arg), **button_param)
        self.but_div.grid(row=4, column=4)
        self.but_fact = tk.Button(
            self, text="!", command=self.factorial, **button_param)
        self.but_fact.grid(row=2, column=5)
        self.but_pow = tk.Button(
            self, text="^", command=lambda arg="**": self.clicked(arg), **button_param)
        self.but_pow.grid(row=3, column=5)
        self.but_result = tk.Button(
            self, text="=", command=self.result, **button_param)
        self.but_result.grid(row=1, column=5)
        self.but_square_root = tk.Button(
            self, text="√", command=self.square, **button_param)
        self.but_square_root.grid(row=4, column=5)
        self.but_open_paren = tk.Button(
            self, text="(", command=lambda arg="(": self.clicked(arg), **button_param)
        self.but_open_paren.grid(row=1, column=6)
        self.but_close_paren = tk.Button(
            self, text=")", command=lambda arg=")": self.clicked(arg), **button_param)
        self.but_close_paren.grid(row=2, column=6)
        self.but_dot = tk.Button(
            self, text=".", command=lambda arg=".": self.clicked(arg), **button_param)
        self.but_dot.grid(row=4, column=2)
        self.entry = tk.Entry(self, relief="flat", font="Arial 15 bold")
        self.entry.grid(row=0, columnspan=7, sticky=tk.W + tk.E)
        self.master.bind("key", self.key_binding)
        self.master.bind("<Return>", self.return_key)
        self.mainloop()

    def key_binding(self, event):
        self.entry.insert("end", event.char)

    def clicked(self, char):
        """When button is clicked, the corresponding value is inserted into the entry."""
        self.entry.insert("end", char)

    def reset(self):
        """Reset all the operations passed."""
        self.entry.delete(0, "end")

    def delete(self):
        """Delete characters from end of the entry one by one."""
        entry = self.entry.get()
        self.reset()
        entry_new = entry[:-1]
        self.entry.insert(0, entry_new)

    def result(self):
        try:
            result = eval(parser.expr(self.entry.get()).compile())
            self.entry.delete(0, "end")
            self.entry.insert("end", result)
        except ZeroDivisionError:
            tk.messagebox.showerror(
                title="Zero Division",
                message="Cannot be divided by zero!"
            )
            self.entry.delete(0, "end")
        except SyntaxError:
            tk.messagebox.showerror(
                title="Invalid Operation",
                message="Invalid operation!"
            )
            self.entry.delete(0, "end")

    def factorial(self):
        """Calculate the factorial value of the given number."""
        try:
            n = factorial(int(self.entry.get()))
            self.entry.delete(0, "end")
            self.entry.insert("end", n)
        except ValueError:
            tk.messagebox.showerror(
                title="Invalid Value",
                message="You entered an invalid value!")
            self.entry.delete(0, "end")
        except OverflowError:
            tk.messagebox.showerror(
                title="Overflow",
                message="Value exceeded the limit!")
            self.entry.delete(0, "end")

    def square(self):
        try:
            result = sqrt(int(self.entry.get()))
            self.entry.delete(0, "end")
            self.entry.insert("end", result)
        except ValueError:
            tk.messagebox.showerror(
                title="Invalid Value",
                message="You entered an invalid value!"
            )
            self.entry.delete(0, "end")

    def return_key(self, event):
        """Calculate the result when pressed Enter."""
        self.result()

def main():
    Calculator()

if __name__ == "__main__":
    main()


import dulwich
from dulwich import porcelain
import os
git_repo = porcelain.Repo("/home/lukaszwelnic/Decentralization/Photos_cloud")
from datetime import datetime

# commits = []
# commit = git_repo.get_object(git_repo.head())
# commit.message
# commit.author
# commit.tree

# tree = git_repo.get_object(commit.tree)

def show_changes(commit_id: bytes):
    commit = git_repo.get_object(commit_id)
    if not commit.parents:
        return
    new_files = git_repo.get_object(commit.tree).items()

    old_files = git_repo.get_object(git_repo.get_object(commit.parents[0]).tree).items()

    for i in range(0, len(new_files)):
        if i >= len(old_files):
            break
        if not [file for file in old_files if file.path == new_files[i].path]:
            print(f"file {new_files[i].path} is new")
        elif new_files[i].sha != old_files[i].sha:
            print(f"file {new_files[i].path} was changed")

def get_commit_history():
    commits = []
    # that commit object gives me the list of files
    # this is how i can know what files have been changed
    commit = git_repo.get_object(git_repo.head())
    commits = [commit.id]
    while True:
        if not commit.parents:
            break
        commits.append(commit.parents[0])
        commit = git_repo.get_object(commit.parents[0])

    commits.reverse()
    return commits

# commits_list = ['a20ca157a4c69881be82592e3a098a331e6ce4c7', 'eff93cc7dad0952b7ee07eaed444aab004aea65e',
#                 'f05a4d33a32533171726df6ced60b99379444db0']
#
# commit_mess = ['Specified 1', 'Specified 2', 'Specified 3']
#
#
commits = get_commit_history()

# version_control(git_repo, commits_list, commit_mess)

# status = porcelain.status(git_repo)

# print(commits)
#
# for com in commits:
#     print("\nCommit", com, ":")
#     show_changes(com)

# print(os.path.getmtime('/home/lukaszwelnic/SharedFolder/HostShare/spotify-party-planner-service/Dockerfile'))
print((datetime.utcnow() - datetime.fromtimestamp(os.path.getmtime('/home/lukaszwelnic/SharedFolder/HostShare/spotify-party-planner-service/Dockerfile'))).total_seconds())


from django.conf.urls import patterns, url

from tickerwatch import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^register/$', views.register, name='register'),
    url(r'^login/$', views.user_login, name='login'),
    url(r'^logout/$', views.user_logout, name='logout'),
    url(r'^add_stock/$', views.add_stock, name='add_stock'),
    url(r'^profile/$', views.profile, name='profile'),
    url(r'^text/$', views.text, name='text'),
    url(r'^text_demo/$', views.text_demo, name='text_demo'),
)


from numpy import *
import sys
def file2Mat(fileA,fileB,eletype,N,M,L):
    A=empty([M,N],dtype=eletype)
    B=empty([N,L],dtype=eletype)
    try:
        for i in range(M):
            newline=fileA.readline()
            newline=newline.split()
            for j in range(N):
                if eletype==float:
                    A[i,j]=float(newline[j])
                else:
                    A[i,j]=int(newline[j])

        for i in range(N):
            newline=fileB.readline()
            newline=newline.split()
            for j in range(L):
                if eletype==float:
                    B[i,j]=float(newline[j])
                else:
                    B[i,j]=int(newline[j])

        C=dot(A,B)
        return A,B,C
    except:
        sys.exit(3)

def main():
    inputCmd=sys.argv
    numCmd=len(sys.argv)
    A=0
    B=0
    C=0
    if numCmd==8 or numCmd==6:
        pass
    else:
        sys.exit(0)
    if sys.argv[1]=="int" or sys.argv[1]=="double":
        pass
    else:
        sys.exit(1)
    if numCmd==6:
        try:
            N=int(sys.argv[2])
            M=N;
            L=N;
        except:
            sys.exit(1)
        try:
            fileA=open(sys.argv[3])
            fileB=open(sys.argv[4])
        except:
            sys.exit(2)
        global A,B,C
        A,B,C=file2Mat(fileA,fileB,int,N,M,L)
    else:
        try:
            M=int(sys.argv[2])
            N=int(sys.argv[2])
            L=int(sys.argv[2])
        except:
            sys.exit(1)
        try:
            fileA=open(sys.argv[5])
            fileB=open(sys.argv[6])
        except:
            sys.exit(2)
        global A,B,C
        A,B,C=file2Mat(fileA,fileB,float,N,M,L)

    try:
        fileC=open(argv[numCmd-1],"w")
    except:
        sys.exit(2)

    writeContent=''
    for i in range(M):
        for j in range(L):
            writeContent+=str(C[i,j])
            if j==L-1:
                writeContent+=' '
            else:
                writeContent+='\n'

    fileC.write(writeContent)
    fileC.close()

if __name__=="__main__":
    main();


import sqlite3

TRANSLATION_TABLE = "translation_table"
LEMMA_ADDS_TABLE = "lemma_adds_table"
WORD_KEY = "word"
LEMMA_KEY = "lemma"
ADDS_KEY = "adds"
TRANSLATION_KEY ="translation"

class DatabaseManager:
    def __init__(self, db_name="vocabs.db"):
        self.conn = sqlite3.connect(db_name)

    def create_lemma_adds_table(self):
        cursor = self.conn.cursor()

        create_table = f"CREATE TABLE IF NOT EXISTS {LEMMA_ADDS_TABLE} " \
                       f"({WORD_KEY} text, {LEMMA_KEY} text, {ADDS_KEY} text, PRIMARY KEY ({WORD_KEY}))"
        cursor.execute(create_table)

        self.conn.commit()

    def create_translation_table(self):
        cursor = self.conn.cursor()

        create_table = f"CREATE TABLE IF NOT EXISTS {TRANSLATION_TABLE} " \
                       f"({LEMMA_KEY} text, {ADDS_KEY} text, {TRANSLATION_KEY} text, " \
                       f"CONSTRAINT lemma_adds PRIMARY KEY ({LEMMA_KEY}, {ADDS_KEY}))"
        cursor.execute(create_table)

        self.conn.commit()

    def insert_lemma_adds(self, word, lemma, adds):
        self.insert_lemma_adds_multiple([(word, lemma, adds)])

    def insert_lemma_adds_multiple(self, word_lemma_adds_list):
        """
        Insert into lemma_adds table
        Args:
            word_lemma_adds_list(list((str, str, str))): list of tuples of word, lemma and adds
        """
        self.create_lemma_adds_table()
        cursor = self.conn.cursor()

        for params in word_lemma_adds_list:
            try:
                insert = f"INSERT INTO {LEMMA_ADDS_TABLE} VALUES (?, ?, ?)"
                cursor.execute(insert, params)
            except sqlite3.IntegrityError:
                update = f"UPDATE {LEMMA_ADDS_TABLE} SET {LEMMA_KEY}=?, {ADDS_KEY}=? WHERE {WORD_KEY}=?"
                cursor.execute(update, (params[1], params[2], params[0]))

        self.conn.commit()

    def insert_translation(self, lemma, adds, translation):
        self.insert_translation_multiple([(lemma, adds, translation)])

    def insert_translation_multiple(self, lemma_adds_translation_list):
        """
        Insert into translation table
        Args:
            lemma_adds_translation_list(list((str, str, str))): list of tuples of lemma, adds and translation
        """
        self.create_translation_table()
        cursor = self.conn.cursor()

        for params in lemma_adds_translation_list:
            try:
                insert = f"INSERT INTO {TRANSLATION_TABLE} VALUES (?, ?, ?)"
                cursor.execute(insert, params)
            except sqlite3.IntegrityError:
                update = f"UPDATE {TRANSLATION_TABLE} SET {TRANSLATION_KEY}=? WHERE {LEMMA_KEY}=? and {ADDS_KEY}=?"
                cursor.execute(update, (params[2], params[0], params[1]))

        self.conn.commit()

    def retrieve_lemma_adds(self, word):
        return self.retrieve_lemma_adds_multiple([word])[0]

    def retrieve_lemma_adds_multiple(self, words):
        self.create_lemma_adds_table()
        cursor = self.conn.cursor()

        select = f"SELECT * FROM {LEMMA_ADDS_TABLE} WHERE {WORD_KEY}=?"

        result = []
        for word in words:
            cursor.execute(select, (word, ))
            row = cursor.fetchone()
            if row is None:
                row = (word, None, None)
            result.append(row)
        return result

    def retrieve_translation(self, lemma, adds):
        return self.retrieve_translation_multiple([(lemma, adds)])[0]

    def retrieve_translation_multiple(self, lemma_adds_list):
        self.create_translation_table()
        cursor = self.conn.cursor()

        select = f"SELECT * FROM {TRANSLATION_TABLE} WHERE {LEMMA_KEY}=? AND {ADDS_KEY}=?"

        result = []
        for params in lemma_adds_list:
            cursor.execute(select, params)
            row = cursor.fetchone()
            if row is None:
                row = (params[0], params[1], None)
            result.append(row)
        return result

    def close(self):
        self.conn.close()

if __name__ == '__main__':
    manager = DatabaseManager("test_vocabs")
    manager.create_lemma_adds_table()
    manager.create_translation_table()
    manager.insert_lemma_adds_multiple([("wort1", "lemma1", "adds1"), ("wort2", "lemma2", "adds2"), ("wort3", "lemma3", "adds3")])
    print(manager.retrieve_lemma_adds_multiple(["wort1", "wort3", "wort5"]))
    manager.insert_lemma_adds_multiple([("wort1", "lemma13", "adds13"), ("wort4", "lemma4", "adds4"), ("wort2", "lemma2", "adds2"), ("wort1", "lemma14", "adds14")])
    print(manager.retrieve_lemma_adds_multiple(["wort1", "wort3", "wort2", "wort4"]))
    manager.insert_translation_multiple([("lemma1", "adds1", "trans1"), ("lemma2", "adds2", "trans2")])
    print(manager.retrieve_translation_multiple([("lemma2", "adds2"), ("lemma1", "adds3"), ("lemma1", "adds1"), ("lemma3", "adds3")]))
    manager.insert_translation_multiple([("lemma1", "adds13", "trans1"), ("lemma3", "adds3", "trans3")])
    print(manager.retrieve_translation_multiple([("lemma3", "adds3"), ("lemma1", "adds1"), ("lemma1", "adds13")]))


from tkinter import *
from tkinter import ttk
from pytube import YouTube

import unicodedata
import re

import os

def slugify(value, allow_unicode=False):
    """
    Taken from https://github.com/django/django/blob/master/django/utils/text.py
    Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
    dashes to single dashes. Remove characters that aren't alphanumerics,
    underscores, or hyphens. Convert to lowercase. Also strip leading and
    trailing whitespace, dashes, and underscores.
    """
    value = str(value)
    if allow_unicode:
        value = unicodedata.normalize('NFKC', value)
    else:
        value = unicodedata.normalize('NFKD',
                                      value).encode('ascii',
                                                    'ignore').decode('ascii')
    value = re.sub(r'[^\w\s-]', '', value.lower())
    return re.sub(r'[-\s]+', '-', value).strip('-_')

def download():
    try:

        link = link_var.get()
        format = format_var.get()
        print(link)
        print(format)

        yt = YouTube(link)
        # print(yt.title)
        yt.title = slugify(yt.title)
        # yt.title = str(uuid.uuid4())

        if format == "1" or format == "mp3":
            yt.streams.first().download()
            os.rename(f'{yt.title}.3gpp', f'{yt.title}.mp3')
            print("MP3 downloaded")
        elif format == "2" or format == "mp4":
            yt.streams.filter(progressive=True, file_extension='mp4').order_by(
                'resolution').desc().first().download()
            print("MP4 downloaded")
        elif format == "3" or format == "both":
            yt.streams.first().download()
            yt.streams.filter(progressive=True, file_extension='mp4').order_by(
                'resolution').desc().first().download()
            os.rename(f'{yt.title}.3gpp', f'{yt.title}.mp3')
            print("MP3 and MP4 downloaded")
        else:
            print("Invalid format")

    except Exception as e:
        print(e)
    link_var.set("")

root = Tk()
root.title("YouTube Video Converter")

frm = ttk.Frame(root, padding=10)
link_var = StringVar(frm)
format_var = StringVar(frm, "1")
frm.grid()
ttk.Entry(frm, textvariable=link_var).grid(column=0, row=0)
ttk.Button(frm, text="Download", command=download).grid(column=2, row=0)

ttk.Radiobutton(frm, text="MP3", value="1", variable=format_var).grid(column=0, row=1)
ttk.Radiobutton(frm, text="MP4", value="2", variable=format_var).grid(column=1, row=1)
ttk.Radiobutton(frm, text="BOTH", value="3", variable=format_var).grid(column=2, row=1)

# ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=2)

root.mainloop()


def solution(numbers):
    result = []

    for i in range(len(numbers)):
        for j in range(i+1, len(numbers)):
            num = numbers[i] + numbers[j]
            result.append(num)
            result_number = set(result)

    return sorted(result_number)

두개 뽑아서 더하기.py


import datetime
import enum
import json
from typing import Dict

from ravendb import constants
from ravendb.documents.conventions import DocumentConventions
from ravendb.documents.queries.index_query import IndexQuery
from ravendb.documents.queries.query import ProjectionBehavior
from ravendb.tools.utils import Utils

class JsonExtensions:
    @staticmethod
    def try_get_conflict(metadata: dict) -> bool:
        if constants.Documents.Metadata.CONFLICT in metadata:
            return bool(metadata.get(constants.Documents.Metadata.CONFLICT))
        return False

    @staticmethod
    def write_index_query(conventions: DocumentConventions, query: IndexQuery) -> dict:
        generator: Dict[str, object] = {"Query": query.query}
        if query.is_page_size_set and query.page_size >= 0:
            generator["PageSize"] = query.page_size
        if query.wait_for_non_stale_results:
            generator["WaitForNonStaleResults"] = query.wait_for_non_stale_results

        if query.start is not None and query.start > 0:
            generator["Start"] = query.start

        if query.wait_for_non_stale_results_timeout is not None:
            generator["WaitForNonStaleResultsTimeout"] = query.wait_for_non_stale_results_timeout

        if query.disable_caching:
            generator["DisableCaching"] = query.disable_caching

        if query.skip_duplicate_checking:
            generator["SkipDuplicateChecking"] = query.skip_duplicate_checking

        if query.query_parameters is not None:
            generator["QueryParameters"] = JsonExtensions.params_deep_convert_to_json(
                query.query_parameters, conventions
            )
        else:
            generator["QueryParameters"] = None
        if query.projection_behavior is not None and query.projection_behavior is not ProjectionBehavior.DEFAULT:
            generator["ProjectionBehavior"] = query.projection_behavior.value
        return generator

    @staticmethod
    def params_deep_convert_to_json(
        query_parameters: Dict[str, object], conventions: DocumentConventions
    ) -> Dict[str, object]:
        """
        Converts params to serializable (by json.dump) json dictionary.
        If there's custom to_json() method defined inside the parameter class, it is used to do so (mainly used to
        fix keys casing).
        Collections and dicts are converted deeply.
        """
        updated_params = {}
        for name, value in query_parameters.items():
            updated_params[name] = JsonExtensions._convert_parameter_to_json(value, conventions)
        return updated_params

    @staticmethod
    def _convert_parameter_to_json(param: object, conventions: DocumentConventions) -> object:
        if isinstance(param, list):
            param: list
            updated = []
            for item in param:
                updated.append(JsonExtensions._convert_parameter_to_json(item, conventions))
            return updated

        elif isinstance(param, set):
            param: set
            updated = set()
            for item in param:
                updated.add(JsonExtensions._convert_parameter_to_json(item, conventions))
            return updated

        elif isinstance(param, dict):
            param: dict
            updated = {}
            for key, value in param.items():
                updated.update({key: JsonExtensions._convert_parameter_to_json(value, conventions)})
            return updated

        elif isinstance(param, tuple):
            param: tuple
            updated = []
            for i in range(len(param)):
                updated.append(JsonExtensions.params_deep_convert_to_json(param[i], conventions))
            return tuple(updated)

        # todo: create typing protocol (Python 3.8) with to_json inside and typehint the param when it has to_json
        elif constants.json_serialize_method_name in param.__class__.__dict__:
            return param.__class__.__dict__.get(constants.json_serialize_method_name)(param)
        else:
            return param

    @staticmethod
    def write_value_as_bytes(value: object) -> bytes:
        return (
            json.dumps(value.to_json())
            if getattr(value, "to_json", None) and getattr(value.to_json, "__call__", None)
            else json.dumps(value)
        ).encode("utf-8")


from datetime import datetime
from PIL import Image, ImageDraw, ImageFont

import qrcode

class QRCard:

    def __init__(self, qrCode, artWork, title):

        self.qrCode = qrCode
        self.artWork = artWork
        self.title = title

    def generate(self):

        # Create the Card image - Actual size is 78mm x 45mm - 300dpi = 921 x 532
        cardWidth = 921 * 2
        cardHeight = 532
        borderSize = 2
        marginSize = 10

        self.imgCard = Image.new('RGB', (cardWidth, cardHeight))

        # Draw bounding rectangle
        draw = ImageDraw.Draw(self.imgCard)
        draw.rectangle((0, 0, cardWidth - 1, cardHeight - 1), fill='white', outline='grey', width=2)

        # Draw vertical center line
        draw.line((int(cardWidth / 2) - 1, 0, int(cardWidth / 2) - 1, cardHeight), fill='grey', width=2)

        # Create QR code image
        qr = qrcode.QRCode(version=1, box_size=16, border=5)

        qr.add_data(self.qrCode)

        qr.make(fit=True)

        imgQR = qr.make_image(fill='black', back_color='white')

        qrWidth, qrHeight = imgQR.size

        # Get a font
        font = ImageFont.truetype('/usr/share/fonts/truetype/piboto/Piboto-Bold.ttf', 30)

        # Add some useful meta to the qr card in readable (qrcard value, date)
        imgCardMeta = Image.new("RGB", (400, 100), (255, 255, 255))

        metaWidth, metaHeight = imgCardMeta.size

        writing = ImageDraw.Draw(imgCardMeta)

        date = datetime.now().strftime("%d/%m/%Y %H:%M:%S")

        textWidth, textHeight, metaWrapped = self.textWrap([self.qrCode, date], font, writing, metaWidth, metaHeight)

        writing.text((int((metaWidth - textWidth) / 2) ,2), metaWrapped, font=font, align='center', fill=(0,0,0,255))

        imgCardMeta = imgCardMeta.transpose(Image.ROTATE_90)

        metaWidth, metaHeight = imgCardMeta.size

        # Paste the text image on to the card image
        self.imgCard.paste(imgCardMeta, ((int(cardWidth / 2) - metaWidth - borderSize), int((cardHeight - metaHeight) / 2)))

        # Paste the QR code image onto the card image
        self.imgCard.paste(imgQR, (3, int((cardHeight - qrHeight) / 2)))

        # Load the artwork image, rotate and resize
        imgArtwork = Image.open(self.artWork).convert('RGB')

        imgArtwork = imgArtwork.transpose(Image.ROTATE_270)

        imageHeight = cardHeight - (2 * (borderSize + marginSize))
        imageWidth = imageHeight

        imgArtwork = imgArtwork.resize((imageWidth, imageHeight))

        # Paste the artwork image on to the card image
        self.imgCard.paste(imgArtwork, (cardWidth - (imageWidth + borderSize + marginSize), borderSize + marginSize))

        # Get a font
        font = ImageFont.truetype('/usr/share/fonts/truetype/piboto/Piboto-Bold.ttf', 75)

        # Draw the metadata - Artist, Album
        imgMeta = Image.new("RGB", (cardHeight - ((borderSize + marginSize + 10) * 2), int(cardWidth / 2) - (imageWidth + ((borderSize + marginSize) * 2))), (255, 255, 255))

        metaWidth, metaHeight = imgMeta.size

        writing = ImageDraw.Draw(imgMeta)

        textWidth, textHeight, metaWrapped = self.textWrap(self.title, font, writing, metaWidth, metaHeight)

        writing.text((int((metaWidth - textWidth) / 2) ,2), metaWrapped, font=font, align='center', fill=(0,0,0,255))

        imgMeta = imgMeta.transpose(Image.ROTATE_270)
        metaWidth, metaHeight = imgMeta.size

        # Paste the text image on to the card image
        self.imgCard.paste(imgMeta, (cardWidth - (imageWidth + borderSize + marginSize + metaWidth), int((cardHeight - metaHeight) / 2)))

    def save(self, fileName):

        self.imgCard.save(fileName)

    def textWrap(self, paras, font, draw, max_width, max_height):

        if not isinstance(paras, list):
            paras = [paras]

        lines = [[]]

        for text in paras:

            words = text.split()

            for word in words:

                # try putting this word in last line then measure
                lines[-1].append(word)
                (w,h) = draw.multiline_textsize('\n'.join([' '.join(line) for line in lines]), font=font)

                if w > max_width: # too wide

                    # take it back out, put it on the next line, then measure again
                    lines.append([lines[-1].pop()])
                    (w,h) = draw.multiline_textsize('\n'.join([' '.join(line) for line in lines]), font=font)

                    if h > max_height: # too high now, cannot fit this word in, so take out - add ellipses

                        lines.pop()

                        # try adding ellipses to last word fitting (i.e. without a space)
                        lines[-1][-1] += '...'

                        # keep checking that this doesn't make the textbox too wide,
                        # if so, cycle through previous words until the ellipses can fit
                        while draw.multiline_textsize('\n'.join([' '.join(line) for line in lines]),font=font)[0] > max_width:
                            lines[-1].pop()
                            lines[-1][-1] += '...'
                        break

            if len(paras) > 1:
                lines[-1].append('\n')

        return [w, h, '\n' . join([' ' . join(line) for line in lines])]


#!/usr/bin/env python3
import copy
import time
import random
import math
import argparse
from rpi_ws281x import PixelStrip

# LED strip configuration:
LED_COUNT = 100  # Number of LED pixels.
LED_PIN = 18  # GPIO pin connected to the pixels (18 uses PWM!).
LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA = 10  # DMA channel to use for generating signal (try 10)
LED_BRIGHTNESS = 255  # Set to 0 for darkest and 255 for brightest
LED_INVERT = False  # True to invert the signal (when using NPN transistor level shift)
LED_CHANNEL = 0  # set to '1' for GPIOs 13, 19, 41, 45 or 53

class Color:
    def __init__(self, red=0, green=0, blue=0):
        self.red = red
        self.green = green
        self.blue = blue
        self.black = self.red == 0 and self.green == 0 and self.blue == 0

    def __iadd__(self, other):
        if other.black:
            return self
        if self.black is False:
            self.red += other.red
            self.green += other.green
            self.blue += other.blue
        else:
            self.black = False
            self.red = other.red
            self.green = other.green
            self.blue = other.blue
        return self

    def __imul__(self, other):
        if self.black:
            return self
        if other < 0:
            other = 0
        self.red *= other
        self.green *= other
        self.blue *= other
        return self

    def get(self):
        if self.black:
            return 0
        if self.red > 255:
            self.red = 255
        if self.green > 255:
            self.green = 255
        if self.blue > 255:
            self.blue = 255
        return (round(self.red) << 8) | (round(self.green) << 16) | round(self.blue)

def wheel(pos):
    """Generate rainbow colors across 0-255 positions."""
    if pos < 85:
        return Color(pos * 3, 255 - pos * 3, 0)
    elif pos < 170:
        pos -= 85
        return Color(255 - pos * 3, 0, pos * 3)
    else:
        pos -= 170
        return Color(0, pos * 3, 255 - pos * 3)

def fixcolor(pos):
    if pos == 0:
        return Color(255, 0, 0)
    elif pos == 1:
        return Color(0, 255, 0)
    elif pos == 2:
        return Color(0, 0, 255)
    elif pos == 3:
        return Color(128, 128, 0)
    elif pos == 4:
        return Color(0, 128, 128)
    elif pos == 5:
        return Color(128, 0, 128)
    return Color(255, 255, 255)

class LightFunc:
    def __init__(self):
        self.state = 0

    def get(self, i) -> Color:
        return Color()

    def next_frame(self):
        self.state += 1

class LightFuncN:
    def __init__(self):
        self.state = [0] * LED_COUNT

    def get(self, i) -> Color:
        return Color()

    def next_frame(self):
        for i in range(LED_COUNT):
            if self.state[i]:
                self.state[i] -= 1

class FuncRainbow(LightFunc):
    def __init__(self):
        super().__init__()
        self.wave = random.randrange(2, 5) / 10
        self.pos = 0
        self.shift = random.randrange(20, 100) / 200

    def get(self, i) -> Color:
        c = wheel((self.state + i) & 255)
        c *= math.sin(i * self.wave + self.pos) * 0.4 + 0.6
        return c

    def next_frame(self):
        self.state += 1
        self.state &= 255
        self.pos += self.shift

class FuncMoveingDots1(LightFunc):
    def __init__(self, brighness=1.00, speed=1.00):
        super().__init__()
        self.brighness = brighness
        self.color = wheel(random.randrange(256))
        self.wave = random.randrange(2, 5) / 10
        self.shift = random.randrange(-100, 100) / 200 * speed

    def get(self, i) -> Color:
        m = math.sin(i * self.wave + self.state) * self.brighness
        if m < 0.1:
            c = Color()
        else:
            c = copy.copy(self.color)
            c *= m
        return c

    def next_frame(self):
        self.state += self.shift

class FuncMoveingDots2(LightFunc):
    def __init__(self):
        super().__init__()
        self.color = wheel(random.randrange(256))
        self.wave = 2 * math.pi * (random.randrange(3) + 1) / LED_COUNT
        self.speed = random.randrange(-100, 100) / 200

    def get(self, i) -> Color:
        m = math.sin(i * self.wave + self.state) * 4 - 3
        if m < 0.1:
            c = Color()
        else:
            c = copy.copy(self.color)
            c *= m
        return c

    def next_frame(self):
        self.state += self.speed

class FuncMoveCombine(LightFunc):
    def __init__(self):
        super().__init__()
        self.f1 = FuncMoveingDots1(0.2, 0.1)
        self.f2 = FuncMoveingDots2()

    def get(self, i) -> Color:
        c = self.f1.get(i)
        c += self.f2.get(i)
        return c

    def next_frame(self):
        self.f1.next_frame()
        self.f2.next_frame()

class FuncRGBSinWave(LightFunc):
    def __init__(self):
        super().__init__()
        self.wave = []
        self.speed = []
        self.pos = []
        for i in range(3):
            self.wave.append(2 * math.pi * (random.randrange(3) + 1) / LED_COUNT)
            self.speed.append(random.randrange(-100, 100) / 500)
            self.pos.append(random.randrange(-314, 314) / 100)

    def get(self, i) -> Color:
        c = []
        for ci in range(3):
            c.append(3 ** (math.sin(i * self.wave[ci] + self.pos[ci]) * 5 - 5) * 255)
        r, g, b = c
        return Color(r, g, b)

    def next_frame(self):
        for i in range(3):
            self.pos[i] += self.speed[i]

class FuncRGBSawWave(LightFunc):
    def __init__(self):
        super().__init__()
        self.wave = []
        self.speed = []
        self.pos = []
        for i in range(3):
            self.wave.append((random.randrange(3) + 1) / LED_COUNT)
            self.speed.append(random.randrange(-100, 100) / 4000)
            self.pos.append(random.randrange(100) / 100)

    def get(self, i) -> Color:
        c = []
        for ci in range(3):
            y = i * self.wave[ci] + self.pos[ci]
            c.append(3 ** ((y - math.floor(y)) * 5 - 5) * 255)
        r, g, b = c
        return Color(r, g, b)

    def next_frame(self):
        for i in range(3):
            self.pos[i] += self.speed[i]

class FuncFade1(LightFuncN):
    def __init__(self):
        super().__init__()
        self.color = wheel(random.randrange(256))

    def get(self, i) -> Color:
        s = self.state[i]
        if s == 0:
            return Color()
        ret = copy.copy(self.color)
        if s < 20:
            ret *= s / 20
        else:
            ret *= (25 - s) / 5
        return ret

    def next_frame(self):
        super().next_frame()
        if random.randrange(5) == 0:
            i = random.randrange(LED_COUNT)
            if self.state[i] == 0:
                self.state[i] = 24

class FuncFade2(LightFuncN):
    def __init__(self):
        super().__init__()
        self.fast = 20
        self.slow = 50
        self.slow2 = self.slow * 2
        self.color1 = wheel(random.randrange(256))
        self.color2 = fixcolor(random.randrange(7))
        self.color2 *= 0.08
        for i in range(LED_COUNT):
            self.state[i] = random.randrange(self.slow * 2)

    def get(self, i) -> Color:
        s = self.state[i]
        ret = copy.copy(self.color2)
        if s <= self.slow2:
            if s < self.slow:
                ret *= (self.slow - s) / self.slow
            else:
                ret *= (s - self.slow) / self.slow
            return ret
        chigh = copy.copy(self.color1)
        if s < self.slow2 + self.fast:
            chigh *= (s - self.slow2) / self.fast
            ret += chigh
        else:
            chigh *= (self.slow2 + self.fast + 5 - s) / 5
            return chigh
        return ret

    def next_frame(self):
        for i in range(LED_COUNT):
            if self.state[i]:
                self.state[i] -= 1
            else:
                self.state[i] = self.slow2
        if random.randrange(10) == 0:
            i = random.randrange(LED_COUNT)
            if self.state[i] <= self.slow2:
                self.state[i] = self.slow2 + self.fast + 4

class FuncSparkling1(LightFuncN):
    def __init__(self):
        super().__init__()
        self.slow = 50
        self.slow2 = self.slow * 2
        self.color1 = wheel(random.randrange(256))
        self.color2 = fixcolor(random.randrange(7))
        self.color2 *= 0.08
        for i in range(LED_COUNT):
            self.state[i] = random.randrange(self.slow * 2)

    def get(self, i) -> Color:
        s = self.state[i]
        if random.randrange(LED_COUNT * 10) == 0:
            ret = copy.copy(self.color1)
        else:
            ret = copy.copy(self.color2)
            if s <= self.slow2:
                if s < self.slow:
                    ret *= (self.slow - s) / self.slow
                else:
                    ret *= (s - self.slow) / self.slow
        return ret

    def next_frame(self):
        for i in range(LED_COUNT):
            if self.state[i]:
                self.state[i] -= 1
            else:
                self.state[i] = self.slow2

class Tree:
    def __init__(self, arguments):
        self.args = arguments
        self.strip = PixelStrip(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL)
        self.strip.begin()
        self.func1 = None  # typing.Optional[LightFunc, LightFuncN]
        self.func2 = None  # typing.Optional[LightFunc, LightFuncN]
        self.mix = 0
        self.funclist = [FuncRainbow, FuncMoveingDots1, FuncMoveingDots2, FuncMoveCombine, FuncRGBSinWave,
                         FuncRGBSawWave, FuncFade1, FuncFade2, FuncSparkling1]
        self.fixfunc = None
        if self.args.action is not None and self.args.action < len(self.funclist):
            self.fixfunc = self.funclist[self.args.action]
        if self.args.wait < 0:
            self.args.wait = 0
        random.seed()

    def _random_func(self):
        choice = self.fixfunc if self.fixfunc is not None else random.choice(self.funclist)
        if self.args.v:
            print(f"Next scene: {choice.__name__}")
        return choice()

    def run(self):
        self.func1 = self._random_func()
        t = time.time()
        t_next_scene = t + self.args.wait
        t_next = t + 0.04
        t_fps = t
        fps = 0
        try:
            while True:
                for i in range(LED_COUNT):
                    c = self.func1.get(i)
                    if self.func2 is not None:
                        c *= (1 - self.mix)
                        c2 = self.func2.get(i)
                        c2 *= self.mix
                        c += c2
                    try:
                        self.strip.setPixelColor(i, c.get())
                    except OverflowError:
                        print(c)
                        print(c.get())
                self.strip.show()
                self.func1.next_frame()
                t = time.time()
                if self.func2 is None:
                    if t_next_scene < t:
                        self.func2 = self._random_func()
                        self.mix = 0
                else:
                    self.mix += 0.02
                    if self.mix >= 1:
                        self.func1 = self.func2
                        self.func2 = None
                        t_next_scene = t + self.args.wait
                    else:
                        self.func2.next_frame()
                if self.args.fps:
                    fps += 1
                    if t_fps + 1 <= t:
                        t_fps += 1
                        print(f"FPS: {fps}")
                        fps = 0
                t = time.time()
                w = t_next - t
                if w >= 0.01:
                    t_next += 0.04
                else:
                    w = 0.01
                    t_next = t + 0.05
                time.sleep(w)
        except KeyboardInterrupt:
            pass
        if self.args.clear:
            for i in range(LED_COUNT):
                self.strip.setPixelColor(i, 0)
            self.strip.show()

if __name__ == '__main__':
    print('Press Ctrl-C to quit.')
    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--action", type=int, help="selected action", default=None)
    parser.add_argument("-w", "--wait", type=int, help="wait per screen", default=20)
    parser.add_argument('-c', '--clear', action='store_true', help='clear the display on exit')
    parser.add_argument('-f', '--fps', action='store_true', help='display FPS')
    parser.add_argument('-v', action='store_true', help='Verbose')
    args = parser.parse_args()
    tree = Tree(args)
    tree.run()


"""

1388번 - 바닥 장식
https://www.acmicpc.net/problem/1388

전체 배열을 확인 하면서 -나 |가 있을 때 가로, 세로로 이동하며 배열을 바꾼다.
횟수는 처음 확인 했을 때만 더한다.

"""

import sys

n, m = map(int, sys.stdin.readline().split())
room = [list(sys.stdin.readline()) for _ in range(n)]
count = 0

def change(nx, ny, dx, dy, s):
    while room[ny][nx] == s:
        room[ny][nx] = '.'
        if nx + dx < m and ny + dy < n:
            nx += dx
            ny += dy

for x in range(m):
    for y in range(n):
        if room[y][x] == '-':
            count += 1
            change(x, y, 1, 0, '-')
        elif room[y][x] == '|':
            count += 1
            change(x, y, 0, 1, '|')

print(count)

"""
6 9
-||--||--
--||--||-
|--||--||
||--||--|
-||--||--
--||--||-
"""


from sage.all import *
from sage.coding.linear_code import AbstractLinearCode
from sage.coding.encoder import Encoder
from sage.coding.decoder import Decoder, DecodingError
from sage.coding.grs_code import GeneralizedReedSolomonCode

####################### code ###############################

class TamoBergCode(AbstractLinearCode):
    _registered_encoders = {}
    _registered_decoders = {}

    def __init__(self, base_field, length, dimension, locality, local_minimum_distance=2, sub_group_type="any"):

        if not base_field.is_finite():
            raise ValueError("base_field has to be a finite field")

        super().__init__(base_field, length, "VectorEncoder", "ErasureDecoder")

        self._dimension = dimension
        self._locality = locality
        self._local_minimum_distance = local_minimum_distance
        self._base_mult_group = base_field.list()[1:base_field.cardinality()]
        self._mult_sub_groups = self._list_mult_subgroups()
        self._add_sub_groups = self._list_add_subgroups()

        if sub_group_type == "any":
            try:
                self._mult_sub_groups[locality + local_minimum_distance - 1]
                self._sub_group = self._mult_sub_groups[locality + local_minimum_distance - 1]
                self._sub_group_type = "mult"
            except KeyError:
                try:
                    self._add_sub_groups[locality + local_minimum_distance - 1]
                    self._sub_group = self._add_sub_groups[locality + local_minimum_distance - 1]
                    self._sub_group_type = "add"
                except KeyError:
                    print("Can't find any subgroup of size: ",locality + local_minimum_distance - 1)

        elif sub_group_type == "mult":
            try:
                self._mult_sub_groups[locality + local_minimum_distance - 1]
                self._sub_group = self._mult_sub_groups[locality + local_minimum_distance - 1]
                self._sub_group_type = "mult"
            except KeyError:
                print("Can't find mult subgroup of size: ", locality + local_minimum_distance - 1)

        elif sub_group_type == "add":
            try:
                self._add_sub_groups[locality + local_minimum_distance - 1]
                self._sub_group = self._add_sub_groups[locality + local_minimum_distance - 1]
                self._sub_group_type = "add"
            except KeyError:
                print("Can't find add subgroup of size: ", locality + local_minimum_distance - 1)

        self._parition_size = int(length /(locality + local_minimum_distance - 1))
        self._partition = self._list_sub_group_cosets()[:self._parition_size]
        self._evaluation_points = flatten(self._partition)

    def __eq__(self, other):
        return isinstance(other, TamoBergCode) \
            and self.length() == other.length() \
            and self.dimension() == other.dimension() \
            and self.locality() == other.locality()

    def _repr_(self):
        return "[%s, %s, %s] Tamo-Berg Code over GF(%s)"\
            % (self.length(), self.dimension(), self.locality(), self.base_field().cardinality())

    def _list_mult_subgroups(self):
        multiplicative_subgroups = {}
        for j in self._base_mult_group:
            tmp = []
            first_identity_found = 0
            for i in range(0, len(self._base_mult_group)):
                if (j**i == 1 & first_identity_found == 1):
                    break
                tmp.append(j**i)
                first_identity_found = 1

            tmp.sort()
            multiplicative_subgroups[len(tmp)] = tmp

        return multiplicative_subgroups

    def _list_add_subgroups(self):
        additive_subgroups = {}
        F = self.base_field()
        p = F.characteristic()
        for i in range(1, F.degree()):
            tmp = []
            Sub_F = GF(p**i, name="a", repr="int")
            for elm in Sub_F:
                tmp.append(F.from_integer(int(str(elm))))
            tmp.sort()
            additive_subgroups[len(tmp)] = tmp

        return additive_subgroups

    def _list_sub_group_cosets(self):
        F = self.base_field()
        h_cosets = []
        for g in self._base_mult_group:
            tmp = []
            for h in self._sub_group:
                if (self._sub_group_type == "mult"):
                    tmp.append(h * g)
                elif (self._sub_group_type == "add"):
                    tmp.append(h + g)
            tmp.sort()
            h_cosets.append(tmp)

        return list(map(list, set(map(lambda i: tuple(i), h_cosets))))

    def partition(self):
        return self._partition, self._parition_size

    def sub_group(self):
        return self._sub_group, self._sub_group_type

    def evaluation_points(self):
        return self._evaluation_points

    def locality(self):
        return self._locality

    def minimum_distance(self):
        return (self.length() - self.dimension() + 1 - ((ceil(self.dimension() / self.locality())-1)*(self._local_minimum_distance-1)))

    def local_minimum_distance(self):
        return self._local_minimum_distance

####################### encoders ###############################

class TamoBergVectorEncoder(Encoder):

    def __init__(self, code):
        self._partition, self._partition_size = code.partition()
        self._sub_group, self._sub_group_type = code.sub_group()
        self._base_poly_ring = PolynomialRing(code.base_field(), 'x')
        self._annihilator = self._calc_annihilator(code.evaluation_points(),self._base_poly_ring)
        self._quotient_poly_ring = self._base_poly_ring.quotient(self._annihilator, 'x')
        self._good_poly = self._calc_good_poly(self._sub_group, self._sub_group_type, self._quotient_poly_ring)
        self._algebra_basis = self._calc_algebra_basis(self._good_poly, self._partition_size)
        self._enc_basis = self._calc_enc_basis(self._algebra_basis, code.locality(), self._quotient_poly_ring)

        self._max_dimension = len(self._enc_basis)
        if(code.dimension() > self._max_dimension):
            raise ValueError("code dimension is too big. maximum code dimension: ", self._max_dimension)

        super().__init__(code)

    def _repr_(self):
        return "Vector Encoder for %s" % self.code()

    def _calc_annihilator(self, pts, R):
        a = R.gen()
        h = 1
        for p in pts:
            h = h * (a - p)
        return h

    def _calc_good_poly(self, sub_group, sub_group_type, S):
        x = S.gen()
        if (sub_group_type == "mult"):
            good_poly = x**len(sub_group)
        else:
            good_poly = S.one()
            for h in sub_group:
                good_poly = good_poly * (x - h)

        return good_poly

    def _calc_algebra_basis(self, good_poly, partition_size):
        algebra_basis = []
        for i in range(0, partition_size):
            algebra_basis.append(good_poly**i)

        return algebra_basis

    def _calc_enc_basis(self, algebra_basis, r, S):
        x = S.gen()
        enc_basis = []
        for i in range(0, r):
            for p in algebra_basis:
                enc_basis.append(p * (x**i))

        enc_basis.sort()

        return enc_basis

    def enc_basis(self):
        return self._enc_basis

    def enc_poly(self):
        return self._enc_poly

    def enc_algebra_basis(self):
        return self._algebra_basis

    def enc_good_poly(self):
        return self._good_poly

    @cached_method
    def generator_matrix(self):
        C = self.code()
        alphas = C.evaluation_points()
        g = matrix(C.base_field(), C.dimension(), C.length(),
                   lambda i, j: self._enc_basis[i].lift()(alphas[j]))
        g.set_immutable()
        return g

######################### decoders #################################

class TamoBergErasureDecoder(Decoder):

    def __init__(self, code):
        input_space = cartesian_product([code.ambient_space(),VectorSpace(GF(2),code.ambient_space().dimension())])
        super().__init__(code, input_space, "VectorEncoder")

    def _repr_(self):
        return "Erasure Decoder for %s" % self.code()

    def decode_to_code(self, word_and_erasure_vector):
        C = self.code()
        word, erasure_vector = word_and_erasure_vector
        m = C.locality() + C.local_minimum_distance() - 1
        erasure_vector_list = [erasure_vector[x:x + m] for x in range(0, len(erasure_vector), m)]
        word_list = [word[x:x + m] for x in range(0, len(word), m)]
        partition, _ = C.partition()

        for i in range(0, len(erasure_vector_list)):
            erasure_vec = erasure_vector_list[i]
            if erasure_vec.hamming_weight() >= self.code().local_minimum_distance():
                raise DecodingError("Too many erasures in the received word")
            elif erasure_vec.hamming_weight() != 0:
                pts = []
                err = []
                for j in range(0, m):
                    if (erasure_vec[j] == 0):
                        pts.append((partition[i][j], word_list[i][j]))
                    else:
                        err.append(j)

                R = PolynomialRing(C.base_field(), 'x')
                d = R.lagrange_polynomial(pts)

                for e in err:
                    word_list[i][e] = d(partition[i][e])

        l = []
        for vec in word_list:
            for v in vec:
                l.append(v)

        return (vector(C.base_field(), l))

class TamoBergErrorDecoder(Decoder):

    def __init__(self, code):
        input_space = cartesian_product([code.ambient_space(),VectorSpace(GF(2),code.ambient_space().dimension())])
        super().__init__(code, input_space, "VectorEncoder")

    def _repr_(self):
        return "Erasure Decoder for %s" % self.code()

    def decode_to_code(self, r):
        C = self.code()
        F = C.base_field()
        n, k = C.length(), C.dimension()

        m = C.locality() + C.local_minimum_distance() - 1
        r_list = [r[x:x + m] for x in range(0, len(r), m)]

        partition, _ = C.partition()

        corr_c = []

        for i in range(0, len(r_list)):
            try:
                local_grs = GeneralizedReedSolomonCode(evaluation_points=partition[i], dimension=C.locality())
                local_decoder = local_grs.decoder("BerlekampWelch")
                local_corr_c = local_decoder.decode_to_code(vector(F, r_list[i]))
                corr_c.append(local_corr_c.list())
            except:
                corr_c.append(r_list[i].list())

        corr_c = flatten(corr_c)

        return vector(F, corr_c)

####################### registration ###############################
TamoBergCode._registered_encoders["VectorEncoder"] = TamoBergVectorEncoder
TamoBergCode._registered_decoders["ErasureDecoder"] = TamoBergErasureDecoder
TamoBergCode._registered_decoders["ErrorDecoder"] = TamoBergErrorDecoder


import numpy as np

class Dense:
    '''
    Base class for dense (fully connected) layer.
    Inputs:
        - n_inputs: Number of inputs to the layer (ie number of neurons from the previous layer)
        - n_neurons: Number of neurons in the layer
        - weight_init: Initialization method for neuron weights, to be passed to Neuron class. Default: Gaussian - standard normal
        - activation: Activation function [pass to Neuron class]
    '''
    def __init__(self, n_inputs=1, n_neurons=5, weight_init='Gaussian', activation=None):
        self.n_inputs = n_inputs
        self.n_neurons = n_neurons
        self.weight_init = weight_init
        self.activation = activation

        self.weights, self.bias = self.initialize_weights(size=(self.n_inputs, self.n_neurons), type=self.weight_init)

    def initialize_weights(self, size, type='Gaussian'):
        if self.weight_init == 'Gaussian':
            weights = np.random.normal(0.0, 1.0, size=size)
            bias = np.random.normal(0.0, 1.0)
        elif self.weight_init == 'Uniform':
            weights = np.ones(size)
            bias = np.array(1)

        return weights, bias

    def eval_activation(self, x):
        if self.activation is None:
            return x
        elif self.activation == 'relu':
            return np.maximum(x, 0)
        elif self.activation == 'tanh':
            return np.tanh(x)
        elif self.activation == 'sigmoid':
            return 1 / (1 + np.exp(-x))
        else:
            return -1

    def grad_activation(self, x): # gradients of activation functions
        if self.activation is None:
            return np.ones(x.shape)
        elif self.activation == 'relu':
            return np.heaviside(x, 0) # setting gradient to zero at non-differentiable point
        elif self.activation == 'tanh':
            return np.ones(x.shape) - (np.tanh(x) * np.tanh(x)) # derivative is 1 - tanh^2(x)
        elif self.activation == 'sigmoid':
            return x * (np.ones(x.shape) - x) # derivative is x(1-x)
        else:
            return 0

    def forward(self, x):
        self.x = self.eval_activation(np.dot(self.weights.T, x) + self.bias)
        return self.x

if __name__ == '__main__':
    # build a 3 layer network:
    input_size = 3

    x = np.array([3,1,5])

    input0 = Dense(n_inputs=3, n_neurons=2, weight_init='Gaussian', activation='relu')
    hidden1 = Dense(n_inputs=2, n_neurons=4, weight_init='Gaussian', activation='relu')
    hidden2 = Dense(n_inputs=4, n_neurons=6, weight_init='Gaussian', activation='relu')
    hidden3 = Dense(n_inputs=6, n_neurons=6, weight_init='Gaussian', activation='relu')
    hidden4 = Dense(n_inputs=6, n_neurons=4, weight_init='Gaussian', activation='relu')
    out0 = Dense(n_inputs=4, n_neurons=1, weight_init='Gaussian', activation='sigmoid')

    y = input0.forward(x)
    print(y)
    y = hidden1.forward(y)
    print(y)
    y = hidden2.forward(y)
    print(y)
    y = hidden3.forward(y)
    print(y)
    y = hidden4.forward(y)
    print(y)
    y = out0.forward(y)
    print(y)