from collections import deque, defaultdict
import sys

input = sys.stdin.readline

# N은 최대 5 * 10^4, T는 최대 2 * 10^5
N, T = map(int, input().rstrip().split())

steps = defaultdict(list)
for _ in range(N):
    x, y = map(int, input().rstrip().split())
    steps[y].append(x)

q = deque([(0, 0, 0)])

answer = False

while q:
    level, x, y = q.popleft()

    if y >= T:
        answer = level
        break

    # 이동할 수 있는 범위 내에 홈을 모두 계산
    for dx in range(-2, 3):
        for dy in range(-2, 3):
            if x + dx in steps[y + dy]:
                steps[y + dy].remove(x + dx)
                q.append((level + 1, x + dx, y + dy))

    # print(steps)
    # print(q)
    # print()

print(answer if answer else -1)


# -*- coding: utf-8 -*-
"""
Created on Tue Nov 26 10:38:27 2019

@author: zahmed

this program is part of the SENSOR_CLASSIFIER program's pre-processing routine
it will take in all the data from the sensor folder and display it
"""
import os
import pandas as pd
#from sklearn.preprocessing import minmax_scale
from sklearn.preprocessing import StandardScaler
from scipy import interpolate
from scipy.interpolate import splrep, sproot
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
import peakutils
from peakutils.plot import plot as pplot

scaler =StandardScaler()

#path to directory with the relevant files
path_dir = r'C:\Interpolation_Project\ring_resonator\09032015_LeTi_T_depn\Chip_7\Device_20'

#loop over the files and then create a list of file names to later iterate over

filenames = []
Q = []
asym = []
number_of_peaks = []
fbg_decomp = []

cols = ['x', 'y']
for  fname in os.listdir(path_dir):
    print(fname)
    file_path = (os.path.join(path_dir, fname))
    df = pd.read_csv(file_path, sep = '\t', header = 8,  engine = 'python',usecols=[0,1], names =cols )
    df.sort_values(by='x', ascending =True, inplace = True)
    df.drop_duplicates( inplace =True)
#    df.plot('x','y')
    freq_axis = np.fft.fftfreq(df['x'].count())
    power = np.fft.fft(df['y']).real
    df1 = pd.DataFrame(power)
    power_scale = scaler.fit_transform(df1)
#    plt.plot(power_scale[:180])
    power_freq = pd.DataFrame(power_scale, columns=['power']); print(len(power_freq))
    pad = np.arange(93,180,1)
    power_freq_pad = pd.concat([power_freq, pd.DataFrame(index = pad)], axis = 0, sort=False)
    power_freq_pad.fillna(0,inplace = True)
#    plt.plot(power_freq)
    fft_profile = power_freq_pad[:180].transpose()
    indexes = peakutils.indexes(df.y, thres=0.1, min_dist=100)
    fft_profile['device'] = 'ring_resonator_single_mode'
    fft_profile['asym'] = stats.skew(df.y)
    fft_profile['num_peaks'] = len(indexes)
    pplot(df.x, df.y, indexes)
    plt.show()
#    print(indexes)
    tck = interpolate.splrep(df.x,df.y,s=0.00000001) # s =m-sqrt(2m) where m= #datapts and s is smoothness factor
    x_ = np.arange (df.x.min(),df.x.max(), 0.003)
    y_ = interpolate.splev(x_, tck, der=0)
#    plt.plot(x_,y_)
#    plt.plot(df.x, df.y)
    HM =(np.max(y_)-np.min(y_))/2
    w = splrep(x_, y_ - HM, k=3)
#        print(sproot(w_j))
    try:
        if len(sproot(w))%2 == 0:
            r1 , r2 = sproot(w)
            print(r1, r2)
            FWHM = np.abs(r1 - r2)
            center_wavelength = r1 + FWHM/2
            Q = (center_wavelength/FWHM)
        else:
            Q = 23066
    except (TypeError, ValueError):
        Q = 23066
        print(fname,'error')
        continue

    fft_profile['Q'] = Q
    print(fft_profile)
    #output normalized fft profile

#    fft_decomp.append(fft_profile)
#    fft_profile.to_csv('fft'+fname)
#

#df_q = pd.DataFrame({'filnames':file_names,'fft':fft_p ,'quality_factor':Q, 'skew':asym, 'number_of_peaks': number_of_peaks})
#df_q.to_csv('peak_characteristics')


from flask import Flask
import os
from config import (
    MAIN_DOMAIN,
    MAIN1_DOMAIN,
    MAINTANENCE_TRUE,
    SSL
)

def create_app():
    APP_DOMAIN = MAIN_DOMAIN
    APP1_DOMAIN = MAIN1_DOMAIN
    response = requests.get("https://uptimerobot.com/inc/files/ips/IPv4.txt")
    UPTIMEROBOT_IPS = response.content
    app.logger.debug('Getting uptimerobot ips')
    app = Flask(__name__, host_matching=True, static_host=APP_DOMAIN)

    @app.before_request  # Suoritetaan aina ennen pyyntöön vastaamista
    def before():

        if MAINTANENCE_TRUE == True:
            if request.remote_addr in UPTIMEROBOT_IPS or request.remote_addr in MAINTANENCE_IPS:
                app.logger.info(
                    "Letted user in, because user is from us or uptimerobot")
            else:
                abort(503)
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    @app.route("/ping/")
    def ping():
        return 'pong'
    from . import id
    from . import second
    from . import index
    app.register_blueprint(second.second)
    app.register_blueprint(index.app1)
    app.register_blueprint(index.app2)
    app.register_blueprint(id.id)
    return app

def run_app():
    app = create_app()
    if __name__ == '__main__':
        app.run(host=MAIN_DOMAIN, port=443, debug=False,
                threaded=True, ssl_context=SSL)


#!/usr/bin/env python3
import unittest
import os

from networkit import *

class TestSparsification(unittest.TestCase):

	def setUp(self):
		self.G = readGraph("input/jazz.graph", Format.METIS)
		self.G.indexEdges()
		self.sparsifiers = [
			sparsification.SimmelianSparsifierParametric(10),
			sparsification.SimmelianSparsifierNonParametric(),
			sparsification.QuadrilateralSimmelianSparsifier(),
			sparsification.DegreeMultiscaleSparsifier(lambda d1, d2: max(d1,d2)),
			sparsification.SimmelianMultiscaleSparsifier(),
			sparsification.LocalSimilaritySparsifier(),
			sparsification.MultiscaleSparsifier(),
			sparsification.RandomEdgeSparsifier(),
			sparsification.RandomNodeEdgeSparsifier(),
			sparsification.ForestFireSparsifier(0.6, 5.0),
			sparsification.LocalDegreeSparsifier(),
			sparsification.SCANSparsifier()
		]

	def testGetSparsifiedGraphOfSize(self):
		"""
		Checks whether the sizes of the sparsified graphs are approximately
		of the expected size. This test is supposed to verify that all
		sparsification methods can be run without errors.
		"""

		minExpectedRatio = 0.15
		targetRatio = 0.2
		maxExpectedRatio = 0.25

		for sparsifier in self.sparsifiers:
			S = sparsifier.getSparsifiedGraphOfSize(self.G, targetRatio)
			ratio = S.numberOfEdges() / self.G.numberOfEdges()
			self.assertGreaterEqual(ratio, minExpectedRatio)
			self.assertLessEqual(ratio, maxExpectedRatio)

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


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('clients', '0020_remove_statusi_status_discount'),
    ]

    operations = [
        migrations.RenameField(
            model_name='statusi',
            old_name='discount',
            new_name='status_discount',
        ),
    ]


# api.py
from flask import Flask, request, jsonify
from transformers import pipeline

app = Flask(__name__)

# Load the text generation model
generator = pipeline("text-generation")

@app.route("/generate_text", methods=["POST"])
def generate_text():
    data = request.get_json()
    prompt = data["prompt"]

    if prompt:
        generated_text = generator(prompt, max_length=50, do_sample=True)
        return jsonify({"generated_text": generated_text[0]["generated_text"]})
    else:
        return jsonify({"error": "Prompt is required."})

if __name__ == "__main__":
    app.run(debug=True)


## Permet d'enregistrer les différentes stations de chaque métro
## pour les remettre dans l'ordre à la main

import pandas as pd

# source : https://www.ratp.fr/plans-lignes/metro/14

datas = pd.read_csv("stations.csv", sep=";")

lignes = datas["ligne"].unique()

for ligne in lignes:
    stations = datas[datas["ligne"] == ligne]["name"].to_list()
    with open(f"lignes/metro_{ligne}.txt", "w", encoding="utf-8") as file:
        file.write("\n".join(stations))


import numpy as np
import matplotlib.pyplot as plt

def laplace_jacobi(u, tol=1e-6, max_iter=1000):
    rows, cols = u.shape
    u_new = u.copy()
    iteration = 0
    while iteration < max_iter:
        u = u_new.copy()
        for i in range(1, rows-1):
            for j in range(1, cols-1):
                u_new[i, j] = 0.25 * (u[i+1, j] + u[i-1, j] + u[i, j+1] + u[i, j-1])

        # Apply boundary conditions
        u_new[:, 0] = T_left  # Left boundary
        u_new[:, -1] = T_right  # Right boundary

        residual = np.max(np.abs(u_new - u))
        if residual < tol:
            break

        iteration += 1

    return u_new, iteration

