"""
The base for this "glitch" is a fork of (@aparrish) Allison Parrish's amazing example using Flat + Bezmerizing to draw SVG.
I'm using a bizarre set of functions in flat_processing.py to make flat look like Processing Python mode I'm more used to.

Many thanks to Marco Aurelio "Macarena"
"""

import random
from flask import Flask, send_file, request
from flat_processing import *

sf = 1
sf_value = 10
sf_min = 1
sf_max = 20
colunas = 8
seed_value = 1

gliphs = [lambda x, y, s: rect(x, y, s, s),
          lambda x, y, s: ellipse(x, y, s, s),
          lambda x, y, s: triangle(x - s, y, x - s, y + s, x, y + s),
          lambda x, y, s: triangle(x + s, y, x + s, y - s, x, y - s),
          ]

def ensamble(ex, ey, eo):
    noStroke()
    for i in range(eo):
        if i % 2:
            fill(150, 0, 150, 150)
        else:
            fill(0, 50, 150, 150)
        order, spacing, side = random.randint(3, 6), 14, 7
        x = (1 + random.randint(-5, 4)) * side * sf
        y = (1 + random.randint(-5, 4)) * side * sf
        grid(ex+x,
             ey+y,
             order,
             spacing * sf,
             random.choice(gliphs),
             side * sf)

def grid(x, y, order, spacing, function, *args):
    if type(order) is tuple:
        cols, rows = order
    else:
        cols = rows = order
    xo, yo = (x - cols * spacing / 2 , y - rows * spacing / 2)
    for i in range(cols):
        gx = spacing / 2 + i * spacing
        for j in range(rows):
            gy = spacing/2 + j * spacing
            function(xo + gx, yo + gy, *args)

app = Flask(__name__)

@app.route('/draw.svg', methods=['GET'])
def draw():
    global colunas, sf_value, sf, seed_value
    query = request.url[len(request.base_url):]
    colunas_value = request.args.get('colunas') or colunas
    sf_value = request.args.get('sf') or sf_value
    sf = int(sf_value) / 10
    seed = request.args.get('seed') or seed_value
    seed_value = int(seed)

    size(1400 * sf, 700 * sf)
    background(240, 240, 200)

    print(f"seed: {seed_value}")
    random.seed(seed_value)
    grid(width / 2, height / 2, (colunas, 4), 150 * sf, ensamble, 5)

    page.svg('temp.svg')
    return send_file("temp.svg", mimetype='image/svg+xml')

@app.route('/', methods=['GET'])
def index():
  global sf_value, colunas, sf, seed_value
  query = request.url[len(request.base_url):]
  colunas_value = request.args.get('colunas') or colunas
  colunas = int(colunas_value)
  sf_value = request.args.get('sf') or sf_value
  sf = int(sf_value) / 10
  seed = request.args.get('seed') or seed_value
  seed_value = int(seed)

  return f"""
  <link href="https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@200&display=swap" rel="stylesheet">

  <form action="" method="GET">

   cols
  <input id="colunas" name="colunas" value="{colunas_value}" />
  seed
  <input id="seed" name="seed" value="{seed_value}" />
   scale ({sf_value})
  <input id="sf" type="range" name="sf" min="{sf_min}" max="{sf_max}" value="{sf_value}" />
  <input type="submit" value="redraw">

  </form>

"""

if __name__ == '__main__':
    app.run()


import pywinusb.hid as hid

import time

from cm import Led

def make_rgb(r, g, b):
    return [r, g, b]

def create_static(r, g, b, num):
    ret = []

    for _ in range(num):
        ret += make_rgb(r, g, b)

    return ret

def main():
    led = Led()
    led.set_led_count(14)
    led.set_mode(7)

    try:
        while True:
            for i in range(14):
                colors = [0]*14*3
                colors[i*3] = 255

                led.set_colors(colors)
                time.sleep(0.05)
            for i in reversed(range(1,13)):
                colors = [0]*14*3
                colors[i*3] = 255

                led.set_colors(colors)
                time.sleep(0.05)

    except KeyboardInterrupt:
        pass

    #led.close()

if __name__ == '__main__':
    main()


from flask import Flask, request, render_template, json
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import joblib
import boto
from boto.s3.key import Key
from boto.s3.connection import S3Connection
import os.path

# Constant variables
MODEL_FILE_NAME = 'finalized_model.p'
MODEL_LOCAL_PATH = MODEL_FILE_NAME

# create a flask object
sp = None
model = None
app = Flask(__name__)

# initiate spotify credentials
def initiate_spotify_credentials():
    global sp

    cid =""
    secret = ""
    client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)
    sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
    sp.trace=False

# load model
def load_model():
    global model

    # download model from aws bucket if it doesn't exist in local path
    if not os.path.isfile(MODEL_LOCAL_PATH):

        REGION_HOST = 's3.us-east-2.amazonaws.com'
        BUCKET_NAME = 'music-genre-recommender-model'

        conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY, host=REGION_HOST)
        bucket = conn.get_bucket(BUCKET_NAME)

        key_obj = Key(bucket)
        key_obj.key = MODEL_FILE_NAME

        key_obj.get_contents_to_filename(MODEL_LOCAL_PATH)

    model = joblib.load(MODEL_LOCAL_PATH)

# select genre
def select_genre(track_data):

    input_df = [track_data]

    # make a prediction
    prediction = model.predict(input_df)[0]

    #predition message
    message_array = ["Your song is Electronic",
                     "Your song is Hip-Hop",
                     "Your song is Rock"]

    return message_array[prediction]

# creates an association between the / page and the entry_page function (defaults to GET)
@app.route('/')
def entry_page():
    return render_template('index.html')

# creates an association between the /predict_recipe page and the render_message function
# (includes POST requests which allow users to enter in data via form)
@app.route('/predict_genre_song/', methods=['GET', 'POST'])
def render_message_song():

    artist = request.form['artist']
    song = request.form['song']

    song_parsed = song.replace("'", "")
    q = 'artist:' + artist + ' track:' + song_parsed
    q = q.encode(encoding='UTF-8',errors='strict')
    track_search = sp.search(q=q, type="track", limit=1)
    track_items = track_search['tracks']['items']
    if len(track_items) > 0:
        audio_features = sp.audio_features(track_items[0]['id'])
        music_data_categories = ['danceability', 'energy', 'speechiness', 'acousticness',
                   'instrumentalness', 'liveness', 'valence', 'tempo']
        key_audio_features = { key: audio_features[0][key] for key in music_data_categories }
        final_message = select_genre(list(key_audio_features.values()))
    else:
        final_message = 'Cannot find track listing for ' + artist + '-' + song

    return render_template('index.html', message=final_message)