# Set up the grid and parameters
L = 1.0  # Dimensions of the plate
Nx, Ny = 50, 50  # Number of grid points
T_left, T_right = 200.0, 200.0  # Temperature boundary conditions

# Initialize temperature distribution
T = np.zeros((Nx, Ny))

# Solve Laplace's equation using Jacobi method
solution, iterations = laplace_jacobi(T)

# Plot the solution
x = np.linspace(-L/2, L/2, Nx)
y = np.linspace(-L/2, L/2, Ny)
X, Y = np.meshgrid(x, y)

plt.contourf(X, Y, solution, cmap='hot', levels=50)
plt.colorbar(label='Temperature')
plt.title(f'Temperature Distribution on a Metal Plate\nIterations: {iterations}')
plt.xlabel('x')
plt.ylabel('y')
plt.show()


# %%

import sys
sys.path.append("../../../src")
sys.path.append("../../../scripts")

from dhs_scraper import DhsArticle, stream_to_jsonl
from data_file_paths import S0_JSONL_ALL_ARTICLES_FILE, S0_JSONL_ALL_ARTICLES_PARSED_FILE, localize

# %matplotlib inline

"""
Loads all the DhsArticle with their page_content from S0_JSONL_ALL_ARTICLES_FILE, parses them and save them back to S0_JSONL_ALL_ARTICLES_PARSED_FILE file.

Used mainly for statistics in s2_dhs_stats.py.
"""

language="fr"

jsonl_articles_content_file = localize(S0_JSONL_ALL_ARTICLES_FILE, language)
jsonl_articles_parsed_file = localize(S0_JSONL_ALL_ARTICLES_PARSED_FILE, language)

buffer_size = 10
info_interval = 100

# %%

def parsed_articles_without_page_content_generator(articles, already_visited_ids, info_interval=info_interval):
    for i, a in enumerate(articles):
        if a.id not in already_visited_ids:
            a.parse_article()
            if i % info_interval == 0:
                print(f"parsing articles, currently at {i}th article....")
            a.drop_page()
            yield a

# %%

unparsed_articles = list(DhsArticle.load_articles_from_jsonl(jsonl_articles_content_file))

# %%

already_visited_ids = set(DhsArticle.get_articles_ids(jsonl_articles_parsed_file))

# %%
stream_to_jsonl(
    jsonl_articles_parsed_file,
    parsed_articles_without_page_content_generator(
        unparsed_articles,
        already_visited_ids
    ),
    buffer_size=buffer_size
)
# %%


from functions.libs import *

def getdamageold(lv, att, df, puis, cm):
    return round((((lv*0.4+2)*att*puis)/(df*50)+2)*cm*randomize(0.85, 1))

def getdamage(self, other, attackname):
    attackname = getid(attackname)
    self = getdata(self)
    other = getdata(other)

    if os.path.exists(f'data/attack/{attackname}.json'):
        attack = getdata(f'data/attack/{attackname}.json')
    else:
        attack = {'power': 60, 'precision': 100, 'category': '', 'type': 'Normal'}

    category = attack['category']
    power = attack['power']
    level = self['leveling']['level']
    attack_stat = self['fight']['stats'][f'atk{category}']
    defense_stat = other['fight']['stats'][f'def{category}']

    result = ((level*0.4+2)*attack_stat*power)/(defense_stat*50)+2
    result *= randomize(0.85, 1)
    if random() < 0.1:
        result *= 2
    result = round(result)

    return max(1, result)

def registerattacks(poke):
    baseattackdata = {'power': 60,
                      'precision': 100,
                      'category': '',
                      'type': 'Normal'}

    poke = getdata(poke)
    attacks = poke['fight']['attacks']
    for a in attacks:
        if a == '': return
        a = getid(a)
        print(a, os.path.exists(f'data/attack/{a}.json'))
        #if not os.path.exists(f'data/attack/{a}.json'):
        setdata(f'data/attack/{a}.json', baseattackdata)


from aiogram.types import Message
from aiogram.dispatcher.storage import FSMContext

from loader import dp
from sql import User
from states import Anketa

@dp.message_handler(state=Anketa.name)
async def name(message: Message, state: FSMContext):
    user = User.get(User.tg_id == message.from_user.id)
    user.name = message.text
    user.save()

    await message.answer('Теперь отправте ссылку на свою соц сеть')
    await Anketa.link.set()

@dp.message_handler(state=Anketa.link)
async def link(message: Message, state: FSMContext):
    user = User.get(User.tg_id == message.from_user.id)
    user.link = message.text
    user.save()

    await message.answer('Сколько у вас подписчиков')
    await Anketa.subs.set()

@dp.message_handler(state=Anketa.subs)
async def subs(message: Message, state: FSMContext):
    try:
        user = User.get(User.tg_id == message.from_user.id)
        user.subs = int(message.text)
        user.save()

        await message.answer('Пришлите ваш город')
        await Anketa.city.set()

    except ValueError:
        await message.answer('Отправте только число')

@dp.message_handler(state=Anketa.city)
async def city(message: Message, state: FSMContext):
    user = User.get(User.tg_id == message.from_user.id)
    user.city = message.text
    user.save()

    await message.answer('Поздравляем вы прошли регистрацию, мы будем вам присылать свежие новости')
    await state.finish()


import sys

def textencode():
    curr_row = 0
    curr_col = 0
    toreturn = ""

    #Get the input from file using command line
    inFile = sys.argv[1]
    with open(inFile,'r') as i:
        lines = i.readlines()

    #Complete matrix storing each alphabet
    alphabets_matrix = [
        ['A', 'B', 'C', 'D', 'E' ],
        ['F', 'G', 'H', 'I', 'J' ],
        ['K', 'L', 'M', 'N', 'O' ],
        ['P', 'Q', 'R', 'S', 'T' ],
        ['U', 'V', 'W', 'X', 'Y'],
        ['Z']
    ]

    #Run a loop to go over all the words in the file
    for line in lines:
        nextlinechar = 0

        #Traverse across keyboard to get the code of each alphabet/letter
        for letter in line:
            #for each word start from 0,0 in matrix
            if letter == ' ':
                curr_col = 0
                curr_row = 0
                nextlinechar = 0

            #Code should work on multiple lines, when reading from file next line is written as /n so code should ignore that
            if letter == '/':
                nextlinechar += 1
                pass
            if nextlinechar == 1:
                if(letter == 'n'):
                    nextlinechar += 1
                    pass
                else:
                    nextlinechar = 0

            #get the row and columnof the letter we are looking for
            row = -1
            for i, matrixrow in enumerate(alphabets_matrix):
                if letter in matrixrow:
                    row = i
                    col = matrixrow.index(letter)

            #If letter was not found that means there are special characters which need to be ignored so if row -1 then not a letter
            if(row != -1):
                move_ver = curr_row - row
                move_hor = curr_col - col

                if move_ver < 0:
                    for i in range(abs(move_ver)):
                        toreturn += 'd'
                elif move_ver > 0:
                    for i in range(move_ver):
                        toreturn += 'u'
                if move_hor < 0:
                    for i in range(abs(move_hor)):
                        toreturn += 'r'
                elif move_hor > 0:
                    for i in range(move_hor):
                        toreturn += 'l'
                toreturn += '#'

                curr_row = row
                curr_col = col

    return toreturn

print(textencode())


import requests, json, argparse, os, uuid, time

def ttsmaker_query(text, output_file, token="ttsmaker_demo_token", voice_id=147, audio_format="mp3", speed=1.00, volume=1, paragraph_pause=0):
    if "\n" in text:
        concat_command = "sox "
        for text_frag in text.split("\n"):
            if len(text_frag):
                frag = str(uuid.uuid4()) + "." + audio_format
                ttsmaker_query(text_frag, frag, token, voice_id, audio_format, speed, volume, paragraph_pause)
                concat_command += frag + " "
        concat_command += "-C 0 " + output_file + " silence -l 1 0.1 1% -1 0.55 1%"
        os.system(concat_command)
        return output_file

    url = 'https://api.ttsmaker.com/v1/create-tts-order'
    headers = {'Content-Type': 'application/json; charset=utf-8'}
    params = {
        'token': token,
        'text': text,
        'voice_id': voice_id,
        'audio_format': audio_format,
        'audio_speed': 1.0,
        'audio_volume': volume,
        'text_paragraph_pause_time': paragraph_pause
    }
    response = requests.post(url, headers=headers, data=json.dumps(params)).json()
    time.sleep(1)

    with open(os.path.abspath(output_file), "wb+") as out:
        content = requests.get(response["audio_file_url"], stream=True).content
        out.write(content)

    os.system("sox " + " -v " + str(volume) + " " + output_file + " -C 0 TMP" + output_file + " silence -l 1 0.1 1% -1 0.55 1% tempo " + str(speed))
    os.system("mv TMP" + output_file + " " + output_file)
    return output_file

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--text", required=True)
    parser.add_argument("--token", default="ttsmaker_demo_token")
    parser.add_argument("--voice-id", type=int, default=147)
    parser.add_argument("--format", default="mp3")
    parser.add_argument("--speed", type=float, default=1.00)
    parser.add_argument("--volume", type=float, default=1)
    parser.add_argument("--paragraph-pause", type=int, default=0)
    parser.add_argument("--output-file", required=True)
    args = parser.parse_args()

    ttsmaker_query(args.text, args.output_file, args.token, args.voice_id, args.format, args.speed, args.volume, args.paragraph_pause)


from __future__ import division, print_function
from collections import OrderedDict
import numpy as np

def assert_compatible_keys(the_dict, allowed, errorprefix):
    for key in the_dict:
        assert_in(value=key, allowed=allowed, errorprefix=errorprefix)

def assert_in(value, allowed, errorprefix):
    assert value in allowed,\
        errorprefix+str(value)+" not in allowed values: "+str(allowed)

def assert_has_keys(the_dict, required, errorprefix):
    for key in required:
        assert key in the_dict, (
            errorprefix+key+" must be specified. Provided keys are: "
            +str(the_dict.keys()))

def get_endmember_idx_mapping(endmember_names):
    """
    Get a mapping from endmember name to indexes with all the subtypes
     corresponding to that endmember. The subtypes should be denoted with
     _subtype.
    """
    endmembername_to_indices = OrderedDict()

    for idx,endmember_name in enumerate(endmember_names):
        if "_" in endmember_name:
            endmembername_core = endmember_name.split("_")[0]
        else:
            endmembername_core = endmember_name
        if endmembername_core not in endmembername_to_indices:
            endmembername_to_indices[endmembername_core] = []
        endmembername_to_indices[endmembername_core].append(idx)

    return endmembername_to_indices

def collapse_endmembers_by_idxmapping(endmember_fractions,
                                      endmembername_to_indices):
    endmember_names = endmembername_to_indices.keys()
    remapped_endmember_fractions = np.zeros(
        (len(endmember_fractions), len(endmember_names)))
    for remapped_idx,endmember_name in enumerate(endmember_names):
        idxs = endmembername_to_indices[endmember_name]
        for idx in idxs:
            remapped_endmember_fractions[:,remapped_idx] +=\
                endmember_fractions[:,idx]
    return remapped_endmember_fractions

def organize_converted_vars_by_groupname(converted_variables,
                                         convertedparam_groups):
    """
    converted_variables: a matrix of dimensions
        num_converted_variables X num_parameters
    """
    groupname_to_totalconvertedvariable = OrderedDict()
    groupname_to_effectiveconversionratios = OrderedDict()
    convar_idx = 0
    for convertedparam_group in convertedparam_groups:
        groupname = convertedparam_group.groupname
        #each type of converted variable may have multiple instances of
        # itself corresponding to different conversion ratios
        convar_vals = converted_variables[:,
            convar_idx:
            convar_idx+len(convertedparam_group.conversion_ratios)]
        convar_idx += len(convertedparam_group.conversion_ratios)
        #sanity check the signs; for each entry they
        # should either be all positive or all negative, within numerical
        # precision
        for convar_vals_row in convar_vals:
            if ((all(convar_vals_row >= 0) or
                 all(convar_vals_row <= 0))==False):
                print("WARNING: sign inconsistency in "
                      +groupname+":", convar_vals_row)
        total_convar = np.sum(convar_vals, axis=-1)
        groupname_to_totalconvertedvariable[groupname] =\
            total_convar
        #proportions of the converted variable used at differnet ratios
        with np.errstate(divide='ignore', invalid='ignore'):
            convarusage_proportions = (
                convar_vals/total_convar[:,None])
            effective_conversion_ratios = OrderedDict()
            conversion_ratios_dict =\
                convertedparam_group.get_conversion_ratios_dict()
            effective_conversion_ratios = OrderedDict([
                (relevant_param_name,
                 convarusage_proportions@conversion_ratio)
                for relevant_param_name,conversion_ratio in
                conversion_ratios_dict.items()
             ])
            groupname_to_effectiveconversionratios[groupname] =\
                effective_conversion_ratios

    return (groupname_to_totalconvertedvariable,
            groupname_to_effectiveconversionratios)

#import gsw
#
#
##Remineralization ratios for computing PO, NO and SiO values
#R_PO = 155
#R_SiO = 15
#R_NO = 9.68
#
#
#def augment_df_with_PO_NO_SiO(df):
#    """
#    Augments a data frame with the values for PO, NO and SiO. Assumes there are
#    columns 'phosphate', 'nitrate', 'silicate' and 'oxygen' in the data frame.
#
#    PO = phosphate*155 + oxygen
#    NO = nitrate*9.68 + oxygen
#    SiO = silicate*15 + oxygen
#
#    Args:
#        df: the pandas  data frame
#    """
#    df["PO"] = df["oxygen"] + df["phosphate"]*R_PO
#    df["NO"] = df["oxygen"] + df["nitrate"]*R_NO
#    df["SiO"] = df["oxygen"] + df["silicate"]*R_SiO
#
#
#def prepare_water_mass_df(water_mass_arr):
#    df = pd.DataFrame(data=water_mass_arr,
#                      columns=["watermassname",
#                               "potential_temp", "practical_salinity",
#                               "oxygen", "phosphate", "silicate",
#                               "nitrate", "spiciness", "PV"])
#    augment_df_with_PO_NO_SiO(df)
#    return df
#
#
#def prepare_observations(input_file):
#    """
#    This code is specific to Rian's data format
#    """
#    header = ["c"+str(i) for i in range(1,30)]
#    header[4] = "bottle flag"
#    header[16] = "bottle salinity flag"
#    header[20] = "bottle oxygen flag"
#    header[22] = "silicate flag"
#    header[24] = "nitrate flag"
#    header[28] = "phosphate flag"
#
#    header[11] = "CTD pressure"
#    header[12] = "CTD temperature"
#    header[15] = "practical_salinity"
#    header[8] = "latitude"
#    header[9] = "longitude"
#
#    header[0] = "stnnbr"
#    header[5] = "geotrc_ID"
#    header[10] = "bottom depth"
#    header[19] = "oxygen"
#    header[21] = "silicate"
#    header[23] = "nitrate"
#    header[27] = "phosphate"
#
#    gp15_df = pd.read_csv(
#        "names_added_GP15OMPA_33RR20180918_only_gs_rosette_clean1_hy1.csv",
#         names=header, na_values = -999)
#
#    #remove bad data
#    for flag_type in ["bottle flag", "bottle salinity flag", "bottle oxygen flag",
#                  "silicate flag", "nitrate flag", "phosphate flag"]:
#        gp15_df = gp15_df[gp15_df[flag_type] <= 2]
#    gp15_df = pd.DataFrame(gp15_df)
#
#    augment_df_with_PO_NO_SiO(gp15_df)
#
#    #absolute salinty
#    absolute_salinity = gsw.SA_from_SP(SP=gp15_df["practical_salinity"],
#                                       p=gp15_df["CTD pressure"],
#                                       lon=gp15_df["longitude"],
#                                       lat=gp15_df["latitude"])
#    gp15_df["absolute_salinity"] = absolute_salinity
#
#    #conservative temp
#    conservative_temp = gsw.CT_from_t(SA=absolute_salinity,
#                                  t=gp15_df["CTD temperature"],
#                                  p=gp15_df["CTD pressure"])
#    gp15_df["conservative_temp"] = conservative_temp
#
#    #potential temp
#    potential_temp = gsw.pt_from_CT(SA=absolute_salinity,
#                                CT=conservative_temp)
#    gp15_df["potential_temp"] = potential_temp
#
#    #sig0
#    sig0 = gsw.rho(SA=absolute_salinity, CT=conservative_temp, p=0) - 1000
#    gp15_df["sig0"] = sig0
#
#    z = gsw.z_from_p(p=gp15_df["CTD pressure"], lat=gp15_df["latitude"])
#    depth = -z #https://github.com/TEOS-10/python-gsw/blob/7d6ebe8114c5d8b4a64268d36100a70e226afaf6/gsw/gibbs/conversions.py#L577
#    gp15_df["depth"] = depth
#
#    spic0 = gsw.spiciness0(SA=absolute_salinity, CT=conservative_temp)
#    gp15_df["spiciness"] = spic0
#
#    #calculation of planetary vorticity
#    rho_ref = 1000.0 #reference density
#    Omega = 2*np.pi/86400;
#    f = np.mean(2*Omega*np.sin(gp15_df["latitude"]*(np.pi/180.0)))
#    PV = -(f/rho_ref)*(np.gradient(sig0, depth))
#    gp15_df["PV"] = PV #potential vorticity
#
#    print("Rows:",len(gp15_df))
#    gp15_df = gp15_df.dropna()
#    print("Rows without NA values:",len(gp15_df))


"""
Lexicographic permutations

Problem 24
A permutation is an ordered arrangement of objects. For example,
3124 is one possible permutation of the digits 1, 2, 3 and 4.
If all of the permutations are listed numerically or alphabetically,
we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:

012   021   102   120   201   210

What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
"""
import time

def hasIndexK(a):
    """Check if k index exists in given sequence"""
    if findIndexK(a) is None:
        return False
    else:
        return True

def findIndexK(a):
    """Find the largest index k such that a[k] < a[k + 1].
    If no such index exists, the permutation is the last permutation."""
    n = len(a)
    ks = []

    for i in range(n - 1):
        if a[i] < a[i + 1]:
            ks.append(i)

    if len(ks) == 0:
        return None
    else:
        return max(ks)