if __name__ == '__main__':
    initiate_spotify_credentials()
    load_model()
    app.run(host='0.0.0.0', port=80)


import pandas as pd

# read csv and save it as pandas dataframe
interest_rate_data = pd.read_excel('fred_data.xlsx')

interest_rate_data["FEDFUNDS_DIFF"] = interest_rate_data["FEDFUNDS"].diff(1)
interest_rate_data = interest_rate_data.fillna(0)

# print data shape
print("data shape: ", interest_rate_data.shape)

# print column names
print(interest_rate_data.columns)

col = interest_rate_data.columns.to_list()
col.remove('year')
col.remove('month')
col.remove('FEDFUNDS')
col.remove("FEDFUNDS_DIFF")

from itertools import combinations
import math

# print(math.comb(24,3))
# print(list(combinations(col,3)))
# print(len(list(combinations(col,3))))
# print(list(combinations(col,3))[0])
# print(list(combinations(col,3))[0][0])

# machine learning
import sklearn
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LinearRegression, Ridge, Lasso
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
import tqdm

def linModel(X_list):
  # You need to choose variables
  # X_list = [*list(combinations(col,3))[i]]
  # print(X_list)

  # Split-out train and test dataset
  # start from Jan 1990
  # train samples: years 1990 to 2010, test samples: years 2011 to 2023
  interest_rate_data_test = interest_rate_data.loc[(interest_rate_data['year'] >= 2011)].copy()
  interest_rate_data_train = interest_rate_data.loc[(interest_rate_data['year'] >= 1990) & (interest_rate_data['year'] <= 2010)].copy()

  X_train = (interest_rate_data_train[X_list]).values
  y_train = (interest_rate_data_train['FEDFUNDS']).values
  X_test = (interest_rate_data_test[X_list]).values
  y_test = (interest_rate_data_test['FEDFUNDS']).values

  # Make predictions on validation dataset
  model = LinearRegression()
  #model = Ridge(alpha=1)
  #model = Lasso(alpha=0.05)

  # Standardization: necessary for Lasso or Ridge regression, does not affect linear regression
  sc = StandardScaler()
  X_train = sc.fit_transform(X_train)
  X_test = sc.transform(X_test)

  # fit and predict
  model.fit(X_train, y_train)
  y_pred = model.predict(X_test)

  # Evaluate predictions
  # The coefficients
  # print('Coefficients:')
  # for i in range(len(X_list)):
    # print(X_list[i],": %.3f" % model.coef_[i])

  # print()

  # The mean squared error, correlation, r-square
  # print('ML - Mean squared error: %.2f' % mean_squared_error(y_test, y_pred))
  # print('ML - Correlation: %.2f' % np.corrcoef(y_test, y_pred)[0,1])
  # print('ML - R square: %.2f' % r2_score(y_test, y_pred))
  # print()

  # equilibrium real fed funds rate (assumed to be 2.5%)
  # desired (target) inflation rate (assumed to be 2%)
  #taylor = inflation+2.5+0.5*(inflation-2)+0.5*output_gap
  interest_rate_data['Taylor'] = interest_rate_data['INFLATION']+2.5+0.5*(interest_rate_data['INFLATION']-2)+0.5*interest_rate_data['OUTPUT_GAP']
  y_taylor_pred = interest_rate_data['Taylor'].loc[(interest_rate_data['year'] >= 2011)].values

  # The mean squared error, correlation, r-square
  # print('Taylor - Mean squared error: %.2f' % mean_squared_error(y_test, y_taylor_pred))
  # print('Taylor - Correlation: %.2f' % np.corrcoef(y_test, y_taylor_pred)[0,1])
  # print('Taylor - R square: %.2f' % r2_score(y_test, y_taylor_pred))

  result = [X_list,
            mean_squared_error(y_test, y_pred),np.corrcoef(y_test, y_pred)[0,1],
            r2_score(y_test, y_pred), mean_squared_error(y_test, y_taylor_pred),
            np.corrcoef(y_test, y_taylor_pred)[0,1],r2_score(y_test, y_taylor_pred)]

  return result

combinations_num = list(combinations(col, 2))

result_dict = {
    "index": [],
    "ML-MSE": [],
    "ML-Corr": [],
    "ML-R2": [],
}
for list_of_x in tqdm.tqdm(combinations_num):
    index, ml_mse, ml_corr, ml_r2, t_mse, t_corr, t_r2 = linModel(list(list_of_x))
    result_dict["index"].append(index)
    result_dict["ML-MSE"].append(ml_mse)
    result_dict["ML-Corr"].append(ml_corr)
    result_dict["ML-R2"].append(ml_r2)

result_df = pd.DataFrame(result_dict)
result_df.to_csv("./result_x_2.csv")


# -*- coding: utf-8 -*-
"""Скрипт предназначен для вычитания шумов из спектров.

Для определения шума берутся файлы с высоким запирающим напряжением.
На вход должны подаваться обработанные точки.

Input:
fill_dir - path to folder with processed Lan10-12PCI fill data
points_high - high voltage points wildcard
points_high_2 - high voltage points 2 wildcard
points_path - list of low HV points wildcard

Output:
Averaged energy spectrums with and w/o corrected tails for list of intresred
points.
"""
# pylint: disable-msg=R0914

from glob import glob
from os import path

import dfparser
import matplotlib.pyplot as plt
import numpy as np
import seaborn

def get_amps(filepath: str) -> np.ndarray:
    """Extract amplitudes from processed file."""
    _, _, data = dfparser.parse_from_file(filepath)
    p_high = dfparser.Point()
    p_high.ParseFromString(data)

    amps = np.hstack([list(block.events.amplitudes)
                      for block in p_high.channels[0].blocks])
    return amps