def findIndexL(a, k):
    """Find the largest index l greater than k such that a[k] < a[l]."""
    n = len(a)
    ls = []

    if k is not None:
        for i in range(n):
            if a[k] < a[i] and i > k:
                ls.append(i)

    if ls:
        return max(ls)
    else:
        return None

def swapValues(a, k, l):
    """Swap the value of a[k] with that of a[l]"""
    ak = a[k]
    al = a[l]
    a[k] = al
    a[l] = ak

    return a

def reverseSeq(a, k):
    """Reverse the sequence from a[k + 1] up to and including the final element a[n]."""
    head = a[:k + 1]
    tail = a[k + 1:]
    tail = tail[::-1]

    return head + tail

def lexicographicPermutationsGenerator(a):
    """
    The following algorithm generates the next permutation lexicographically after a given permutation.
    It changes the given permutation in-place.

    Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.
    Find the largest index l greater than k such that a[k] < a[l].
    Swap the value of a[k] with that of a[l].
    Reverse the sequence from a[k + 1] up to and including the final element a[n].

    :param a: given sequence
    :return: next
    """
    yield a

    while hasIndexK(a):
        k = findIndexK(a)
        l = findIndexL(a, k)
        a = swapValues(a, k, l)
        a = reverseSeq(a, k)

        yield a

def debug(a):
    print(a)
    print(hasIndexK(a))
    k = findIndexK(a)
    print(f'k={k}')
    l = findIndexL(a, k)
    print(f'l={l}')
    a = swapValues(a, k, l)
    print(a)
    a = reverseSeq(a, k)
    print(a)

def main(a):
    a = sorted(a)
    lex = lexicographicPermutationsGenerator(a)

    nth = 0
    lexPerm = None

    while nth < 1_000_000:
        lexPerm = next(lex)
        nth += 1

    print(f'{nth}th - {lexPerm}')

if __name__ == '__main__':
    start = time.time()

    a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    # a = [0, 1, 2]

    # debug(a)
    main(a)

    end = time.time()
    print(f"{(end - start):.6f} seconds")


#!/usr/bin/env python3
import sys
import wave
import shutil

import pyaudio
from requests import Session, post, get

SPEECH_PRO_WAV = 'https://www.speechpro.ru/voice-fabric/text-to-voice'
SPEECHPRO_URL = 'https://www.speechpro.ru/'

class SessionSpeech:
    """download wav from speechpro"""

    def __init__(self, url, url_download):
        self.url = url
        self.download_url = url_download
        self.ses = Session()
        self.headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Encoding': 'gzip, deflate, sdch',
            'Accept-Language': 'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,und;q=0.2',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'DNT': 1,
            'Host': 'www.speechpro.ru',
            'Pragma': 'no-cache',
            'Upgrade-Insecure-Requests': 1,
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 '
                          '(KHTML, like Gecko) Ubuntu Chromium/61.0.3163.79 Chrome/61.0.3163.79 Safari/537.36',
        }
        res = self.ses.get(url)
        self.csrftoken = self.ses.cookies.get_dict()['csrftoken']
        self.cookie = self.ses.cookies.get_dict()['sessionid']

    def text_to_speech(self, text_to_voice, listen=False, path=None):
        cookies = {
            'sessionid': self.cookie,
            'csrftoken': self.csrftoken,
        }

        headers = {
            'Pragma': 'no-cache',
            'Origin': 'http://www.speechpro.ru',
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4,und;q=0.2',
            'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 '
                          '(KHTML, like Gecko) Ubuntu Chromium/61.0.3163.79 Chrome/61.0.3163.79 Safari/537.36',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Cache-Control': 'no-cache',
            'X-Requested-With': 'XMLHttpRequest',
            'Connection': 'keep-alive',
            'Referer': 'https://www.speechpro.ru',
            'DNT': '1',
        }

        data = [
            ('text',
             text_to_voice),
            ('csrfmiddlewaretoken', self.csrftoken),
        ]
        res = post(self.download_url, headers=headers, cookies=cookies, data=data)
        print('Response for debug: ', res)
        wav_url = res.json()['response']
        wav_url_file = headers['Origin'] + '/' + wav_url
        chunk = 1024
        r = get(wav_url_file, stream=True)
        if listen:
            wf = wave.open(r.raw, 'rb')
            p = pyaudio.PyAudio()
            stream = p.open(
                    format=p.get_format_from_width(wf.getsampwidth()),
                    channels=wf.getnchannels(),
                    rate=wf.getframerate(),
                    output=True)
            data = wf.readframes(chunk)

            while data != '':
                stream.write(data)
                data = wf.readframes(chunk)

            stream.close()
            p.terminate()
        else:
            if r.status_code == 200:
                with open(path, 'wb') as f:
                    r.raw.decode_content = True
                    shutil.copyfileobj(r.raw, f)

if __name__ == "__main__":
    c = SessionSpeech(SPEECHPRO_URL, SPEECH_PRO_WAV)
    try:
        text = sys.argv[1]
    except IndexError:
        text = 'Например, вот такой текст, всё равно что тут будет:) и даже если 2323445 миллионов...'
    c.text_to_speech(text, listen=False, path='file.wav') #Path путь для сохранения файла.


from PIL import Image
import numpy as np

import torch
import torchvision.transforms as tr

from model.deeplab import DeepLab
from customer_utils.lable_img import decode_segmap

device = torch.device('cuda:0')

checkpoint = torch.load("/home/chengxiao/pycharmProject/myDeepLabV3Plus/ckp/resnet101/model79_0.6293811152760053.pth")

model = DeepLab(num_classes=21,
                backbone='mobilenet',
                output_stride=16,
               )
# model = torch.nn.DataParallel(model)

model.load_state_dict(checkpoint)
model.eval()
model.to(device)

def transform(image):
    return tr.Compose([
        # tr.Resize(513),
        # tr.CenterCrop(513),
        tr.ToTensor(),
        tr.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))
    ])(image)

torch.set_grad_enabled(False)

image = Image.open('person_with_car1.jpg')
inputs = transform(image).to(device)
print("one")
output = model(inputs.unsqueeze(0)).squeeze().cpu().numpy()
print("one")
pred = np.argmax(output, axis=0)

# Then visualize it:
decode_segmap(pred, dataset="coco", plot=True)


import numpy as np
import torchvision
import torchvision.transforms.functional as TF
import cv2
import annotate
import training
import torch
import data