def _main():
    fill_dir = "/home/chernov/data_processed/2017_05/Fill_3/"
    points_high = "*/p1(30s)(HV1=18600).df"
    points_high_2 = "*/p2(30s)(HV1=18550).df"
    points_high_filepaths = glob(path.join(fill_dir, points_high)) + \
        glob(path.join(fill_dir, points_high_2))

    points_path = ["*/p0(30s)(HV1=16000).df",
                   "*/p36(30s)(HV1=17000).df",
                   "*/p80(30s)(HV1=15000).df",
                   "*/p102(30s)(HV1=14000).df"]

    hist_bins_num = 50
    hist_range = (700, 1500)

    amps_all = np.hstack([get_amps(fp) for fp in points_high_filepaths])
    hist_n, bins_n = np.histogram(amps_all, hist_bins_num, range=hist_range)
    hist_n = hist_n/len(points_high_filepaths)

    # plt.step((bins_n[1:] + bins_n[:-1])/2, hist_n)

    fig_all, ax_all = plt.subplots()
    ax_all.set_yscale("log", nonposx='clip')
    fig_all.canvas.set_window_title("Corrected points tails")
    fig_all.suptitle("Corrected points tails")
    ax_all.set_xlabel("Bins, ch")

    for point_path in points_path:
        points = glob(path.join(fill_dir, point_path))
        amps_p = np.hstack([get_amps(fp) for fp in points])
        hist_p, _ = np.histogram(amps_p, hist_bins_num, range=hist_range)
        hist_p = hist_p/len(points)
        hist_corr = hist_p - hist_n

        fig, axes = plt.subplots()
        fig.canvas.set_window_title(point_path)
        fig.suptitle("Tail with removed noise")
        axes.set_title("File - %s." % (point_path,))
        axes.set_xlabel("Bins, ch")
        axes.set_xlim(*hist_range)
        axes.set_yscale("log", nonposx='clip')
        axes.step((bins_n[1:] + bins_n[:-1])/2, hist_p, label="Original")
        axes.step((bins_n[1:] + bins_n[:-1])/2, hist_corr, label="Corrected")
        ax_all.step((bins_n[1:] + bins_n[:-1])/2, hist_corr, label=point_path)
        axes.legend()

    ax_all.legend()

if __name__ == "__main__":
    seaborn.set_context("poster")
    _main()


jogador = {'nomeDoJogador': input('Nome do jogador: '),
           'partidasJogadas': int(input('Partidas jogadas: ')),
           'gols': [],}

for c in range(1, jogador['partidas jogadas'] + 1):
    jogador['gols'].append(int(input(f'Quantidade de gols feitos na partida {c}: ')))

jogador['totalDeGols'] = sum(jogador['gols'])

for k, v in jogador.items():
    print(f'{k.capitalize()} = {v}')

print(f'O jogador {jogador["nomeDoJogador"]} jogou {jogador["partidasJogadas"]} partidas')

for i, a in enumerate(jogador['gols']):
    print(f'    Na {i} partida, o jogador fez {a} gols')

print(f'No total, {jogador["nomeDoJogador"]} fez {jogador["totalDeGols"]}')

cursoEmVídeo/Mundo 3/Aula 19 (Dicionário)/Desafio 093.py


# Прочитать сохранённый csv-файл из задания №17 и сохранить данные
# в excel-файл, кроме возраста – столбец с этими данными не нужен.

import openpyxl
import csv

# with open('home17.csv', encoding='utf-8') as f:
#     file_read = csv.reader(f)
#     count = 0
#     for row in file_read:
#         print(f'{row[0]} | {row[1]} | {row[2]}')
#     if count == 0:
#         print('-' * 20)
#     count += 1

work_book = openpyxl.Workbook()
print(work_book.sheetnames)
work_sheet = work_book.create_sheet(title='Home sheet', index=0)
with open('home17.csv', encoding='utf-8') as f:
    csv_file = list(csv.reader(f))

for row_index, row in enumerate(csv_file):
    for col_index, value in enumerate(row):
        cell = work_sheet.cell(row=col_index + 1, column=row_index + 1)
        cell.value = value
work_sheet.delete_rows(2)
work_sheet.insert_rows(1)
work_sheet['B1'] = 'Person_1'
work_sheet['C1'] = 'Person_2'
work_sheet['D1'] = 'Person_3'
work_sheet['E1'] = 'Person_4'
work_sheet['F1'] = 'Person_5'
work_sheet.insert_rows(2)
work_sheet['A2'] = 'id_'
work_sheet['B2'] = '678945'
work_sheet['C2'] = '457328'
work_sheet['D2'] = '897678'
work_sheet['E2'] = '978575'
work_sheet['F2'] = '788765'

work_book.save("home18.xlsx")
# work_book = openpyxl.load_workbook("home18.xlsx")

work_b = openpyxl.load_workbook('home18.xlsx')

w_sheet = work_b['Home sheet']

cell_ = w_sheet.cell(row=1, column=1)
print(cell_)

# name_of_filds = ['Name', 'Grade', 'Age']
# field_01 = ['Jack', '3', '10']
# field_02 = ['Tom', '5', '12']
# field_03 = ['Sam', '11', '18']
#
#
# wb = openpyxl.Workbook()
# print(wb.sheetnames)
#
# wb.create_sheet(title='Первый лист', index=0)
# print(wb.sheetnames)
#
# wb.remove(wb['Sheet'])
# print(wb.sheetnames)
#
# sheet = wb['Первый лист']
# print(sheet)
#
# for row_index, row in enumerate((name_of_filds, field_01, field_02, field_03)):
#     for col_index, value in enumerate(row):
#         cell = sheet.cell(row=row_index+1, column=col_index+1)
#         cell.value = value
#
# wb.save('task_03.xlsx')
#
#
# wb = openpyxl.load_workbook('task_03.xlsx')
# sheets = wb.sheetnames
# print(sheets)
#
# sheet_2 = wb.active
# print(sheet_2)
#
# sheet = wb['Первый лист']
# print(sheet)
#
# print(sheet['D1'].value)
#
# rows = sheet.max_row
# cols = sheet.max_column
#
# print(rows)
# print(cols)
#
# name_of_fields = []
# fields_values = []
#
# for i in range(1, rows+1):
#     value_row = []
#     for j in range(1, cols+1):
#         cell = sheet.cell(row=i, column=j)
#         value = str(cell.value)
#         if i == 1:
#             name_of_fields.append(value)
#         else:
#             value_row.append(value)
#     if i != 1:
#         fields_values.append(value_row)
#
# print(name_of_fields)
# print(fields_values)


import flet as ft

class Task(ft.UserControl):
    """
    Representa una tarea en la lista de tareas.

    Args:
        task_name (str): El nombre de la tarea.
        task_status_change (function): Maneja el cambio de estado (completado o no) de la tarea.
        task_delete (function): Una función que se llama al eliminar la tarea.

    Methods:
        edit_clicked: Maneja el evento de edición de la tarea.
        save_clicked: Maneja el evento de guardado de la tarea editada.
        delete_clicked: Maneja el evento de eliminación de la tarea.
    """

    def __init__(self, task_name, task_status_change, task_delete):
        super().__init__()
        self.completed = False
        self.task_name = task_name
        self.task_status_change = task_status_change
        self.task_delete = task_delete

    def build(self):
        # Construye la interfaz de usuario para representar una tarea de la lista
        self.display_task = ft.Checkbox(
            value=False, label=self.task_name, on_change=self.status_change
        )
        self.edit_name = ft.TextField(expand=1)

        self.display_view = ft.Row(
            alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
            vertical_alignment=ft.CrossAxisAlignment.CENTER,
            controls=[
                self.display_task,
                ft.Row(
                    spacing=0,
                    controls=[
                        ft.IconButton(
                            icon=ft.icons.CREATE_OUTLINED,
                            tooltip="Edit To-Do",
                            on_click=self.edit_clicked,
                        ),
                        ft.IconButton(
                            ft.icons.DELETE_OUTLINE,
                            tooltip="Delete To-Do",
                            on_click=self.delete_clicked,
                        ),
                    ],
                ),
            ],
        )

        self.edit_view = ft.Row(
            visible=False,
            alignment=ft.MainAxisAlignment.SPACE_BETWEEN,
            vertical_alignment=ft.CrossAxisAlignment.CENTER,
            controls=[
                self.edit_name,
                ft.IconButton(
                    icon=ft.icons.DONE_OUTLINE_OUTLINED,
                    icon_color=ft.colors.GREEN,
                    tooltip="Update To-Do",
                    on_click=self.save_clicked,
                ),
            ],
        )
        return ft.Column(controls=[self.display_view, self.edit_view])

    def edit_clicked(self, e):
        # Maneja el evento de edición de la tarea.
        self.edit_name.value = self.display_task.label
        self.display_view.visible = False
        self.edit_view.visible = True
        self.update()

    def save_clicked(self, e):
        # Maneja el evento de guardado de la tarea editada.
        self.display_task.label = self.edit_name.value
        self.display_view.visible = True
        self.edit_view.visible = False
        self.update()

    def status_change(self, e):
        # Maneja el cambio de estado (completo o no) de la tarea.
        self.completed = self.display_task.value
        self.task_status_change(self)

    def delete_clicked(self, e):
        # Maneja el evento de eliminación de la tarea.
        self.task_delete(self)

First Projects/To Do app reusable/tasks.py


import sys
from pyspark import SparkContext
from csv import reader
from operator import add

sc = SparkContext()
line = sc.textFile(sys.argv[1], 1)
line = line.mapPartitions(lambda x: reader(x))
task = line.map(lambda x: x[16])

def state(x):
	if x == 'NY':
		return ('NY', 1)
	else:
		return ('Other', 1)

count = task.map(lambda x : state(x))
result = count.reduceByKey(add)
result.map(lambda x: x[0] + '\t' + str(x[1])).saveAsTextFile("task4.out")
sc.stop()


import logging
from random import randint
from typing import Optional

import requests
from django.core.cache import cache

from apps.base.utils import live_settings
from apps.phone_notifications.exceptions import FailedToMakeCall, FailedToStartVerification
from apps.phone_notifications.phone_provider import PhoneProvider, ProviderFlags
from apps.zvonok.models.phone_call import ZvonokCallStatuses, ZvonokPhoneCall

ZVONOK_CALL_URL = "https://zvonok.com/manager/cabapi_external/api/v1/phones/call/"

logger = logging.getLogger(__name__)

class ZvonokPhoneProvider(PhoneProvider):
    """
    ZvonokPhoneProvider is an implementation of phone provider which supports only voice calls (zvonok.com).
    """

    def make_notification_call(self, number: str, message: str) -> ZvonokPhoneCall:
        speaker = None
        body = None

        if live_settings.ZVONOK_AUDIO_ID:
            message = f'<audio id="{live_settings.ZVONOK_AUDIO_ID}"/>'
        else:
            speaker = live_settings.ZVONOK_SPEAKER_ID

        try:
            response = self._call_create(number, message, speaker)
            response.raise_for_status()
            body = response.json()
            if not body:
                logger.error("ZvonokPhoneProvider.make_notification_call: failed, empty body")
                raise FailedToMakeCall(graceful_msg=f"Failed make notification call to {number}, empty body")
            call_id = body.get("call_id")

            if not call_id:
                logger.error("ZvonokPhoneProvider.make_notification_call: failed, missing call id")
                raise FailedToMakeCall(graceful_msg=self._get_graceful_msg(body, number))

            logger.info(f"ZvonokPhoneProvider.make_notification_call: success, call_id {call_id}")

            return ZvonokPhoneCall(
                status=ZvonokCallStatuses.IN_PROCESS,
                call_id=call_id,
                campaign_id=live_settings.ZVONOK_CAMPAIGN_ID,
            )

        except requests.exceptions.HTTPError as http_err:
            logger.error(f"ZvonokPhoneProvider.make_notification_call: failed {http_err}")
            raise FailedToMakeCall(graceful_msg=self._get_graceful_msg(body, number))
        except (requests.exceptions.ConnectionError, requests.exceptions.JSONDecodeError, TypeError) as err:
            logger.error(f"ZvonokPhoneProvider.make_notification_call: failed {err}")
            raise FailedToMakeCall(graceful_msg=f"Failed make notification call to {number}")

    def make_call(self, number: str, message: str):
        body = None
        speaker = live_settings.ZVONOK_SPEAKER_ID

        try:
            response = self._call_create(number, message, speaker)
            response.raise_for_status()
            body = response.json()
            if not body:
                logger.error("ZvonokPhoneProvider.make_call: failed, empty body")
                raise FailedToMakeCall(graceful_msg=f"Failed make call to {number}, empty body")

            call_id = body.get("call_id")

            if not call_id:
                raise FailedToMakeCall(graceful_msg=self._get_graceful_msg(body, number))
            logger.info(f"ZvonokPhoneProvider.make_call: success, call_id {call_id}")

        except requests.exceptions.HTTPError as http_err:
            logger.error(f"ZvonokPhoneProvider.make_call: failed {http_err}")
            raise FailedToMakeCall(graceful_msg=self._get_graceful_msg(body, number))
        except (requests.exceptions.ConnectionError, requests.exceptions.JSONDecodeError, TypeError) as err:
            logger.error(f"ZvonokPhoneProvider.make_call: failed {err}")
            raise FailedToMakeCall(graceful_msg=f"Failed make call to {number}")

    def _call_create(self, number: str, text: str, speaker: Optional[str] = None):
        params = {
            "public_key": live_settings.ZVONOK_API_KEY,
            "campaign_id": live_settings.ZVONOK_CAMPAIGN_ID,
            "phone": number,
            "text": text,
        }

        if speaker:
            params["speaker"] = speaker

        return requests.post(ZVONOK_CALL_URL, params=params)

    def _get_graceful_msg(self, body, number):
        if body:
            status = body.get("status")
            data = body.get("data")
            if status == "error" and data:
                return f"Failed make call to {number} with error: {data}"
        return f"Failed make call to {number}"

    def make_verification_call(self, number: str):
        code = str(randint(100000, 999999))
        cache.set(self._cache_key(number), code, timeout=10 * 60)
        codewspaces = "   ".join(code)

        body = None
        speaker = live_settings.ZVONOK_SPEAKER_ID

        try:
            response = self._call_create(number, f"Your verification code is {codewspaces}", speaker)
            response.raise_for_status()
            body = response.json()
            if not body:
                logger.error("ZvonokPhoneProvider.make_verification_call: failed, empty body")
                raise FailedToMakeCall(graceful_msg=f"Failed make verification call to {number}, empty body")

            call_id = body.get("call_id")
            if not call_id:
                raise FailedToStartVerification(graceful_msg=self._get_graceful_msg(body, number))
        except requests.exceptions.HTTPError as http_err:
            logger.error(f"ZvonokPhoneProvider.make_verification_call: failed {http_err}")
            raise FailedToStartVerification(graceful_msg=self._get_graceful_msg(body, number))
        except (requests.exceptions.ConnectionError, requests.exceptions.JSONDecodeError, TypeError) as err:
            logger.error(f"ZvonokPhoneProvider.make_verification_call: failed {err}")
            raise FailedToStartVerification(graceful_msg=f"Failed make verification call to {number}")

    def finish_verification(self, number, code):
        has = cache.get(self._cache_key(number))
        if has is not None and has == code:
            return number
        else:
            return None

    def _cache_key(self, number):
        return f"zvonok_provider_{number}"

    @property
    def flags(self) -> ProviderFlags:
        return ProviderFlags(
            configured=True,
            test_sms=False,
            test_call=True,
            verification_call=True,
            verification_sms=False,
        )