def read_from_video(model, im_size, device):
    cap = cv2.VideoCapture(0)
    if not cap.isOpened():
        print("Cannot open camera")
        exit()
    while True:
        # capture fram by frame
        ret, frame = cap.read()

        # if frame is read correctly - ret is True
        if not ret:
            print("Can't recieve frame (stream end?). Exiting...")
            break
        # operations onq
        # frames here
        # frame = img -> preproccess -> call predict

        og_frame = frame

        # should do all this in predict not here
        frame = cv2.resize(frame, dsize=(im_size,im_size))
        #frame = frame.reshape(3, im_size, im_size)
        frame = TF.to_tensor(frame)
        frame = TF.normalize(frame, mean= (0.4914, 0.4822, 0.4465), std= (0.2023, 0.1994, 0.2010))

        h_scale = im_size / og_frame.shape[1]
        w_scale = im_size / og_frame.shape[0]

        coordinates = training.predict(model, frame.unsqueeze(0).to(device))
        scaled_coordinates = data.scale_labels_back(coordinates[:,16:].squeeze().tolist(), h_scale, w_scale)
        coordinates = coordinates.squeeze().tolist()[0:16] + scaled_coordinates
        frame = annotate.get_annotate_flat_image(coordinates, image=og_frame)

        '''
        coordinates = training.predict(model, frame.unsqueeze(0).to(device))
        coordinates = data.scale_labels_back(coordinates.squeeze().tolist(), h_scale, w_scale)
        frame = annotate.get_annotate_flat_image(coordinates, image=og_frame)
        '''
        # display frame
        cv2.imshow('frame', frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # when everything done, realse capture
    cap.release()
    cv2.destroyAllWindows()


#!/usr/bin/python2
# -*- coding: utf-8 -*-

"""
Zadanie 103

Napisz funkcje `oov(text, vocab)`, która zwraca listę wyrazów (bez
duplikatów), które występują w tekście `text` i nie występują w
liście znanych wyrazów `vocab`. Argumenty funkcji `text` i `vocab`
to odpowiednio łańcuch znakowy i lista łańuchów znakowych.
Wszystkie wyrazy należy zmienić na małe litery. (OOV = out of
vocabulary)

NAME: oov
PARAMS: string, list
RETURN: list
POINTS: 3
"""

import unittest
from Task103 import oov

class Task103Test(unittest.TestCase):
    """Testy do zadania 103."""

    def test(self):
        """Prosty test."""
        text   = "This is a string , which I will use for string testing"
        vocab  = [',', 'this', 'is', 'a', 'which', 'for', 'will', 'I']
        oo_voc = ['string', 'testing', 'use']

        self.assertEqual(set(oov(text, vocab)), set(oo_voc))

if __name__ == '__main__':
    unittest.main()


import unittest

from dbt.adapters.spark import SparkColumn

class TestSparkColumn(unittest.TestCase):
    def test_convert_table_stats_with_no_statistics(self):
        self.assertDictEqual(SparkColumn.convert_table_stats(None), {})

    def test_convert_table_stats_with_bytes(self):
        self.assertDictEqual(
            SparkColumn.convert_table_stats("123456789 bytes"),
            {
                "stats:bytes:description": "",
                "stats:bytes:include": True,
                "stats:bytes:label": "bytes",
                "stats:bytes:value": 123456789,
            },
        )

    def test_convert_table_stats_with_bytes_and_rows(self):
        self.assertDictEqual(
            SparkColumn.convert_table_stats("1234567890 bytes, 12345678 rows"),
            {
                "stats:bytes:description": "",
                "stats:bytes:include": True,
                "stats:bytes:label": "bytes",
                "stats:bytes:value": 1234567890,
                "stats:rows:description": "",
                "stats:rows:include": True,
                "stats:rows:label": "rows",
                "stats:rows:value": 12345678,
            },
        )


import random

zar1 = int(input("İstediğiniz ilk zar değerini giriniz: "))
zar2 = int(input("İstediğiniz ikinci zar değerini giriniz: "))

sayac = 0

while "x" != "y":
    sayac = sayac + 1
    a = random.randint(1,6)
    b = random.randint(1,6)
    print(str(sayac)+". deneme",a,b)
    if zar1 == a and zar2 == b:
        print("İstediğiniz 2 zar değeri de ",sayac,".denemede bulundu")
        break

Girdiğiniz 2 zar değerini kaçıncı adımda bulduğunu söyleyen uygulama.py


#!/usr/bin/env python3
import argparse
import logging
import os
import sys
import shutil
PROJECT_NAME = "ElectrsCash"
GIT_REPO = "https://github.com/BitcoinUnlimited/{}.git".format(PROJECT_NAME)
# When released put a tag here 'v2.0.0'
# When in development, put 'master' here.
GIT_BRANCH = "v3.0.0"
# When released put a hash here: "aa95d64d050c286356dadb78d19c2e687dec85cf"
# When in development, put 'None' here
EXPECT_HEAD = "9288d9f1bc828e06dca3b8783567c7557530740b"

ROOT_DIR = os.path.realpath(
        os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
ELECTRS_DIR = os.path.join(ROOT_DIR, PROJECT_NAME)
ELECTRS_BIN = "electrscash"

parser = argparse.ArgumentParser()
parser.add_argument('--allow-modified', help='Allow building modified/dirty repo',
        action = "store_true")
parser.add_argument('--verbose', help='Sets log level to DEBUG',
        action = "store_true")
parser.add_argument('--dst', help='Where to copy produced binary',
    default=os.path.join(ROOT_DIR, "src"))
parser.add_argument('--target', help='Target platform (e.g. x86_64-pc-linux-gnu)',
    default="x86_64-unknown-linux-gnu")
parser.add_argument('--debug', help="Do a debug build", action = "store_true")
parser.add_argument('--builddir', help="Out of source build directory", default=None)
args = parser.parse_args()

level = logging.DEBUG if args.verbose else logging.INFO

logging.basicConfig(format = '%(asctime)s.%(levelname)s: %(message)s',
        level=level,
        stream=sys.stdout)

def bail(*args):
    logging.error(*args)
    sys.exit(1)

def check_dependencies():
    v = sys.version_info
    if v[0] < 3 or (v[0] == 3 and v[1] < 3):
        bail("python >= 3.3 required");

    try:
        import git
    except Exception as e:
        logging.error("Failed to 'import git'")
        logging.error("Tip: Install with: python3 -m pip install gitpython")
        logging.error("Tip: On Debian/Ubuntu you can install python3-git")
        bail(str(e))

    import shutil
    if shutil.which("cargo") is None:
        logging.error("Cannot find 'cargo', will not be able to build {}".format(PROJECT_NAME))
        logging.error("You need to install rust (1.38+) https://rustup.rs/")
        logging.error("Tip: On Debian/Ubuntu you need to install cargo")
        bail("rust not found")

    if shutil.which("clang") is None:
        logging.error("Cannot find 'clang', will not be able to build {}".format(PROJECT_NAME))
        logging.error("Tip: On Debian/Ubuntu you need to install clang")
        bail("clang not found")

    if not os.path.isdir(args.dst):
        bail("--dst provided '%s' is not a directory", args.dst)

def clone_repo():
    import git
    logging.info("Cloning %s to %s", GIT_REPO, ELECTRS_DIR)
    repo = git.Repo.clone_from(GIT_REPO, ELECTRS_DIR, branch=GIT_BRANCH)

def verify_repo(allow_modified):
    import git
    repo = git.Repo(ELECTRS_DIR)
    if repo.is_dirty():
        logging.error("Validation failed - %s has local modifications. Use `--allow-modified` if you wanted to build from a dirty repository", ELECTRS_DIR)
        allow_modified or bail("Bailing")

    if EXPECT_HEAD == None:
        logging.warning("ElectrsCash is not fixed to a specific revision.  Please assign the EXPECT_HEAD variable in build_electrs.py before releasing.")
    if EXPECT_HEAD != None and repo.head.object.hexsha != EXPECT_HEAD:
        # TODO: Add command line option to reset HEAD to GIT_BRANCH at EXPECT_HEAD
        logging.error("Validation failed - %s HEAD differs from expected (%s vs %s)",
                PROJECT_NAME, repo.head.object.hexsha, EXPECT_HEAD)
        allow_modified or bail("Bailing")

def output_reader(pipe, queue):
    try:
        with pipe:
            for l in iter(pipe.readline, b''):
                queue.put(l)
    finally:
        queue.put(None)

def cargo_run(args):
    import subprocess
    from threading import Thread
    from queue import Queue

    cargo = shutil.which("cargo")
    args = [cargo] + args
    logging.info("Running %s", args)
    assert cargo is not None

    p = subprocess.Popen(args, cwd = ELECTRS_DIR,
        stdout = subprocess.PIPE, stderr = subprocess.PIPE)

    q = Queue()
    Thread(target = output_reader, args = [p.stdout, q]).start()
    Thread(target = output_reader, args = [p.stderr, q]).start()

    for line in iter(q.get, None):
        logging.info(line.decode('utf-8').rstrip())

    p.wait()
    rc = p.returncode
    assert rc is not None
    if rc != 0:
        bail("cargo failed with return code %s", rc)

def get_target(makefile_target):
    # Try to map target passed from makefile to the equalent in rust
    # To see supported targets, run: rustc --print target-list

    # Trim away darwin version number
    if makefile_target.startswith('x86_64-apple-darwin'):
        makefile_target = 'x86_64-apple-darwin'

    target_map = {
            'x86_64-pc-linux-gnu' : 'x86_64-unknown-linux-gnu',
            'i686-pc-linux-gnu' : 'i686-unknown-linux-gnu',
            'x86_64-apple-darwin': 'x86_64-apple-darwin'
    }

    if makefile_target in target_map:
        return target_map[makefile_target]

    if makefile_target in target_map.values():
        return makefile_target

    logging.warn("Target %s is not mapped, passing it rust and hoping it works"
            % makefile_target)
    return makefile_target

check_dependencies()

if not os.path.exists(ELECTRS_DIR):
    clone_repo()
verify_repo(args.allow_modified)

def build_flags(debug, target, builddir):
    flags = ["--target={}".format(get_target(target))]
    if builddir is not None:
        flags.append("--target-dir={}".format(os.path.abspath(builddir)))
    if debug:
        return flags
    return flags + ["--release"]

cargo_run(["build", "--verbose", "--locked"] + build_flags(args.debug, args.target, args.builddir))
cargo_run(["test", "--verbose", "--locked"] + build_flags(args.debug, args.target, args.builddir))

def build_type_dir(debug):
    if debug:
        return "debug"
    return "release"

def binary_dir(target, debug, builddir):
    """
    The directory where the electrscash binaries are built.
    """
    root = builddir if builddir is not None else os.path.join(ELECTRS_DIR, "target")
    return os.path.join(root, get_target(target), build_type_dir(debug))

src = os.path.join(binary_dir(args.target, args.debug, args.builddir), ELECTRS_BIN)
logging.info("Copying %s to %s", src, args.dst)
shutil.copy(src, args.dst)

logging.info("Done")


"""
You notice that the device repeats the same frequency change
list over and over.
To calibrate the device, you need to find the first frequency it reaches twice.
"""

FILENAMES = ['tests_part_2/test_a.txt', 'tests_part_2/test_b.txt',
             'tests_part_2/test_c.txt', 'tests_part_2/test_d.txt', 'input.txt']

def get_first_dupe_frequency(filename):
    frequency = 0
    found_frequencies = {frequency, }
    is_dupe_found = False
    with open(filename) as changes:
        while not is_dupe_found:
            for change in changes:
                frequency += int(change)
                if frequency in found_frequencies:
                    return frequency
                found_frequencies.add(frequency)
            changes.seek(0)

    return frequency

for filename in FILENAMES:
    print('Frequency for changes in {}:'.format(
        filename), get_first_dupe_frequency(filename))


sample_data = """noop
addx 3
addx -5"""

long_sample_data = """addx 15
addx -11
addx 6
addx -3
addx 5
addx -1
addx -8
addx 13
addx 4
noop
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx 5
addx -1
addx -35
addx 1
addx 24
addx -19
addx 1
addx 16
addx -11
noop
noop
addx 21
addx -15
noop
noop
addx -3
addx 9
addx 1
addx -3
addx 8
addx 1
addx 5
noop
noop
noop
noop
noop
addx -36
noop
addx 1
addx 7
noop
noop
noop
addx 2
addx 6
noop
noop
noop
noop
noop
addx 1
noop
noop
addx 7
addx 1
noop
addx -13
addx 13
addx 7
noop
addx 1
addx -33
noop
noop
noop
addx 2
noop
noop
noop
addx 8
noop
addx -1
addx 2
addx 1
noop
addx 17
addx -9
addx 1
addx 1
addx -3
addx 11
noop
noop
addx 1
noop
addx 1
noop
noop
addx -13
addx -19
addx 1
addx 3
addx 26
addx -30
addx 12
addx -1
addx 3
addx 1
noop
noop
noop
addx -9
addx 18
addx 1
addx 2
noop
noop
addx 9
noop
noop
noop
addx -1
addx 2
addx -37
addx 1
addx 3
noop
addx 15
addx -21
addx 22
addx -6
addx 1
noop
addx 2
addx 1
noop
addx -10
noop
noop
addx 20
addx 1
addx 2
addx 2
addx -6
addx -11
noop
noop
noop"""

import os
from pprint import pprint

def pixel_drawable(cycle: int, x: int) -> int:
    cycle_column = cycle % 40 - 1
    x_range = [x - 1, x, x + 1]
    if cycle_column in x_range:
        return cycle - 1
    return -1

def is_signal_event(cycle: int) -> bool:
    if cycle % 40 == 20:
        return True
    return False

def execute(instructions: list[str]) -> tuple[dict[int, int], list[str]]:
    x = 1
    cycle = 0
    screen = ["." for i in range(40 * 6)]
    signal_strength: dict[int, int] = dict()
    for instruction in instructions:
        if instruction == "noop":
            # start of cycle
            cycle += 1
            if is_signal_event(cycle):
                signal_strength[cycle] = cycle * x

            draw_pixel = pixel_drawable(cycle, x)
            if draw_pixel != -1:
                screen[draw_pixel] = "#"
            continue

        action, value = instruction.split()
        if action == "addx":
            # start of cycle
            cycle += 1
            if is_signal_event(cycle):
                signal_strength[cycle] = cycle * x

            draw_pixel = pixel_drawable(cycle, x)
            if draw_pixel != -1:
                screen[draw_pixel] = "#"

            # 2nd cycle
            cycle += 1
            if is_signal_event(cycle):
                signal_strength[cycle] = cycle * x

            draw_pixel = pixel_drawable(cycle, x)
            if draw_pixel != -1:
                screen[draw_pixel] = "#"

            x += int(value)

    return signal_strength, screen

def draw_screen(screen: list[str]) -> None:
    i = 0
    for y in range(6):
        row = []
        for x in range(40):
            row.append(screen[i])
            i += 1
        print("".join(row))

if __name__ == "__main__":
    basedir = os.path.dirname(__file__)
    with open(os.path.join(basedir, "data.txt"), "rt") as f:
        question_data = f.read().splitlines()

    test_ss, test_screen = execute(long_sample_data.strip().splitlines())
    question_ss, question_screen = execute(question_data)
    print("Test| sum of signal strengths:", sum(test_ss.values()))
    draw_screen(test_screen)
    print("Question| sum of signal strengths:", sum(question_ss.values()))
    draw_screen(question_screen)


import argparse
import re
import urllib

import bs4

def get_last_version():
    qt_release_repo = "https://download.qt.io/official_releases/qt/"

    with urllib.request.urlopen(qt_release_repo) as p:
        page = bs4.BeautifulSoup(p.read(), 'html5lib')

    major_version_dir = page.find('table').find_all('tr')[3].find('a').get('href')
    major_version_dir_url = urllib.parse.urljoin(qt_release_repo, major_version_dir)

    with urllib.request.urlopen(major_version_dir_url) as p:
        page = bs4.BeautifulSoup(p.read(), 'html5lib')

    latest_version = page.find('table').find_all('tr')[3].find('a').text[:-1]

    return latest_version

def get_docs_urls(qt_version):
    qt_version_flat = qt_version.replace('.', '')
    qt_version_major = qt_version_flat[0]
    qt_docs_repo_root = f"https://download.qt.io/online/qtsdkrepository/windows_x86/desktop/qt{qt_version_major}_{qt_version_flat}_src_doc_examples"
    qt_docs_repo_xml = f"{qt_docs_repo_root}/Updates.xml"

    try:
        with urllib.request.urlopen(qt_docs_repo_xml) as p:
            page = bs4.BeautifulSoup(p.read(), 'xml')
    except urllib.error.HTTPError as e:
        if e.code == 404:
            raise ValueError(f"Documentation repository XML for Qt v.{qt_version} not found!") from e

    packages = [p.parent for p in page.find_all("Name", text=re.compile("^qt\..*?\.doc(\..*)?$"))]

    docs_urls = []
    for package in packages:
        package_name = package.find("Name").text
        package_version = package.find("Version").text
        package_archives = [p.strip() for p in package.find("DownloadableArchives").text.split(",") if p.strip()]

        for archive_name in package_archives:
            docs_urls.append(f"{qt_docs_repo_root}/{package_name}/{package_version}{archive_name}")

    if not docs_urls:
        raise RuntimeError(f"No documentation archives for Qt v.{qt_version} found!")

    return docs_urls

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--latest-version', action='store_true', help="get latest Qt version number")
    group.add_argument('--docs-latest', action='store_true', help="get list of URLs for latest version of Qt documentation archives")
    group.add_argument('--docs', metavar='VERSION', help="get list of URLs for selected version of Qt documentation archives")
    args = vars(parser.parse_args())

    if args['latest_version']:
        print(get_last_version())
    if args['docs_latest']:
        version = get_last_version()
        docs_urls = get_docs_urls(version)

        for url in docs_urls:
            print(url)
    if args['docs']:
        docs_urls = get_docs_urls(args['docs'])

        for url in docs_urls:
            print(url)


#!/usr/bin/python3
# This is very experimental so use at your own risk
# make a backup of whitelist.json as it MAY ACIDENTALLY ERASE FILES
# more testing is needed.

import json
from requests_cache import CachedSession
import sys
import argparse
import time

parser = argparse.ArgumentParser()
#parser.add_argument('-u','--username')
parser.add_argument('command',choices=['add','delete'])
parser.add_argument('username')
parser.add_argument('-f','--file',default='whitelist.json')
args = parser.parse_args()
username = args.username

# cached session to prevent spamming requests.
session = CachedSession('/tmp/minecraft_whitelist_edit', backend='filesystem')
response = session.request("GET","https://api.mojang.com/users/profiles/minecraft/"+username)

if response.status_code != 200:
	if response.status_code == 204:
		sys.exit("User does not exist")
	sys.exit("Mojang API responded with code other than 200 or 204: {}".format(response.status_code))

# formats the data into the way it looks like in the file normally
user_data = json.loads(response.text)
user_id = user_data.pop("id")

user_id = user_id[:8] + '-' + user_id[8:]
user_id = user_id[:13] + '-' + user_id[13:]
user_id = user_id[:18] + '-' + user_id[18:]
user_id = user_id[:23] + '-' + user_id[23:]

user_data["uuid"] = user_id

try:
	whitelist_file = open(args.file)
except OSError:
	sys.exit("Could not open whitelist file")

try:
	whitelist_data = json.load(whitelist_file)
except json.JSONDecodeError:
	sys.exit("Malformed JSON file.")

whitelist_file.close()

if args.command == 'add':
	for item in whitelist_data:
		if item["uuid"].replace("-","") == user_id.replace("-",""):
			sys.exit("User already whitelisted")
	whitelist_data.append(user_data)
elif args.command == 'delete':
	user_removed = False
	for item in whitelist_data:
		if item["uuid"].replace("-","") == user_id.replace("-",""):
			whitelist_data.remove(item)
			user_removed = True
			break
	if not user_removed:
		sys.exit("No User removed.")

output_file = open(args.file,"w")
json.dump(whitelist_data,output_file,indent="  ")


numbers = 'c:\\Users\\Dima\\Desktop\\numbers.txt'
counter = 0
# из блокнота сразу в числовой массив
with open(numbers) as f:
    list = [int(item) for item in f]
# подсчет
for i in range(len(list)-1):
    if list[i+1] > list[i]:
        counter += 1
print(list)
print(counter)

строки в список.py

строки в список.py


from collections import deque
def solution(s):
    s = deque(list(s))
    result = 0

    while s:
        x = s.popleft()
        x_cnt = 1
        remain_cnt = 0
        while s:
            remain = s.popleft()
            if x == remain:
                x_cnt += 1
            else:
                remain_cnt += 1
            if remain_cnt == x_cnt:
                break
        if x_cnt > 0 or remain_cnt > 0:
            result += 1
    return result

def main():
    print(solution("abracadabra"))

if __name__ == "__main__":
    main()


import math
import pandas as pd
import os
import ast
import pickle

class Recommender():
    def __init__(self, public_transport="kendaraan umum", museums_bin="museums_binary.csv", similarities="similarities.json"):
        dir_path = os.getcwd()
        self.museums_bin = pd.read_csv(dir_path + "/datasets/" + museums_bin)
        self.public_transport = public_transport
        with open(dir_path + '/datasets/' + similarities, 'rb') as fp:
            self.similarities = pickle.load(fp)

    def _convert_length(self, point1, point2):
        if len(point1) > len(point2):
            point2 = point2[:len(point1)] + [0]*(len(point1) - len(point2))
        else:
            point1 = point1[:len(point2)] + [0]*(len(point2) - len(point1))

        return point1, point2

    def _cosine(self, col, point1, point2):
        point1 = list(map(float, point1))
        point2 = list(map(float, point2))

        if col == "ticket_price_1":
            point1, point2 = self._convert_length(point1, point2)

        w = 0
        x = 0
        y = 0
        z = 0
        for i in range(len(point1)):
            x += (point1[i] * point2[i])
            y += math.pow(point1[i], 2)
            z += math.pow(point2[i], 2)
        w = (math.sqrt(y) * math.sqrt(z))
        return 1 - (x / w) if w != 0 else 0

    def _cosine_distance(self, museum_id_1, museum_id_2):
        """
        Search similarity with cosine distance
        """
        a = self.museums_bin.iloc[museum_id_1]
        b = self.museums_bin.iloc[museum_id_2]
        distance = 0
        for val in self.similarities[museum_id_1]:
            if val["id"] == museum_id_2:
                distance = 1 - val["sim"]
                break

        for col, val in a.iteritems():
            if col != "name":
                distance += self._cosine(col,
                    ast.literal_eval(a[col]), ast.literal_eval(b[col]))

        return distance

    def knn(self, base, exist, K):
            distances = []

            for idx, museum in self.museums_bin.iterrows():
                existed = False
                for e in exist:
                    if museum["name"] == e["name"]:
                        existed = True
                        break

                if idx != base.index[0] and not existed:
                    dist = self._cosine_distance(base.index[0], idx)
                    distances.append((idx, dist))

            distances.sort(key=lambda x: x[1])
            neighbors = distances[:K]

            return neighbors

    def recommend(self, entities):
        if self.public_transport == "kendaraan pribadi":
            self.museums_bin.drop(columns=["public_transportation_bin"], axis=1, inplace=True)

        pred_museum = self.museums_bin.loc[self.museums_bin['name'] == entities[0]["name"]]

        K = 15
        neighbors = self.knn(pred_museum, entities[1:], K)
        i = len(entities) + 1

        for neighbor in neighbors:
            museum = self.museums_bin.iloc[neighbor[0]]["name"]
            museum = {
                "id": i,
                "name": museum
            }
            entities.append(museum)
            i += 1

        return entities[:K]


import json
import os

class Paths:
    paths = dict()

    @classmethod
    def initialize(cls, filename):
        """
        Initialize the class data with the file

        Args:
            filename (str): path to the file data
        """

        cls.paths.clear()
        with open(filename, encoding="utf-8") as f:
            cls.paths.update(json.load(f))

    @classmethod
    def folder(cls, key):
        """
        Return the absolute path of the folder specified by its ``key``.
        The ``key`` should be in the path.json file.

        Args:
            key (str): key associated to a folder

        Returns:
            str: absolute path of a folder
        """

        p = cls.paths["folders"][key]
        return os.path.abspath(os.path.join(*p))

    @classmethod
    def file(cls, key):
        """
        Return the absolute path of the file specified by its ``key``.
        The ``key`` should be in the path.json file.

        Args:
            key (str): key associated to a file

        Returns:
            str: path to the file
        """

        folder, *p = cls.paths["files"][key]
        folder = cls.folder(folder)
        return os.path.abspath(os.path.join(folder, *p))

    @classmethod
    def image(cls, key):
        """
        Return the absolute path of the image specified by its ``key``.
        The ``key`` shoulf be in the path.json file.

        Args:
            key (str): key associated to the image

        Returns:
            str: path to the image
        """

        p = cls.paths["images"][key]
        folder = cls.folder("r_images")
        return os.path.abspath(os.path.join(folder, p))


"""commit message

Revision ID: ddb7d60bfa9d
Revises:
Create Date: 2020-03-10 15:50:20.897148

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'ddb7d60bfa9d'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('user',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('role', sa.String(length=10), nullable=True),
    sa.Column('username', sa.String(length=64), nullable=True),
    sa.Column('email', sa.String(length=120), nullable=True),
    sa.Column('password_hash', sa.String(length=128), nullable=True),
    sa.Column('about_me', sa.String(length=140), nullable=True),
    sa.Column('last_seen', sa.DateTime(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)
    op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=True)
    op.create_table('tournament',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('n_entrants', sa.Integer(), nullable=True),
    sa.Column('name', sa.String(length=64), nullable=True),
    sa.Column('organizer_id', sa.Integer(), nullable=True),
    sa.Column('finished', sa.Boolean(), nullable=True),
    sa.ForeignKeyConstraint(['organizer_id'], ['user.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('bracket',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('bracket_type', sa.String(length=20), nullable=True),
    sa.Column('tournament_id', sa.Integer(), nullable=False),
    sa.ForeignKeyConstraint(['tournament_id'], ['tournament.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('lobby',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('tournament_name', sa.String(length=64), nullable=True),
    sa.Column('tournament_id', sa.Integer(), nullable=True),
    sa.Column('to_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['to_id'], ['user.id'], ),
    sa.ForeignKeyConstraint(['tournament_id'], ['tournament.id'], ),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('tournament_name', 'to_id', name='_tournament_org_name_uc')
    )
    op.create_table('bracket_entrants',
    sa.Column('user_id', sa.Integer(), nullable=False),
    sa.Column('bracket_id', sa.Integer(), nullable=False),
    sa.ForeignKeyConstraint(['bracket_id'], ['bracket.id'], ),
    sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
    sa.PrimaryKeyConstraint('user_id', 'bracket_id')
    )
    op.create_table('lobby_seeds',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('user_id', sa.Integer(), nullable=True),
    sa.Column('lobby_id', sa.Integer(), nullable=True),
    sa.Column('seed', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['lobby_id'], ['lobby.id'], ),
    sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('user_id')
    )
    op.create_table('round',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('number', sa.Integer(), nullable=True),
    sa.Column('winners', sa.Boolean(), nullable=True),
    sa.Column('bracket_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['bracket_id'], ['bracket.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('match',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('uuid', sa.Text(length=36), nullable=True),
    sa.Column('user_1', sa.Integer(), nullable=True),
    sa.Column('user_1_score', sa.Integer(), nullable=True),
    sa.Column('user_2', sa.Integer(), nullable=True),
    sa.Column('user_2_score', sa.Integer(), nullable=True),
    sa.Column('winner', sa.Integer(), nullable=True),
    sa.Column('round_id', sa.Integer(), nullable=False),
    sa.Column('winner_advance_to', sa.Integer(), nullable=True),
    sa.Column('loser_advance_to', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['loser_advance_to'], ['match.id'], ),
    sa.ForeignKeyConstraint(['round_id'], ['round.id'], ),
    sa.ForeignKeyConstraint(['user_1'], ['user.id'], ),
    sa.ForeignKeyConstraint(['user_2'], ['user.id'], ),
    sa.ForeignKeyConstraint(['winner'], ['user.id'], ),
    sa.ForeignKeyConstraint(['winner_advance_to'], ['match.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_index(op.f('ix_match_uuid'), 'match', ['uuid'], unique=False)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f('ix_match_uuid'), table_name='match')
    op.drop_table('match')
    op.drop_table('round')
    op.drop_table('lobby_seeds')
    op.drop_table('bracket_entrants')
    op.drop_table('lobby')
    op.drop_table('bracket')
    op.drop_table('tournament')
    op.drop_index(op.f('ix_user_username'), table_name='user')
    op.drop_index(op.f('ix_user_email'), table_name='user')
    op.drop_table('user')
    # ### end Alembic commands ###


"""Utilites functions for the log files."""

import os
import logging
import logging.config

from pathlib import Path

from ..util import read_json

def setup_logging(save_dir, name='logger', verbosity=2,
                  log_config='./logger/logger_config.json',
                  default_level=logging.INFO):
    """Setup logging configuration and get logger
    """
    log_config = Path(log_config)
    if log_config.is_file():
        config = read_json(log_config)
        # modify logging paths based on run config
        for _, handler in config['handlers'].items():
            if 'filename' in handler:
                handler['filename'] = os.path.join(save_dir,
                                                   handler['filename'])

        logging.config.dictConfig(config)
    else:
        print("Warning: logging configuration file is not found in {}.".format(
            log_config))
        logging.basicConfig(level=default_level)

    log_levels = {
        0: logging.WARNING,
        1: logging.INFO,
        2: logging.DEBUG
    }

    if not (verbosity in log_levels.keys()):
        level = default_level
    else:
        level = log_levels[verbosity]

    logger = logging.getLogger(name)
    logger.setLevel(level)
    return logger


import os
import re
import time
import json
import roman
import urllib.request
import pymongo
from pymongo import MongoClient
from bs4 import BeautifulSoup

with open('config.json') as f:
    config = json.load(f)

url = config['url'] #'http://shakespeare.mit.edu/1henryiv/full.html'
cache = 'text.html'
maxage = 100000000 # just in case shakespeare changes anything

if not os.path.isfile(cache) or os.path.getmtime(cache) - time.time() > maxage:
    print('making request...')
    with urllib.request.urlopen(url) as req:
        page = req.read().decode()
        with open(cache, 'w') as f:
            f.write(page)
else:
    print('using cached...')
    with open(cache, 'r') as f:
        page = f.read()

soup = BeautifulSoup(page, 'html.parser')

r = re.compile('(?P<type>SCENE|ACT)\s(?P<num>[IVX]+)\.?\s?(?P<desc>[\s\S]+)?')

last = soup.find('h3')
act, scene = None, None

speakers = set({})
lineblocks = []

last = last.find_next('h3')
print('looking for lines...')
while last:
    # find act / scene headers
    m = r.match(last.text)
    num = m.group('num')
    n = roman.fromRoman(num)

    if m.group('type') == 'ACT':
        act = n # act number

    elif m.group('type') == 'SCENE':
        # create new scene
        scene = n               # scene number
        desc = m.group('desc')  # description

        # for finding by NAME=1.2.3
        text = '.'.join(['(?P<act>{})'.format(act), '(?P<scene>{})'.format(scene)]) + '\.(?P<line>\d+)'
        numre = re.compile(text)
        # for finding by NAME=speech1
        spere = re.compile('speech\d+')

        # find next speaker
        speaker_elem = last.find_next_sibling('p').find('a', {'name':spere})
        while speaker_elem:
            speaker = speaker_elem.b.text.upper() # speaker name

            if speaker == 'Scene III': # wierd bug in html
                scene = 3
                text = '.'.join(['(?P<act>{})'.format(act), '(?P<scene>{})'.format(scene)]) + '\.(?P<line>\d+)'
                numre = re.compile(text)

            else:
                speakers.add(speaker)

                block = speaker_elem.find_next_sibling('blockquote')
                if block:
                    lines_raw = block.find_all('a', {'name':numre})
                    lines = [{'_id':line['name'], 'text':line.text.strip()} for line in lines_raw]
                    if len(lines) > 0:
                        lineblocks.append({'speaker': speaker, 'lines' : lines, 'scene': scene, 'act': act, 'start':lines[0]['_id']})

            speaker_elem = speaker_elem.find_next_sibling('a', {'name':spere})

    last = last.find_next('h3')

client = MongoClient(config['dburl'])#'mongodb://samzagrobelny.com:27017/shakespeare')
db = client.shakespeare

speakertoid = {};

speakerscol = db.speakers
linescol = db.lines
linescol.create_index([("start", pymongo.ASCENDING)])

for speaker in speakers:
    doc = {'name': speaker}
    speakerscol.update_one(doc, {'$set':doc}, upsert=True)

for i, lineblock in enumerate(lineblocks):
    print('{} / {}'.format(i, len(lineblocks)))
    linescol.update_one({'start' : lineblock['start']}, {'$set' : lineblock}, upsert=True)


import sys
sys.path.append("../videoanalytics/src")
import videoanalytics
import cv2
import numpy as np

from datetime import datetime

def add_point_to_roi(event,x,y,flags,param):
    global g_mouse_x, g_mouse_y
    g_mouse_x,g_mouse_y = x,y

if __name__ == "__main__":
    global g_mouse_x, g_mouse_y
    g_mouse_x = 0
    g_mouse_y = 0

    roi_points = []

    INPUT_VIDEO = "../data/media/fishcount/input_videos/003.mp4"

    cap = cv2.VideoCapture(INPUT_VIDEO)

    if (cap.isOpened()== False):
        print("Error opening video stream or file")
    print("Q to quit")

    cv2.namedWindow('Frame',cv2.WINDOW_NORMAL)
    cv2.setMouseCallback('Frame',add_point_to_roi)

    while(cap.isOpened()):
        ret, frame = cap.read()
        if ret == True:

            for roi in roi_points:
                cv2.circle(frame,(roi[0],roi[1]),5,(255,0,0),-1)

            cv2.imshow('Frame',frame)
            pressed_key = cv2.waitKey(25) & 0xFF
            if pressed_key == ord('q'):
                break
            elif pressed_key == ord('a'):
                print(g_mouse_x,g_mouse_y)
                roi_points.append((g_mouse_x,g_mouse_y))
        else:
            break

    cap.release()
    cv2.destroyAllWindows()


import json
import rate as rate_m
import common

json_suffix = {'novelty': '', 'feasibility': '', 'value': ', where x is an integer representing the value in JPY'}

prompts = [{'role': 'user', 'content': (
        'We aim to evaluate the creativity of ideas in an Alternative Uses Tests (AUT) based on specific criteria. '
        'Please rate our idea, given below, in terms of its {Measure}, which is defined as follows:'
        '\n'
        '{definition}'
        '\n\n'
        'Proceed as follows in your evaluation. '
        'First, briefly describe the idea in your own words. '
        'Then, in a single short paragraph, {elaboration}. '
        'Finally, provide your numeric rating as a json object of the form {{"{measure}":x}}{json_suffix}.'
        '\n\n'
        'Our idea is to use the item "{Question}" as "{Answer}".'
    )},
    {
    'role': 'system',
    'content': common.system
    }
]

async def rate(data):
    requests = get_requests(data)
    await rate_m.entrypoint(requests, n=1, model='gpt-4', temperature=0)

def get_requests(data):
    requests = []
    for index, row in data.iterrows():
        for measure, definition in common.definitions.items():
            prompt = []
            for p in prompts:
                prompt.append({'role': p['role'], 'content': p['content'].format(
                    **row, measure=measure, Measure=measure.capitalize(), definition=definition,
                    elaboration=common.elaborations[measure], json_suffix=json_suffix[measure])})
            requests.append({'messages': prompt, 'index': index, 'process': process, 'data': data, 'measure': measure})
    return requests

def process(request, completion, **kwargs):
    response = completion.choices[0].message.content
    try:
        parsed = parse(response, request["measure"])
    except RuntimeError as e:
        print(f'Failed parse (row {request["index"]}). Prompt:\n\'\'\'{request["messages"][0]["content"]}\'\'\'\nResponse:\n\'\'\'{response}\'\'\'\nError: {e}')
        if kwargs['temperature'] < 0.5:
            return {**kwargs, 'temperature': kwargs['temperature']+.1}
        else:
            print(f'Giving up.')
            parsed = {f'{request["measure"]}_raw': response}

    request['data'].loc[request['index'], parsed.keys()] = parsed

def parse(response, measure):
    result = {f'{measure}_raw': response}

    lines = [l.strip() for l in response.splitlines() if l.strip()]
    if len(lines) == 4:
        # Assume, based on examples, that l0 is translation, l1-2 explanation, l3 rating.
        lines = [lines[0], '\n'.join(lines[1:3]), lines[3]]
    if len(lines) != 3:
        raise RuntimeError('Unexpected number of lines')

    keys = (f'{measure}_idea', measure)
    for key, line in zip(keys, lines):
        result[f'{key}_explanation'] = line

    try:
        ratings = json.loads(lines[-1])
        result.update(ratings)
    except json.JSONDecodeError:
        raise RuntimeError('Final line not valid JSON')

    return result


"""
the different networks need different preprocessing.
if necessary, a preprocessing function should be accompanied with a corresponding postprocessing.
If the output of the preprocessing can't be drawn with pyplot, there should be a postprocessing function.
"""
import numpy as np

def preprocess_vgg16(img):
    # vgg16 expects image in BGR format
    # and a shift is applied
    img = img.astype(np.float32)
    offset = [103.939, 116.779,123.68]
    img -= offset
    return img

def postprocess_vgg16(img):
    img = img.copy()

    # undo the color shift
    offset = [103.939, 116.779,123.68]
    img += offset

    # convert to rgb
    img = img[:,:,:,::-1]

    # matplotlib expects colors in [0,1]
    img /= 255

    return img

def preprocess_yolo(img):
    # yolo expects images in RGB
    # and color values in [0,1]
    img = img.astype(np.float32)
    img = img[:,:,::-1]
    img /= 255
    return img


from flask import Flask, jsonify, render_template, request
from database import load_jobs_from_db, load_job_from_db, add_application_to_db
import re

app = Flask(__name__)

@app.route("/")
def home_route():
    jobs_list = load_jobs_from_db()
    return render_template(
        'home.html',
        jobs=jobs_list,
        company_name='My company name',
        title='Home'
        )

@app.route("/home", methods=['GET', 'POST'])
def home():
    return home_route()

@app.route('/jobs')
def list_jobs():
    return jsonify(
        load_jobs_from_db()
        )

@app.route('/job/<id>')
def show_job(id: int):
    job = load_job_from_db(id)
    if not job:
        return 'Not Found', 404
    return render_template(
        'job_page.html',
        job=job,
        title=job['title'],
        company_name='My company name'
        )

@app.route('/api/job/<id>')
def show_job_json(id: int):
    job = load_job_from_db(id)
    return jsonify(job)

@app.route('/job/<id>/apply', methods=['POST'])
def apply_job(id: int):
    job = load_job_from_db(id)
    data = request.form
    add_application_to_db(id, data)
    return render_template(
        'application_submited.html',
        company_name='My company name',
        application = data,
        title= 'Submited',
        role=job
        )

if __name__ == '__main__':
    app.run(host = '0.0.0.0', debug = True)