import numpy as np
import skimage.filters as skf
import cv2
from sklearn.cluster import KMeans
from sklearn.utils import shuffle
from scipy import ndimage

def background_filter(in_img):
    mask_shape = list(in_img.shape)
    mask_shape[2] = 1
    mask = np.ones(mask_shape, dtype=int)

    mask[in_img[:, :, 0] < 200] = 0
    mask[in_img[:, :, 2] > 210] = 0

    kernel = np.ones((5,5),np.uint8)
    closing = cv2.morphologyEx(np.float64(mask.squeeze()), cv2.MORPH_CLOSE, kernel)
    mask = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel)
    mask = np.expand_dims(mask, axis=2).astype(np.int32)

    return mask

def fibrosis_segmentation(in_img):
    # Params

    # Create mask
    print("# Create mask")
    in_img_shape = in_img.shape
    bg_mask = background_filter(in_img)
    masked_img = in_img * bg_mask

    # KMEANS clustering
    print("# Kmeans clustering")

    w, h, d = tuple(masked_img.shape)
    vec_masked_img = np.reshape(masked_img, (w * h, d))

    image_array_sample = shuffle(vec_masked_img, random_state=0, n_samples=100_000)
    kmeans = KMeans(n_clusters=3, n_init=10, random_state=0).fit(
        image_array_sample
    )
    km_labels = kmeans.predict(vec_masked_img)
    km_centers = kmeans.cluster_centers_

    # Create Fibrosis mask
    print("# Fibrosis mask")
    background_label = np.argmin(np.mean(km_centers, axis=1))
    tissue_label = np.argmax(np.mean(km_centers, axis=1))
    fibrosis_label = 3 - (background_label + tissue_label)

    _, counts = np.unique(km_labels, return_counts=True)

    fib_mask_shape = list(in_img_shape)
    fib_mask_shape[2] = 1
    fib_mask = np.zeros(fib_mask_shape, dtype=int)

    km_mask = km_labels.reshape((fib_mask_shape))
    fib_mask[km_mask == fibrosis_label] = 1

    fib_mask[masked_img[:, :, 2] > 175] = 0

    print("# Border check")
    bg_mask = np.array(bg_mask, np.uint8)
    cnts, _ = cv2.findContours(bg_mask.squeeze(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    s = list(fib_mask.shape)
    s[2] = 3
    bimgs = np.zeros(s)
    bimgs = np.array(bimgs, np.uint8)
    cv2.drawContours(bimgs, cnts, -1, (255, 255, 255), 3)
    bimgs = cv2.cvtColor(bimgs, cv2.COLOR_BGR2GRAY)
    bimgs[bimgs!=0]=255
    fib_mask[bimgs == 255] = 2

    # Look for labelled areas which connect with the tissue borders
    labeled_array, num_features = ndimage.label(fib_mask)
    max_vals = ndimage.maximum(fib_mask,labeled_array,range(1,num_features+1))
    m_idx = np.where(max_vals==2)[0] + 1

    # remove those areas
    max_index = np.ones(num_features + 1, np.uint8)
    max_index[m_idx] = 0
    fib_mask = fib_mask * max_index[labeled_array]

    if fibrosis_label == 3: cpa = 0
    else:
        cpa = np.sum(fib_mask)/(counts[tissue_label] + counts[fibrosis_label])

    return fib_mask, cpa


# Author: Vinicius Resende
# 22/05/2019 - 21:05
# resendeviniciush@gmail.com

import numpy as np
import random
import math

class HiddenLayer():

  weights = []
  layers = []

  def __init__(self, number_neurons, number_input_neurons):
    self.weights = 1 - np.random.random((number_input_neurons, number_neurons))
    self.layers = np.full((number_input_neurons, number_neurons), 0)

  def get_weights(self):
    return self.weights

  def get_layers(self):
    return self.layers

class MultiLayerPerceptron():

  n_layers = 0
  cycles = 0
  n_neurons = 0
  weights = []
  bias = []
  outputfromlayer = []
  output = []
  X = []
  y = []
  alpha = 0
  outputbias = 0
  def __init__(self, n_layers, n_neurons, cycles):

    self.n_layers = n_layers
    self.cycles = cycles
    self.n_neurons = n_neurons

  def act_function(self, x, option):

    if option == 1:
      return 1 / (1 + np.exp(-x))
    else:
      return x * (1 - x)

  def feed_forward(self):

    out = np.dot(self.X, self.weights[0]) + np.transpose(self.bias[0])
    self.outputfromlayer[0] = self.act_function(out, 1)

    for i in range(1, self.n_layers - 1):
      out = np.dot(self.outputfromlayer[i - 1], self.weights[i]) + np.transpose(self.bias[i])
      self.outputfromlayer[i] = self.act_function(out, 1)

    out = np.dot(self.outputfromlayer[self.n_layers - 2], self.weights[self.n_layers - 1])
    out += self.outputbias
    self.outputfromlayer[self.n_layers - 1] = self.act_function(out, 1)

  def back_propagation(self):

    layerserrors = [0 for i in range(self.n_layers)]
    layersdelta = [0 for i in range(self.n_layers)]
    layersadjust = [0 for i in range(self.n_layers)]

    layerserrors[self.n_layers - 1] = ((self.outputfromlayer[self.n_layers - 1] - self.y))
    layersdelta[self.n_layers - 1] = (layerserrors[self.n_layers - 1] * self.act_function(self.outputfromlayer[self.n_layers - 1], 2))

    for i in range(self.n_layers - 2, -1, -1):
      layerserrors[i] = np.dot(layersdelta[i + 1], self.weights[i + 1].T)
      layersdelta[i] = (layerserrors[i] * self.act_function(self.outputfromlayer[i], 2))

    layersadjust[0] = self.X.T.dot(layersdelta[0])

    for i in range(1, self.n_layers):
      layersadjust[i] = self.outputfromlayer[i - 1].T.dot(layersdelta[i])
      if i < self.n_layers - 1:
        self.bias[i] -= self.alpha * np.sum(layersdelta[i], axis = 0)
      self.weights[i] -= layersadjust[i]

    self.outputbias -= self.alpha * np.sum(layersdelta[self.n_layers - 1], axis = 0)
    self.bias[0] -= self.alpha * np.sum(layersdelta[0], axis = 0)

    self.weights[0] -= layersadjust[0]

  def fit(self, X, y, alpha = 0.0001):

    self.X = X
    self.y = y
    self.n_layers -= 1
    self.alpha = alpha
    self.weights.append(HiddenLayer(self.n_neurons, len(X[0])).get_weights())
    self.outputfromlayer.append(HiddenLayer(self.n_neurons, len(X[0])).get_layers())

    for i in range(self.n_layers - 2):
      self.weights.append(HiddenLayer(self.n_neurons, self.n_neurons).get_weights())
      self.outputfromlayer.append(HiddenLayer(self.n_neurons, self.n_neurons).get_layers())

    self.weights.append(HiddenLayer(1, self.n_neurons).get_weights())
    self.outputfromlayer.append(HiddenLayer(1, self.n_neurons).get_layers())
    self.bias = [[1 - random.random() for i in range(self.n_neurons)] for j in range(self.n_layers)]
    self.outputbias = 1 - random.random()
    for i in range(self.cycles):
      self.feed_forward()
      self.back_propagation()

  def predict(self, test):

    outputfromlayer = []
    outputfromlayer.append(self.act_function(np.dot(test, self.weights[0]) + np.transpose(self.bias[0]), 1))
    for i in range(1, self.n_layers - 1):
      outputfromlayer.append(self.act_function(np.dot(outputfromlayer[i - 1], self.weights[i]) + np.transpose(self.bias[i]), 1))
    out = np.dot(outputfromlayer[self.n_layers - 2], self.weights[self.n_layers - 1]) + self.outputbias
    return self.act_function(out ,1)

Neural Networks/MLP - MultiLayerPerceptron/MultiLayerPerceptron.py


import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

import nav_analysis.rl.efficient_net
import nav_analysis.rl.resnet
from habitat.sims.habitat_simulator import SimulatorActions
from nav_analysis.rl.dpfrl import DPFRL
from nav_analysis.rl.frn_layer import FRNLayer
from nav_analysis.rl.layer_norm_lstm import LayerNormLSTM
from nav_analysis.rl.ppo.utils import CategoricalNet, Flatten
from nav_analysis.rl.running_mean_and_var import ImageAutoRunningMeanAndVar
from nav_analysis.rl.ppo.policy import Policy, ResNetEncoder, Net

def gather_last_from_packed_seq(
    x: torch.nn.utils.rnn.PackedSequence, lengths: torch.Tensor,
) -> torch.Tensor:
    r"""Takes a packed sequence returns the last element in each sequence contained.

    When working with rnns and padded seqs, it is nice to do the following

    .. code::python

        x = <padded_rnn_input>
        lengths = <length of each seq in x>

        x = torch.nn.utils.rnn.pack_padded_sequence(x, lengths, enforce_sorted=False)

        x, _ = rnn(x)

        x, _ = torch.nn.utils.rnn.pad_packed_sequence(x)

        x = torch.gather(x, dim=0, index=(lengths - 1).view(1, x.size(1), 1).expand_as(x[0:1])).squeeze(0)

    to produce an encoding of a sequence.  However, padding the packed sequence is expensive and memory inefficient,
    this method can be used instead!

    .. code::python

        x = <padded_rnn_input>
        lengths = <length of each seq in x>

        x = torch.nn.utils.rnn.pack_padded_sequence(x, lengths, enforce_sorted=False)

        x, _ = rnn(x)

        x = gather_last_from_packed_seq(x, lengths)

    Not that for this method, batch_first=False and batch_first=True are identical!

    :param x: The packed sequence
    :param lengths: The length of each sequence

    :return: A tensor of size (lengths.size(0), x.data.size(1))
    """
    B = len(lengths)

    sorted_lengths = torch.index_select(lengths, dim=0, index=x.sorted_indices)

    offsets = torch.cumsum(
        torch.cat(
            (
                torch.zeros(
                    (1,), device=x.batch_sizes.device, dtype=x.batch_sizes.dtype
                ),
                x.batch_sizes,
            )
        ).to(device=x.data.device),
        dim=0,
    )

    gather_inds = torch.index_select(
        offsets, dim=0, index=sorted_lengths - 1
    ) + torch.arange(B, device=x.data.device, dtype=sorted_lengths.dtype)

    gather_inds = (
        torch.index_select(gather_inds, dim=0, index=x.unsorted_indices)
        .view(B, 1)
        .expand(B, x.data.size(1))
    )

    return torch.gather(x.data, dim=0, index=gather_inds)

class MemoryLimitedPolicy(Policy):
    def __init__(
        self,
        observation_space,
        action_space,
        hidden_size=512,
        num_recurrent_layers=1,
        blind=0,
        use_aux_losses=True,
        rnn_type="GRU",
        resnet_baseplanes=32,
        backbone="resnet50",
        task="pointnav",
        norm_visual_inputs=False,
        two_headed=False,
        max_memory_length=2,
    ):
        nn.Module.__init__(self)
        assert not two_headed
        self.dim_actions = action_space.n

        self.net = MemoryLimitedNet(
            observation_space=observation_space,
            hidden_size=hidden_size,
            num_recurrent_layers=num_recurrent_layers,
            blind=blind,
            rnn_type=rnn_type,
            backbone=backbone,
            resnet_baseplanes=resnet_baseplanes,
            norm_visual_inputs=norm_visual_inputs,
            task=task,
            max_memory_length=max_memory_length,
        )

        self.action_distribution = CategoricalNet(
            self.net.output_size, self.dim_actions, task=task
        )

        assert not blind or not use_aux_losses
        if use_aux_losses:
            self.representation_egomotion_head = nn.Linear(
                hidden_size, self.dim_actions
            )
            self.gps_head = nn.Linear(
                hidden_size, observation_space.spaces["gps"].shape[0]
            )
            self.delta_pos_head = nn.Linear(hidden_size, 3)

        self.use_aux_losses = use_aux_losses

class MemoryLimitedNet(Net):
    """Network which passes the input image through CNN and concatenates
    goal vector with CNN's output and passes that through RNN.
    """

    def __init__(
        self,
        observation_space,
        hidden_size,
        num_recurrent_layers,
        blind,
        rnn_type,
        backbone,
        resnet_baseplanes,
        norm_visual_inputs,
        task,
        max_memory_length,
    ):
        super().__init__(
            observation_space,
            hidden_size,
            num_recurrent_layers,
            blind,
            rnn_type,
            backbone,
            resnet_baseplanes,
            norm_visual_inputs,
            task,
        )

        self._max_memory_length = max_memory_length

    def forward(self, observations, rnn_hidden_states, prev_actions, masks):
        # Observations come in as a (B, ..., C, self._max_memory_length) tensor,
        # Put things as (self._max_memory_length * B, ..., C) to then make
        # but we want (self._max_memory_length, B, C) later
        for k, v in observations.items():
            dim_order = list(range(v.ndim))
            dim_order = dim_order[-1:] + dim_order[0:-1]

            v = v.permute(*dim_order)
            size = list(v.size())
            size = [size[0] * size[1]] + size[2:]
            v = v.reshape(*size)

            observations[k] = v

        cnn_input = []
        if self._n_input_rgb > 0:
            rgb_observations = observations["rgb"]
            # permute tensor to dimension [BATCH x CHANNEL x HEIGHT X WIDTH]
            rgb_observations = rgb_observations.permute(0, 3, 1, 2)
            rgb_observations = rgb_observations / 255.0  # normalize RGB
            rgb_observations = (self.grayscale_kernel * rgb_observations).sum(
                1, keepdim=True
            )

            cnn_input.append(rgb_observations)

        if self._n_input_depth > 0:
            depth_observations = observations["depth"]

            # permute tensor to dimension [BATCH x CHANNEL x HEIGHT X WIDTH]
            depth_observations = depth_observations.permute(0, 3, 1, 2)

            cnn_input.append(depth_observations)

        assert not self._old_goal_format
        goal_observations = self.tgt_embed(observations["pointgoal"])

        prev_actions_emb = self.prev_action_embedding(
            observations["prev_action"].long().squeeze(-1)
        )

        x = []
        cnn_feats = None
        if len(cnn_input) > 0:
            cnn_input = torch.cat(cnn_input, dim=1)
            cnn_input = F.interpolate(
                cnn_input, size=(self._sq_size, self._sq_size), mode="area"
            )
            cnn_input = F.avg_pool2d(cnn_input, 2)
            if self._norm_inputs:
                cnn_input = self.running_mean_and_var(cnn_input)

            cnn_feats = self.cnn(cnn_input)
            x += [cnn_feats]

        x += [goal_observations, prev_actions_emb]
        if self.gps_compass_embed is not None:
            x += [self.gps_compass_embed(observations["gps_and_compass"])]

        if self.dist_to_goal_embed is not None:
            x += [self.dist_to_goal_embed(observations["dist_to_goal"])]

        x = torch.cat(x, dim=1)  # concatenate goal vector

        x = x.view(self._max_memory_length, x.size(0) // self._max_memory_length, -1)

        lengths = (
            (observations["prev_action"].view(x.size(0), x.size(1)) != 0).long().sum(0)
        )
        x = torch.nn.utils.rnn.pack_padded_sequence(
            x, lengths, batch_first=False, enforce_sorted=False
        )

        x, _ = self.rnn(x)

        x = gather_last_from_packed_seq(x, lengths)

        if self._task == "pointnav":
            value = self.critic_linear(x)
        else:
            value = self.critic(x)

        return value, x, rnn_hidden_states, cnn_feats


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm

import os

def extract_values(correct_path, policy):
    file_name0 = "policy_rewards" + str(policy) + "," + str(0) + ".txt"
    file_name1 = "policy_rewards" + str(policy) + "," + str(1) + ".txt"
    return np.loadtxt(os.path.join(correct_path, file_name0)), np.loadtxt(os.path.join(correct_path, file_name1))

def moving_avarage_smoothing(X,k):
	S = np.zeros(X.shape[0])
	for t in range(X.shape[0]):
		if t < k:
			S[t] = np.mean(X[:t+1])
		else:
			S[t] = np.sum(X[t-k:t])/k
	return S

def plot_and_save(rewards, save_path, policy, lb):
        c = cm.rainbow(np.linspace(0, 1, len(rewards)))
        l = lb
        print(l[0])
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(30, 15))

        ax1.set_title('Rewards per episode for agent 0:')
        ax1.set_xlabel('Episode')
        ax1.set_ylabel('Rewards')

        ax2.set_title('Rewards per episode for agent 1')
        ax2.set_xlabel('Episode')
        ax2.set_ylabel('Rewards')

        ax1.set_ylim([-20, 30])
        ax2.set_ylim([-20, 30])

        for i in range(0, 3):
            ax1.plot(np.arange(0, len(rewards[i][0])), rewards[i][0], color=c[i])
            ax2.plot(np.arange(0, len(rewards[i][1])), rewards[i][1], color=c[i])

        ax1.legend(l)
        ax2.legend(l)

        file_name = "learning_curve" + str(policy) + ".png"
        plt.savefig(os.path.join(save_path, file_name))
        plt.close()

PATH = os.getcwd()
PATH = os.path.join(PATH, 'SAR')
PATH = os.path.join(PATH, 'Results')
PATH = os.path.join(PATH, 'QLearning')
load_path = os.path.join(PATH, 'Saved_data')

policy = [0,1,2]
lr = [0.1, 0.1, 0.1]
dr = [0.1, 0.1, 0.1]
er = [0.05, 0.1, 0.3]
label0 = "α=%s, γ=%s, ϵ=%s, ϵ_min=%s, ϵ_max=%s, ϵ_d=%s" %(lr[0], dr[0], er[0], er[0], er[0], er[0])
label1 = "α=%s, γ=%s, ϵ=%s, ϵ_min=%s, ϵ_max=%s, ϵ_d=%s" %(lr[1], dr[1], er[1], er[1], er[1], er[1])
label2 = "α=%s, γ=%s, ϵ=%s, ϵ_min=%s, ϵ_max=%s, ϵ_d=%s" %(lr[2], dr[2], er[2], er[2], er[2], er[2])

label = []
label.append(label0)
label.append(label1)
label.append(label2)

rewards00, rewards01 = extract_values(load_path, policy[0])
rewards10, rewards11 = extract_values(load_path, policy[1])
rewards20, rewards21 = extract_values(load_path, policy[2])

rewards0 = [rewards00, rewards01]
rewards1 = [rewards10, rewards11]
rewards2 = [rewards20, rewards21]

rewards = np.array([rewards0, rewards1, rewards2])

for i in range(0 ,3):
    rewards[i, 0] = moving_avarage_smoothing(rewards[i, 0], 20)
    rewards[i, 1] = moving_avarage_smoothing(rewards[i, 1], 20)

plot_and_save(rewards, load_path, policy, label)

print("done")


# -*- coding: utf-8 -*-
from collections import deque

# 지하철역 클래스
class Station:
    def __init__(self, name):
        self.name = name
        self.neighbors = []

    def add_connection(self, another_station):
        self.neighbors.append(another_station)
        another_station.neighbors.append(self)

# Breadth-First Search 알고리즘
def bfs(start, goal):
    # 변수 정의
    previous = {}
    queue = deque()
    current = None

    # 초기 설정
    previous[start] = None
    queue.append(start)

    # 탐색
    while len(queue) > 0 and current != goal:
        current = queue.popleft()

        for neighbor in current.neighbors:
            if neighbor not in previous.keys():
                queue.append(neighbor)
                previous[neighbor] = current

    # 길이 있으면 경로를 만들어서 리턴
    if current == goal:
        path = [goal]
        x = goal

        while previous[x] != None:
            x = previous[x]
            path.append(x)

        return path

    # 길이 없으면 None 리턴
    return None

# 파일 읽기
stations = {}
in_file = open('stations.txt')

for line in in_file:
    previous_station = None
    data = line.strip().split("-")

    for name in data:
        station_name = name.strip()
        if station_name not in stations.keys():
            current_station = Station(station_name)
            stations[station_name] = current_station
        else:
            current_station = stations[station_name]

        if previous_station != None:
            current_station.add_connection(previous_station)

        previous_station = current_station

in_file.close()

# 테스트
start_name = "당산"
goal_name = "건대입구"

start = stations[start_name]
goal = stations[goal_name]

path = bfs(start, goal)
path.reverse()
for station in path:
    print(station.name)


"""add_village_venues

Revision ID: 7c8d52a17f8f
Revises: 089956059475
Create Date: 2022-05-07 20:47:38.189635

"""

# revision identifiers, used by Alembic.
revision = '7c8d52a17f8f'
down_revision = '089956059475'

from alembic import op
import sqlalchemy as sa

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('venue', sa.Column('village_id', sa.Integer(), nullable=True))
    op.add_column('venue', sa.Column('scheduled_content_only', sa.Boolean(), nullable=True))
    op.create_foreign_key(op.f('fk_venue_village_id_village'), 'venue', 'village', ['village_id'], ['id'])
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(op.f('fk_venue_village_id_village'), 'venue', type_='foreignkey')
    op.drop_column('venue', 'scheduled_content_only')
    op.drop_column('venue', 'village_id')
    # ### end Alembic commands ###


from absl.testing import absltest
import tink
from tink import _kms_clients
from tink import aead
from tink import tink_config

def setUpModule():
  tink_config.register()

class FakeClient(_kms_clients.KmsClient):

  def __init__(self, key_uri):
    self.key_uri = key_uri

  def does_support(self, key_uri: str) -> bool:
    return key_uri == self.key_uri

  def get_aead(self, key_uri: str) -> aead.Aead:
    raise ValueError('unknown key_uri')

class KmsClientsTest(absltest.TestCase):

  def test_register_get_and_reset_kms_clients(self):
    client1 = FakeClient('key_uri1')
    client2 = FakeClient('key_uri2')
    client3 = FakeClient('key_uri3')
    tink.register_kms_client(client1)
    tink.register_kms_client(client2)
    tink.register_kms_client(client3)

    # returns the first registered client that supports the uri.
    self.assertEqual(tink.kms_client_from_uri('key_uri1'), client1)
    self.assertEqual(tink.kms_client_from_uri('key_uri2'), client2)
    with self.assertRaises(tink.TinkError):
      tink.kms_client_from_uri('unknown')

    _kms_clients.reset_kms_clients()
    with self.assertRaises(tink.TinkError):
      tink.kms_client_from_uri('key_uri1')

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


def solution(strings, n):
	lst=[]
	answer=[]
	for word in strings:
		lst.append([word[n],word])
	lst.sort()
	for idx in lst:
		answer.append(idx[1])

	return answer
dic={'u':'sun', 'e':['aed','bed'], 'a':'car'}

print(solution(['sun', 'bed', 'car', 'tune'], 1))

#다른풀이-sorted 사용
#sorted 모듈은 jupyter에 따로 정리!
def strange_sort(strings, n):
    '''strings의 문자열들을 n번째 글자를 기준으로 정렬해서 return하세요'''
    return sorted(strings, key=lambda x: x[n])

프로그래머스/level1_문자열내맘대로정렬.py


from bs4 import BeautifulSoup
import requests

gold = requests.get("https://www.cnbc.com/quotes/XAU=")
gold_soup = BeautifulSoup(gold.content,'lxml')
gold_price = gold_soup.select_one(".QuoteStrip-lastPrice").text.strip()

oil = requests.get("https://www.cnbc.com/quotes/@CL.1")
oil_soup = BeautifulSoup(oil.content,'lxml')
oil_price = oil_soup.select_one(".QuoteStrip-lastPrice").text.strip()

print("XAUUSD : "+gold_price+"\nUSLOIL : "+oil_price)