# 35.1-1 이웃 요소의 평균값을 가지는 리스트 만들기

import random

ELEMENTS_OF_A = 20
ELEMENTS_OF_NEW = ELEMENTS_OF_A - 2

a = [None] * ELEMENTS_OF_A
new = [None] * ELEMENTS_OF_NEW

for i in range(ELEMENTS_OF_A):
    a[i] = random.randint(0, 20)

print("a_lst:", a)

# 방법 A
for j in range(ELEMENTS_OF_NEW):
    sum_a = a[j] + a[j+1] + a[j+2]
    new[j] = round(sum_a / 3, 2)

print("new_a_lst:", new)

# 방법 B
import math

new_lst = []
for k in range(ELEMENTS_OF_A - 2):
    new_lst.append(math.fsum(a[k:k+3]) / 3)

print("new_lst:", new_lst)

# 35.1-2 최댓값을 저장하는 리스트 만들기

ELEMENTS_M_N = 20

m = [None] * ELEMENTS_M_N
n = [None] * ELEMENTS_M_N

for i in range(ELEMENTS_M_N):
    m[i] = random.randint(1, 30)
    n[i] = random.randint(1, 30)

print("m_lst:", m)
print("n_lst:", n)

new_arr = []
for j in range(ELEMENTS_M_N):
    max_value = max(m[j], n[j])
    new_arr.append(max_value)

print("new_arr:", new_arr)

# 35.1-3 1차원 리스트 병합하기

ELEMENTS_A = 12
ELEMENTS_B = 13

lst_a = [None] * ELEMENTS_A
lst_b = [None] * ELEMENTS_B

for i in range(ELEMENTS_A):
    lst_a[i] = random.randint(1, 10)

for j in range(ELEMENTS_B):
    lst_b[j] = random.randint(1, 10)

new_arrA = [None] * (ELEMENTS_A + ELEMENTS_B)

# 방법 A
for k in range(ELEMENTS_A + ELEMENTS_B):

    if k < ELEMENTS_A:
        new_arrA[k] = lst_a[k]
    else:
        new_arrA[k] = lst_b[k-ELEMENTS_A]

print("lst_a:", lst_a)
print("lst_b:", lst_b)
print("new_arrA:", new_arrA)

# 방법 B
new_arrB = lst_a + lst_b
print("new_arrB:", new_arrB)

# 방법 C
new_arrC = []

for i in range(ELEMENTS_A):
    new_arrC.append(lst_a[i])

for i in range(ELEMENTS_B):
    new_arrC.append(lst_b[i])

print("new_arrC:", new_arrC)

# 35.1-4  2차원 리스트 병합하기
two_depth_columns = 5
two_depth_a_rows = 4
two_depth_b_rows = 10
two_depth_new_rows = two_depth_a_rows + two_depth_b_rows

two_depth_a = [[None] * two_depth_columns for i in range(two_depth_a_rows)]
two_depth_b = [[None] * two_depth_columns for i in range(two_depth_b_rows)]

for i in range(two_depth_a_rows):
    for j in range(two_depth_columns):
        two_depth_a[i][j] = random.randint(1, 30)

print("two_depth_a:", two_depth_a)

for i in range(two_depth_b_rows):
    for j in range(two_depth_columns):
        two_depth_b[i][j] = random.randint(1, 30)

print("two_depth_b:", two_depth_b)

# 방법 A
new_A = [ [None] * two_depth_columns for i in range(two_depth_new_rows) ]

for i in range(two_depth_a_rows):
    new_A[i] = two_depth_a[i]

for i in range(two_depth_b_rows):
    new_A[i+two_depth_a_rows] = two_depth_b[i]

print("new_A:", new_A)

# 방법 B
new_B = two_depth_a + two_depth_b
print("new_B:", new_B)

# 방법 C
new_C = []

for i in range(two_depth_a_rows):
    new_C.append(two_depth_a[i])

for i in range(two_depth_b_rows):
    new_C.append(two_depth_b[i])

print("new_C:", new_C)


from hw1_train import *

import sys

test_path = sys.argv[1]
output_path = sys.argv[2]

npzfile = np.load('./hw1.npz')

hr = 9
fea = 162

w = npzfile['arr_0']
b = npzfile['arr_1'][0]

test_x = split_test_data(read_data(test_path), fea)
test_y = predict(w, b, test_x)
output(test_y, output_path)


from django.conf.urls import patterns, url
from visual_widget import views
from data_visualization.views import load_data

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^history', views.history_plot, name='history_plot'),
    url(r'^realtime', views.realtime_plot, name='realtime_plot'),
    url(r'^current_val/$', views.current_val, name='current_val'),
    url(r'^load_data/$', load_data, name='data_loader'),
)


#Um drone de limpeza de ruas deve escolher carregar sempre o lixo de menor peso. Entre os pesos de 3 lixos informados pelo usuário, um programa deve indicar qual deles deve ser carregado pelo drone.

lixo1 = float(input("Informe o peso do lixo 1"))
lixo2 = float(input("Informe o peso do lixo 2"))
lixo3 = float(input("Informe o peso do lixo 3"))

if lixo1<lixo2 and lixo1<lixo3:
    print("O lixo 1 é o lixo mais leve e será carregado")
elif lixo2<lixo1 and lixo2<lixo3:
    print("O lixo 2 é o lixo mais leve e será carregado")
elif lixo3<lixo1 and lixo3<lixo2:
    print("O lixo 3 é o lixo mais leve e será carregado")
else:
    print("Existem lixos com o mesmo peso. Contate o suporte")


from pprint import pformat

class Node:
    def __init__(self, data, parent=None):
        self.data = data
        self.parent = parent
        self.left = None
        self.right = None

    def __repr__(self):
        if self.left is None and self.right is None:
            return str(self.data)
        return pformat({"%s" % self.data: (self.left, self.right)}, indent=1)

class BinarySearchTree:
    def __init__(self):
        self.root = None

    def __str__(self):
        return str(self.root)

    def __insert(self, data):
        node = Node(data)
        if self.is_empty():
            self.root = node
        else:
            parent_node = self.root
            while True:
                if data < parent_node.data:
                    if parent_node.left is None:
                        parent_node.left = node
                        break
                    else:
                        parent_node = parent_node.left
                else:
                    if parent_node.right is None:
                        parent_node.right = node
                        break
                    else:
                        parent_node = parent_node.right

    def level_order_traverse(self, node):
        from queue import Queue
        queue = Queue()
        queue.put(node)
        while not queue.empty():
            node = queue.get()
            print(node.data)
            if node.left:
                queue.put(node.left)
            if node.right:
                queue.put(node.right)

    def is_empty(self):
        # if self.root is None:
        #     return True
        # return False
        return True if self.root is None else False


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

# In[170]:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# # Membaca Data

# In[171]:

txtfile = pd.read_table(r'C:\Users\ASUS-PC\Downloads\USAElectoral2016.txt', sep=',')

# In[172]:

txtfile

# # Mencari Tingkat Elektabilitas Ben Carson dan Jeb Bush di 50 Negara Bagian

# In[173]:

plt.figure(figsize=(30,10))

plt.title('Electability between Jeb Bush and Ben Carson', fontdict={'fontweight':'bold', 'fontsize': 18})

plt.plot(txtfile.State, txtfile.JebBush, 'b.-', label='JebBush')
plt.plot(txtfile.State, txtfile.BenCarson, 'r.-', label='BenCarson')

plt.xticks(txtfile.State)

plt.xlabel('State')
plt.ylabel('Electability')

plt.legend()
plt.show()

# # Mencari Elektabilitas Jeb Bush dan Ben Carson di 5 Negara Bagian Pertama

# In[174]:

plt.figure(figsize=(30,10))

plt.title('Electability between Jeb Bush and Ben Carson di DC,Delaware,Colorado,Maryland, dan Vermont', fontdict={'fontweight':'bold', 'fontsize': 18})

plt.plot(txtfile.State[0:5], txtfile.JebBush[0:5], 'b.-', label='JebBush')
plt.plot(txtfile.State[0:5], txtfile.BenCarson[0:5], 'r.-', label='BenCarson')

plt.xticks(txtfile.State[0:5])

plt.xlabel('State')
plt.ylabel('Electability')

plt.legend()
plt.show()

# # Mencari Elektabilitas Donald Trump di Swing State (Pennsylvania,New York,California,Florida)

# In[184]:

txtfile.iloc[[7,9,14,31], [19]].head()

# #  Mencari Elektabilitas Hillary Clinton di Swing State (Pennsylvania,New York,California,Florida)

# In[185]:

txtfile.iloc[[7,9,14,31], [5]].head()

# # Grafis Garis Elektabilitas Hillary Clinton dan Donald Trump di Swing State

# In[193]:

plt.figure(figsize=(30,10))

plt.title('Electability between Donald Trump and Hillary Clinton di Swing State', fontdict={'fontweight':'bold', 'fontsize': 18})

plt.plot(['Pennsylvania','NewYork','California','Florida'], ['9.67','12.72','9.45','8.44'], label='HillaryClinton')
plt.plot(['Pennsylvania','NewYork','California','Florida'],['60.84','73.22','78.30','73.05'], label='DonaldTrump')

plt.xticks(['Pennsylvania','NewYork','California','Florida'])

plt.xlabel('State')
plt.ylabel('Electability')

plt.legend()
plt.show()

# In[ ]:


#!/usr/bin/env python3

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class ActionBar(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self)
        self.set_title("ActionBar")
        self.set_default_size(200, 200)
        self.connect("destroy", Gtk.main_quit)

        grid = Gtk.Grid()
        self.add(grid)

        label = Gtk.Label()
        label.set_vexpand(True)
        grid.attach(label, 0, 0, 1, 1)

        actionbar = Gtk.ActionBar()
        actionbar.set_hexpand(True)
        grid.attach(actionbar, 0, 1, 1, 1)

        button = Gtk.Button("Cut")
        actionbar.pack_start(button)
        button = Gtk.Button("Copy")
        actionbar.pack_start(button)
        button = Gtk.Button("Paste")
        actionbar.pack_end(button)

    def run(self):
        self.show_all()

window = ActionBar()
window.run()

Gtk.main()


import sys

from typing import Type, Dict

from app.modules.url_shortener.domain.repositories import UrlRepositoryInterface
from app.modules.url_shortener.domain.models import RedirectUrlInterface
from app.modules.url_shortener.domain.models import UrlDomain
from app.shared.utils.utils import from_base62

class RedirectUrlService(RedirectUrlInterface):
    """
    Redirect URL Service
    """

    def __init__(self, url_repository: Type[UrlRepositoryInterface]):
        """
        Constructor

        :param url_repository: Type[UrlRepositoryInterface]
        """
        self.url_repository = url_repository

    def redirect(self, hash: str) -> Dict[bool, UrlDomain]:
        """
        Register URL

        :param data: UrlDomain
        :return: Dict[bool, UrlDomain]
        """

        try:

            response = None

            id_hash = from_base62(hash)

            response = self.url_repository.get_by_id_hash(id_hash)

            if response["success"] is True:
                data = {
                    "id_url": response["data"]["id_url"],
                    "long_url": response["data"]["long_url"],
                    "short_url": response["data"]["short_url"],
                    "id_hash": response["data"]["id_hash"],
                    "hash_url": response["data"]["hash_url"],
                    "status_url": response["data"]["status_url"],
                    "total_access": response["data"]["total_access"] + 1,
                }
                response = self.url_repository.update(data)
                return {"success": True, "data": response}

            return {"success": False, "data": None}

        except Exception as e:
            return {"success": False, "data": None}


# Program to add two numbers

# Solution-1 --> with predefine variable

num1 = 4
num2 = 7
sum = num1 + num2
print("The sum of given two numbers:", sum)

# Solution-2 --> with user input

# we can use int instant float
num1 = float(input("Enter first number:"))
num2 = float(input("Enter secong number:"))
sum = num1 + num2
print("The sum of given two numbers:", sum)


import numpy as np
from sklearn.linear_model import LinearRegression

def moving_average(a):
  return np.cumsum(a) / np.arange(1,len(a)+1)

def convergence_trace(x, mean):
  return np.sum([
    np.abs(moving_average(x[:,i]) - mu)
    for i, mu in enumerate(mean)
  ], axis=0)

def joint_conv_trace(chains, grid):
  joint, index = join_chains(chains)
  means = grid.means.mean(axis=0)
  return index, convergence_trace(joint, means)

def conv_fit(index, errors, cutoff=0.1, burnin=100):
  start = np.argwhere(index > burnin)[0][0]
  lg_ery = np.log10(errors[start:])
  lg_idx = np.log10(index[start:]).reshape((len(lg_ery), 1))
  lreg = LinearRegression()
  lreg.fit(lg_idx, lg_ery)
  score = lreg.score(lg_idx, lg_ery)
  return lreg.coef_[0], lreg.intercept_, score

def join_chains(chains):
  length = sum(len(c) for c, i in chains)
  progress = np.zeros(len(chains)).astype(int)

  samples = np.empty((length, chains[0][0].shape[1]))
  indexes = np.empty(length)
  for i in range(length):
    mini = float('inf')
    minc = None
    for ch, ci in enumerate(progress):
      chain, index = chains[ch]
      if ci >= len(chain):
        continue
      elif index[ci] < mini:
        mini = index[ci]
        minc = ch
    samples[i] = chains[minc][0][progress[minc]]
    indexes[i] = chains[minc][1][progress[minc]]
    progress[minc] += 1

  for ch, ci in enumerate(progress):
    assert(ci == len(chains[ch][0]))

  return samples, indexes

if __name__ == '__main__':
  np.testing.assert_array_equal(moving_average([1,3,5]), [1,2,3])
  pts = np.array([[1,2],[3,2],[5,-1]])
  mus = np.array([2,2])
  np.testing.assert_array_equal(convergence_trace(pts, mus), [1,0,2])

  chains = [
    (
      np.array([[10],[10],[10]]),
      np.array([1,4,9])
    ),
    (
      np.array([[8],[8],[8]]),
      np.array([1,3,7])
    ),
    (
      np.array([[6],[6],[6]]),
      np.array([2,5,6])
    )
  ]

  s, i = join_chains(chains)
  np.testing.assert_array_equal(s,
      [[10],[8],[6],[8],[10],[6],[6],[8],[10]])
  np.testing.assert_array_equal(i,
      [1,1,2,3,4,5,6,7,9])


import brownie
from brownie import Contract
from brownie import config

# test passes as of 21-06-26
def test_migration(
    gov,
    token,
    vault,
    guardian,
    strategist,
    whale,
    strategy,
    chain,
    strategist_ms,
    StrategyUniverseStaking,
    rewardscontract,
):

    ## deposit to the vault after approving
    token.approve(vault, 2 ** 256 - 1, {"from": whale})
    vault.deposit(1000e18, {"from": whale})
    chain.sleep(1)
    strategy.harvest({"from": gov})
    chain.sleep(1)

    # deploy our new strategy
    new_strategy = guardian.deploy(StrategyUniverseStaking, vault, rewardscontract)
    total_old = strategy.estimatedTotalAssets()

    # migrate our old strategy
    vault.migrateStrategy(strategy, new_strategy, {"from": gov})

    # assert that our old strategy is empty
    updated_total_old = strategy.estimatedTotalAssets()
    assert updated_total_old == 0

    # harvest to get funds back in strategy
    new_strategy.harvest({"from": gov})
    new_strat_balance = new_strategy.estimatedTotalAssets()
    assert new_strat_balance >= total_old

    startingVault = vault.totalAssets()
    print("\nVault starting assets with new strategy: ", startingVault)

    # simulate nine days of earnings to make sure we hit at least one epoch of rewards
    chain.sleep(86400 * 9)
    chain.mine(1)

    # simulate a day of waiting for share price to bump back up
    chain.sleep(86400)
    chain.mine(1)

    # Test out our migrated strategy, confirm we're making a profit
    new_strategy.harvest({"from": gov})
    vaultAssets_2 = vault.totalAssets()
    assert vaultAssets_2 > startingVault
    print("\nAssets after 1 day harvest: ", vaultAssets_2)


import unittest
from dmLibrary import create_app
from dmLibrary.external.googleBook import GoogleBook
import time

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class TestBookClass(unittest.TestCase):
    def setUp(self):
        app = create_app()
        self.ctx = app.app_context()
        self.ctx.push()
        self.client = app.test_client()
        self.gb = GoogleBook()
        logger.debug('logged from test_something')

    def tearDown(self):
        """Do the testing """
        pass

    def test_postBook(self):
        """
        test post new book, try update, and delete it
        """

        data = {
            "title":"เรียนรู้วิถีชีวิต ประเพณี พิธีกรรม และความเชื่อแบบบูรณาการ",
            "isbn":"9748846709"
        }
        response = self.client.post('/api/v1/books',json=data)
        logger.info(f"rawResp: {response.data}")
        self.assertEqual(response.status_code, 201)
        respData = response.get_json()
        self.assertEqual(respData["data"]['title'], data['title'])
        self.assertEqual(respData["data"]['isbn'], data['isbn'])
        pageCount = self.gb.getPageCount(data["isbn"])
        self.assertEqual(respData["data"]['pageCount'], 159)
        logger.info(f"respData: {respData}")
        book_id = respData["data"]["id"]

        # try update the title
        data = {
            "title":"test update Book"
        }
        response = self.client.patch(f'/api/v1/books/{book_id}',json=data)
        logger.info(f"rawResp: {response.data}")
        self.assertEqual(response.status_code, 200)
        respData = response.get_json()
        self.assertEqual(respData["data"]['title'], data['title'])
        # delete it
        response = self.client.delete(f'/api/v1/books/{book_id}')
        logger.info(f"rawResp: {response.data}")
        self.assertEqual(response.status_code, 200)


import pandas as pd
from pyproj import Transformer
import matplotlib.pyplot as plt
import numpy as np
from typing import Tuple, Set, List

EARTH_RADIUS = 6378137.0
EARTH_CIRC_M = 2 * np.pi * EARTH_RADIUS
TILE_SIZE_PX = 256
METERS_PER_PIXEL_L0 = EARTH_CIRC_M / TILE_SIZE_PX
PYPROJ = Transformer.from_crs("EPSG:4326", "EPSG:3857")  # EPSG:900913 == EPSG:3857

# inspired from
# - https://www.maptiler.com/google-maps-coordinates-tile-bounds-projection/#5/150.51/68.42

def load_coords(filepath: str):
    """ Loads csv file with coordinates, and returns a numpy array with col-wise coordinates. """
    df = pd.read_csv(filepath, sep=',')
    coords_ll = df[['longitude', 'latitude']].to_numpy()
    coords_ll = coords_ll.transpose()
    return coords_ll

def ll_to_meters(coords_ll):
    # Converts given lat/lon in WGS84 Datum to XY in Spherical Mercator EPSG:3857 (aka EPSG:900913)
    coords_m = PYPROJ.transform(coords_ll[1], coords_ll[0])
    coords_m = np.array(coords_m)
    return coords_m

def meters_to_pixels(coords_m, level):
    # Converts EPSG:3857 to pyramid pixel coordinates in given zoom level
    coords_px = (coords_m + (EARTH_CIRC_M / 2.0)) / meters_per_pixel(level)
    return coords_px

def pixels_to_meters(coords_px, level):
    # Converts pixel coordinates in given zoom level to EPSG:3857
    coords_m = (coords_px * meters_per_pixel(level)) - (EARTH_CIRC_M / 2)
    return coords_m

def pixel_to_raster(coords_px, level):
    # Move the origin of pixel coordinates to top-left corner (like image)
    coords_rx = np.empty_like(coords_px)
    coords_rx[0] = coords_px[0]
    coords_rx[1] = map_size_px(level) - coords_px[1]
    return coords_rx

def raster_to_tile(coords_rx, tile_coord: Tuple[int, int]):
    # Move the origin of pixel coordinates to top-left corner (like image)
    # filter out points outside the tile
    bounds_rx = tile_bounds_rx(tile_coord)
    coords_ti = coords_rx - bounds_rx[:, 0:1]
    return coords_ti

def keep_in_tile_rx(coords_rx, tile_coord: Tuple[int, int]):
    bounds_rx = tile_bounds_rx(tile_coord)
    in_tile = np.vstack([
        coords_rx > bounds_rx[:, 0:1],
        coords_rx < bounds_rx[:, 2:3],
    ])
    in_tile = np.all(in_tile, axis=0)
    return coords_rx[:, in_tile]

def ll_to_raster(coords_ll, level):
    coords_m = ll_to_meters(coords_ll)
    coords_px = meters_to_pixels(coords_m, level=level)
    coords_rx = pixel_to_raster(coords_px, level=level)
    return coords_rx

def ll_to_tile(coords_ll, tile_coord: Tuple[int, int], level):
    coords_m = ll_to_meters(coords_ll)
    coords_px = meters_to_pixels(coords_m, level=level)
    coords_rx = pixel_to_raster(coords_px, level=level)
    coords_ti = raster_to_tile(coords_rx, tile_coord)
    return coords_ti

def nb_tiles(level: int):
    return 2 ** level

def get_tile_coord_list(level: int) -> List[Tuple[int, int]]:
    xx, yy = np.meshgrid(np.arange(nb_tiles(level)), np.arange(nb_tiles(level)))
    tile_coords = np.column_stack([xx.flatten(), yy.flatten()])
    tile_coords = [
        (x, y) for x, y in tile_coords
    ]
    return tile_coords

def map_size_px(level):
    return TILE_SIZE_PX << level

def tile_bounds_rx(tile_coords: Tuple[int, int]):
    # Returns bounds of the given tile in EPSG:900913 coordinates
    coords_tile = np.array([[tile_coords[0], tile_coords[1]]]).transpose()
    square = np.array([
        [0, 0],
        [1, 0],
        [1, 1],
        [0, 1]
    ]).transpose()

    coord_bounds_px = (square + coords_tile) * TILE_SIZE_PX
    return coord_bounds_px

def tile_set_rx(coords_rx: np.ndarray) -> Set[Tuple[int, int]]:
    # returns coordinates of tiles involved
    tile_coords = {(x, y) for x, y in np.floor(coords_rx / TILE_SIZE_PX).astype(int).transpose()}
    return tile_coords

def meters_per_pixel(level):
    # Resolution (meters/pixel) for given zoom level (measured at Equator)
    return METERS_PER_PIXEL_L0 / nb_tiles(level)


import numpy as np
import pandas as pd
import re
from itertools import chain
from IPython.display import Markdown, display
from more_itertools import unique_everseen

from src.davy_data_cleaning import *
from src.manasa_data_cleaning import *
from src.naomi_data_cleaning import *
from src.sara_data_cleaning import *

if __name__ == "__main__":
    #Reading the merged raw dataset from
    data = pd.read_csv('https://raw.githubusercontent.com/FrancescoMariottini/project3/main/inputs/all_sales_data.csv',sep=',',dtype='unicode')

    data['hyperlink'] = clean_hyperlink_column(data)
    data["postcode"] = postcodes_fun(data)
    data["house_is"] = house_is(data)
    data["property_subtype"] = process_property_types(data)
    data["price"] = clean_price_column(data)
    data["sale"] = clean_sale_column(data)
    data["rooms_number"] = process_num_rooms_col(data)
    data["area"] = process_area_col(data)
    data["kitchen_has"] = bool_to_bin("kitchen_has", int, data)
    data["furnished"] = bool_to_bin("furnished", int, data)
    data["open_fire"] = process_open_fire_col(data)
    data["terrace"] = process_terrace(data)
    data["terrace_area"] = process_terrace_area(data)
    data["garden"] = clean_garden_column(data)
    data["garden_area"] = clean_garden_area(data)
    data["land_surface"] = process_land_surf_col(data)
    data["land_plot_surface"] = process_land_plot_col(data)
    data["facades_number"] = facades_num(data)
    data["swimming_pool_has"] = clean_swimming_pool(data)
    data["building_state"] = process_building_state(data)

    #Drop duplicates
    data_dupes = data
    data_dupes = data_dupes.drop('source', axis=1)
    data_dupes = data_dupes.drop('hyperlink', axis=1)
    data_dupes = data_dupes.drop_duplicates()

    #Save the two final files
    data_dupes.to_csv('Datasets/final_with_dupes.csv')
    with open('Datasets/final_with_dupes.csv','r') as f, open('Datasets/final_no_dupes.csv','w') as out_file:
        out_file.writelines(unique_everseen(f))


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

#Agenda con base de datos Sqlite3
#www.pythondiario.com
#Autor: Diego Caraballo

#Modulos importados
import sqlite3
import time
import os

#Conexion con Base de Datos Sqlite3
con = sqlite3.connect("agenda.db")
cursor = con.cursor()
#Comprueba si la tabla existe, en caso de no existir la crea
cursor.execute("""CREATE TABLE IF NOT EXISTS datos (nombre TEXT, telefono TEXT, correo
    TEXT, dire TEXT,empresa TEXT,departamento TEXT,  vigente TEXT, id INTEGER PRIMARY KEY AUTOINCREMENT )""")

cursor.close()

#Declaracion de las funciones

def limpiar():

    """Limpia la pantalla"""

    if os.name == "posix":
        os.system("clear")
    elif os.name == ("ce", "nt", "dos"):
        os.system("cls")

def agregar():

    """Agrega un nuevo contacto a la Agenda"""

    print ("Agregar contacto")
    print ("----------------")
    print ("")

    con = sqlite3.connect("agenda.db")
    cursor = con.cursor()

    nombre = input("Nombre: ")
    telefono = input("Telefono: ")
    correo  = input("Correo: ")
    dire    = input("Direccion: ")
    empresa    = input("Empresa: ")
    departamento    = input("departamento: ")
    vigente = input("vigente (1) No (0): ")

    cursor.execute("insert into datos (nombre, telefono, correo, dire, empresa, departamento, vigente) \
        values ('%s','%s','%s','%s','%s','%s','%s')"%(nombre,telefono,correo,dire,empresa,departamento,vigente))

    con.commit()

    print ("Los datos fueron agregados correctamente")

    cursor.close()
    time.sleep(2)
    main()

def ver():

    """Devuelve todos los contactos de la agenda"""

    print ("Lista de contactos")
    print ("------------------")
    print ("")

    con = sqlite3.connect("agenda.db")
    cursor = con.cursor()

    cursor.execute("SELECT * FROM datos")
    resultado = cursor.fetchall()

    for i in resultado:
        #print ("%s %s %s %s %s" % (i[0],i[1],i[2],i[3],i[5]))
        print (i[0].ljust(80),i[1].ljust(30),i[2].ljust(40),i[3],i[5],sep="|")

    cursor.close()

    print ("")
    input("Presione una tecla para continuar...")

    main()

def buscar():

    """Busca un contacto en la agenda y lo lista"""

    print ("Buscar contacto")
    print ("---------------")
    print ("")

    con = sqlite3.connect("agenda.db")
    cursor = con.cursor()

    buscar = input("Nombre a buscar: ")
    consulta="SELECT * FROM datos WHERE nombre LIKE '%"+buscar+"%'"
    cursor.execute (consulta)

    x = cursor.fetchall()

    print ("")

    for i in x:
        print (i[0].ljust(80),i[1].ljust(30),i[2].ljust(40),i[3],i[5],sep="|")

        print ("")

    cursor.close()

    print ("")
    input("Presione una tecla para continuar...")

    main()

def eliminar():

    """Elimina un contacto de la Agenda"""

    print ("Eliminar contacto")
    print ("-----------------")
    print ("")

    con = sqlite3.connect("agenda.db")
    cursor = con.cursor()

    eliminar = input ("Nombre de contacto a eliminar: ")

    cursor.execute("DELETE FROM datos WHERE nombre='%s'"%(eliminar))

    con.commit()

    cursor.close()

    print ("Contacto eliminao correctamente...")
    input()
    main()

def main():

    """Funcion principal de la Agenda"""

    limpiar()

    print ("-----------------------------------------")
    print ("Esta es la agenda de www.MarstonSoftware.com")
    print ("-----------------------------------------")
    print ("                              Version 1.0")
    print ("""
    [1] Ingresar Contacto
    [2] Listar Contactos
    [3] Buscar Contacto
    [4] Eliminar Contacto
    [0] Salir
    """)

    opcion = input("Ingresa una opción -> ")

    if opcion != "1" and opcion != "2" and opcion != "3" and opcion != "4" and opcion != "5" and opcion != "0":
        print ("Opcion incorrecta")
        input()
        main()
    elif opcion == "1":
        limpiar()
        agregar()
    elif opcion == "2":
        limpiar()
        ver()
    elif opcion == "3":
        limpiar()
        buscar()
    elif opcion == "4":
        limpiar()
        eliminar()
    elif  opcion == "0":
        print ("")
        print ("Bye...")
        print ("No te olvides de visitar www.MarstonSoftware.com :")
        print ("")
        print ("")
        time.sleep(3)
        exit()

main()


import time
import celery.result
import requests

from funboost import boost, BrokerEnum
from funboost.assist.celery_helper import CeleryHelper

@boost('tets_funboost_celery_queue31a5', broker_kind=BrokerEnum.CELERY, concurrent_num=10,is_print_detail_exception=False,
       broker_exclusive_config={'celery_app_config':
                                    {'task_default_rate_limit': '1/s', }}
       )
def fa(x, y):
    time.sleep(3)
    print(6666, x, y)
    requests.get('123')
    1/0
    return x + y

@boost('tets_funboost_celery_queue31b', broker_kind=BrokerEnum.CELERY, concurrent_num=10,
       broker_exclusive_config={'celery_app_config':
                                    {'task_default_rate_limit': '2/s', }}
       )
def fb(a, b):
    time.sleep(2)
    print(7777, a, b)
    return a - b

if __name__ == '__main__':
    fa.consume()
    # fb.consume()

    for i in range(1):
        r = fa.push(i, i + 1)  # type: celery.result.AsyncResult
        # print(type(r), r)
        # print(r.get())
        # fb.push(i, i * 2)

    CeleryHelper.realy_start_celery_worker()

'''

linux celery 报错EntryPoints‘ object has no attribute ‘get‘ ，这么做
https://blog.csdn.net/weixin_73672704/article/details/129477312

pip install frozenlist==1.3.1 geopy==2.2.0 humanize==4.3.0 idna==3.3 importlib-metadata==4.12.0 jsonschema==4.9.0 korean_lunar_calendar==0.2.1 marshmallow==3.17.0 pyOpenSSL==22.0.0 pyrsistent==0.18.1 python-dotenv==0.20.0 pytz==2022.2.1 selenium==4.4.0 simplejson==3.17.6 sniffio==1.2.0 trio==0.21.0 urllib3==1.26.11 wsproto==1.1.0 zipp==3.8.1

# 如果上述安装仍未解决, 则执行以下安装(笔者执行完上述安装即能解决问题)
pip install backoff==2.1.2 colorama==0.4.5 croniter==1.3.5 cryptography==37.0.4 email-validator==1.2.1 flask-compress==1.12 flask-migrate==3.1.0 aiohttp==3.8.1 aiosignal==1.2.0 Mako==1.2.1 Babel==2.10.3

'''


import tempfile
import pandas as pd
from loguru import logger
from typing import BinaryIO

from app.sellers_scraper.amazon import scrape_amazon
from app.sellers_scraper.flipkart import scrape_flipkart
from app.sellers_scraper.myntra import scrape_myntra

def write_to_excel(
    amazon_sellers: list[str],
    flipkart_sellers: list[str],
    myntra_sellers: list[str],
    filename: str,
) -> None:
    amazon_df = pd.DataFrame(
        amazon_sellers,
        columns=["Rating", "Seller Name", "Seller Address"],
    )

    flipkart_df = pd.DataFrame(
        flipkart_sellers,
        columns=["Rating", "Seller Name", "Manufacturer Address", "Packer Address"],
    )

    myntra_df = pd.DataFrame(
        myntra_sellers,
        columns=[
            "Seller Name",
            "Seller Address",
            "Importer Address",
            "Manufacturer Address",
            "Packer Address",
        ],
    )

    with pd.ExcelWriter(filename) as writer:
        if amazon_sellers:
            amazon_df.drop_duplicates(inplace=True)
            amazon_df.to_excel(writer, sheet_name="Amazon", index=None)

        if flipkart_sellers:
            flipkart_df.drop_duplicates(inplace=True)
            flipkart_df.to_excel(writer, sheet_name="Flipkart", index=None)
        if myntra_sellers:
            myntra_df.drop_duplicates(inplace=True)
            myntra_df.to_excel(writer, sheet_name="Myntra", index=None)

def main(excel_file: BinaryIO, filename: str) -> None:
    with tempfile.NamedTemporaryFile(delete=False) as temp_file:
        lines = excel_file.readlines()
        temp_file.writelines(lines)
        temp_file.seek(0)

        amazon_sellers = []
        flipkart_sellers = []
        myntra_sellers = []

        df = pd.read_excel(temp_file)
        product_urls = df["URLs"].dropna().to_list()

        for product_url in product_urls:
            if "amazon" in product_url:
                amazon_sellers += scrape_amazon(product_url)
            elif "flipkart" in product_url:
                flipkart_sellers += scrape_flipkart(product_url)
            elif "myntra" in product_url:
                myntra_sellers += scrape_myntra(product_url)
            else:
                logger.error("invalid url")

        write_to_excel(amazon_sellers, flipkart_sellers, myntra_sellers, filename)


from django import template
from staff.models import Staff
register = template.Library()

@register.simple_tag
def get(value):

    try:
        name = Staff.objects.filter(company=value)
    except Staff.DoesNotExist:
        name = 'vacant'

    return name

# register.filter('get', get)


# -*- coding: utf-8 -*-
"""
Created on Thu Jul  7 16:26:12 2022

@author: jhd9252

title: 11 container with most water

You are given an integer array height of length n. There are n vertical lines
drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the
container contains the most water.

Return the maximum amount of water a container can store.

Notice that you may not slant the container.

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7].
In this case, the max area of water (blue section) the container can contain is 49.

Constraint:
    n == height.length
    2 <= n <= 105
    0 <= height[i] <= 104
"""

class Solution:
    def maxArea(self, height) -> int:

        """
        # brute force for loops
        # time limit exceeded
        res = 0
        for i in range(len(height)):
            for j in range(i+1, len(height)):
                area = (j - i) * min(height[i], height[j])
                res = max(res, area)
        return res
        """

        # two pointer solution
        # update pointers based on the limiting factors of distance and min(height)
        # since the pointers - > factor of distance
        # then shift pointers based on min(height)
        # O(n) running time complexity
        res = 0
        l, r = 0, len(height) - 1
        while l < r:
            area = (r - l) * min(height[l], height[r])
            res = max(res, area)
            if height[l] < height[r]:
                l += 1
            else:
                # else left > right, or l == r.
                r -= 1
        return res


from pathlib import Path

import pytest
import numpy as np

from cgmml.common.depthmap_toolkit.depthmap import Depthmap
from cgmml.common.depthmap_toolkit.visualisation import blur_face, render_rgb, CHILD_HEAD_HEIGHT_IN_METERS

TOOLKIT_DIR = Path(__file__).parents[0].absolute()
OFFSET_X_Y = (0.37, 0.53)
DEPTHMAP_DIR = TOOLKIT_DIR / 'huawei_p40pro'
DEPTHMAP_FPATH = DEPTHMAP_DIR / 'depth' / 'depth_dog_1622182020448_100_282.depth'
RGB_FPATH = DEPTHMAP_DIR / 'rgb' / 'rgb_dog_1622182020448_100_282.jpg'
CALIBRATION_FPATH = str(TOOLKIT_DIR / 'huawei_p40pro' / 'camera_calibration.txt')

def test_blur_face():
    dmap = Depthmap.create_from_zip_absolute(DEPTHMAP_FPATH, RGB_FPATH, CALIBRATION_FPATH)

    # Find top of the object
    floor = dmap.get_floor_level()
    assert floor == pytest.approx(-0.9706086, 0.001)
    mask = dmap.segment_child(floor)
    highest_point = dmap.get_highest_point(mask)  # 3D

    # Render the color data
    output_unblurred = render_rgb(dmap)

    # Blur
    output_blurred = blur_face(output_unblurred, highest_point, dmap, CHILD_HEAD_HEIGHT_IN_METERS)

    # Assert some pixels in whole image change (image not same)
    all_count = dmap.width * dmap.height
    count = np.count_nonzero(output_unblurred - output_blurred) / 3
    ratio_blurred = count / all_count
    assert 0.01 < ratio_blurred < 0.9

    # Assert that blurred around object
    object_x = int(dmap.width * OFFSET_X_Y[0])
    object_y = int(dmap.height * (1.0 - OFFSET_X_Y[1]))
    slice_x = slice(object_x - 2, object_x + 2)
    slice_y = slice(object_y - 2, object_y + 2)
    assert (output_unblurred[slice_x, slice_y] != output_blurred[slice_x, slice_y]).any()

    # Assert that NOT blurred around corner
    corner_x = 0
    corner_y = 0
    slice_x = slice(corner_x, corner_x + 4)
    slice_y = slice(corner_y, corner_y + 4)
    np.testing.assert_array_equal(output_unblurred[slice_x, slice_y], output_blurred[slice_x, slice_y])

if __name__ == "__main__":
    test_blur_face()


from collections import deque

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

n = int(input())
a = [list(map(int, input())) for _ in range(n)]
result = [[0]*n for _ in range(n)]

q = deque()
check = [[False] * n for _ in range(n)]

def bfs(sx, sy, number):
  check[sx][sy] = True
  result[sx][sy] = number
  q.append((sx, sy))

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

    for k in range(4):
      nx, ny = x+dx[k], y+dy[k]

      if 0 <= nx < n and 0 <= ny < n:
        if not check[nx][ny] and a[nx][ny] == 1:
          result[nx][ny] = number
          check[nx][ny] = True
          q.append((nx, ny))

number = 0
for i in range(n):
  for j in range(n):
    if a[i][j] == 1 and not check[i][j]:
      number += 1
      bfs(i, j, number)

print(number)

number_count = []

for i in range(1, number+1):
  count = 0
  for j in range(n):
    for k in range(n):
      if result[j][k] == i:
        count += 1

  number_count.append(count)
number_count.sort()
for el in number_count:
  print(el)


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

x = pylab.arange(-2, 2, 0.1)
sin_ = pylab.sin(x)
cos_ = pylab.cos(x)

pylab.subplot(211)
pylab.plot(x, sin_, 'r-')
pylab.plot(x, cos_, 'b-.')
pylab.legend(('testsin', 'cos'), 'upper left')

pylab.subplot(212)
pylab.plot(x, sin_, 'm-', label="simulation")
pylab.plot(x, cos_, 'g-.', label="test") #プロットデータ指定
pylab.legend(loc = 'upper left')
pylab.suptitle('legend test', fontsize=30)
pylab.show()


from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import TimeSeriesSplit
from sklearn.metrics import mean_squared_error
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

class BlockingTimeSeriesSplit():
    def __init__(self, n_splits):
        self.n_splits = n_splits

    def get_n_splits(self, X, y, groups):
        return self.n_splits

    def split(self, X, y=None, groups=None):
        n_samples = len(X)
        k_fold_size = n_samples // self.n_splits
        indices = np.arange(n_samples)

        margin = 0
        for i in range(self.n_splits):
            start = i * k_fold_size
            stop = start + k_fold_size
            mid = start + int(0.9 * (stop - start))
            yield indices[start: mid], indices[mid + margin: stop]

def grid_search_param(X, y, estimator, grid, k_fold, verbose=1):
    tscv = TimeSeriesSplit(n_splits=k_fold, gap=3, test_size=4)
    RSCV = GridSearchCV(estimator=estimator,
                        param_grid=grid,
                        cv=tscv,
                        n_jobs=-1,
                        scoring='neg_root_mean_squared_error',
                        refit=True,
                        verbose=verbose,
                        pre_dispatch=8,
                        error_score=-999,
                        return_train_score=True)
    RSCV.fit(X, y)
    return RSCV.best_params_, RSCV.best_score_, RSCV.best_estimator_

def optimal_params(X, y, estimator, grid, fold_range, verbose=1):
    best_score = -100000
    for k_fold in fold_range:
        param, score, model = grid_search_param(X,
                                         y,
                                         estimator,
                                         grid,
                                         k_fold,
                                         verbose)
        # scoring: neg_root_mean_squared_error
        if score > best_score:
            best_score = score
            best_param = param
            k = k_fold
            best_model = model

    return k, best_param, best_score, model

def fit_check(y, y_pred, plot=True):
    rmse = np.sqrt(mean_squared_error(y, y_pred))
    if plot:
        plt.plot(y.index, y, label="true value")
        plt.legend()
        plt.xticks(y.index[::100])
        plt.xlabel("")
        plt.ylabel("bitcoin return")
        plt.plot(y.index, y_pred, label="prediction")
        plt.legend()
        plt.show()
    return rmse

def reg_feature_select(coef, features, level=0):
    identify = coef != 0
    model_features = features[identify]
    model_coef = coef[identify]
    model_importance = pd.DataFrame({'features': model_features,
                                     'coef': model_coef}).sort_values('coef', key=abs)

    aggregate = model_importance.coef.apply(lambda x: abs(x)).sum()
    model_importance['importance_ratio'] = model_importance.coef.apply(lambda x: abs(x)/aggregate)
    index = np.where((model_importance['importance_ratio'] >= level).to_numpy() == True)
    model_importance = model_importance.iloc[index]
    plt.figure(figsize=(20,10))
    plt.barh(model_importance.features, model_importance.importance_ratio)
    plt.xlabel("importance")
    plt.ylabel("features")
    plt.show()
    return model_importance

def pca_analysis(X, y, model):
    scaler = StandardScaler()
    y_scaled = pd.DataFrame(scaler.fit_transform(y),
                            columns=y.columns)
    pca_range = range(2, 70)
    rmses = []

    for i in pca_range:
        pca = PCA(n_components=i).fit_transform(X)
        columns = [f"pca{i}" for i in range(pca.shape[1])]
        X_pca = pd.DataFrame(pca, columns=columns)

        model = model.fit(X_pca, y_scaled)
        y_pred = pd.DataFrame(model.predict(X_pca))
        y_pred = pd.DataFrame(scaler.inverse_transform(y_pred), columns=y.columns)
        rmses.append(fit_check(y, y_pred, plot=False))
    plt.plot(rmses)
    plt.xlabel("number of PCA")
    plt.ylabel("RMSE")
    plt.show()
    return rmses

def tree_feature_select(model, features, level):
    feature_importance = pd.DataFrame(
        model.feature_importances_,
        index=features,
        columns=["importance"]).sort_values("importance", ascending=True
    )
    index = np.where((feature_importance.importance >= level).to_numpy() == True)
    df = feature_importance.iloc[index]
    plt.barh(df.index, df.importance)

    return feature_importance.iloc[index].index

def output_html(path, table):
    with open(path,'w') as f:
        f.write(table.as_html())


import os
import cv2 as cv
import shutil
import configparser
import sys

flag = False
rect = [0, 0, 0, 0]
rects=[]
img = []
img1 = []
txt = []
w = 23
h = 32
hf = False
wf = False

def Draw2(events, x, y, flags, param):
    global flag, img, img1, txt, w, h, hf, wf
    if events == cv.EVENT_LBUTTONDOWN:
        txt.write(
            str(x) + ' ' + str(y) + ' ' + str(x + w) + ' ' + str(y + h) + '\n')
        cv.rectangle(img1, (x, y), (x + w, y + h), (80, 80, 80), 1)

    if events == cv.EVENT_MOUSEMOVE:
        img3 = img1.copy()
        img = img3.copy()
        img2 = img1.copy()
        cv.rectangle(img2, (x, y), (x + w, y + h), (0, 0, 0), 1)
        img = img2.copy()

    if events == cv.EVENT_MOUSEWHEEL:
        pass

def Draw(events, x, y, flags, param):
    global flag, rect, rects, img, img1, txt
    if events == cv.EVENT_LBUTTONDOWN:
        rect[0] = x
        rect[1] = y
        flag = True
    elif events == cv.EVENT_LBUTTONUP:
        flag = False
        rects.append(rect.copy())
        #print(rects)
        cv.rectangle(img1, (rect[0], rect[1]), (rect[2], rect[3]),
                     (70, 70, 70), 1)
    if events == cv.EVENT_MOUSEMOVE:
        img3 = img1.copy()
        cv.line(img3, (0, y), (655, y), (30, 30, 30), 1)
        cv.line(img3, (x, 0), (x, 489), (30, 30, 30), 1)
        img = img3.copy()
        if flag:
            rect[2] = x
            rect[3] = y
            img2 = img1.copy()
            cv.rectangle(img2, (rect[0], rect[1]), (rect[2], rect[3]),
                         (0, 0, 0), 1)
            img = img2.copy()

def MakeConfig():
    cf=configparser.ConfigParser()
    cf.add_section('dir')
    cf.set('dir','images_dir','images')
    cf.set('dir','outputs_dir','outputs')
    cf.set('dir','tmp_dir','tmp')

    cf.add_section('label')
    cf.set('label','prefix','20181215')
    cf.set('label','postfix','T3a')
    cf.set('label','length','15')

    cf.add_section('flag')
    cf.set('flag','move2tmp','1')
    cf.set('flag','update_fix','1')

    cf.add_section('image')
    cf.set('image','type','bmp')

    cf.write(open('annotation.config','w'))

if not os.path.exists('annotation.config'):
    MakeConfig()

cf=configparser.ConfigParser()
cf.read('annotation.config')

imagesDir=cf.get('dir','images_dir')
outputsDir=cf.get('dir','outputs_dir')
tmpDir=cf.get('dir','tmp_dir')

imgtype=cf.get('image','type')

labellen=cf.getint('label','length')

isMoveToTmp=cf.getint('flag','move2tmp')
isUpdateFix=cf.getint('flag','update_fix')

if not os.path.exists(imagesDir):
    imagesDir=input('Please enter the images directory: ')
    cf.set('dir','imagesDir',images_dir)
    cf.write(open('annotation.config','w'))
if not os.path.exists(outputsDir):
    os.mkdir('outputs')
if not os.path.exists(tmpDir):
    os.mkdir('tmp')

cv.namedWindow('annotations', cv.WINDOW_NORMAL)
cv.setMouseCallback('annotations', Draw)
imgs = os.listdir(imagesDir)
cnt = len(imgs)
for imgn in imgs:
    print(imagesDir+'/'+imgn, cnt)
    cnt -= 1

    cf.read('annotation.config')
    prefix=cf.get('label','prefix')
    postfix=cf.get('label','postfix')
    print(prefix)
    lenpre=len(prefix)
    lenpost=len(postfix)

    txt = open(outputsDir+'/' + imgn.split('.')[0] + '.txt', 'w')
    img = cv.imread(imagesDir+'/' + imgn)
    img1 = img.copy()
    while (1):
        keyin = -1
        cv.imshow('annotations', img)
        keyin = cv.waitKey(100)
        #if keyin & 0xFF >0 and keyin & 0xFF<255:
         #   print(keyin)
        if keyin & 0xFF == 27:  #esc
            sys.exit()
        if keyin & 0xFF == 13 and len(prefix) == len(rects):
            #print(rects)
            for i in range(len(rects)):
                rect_=rects[i]
                txt.write((prefix+postfix)[i]+' '+str(rect_[0]) + ' ' + str(rect_[1]) + ' ' + str(rect_[2]) + ' ' +str(rect_[3]) + '\n')
            txt.close()
            if isMoveToTmp != 0:
                shutil.move(imagesDir+'/' + imgn, tmpDir+'/' + imgn)
            print('ok: '+prefix)
            rects=[]
            break
        if keyin & 0xFF == 13 and len(prefix) != len(rects):  # Enter
            txt.close()
            count = 0
            break
        if keyin & 0xFF >= 48 and keyin & 0xFF <= 120:
            prefix += chr(keyin)
            if len(prefix)==lenpre and isUpdateFix!=0:
                cf.set('label','prefix',prefix)
                cf.write(open('annotation.config','w'))
            if len(prefix)==labellen and isUpdateFix!=0:
                postfix=prefix[labellen-lenpost:]
                cf.set('label','postfix',postfix)
                cf.write(open('annotation.config','w'))
            print(prefix+'\n')
            cv.putText(img, prefix, (50, 50), cv.FONT_HERSHEY_COMPLEX, 1,
                       (0, 0, 0), 2)
        #if len(prefix+postfix) == labellen:
         #   prefix += postfix
          #  cv.putText(img, prefix, (50, 50), cv.FONT_HERSHEY_COMPLEX, 1,
           #            (0, 0, 0), 2)
        if keyin & 0xFF == 8:
            prefix = prefix[:-1]
            img5=img1.copy()
            cv.putText(img5, postfix + prefix, (80, 80), cv.FONT_HERSHEY_COMPLEX, 1,
                       (0, 0, 0), 2)
            img=img5
            print(prefix+'\n')
cv.destroyAllWindows()


# import cv2

# cap = cv2.VideoCapture(2)

# num = 0

# while cap.isOpened():

#     succes, img = cap.read()

#     k = cv2.waitKey(5)

#     if k == 27:
#         break
#     elif k == ord('s'): # wait for 's' key to save and exit
#         cv2.imwrite('images/img' + str(num) + '.png', img)
#         print("image saved!")
#         num += 1

#     cv2.imshow('Img',img)

# # Release and destroy all windows before termination
# cap.release()

# cv2.destroyAllWindows()
# #

# import cv2

# cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
# cap.set(cv2.CAP_PROP_FRAME_WIDTH, 2028)
# cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1520)

# num = 0

# while cap.isOpened():

#     success, img = cap.read()

#     k = cv2.waitKey(5)

#     if k == 27:
#         break
#     elif k == ord('s'): # wait for 's' key to save and exit
#         cv2.imwrite('img' + str(num) + '.png', img)
#         print("image saved!")
#         num += 1

#     cv2.imshow('Img',img)

# # Release and destroy all windows before termination
# cap.release()
# cv2.destroyAllWindows()

import time
import picamera

# Create a new PiCamera object
camera = picamera.PiCamera()

# Set the resolution of the camera
camera.resolution = (1024, 768)

# Set the preview window size
camera.start_preview(fullscreen=False, window=(0, 0, 1024, 768))

# Capture multiple images
for i in range(1, 15):
    # Wait for the preview to initialize
    time.sleep(10)
    # Capture an image and save it to a file
    camera.capture(f'img{i}.jpg')
    print('done',i )
# Stop the preview
camera.stop_preview()


import os

RED = '\033[41m'
GREEN = '\033[42m'
NC = '\033[0m'
WHITE = '\033[47m'
BLUE = '\033[44m'
G = '\U0001F608'
G_ = '\U0001F480'
P = '\U0001F47D'
F = '\U0001F353'

def display(row,col,mat,pac,ghost,time,f):
	#os.system('clear')
	if len(f):
		for i,j in f:
			mat[i][j] = 'f'
	mat[pac[0]][pac[1]] = 'p'
	for i,j in ghost:
		if (time and (i,j) == (pac[0],pac[1])) == False:
			mat[i][j] = 'g'
	d1 = 'tput cup '
	d2 = ' 30'
	i = 8
	for x in range(row):
		s = ''
		d = d1 + str(i) + d2
		os.system(d)
		for y in range(col):
			if(mat[x][y] == ' '):
				s += WHITE + '  ' + NC
				#print(WHITE + '.' + NC),
			elif(mat[x][y] == '#'):
				s += GREEN + '  ' + NC
				#print(GREEN + '#' + NC),
			elif(mat[x][y] == 'g'):
				#s += RED + '  ' + NC
				if time:
					s += WHITE + G_ + NC
				else:
					s += WHITE + G + NC
			elif(mat[x][y] == 'p') :
				s += WHITE + P + NC
			else:
				s += WHITE + F + NC
		print(s)
		i += 1
	os.system('sleep 0.3')


__author__ = 'mnowotka'

from tastypie import http
from tastypie import fields
from tastypie.resources import ALL
from chembl_webservices.core.resource import ChemblModelResource
from chembl_webservices.core.meta import ChemblResourceMeta
from chembl_webservices.core.serialization import ChEMBLApiSerializer
from chembl_webservices.core.utils import NUMBER_FILTERS, CHAR_FILTERS, FLAG_FILTERS
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Prefetch

try:
    from chembl_compatibility.models import TargetRelations
except ImportError:
    from chembl_core_model.models import TargetRelations
try:
    from chembl_compatibility.models import ChemblIdLookup
except ImportError:
    from chembl_core_model.models import ChemblIdLookup
try:
    from chembl_compatibility.models import TargetDictionary
except ImportError:
    from chembl_core_model.models import TargetDictionary

from chembl_webservices.core.fields import monkeypatch_tastypie_field
monkeypatch_tastypie_field()

# ----------------------------------------------------------------------------------------------------------------------

class TargetRelationsResource(ChemblModelResource):

    target_chembl_id = fields.CharField('target__chembl_id')
    related_target_chembl_id = fields.CharField('related_target__chembl_id')

    class Meta(ChemblResourceMeta):
        queryset = TargetRelations.objects.all()
        excludes = ['targrel_id']
        resource_name = 'target_relation'
        collection_name = 'target_relations'
        serializer = ChEMBLApiSerializer(resource_name, {collection_name: resource_name})
        detail_uri_name = 'target__chembl_id'
        prefetch_related = [
            Prefetch('target', queryset=TargetDictionary.objects.only('chembl')),
            Prefetch('related_target', queryset=TargetDictionary.objects.only('chembl')),
        ]

        fields = (
            'relationship',
        )

        filtering = {
            'target_chembl_id': NUMBER_FILTERS,
            'related_target_chembl_id': CHAR_FILTERS,
            'relationship': CHAR_FILTERS,
        }
        ordering = [field for field in filtering.keys() if not ('comment' in field or
                                                                'description' in field or 'canonical_smiles' in field)]

# ----------------------------------------------------------------------------------------------------------------------

    def get_detail_impl(self, request, basic_bundle, **kwargs):
        """
        Returns a single serialized resource.

        Calls ``cached_obj_get/obj_get`` to provide the data, then handles that result
        set and serializes it.

        Should return a HttpResponse (200 OK).
        """

        try:
            obj, in_cache = self.cached_obj_get_list(bundle=basic_bundle, **self.remove_api_resource_names(kwargs))
            objects = obj.get('target_relations', [])
        except ObjectDoesNotExist:
            return http.HttpNotFound()

        if len(objects) == 1:
            object = objects[0]
            bundle = self.build_bundle(obj=object, request=request)
            bundle = self.full_dehydrate(bundle, **kwargs)
            bundle = self.alter_detail_data_to_serialize(request, bundle)
            return self.create_response(request, bundle)
        else:
            bundles = []

            for ob in obj[self._meta.collection_name]:
                bundle = self.build_bundle(obj=ob, request=request)
                bundles.append(self.full_dehydrate(bundle, for_list=True, **kwargs))

            obj[self._meta.collection_name] = bundles
            obj = self.alter_list_data_to_serialize(request, obj)

            return obj, in_cache

# ----------------------------------------------------------------------------------------------------------------------


import os
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
import sys
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from visualizers import BCVisualizer
from data_io import read_features
from cnn import myMLP

# データフォルダ
DATA_DIR = './dataset/Example/'

# ダミーデータを対象とするか否か
USING_DMY = False

# エントリポイント
if __name__ == '__main__':

    # コマンドライン引数のパース
    parser = argparse.ArgumentParser(description='Example of Perceptron')
    parser.add_argument('--gpu', '-g', default=-1, type=int, help='GPU ID (negative value indicates CPU)')
    parser.add_argument('--epochs', '-e', default=50, type=int, help='number of epochs to learn')
    parser.add_argument('--batchsize', '-b', default=100, type=int, help='learning minibatch size')
    parser.add_argument('--v_interval', '-v', default=5, type=int, help='visualization interval')
    args = parser.parse_args()

    # デバイスの設定
    dev_str = 'cuda:{0}'.format(args.gpu) if torch.cuda.is_available() and args.gpu >= 0 else 'cpu'
    dev = torch.device(dev_str)

    # オプション情報の設定・表示
    epochs = max(1, args.epochs) # 総エポック数（繰り返し回数）
    batchsize = max(1, args.batchsize) # バッチサイズ
    visualization_interval = max(0, args.v_interval) # 何エポックごとに可視化結果を表示するか
    print('device: {0}'.format(dev_str), file=sys.stderr)
    print('epochs: {0}'.format(epochs), file=sys.stderr)
    print('batchsize: {0}'.format(batchsize), file=sys.stderr)
    print('visualization interval: {0}'.format(visualization_interval), file=sys.stderr)
    print('', file=sys.stderr)

    # データの読み込み
    if USING_DMY == False:
        # 男女別身長／体重データを対象とする場合
        labels, features, labeldict, labelnames = read_features(DATA_DIR + 'whg_train.csv') # 学習データ読み込み
        labels_ev, features_ev, labeldict, dmy = read_features(DATA_DIR + 'whg_test.csv', dic=labeldict) # 評価用データ読み込み
    else:
        # ダミーデータを対象とする場合
        labels, features, labeldict, labelnames = read_features(DATA_DIR + 'dmy_train.csv') # 学習データ読み込み
        labels_ev, features_ev, labeldict, dmy = read_features(DATA_DIR + 'dmy_test.csv', dic=labeldict) # 評価用データ読み込み
    labels = np.asarray(labels, dtype=np.int32)
    labels_ev = np.asarray(labels_ev, dtype=np.int32)
    features = np.asarray(features, dtype=np.float32)
    features_ev = np.asarray(features_ev, dtype=np.float32)
    n_samples = features.shape[0] # 学習データの総数
    n_samples_ev = features_ev.shape[0] # 評価用データの総数
    n_dims = features.shape[1] # データの次元数
    n_classes = len(labeldict) # クラス数

    # 二クラス識別器の作成
    model = myMLP(n_dims)
    model = model.to(dev)

    # 可視化の準備
    NUM = 100 # 可視化結果に重畳する実データの数
    a = np.min(features_ev, axis=0)
    b = np.max(features_ev, axis=0)
    perm = np.random.permutation(n_samples_ev)
    hrange = ((11 * a[0] - b[0]) / 10, (11 * b[0] - a[0]) / 10) # 可視化結果における横軸の範囲
    vrange = ((11 * a[1] - b[1]) / 10, (11 * b[1] - a[1]) / 10) # 可視化結果における縦軸の範囲
    data = [labels_ev[perm[ : NUM]], features_ev[perm[ : NUM]]] # 可視化結果に重畳する実データ（評価用データからランダムに NUM 個を選択）
    if USING_DMY == False:
        visualizer_hlabel = 'height (cm)' # 可視化結果における横軸のラベル
        visualizer_vlabel = 'weight (kg)' # 可視化結果における縦軸のラベル
    else:
        visualizer_hlabel = 'data 1'
        visualizer_vlabel = 'data 2'
    visualizer = BCVisualizer(hrange=hrange, vrange=vrange, hlabel=visualizer_hlabel, vlabel=visualizer_vlabel, clabels=labelnames)

    # 初期状態の可視化
    if visualization_interval > 0:
        visualizer.show(model, device=dev, samples=data, title='Initial State') # グラフを表示

    # 損失関数の定義
    loss_func = nn.CrossEntropyLoss() # softmax cross entropy

    # オプティマイザーの用意
    optimizer = optim.Adam(model.parameters())

    # 学習処理ループ
    for e in range(epochs):

        # 現在のエポック番号を表示
        print('Epoch {0}'.format(e + 1), file=sys.stderr)

        # 損失関数の値が小さくなるように識別器のパラメータを更新
        model.train()
        perm = np.random.permutation(n_samples)
        sum_loss = 0
        for i in range(0, n_samples, batchsize):
            model.zero_grad()
            x = torch.tensor(features[perm[i : i + batchsize]], device=dev)
            t = torch.tensor(labels[perm[i : i + batchsize]], device=dev, dtype=torch.long)
            loss = loss_func(model(x), t)
            loss.backward()
            optimizer.step()
            sum_loss += float(loss) * len(x)
            del loss
            del t
            del x

        # 損失関数の現在値を表示
        print('  train loss = {0:.4f}'.format(sum_loss / n_samples), file=sys.stderr)

        # 評価用データに対する識別精度を計算・表示
        model.eval()
        n_failed = 0
        for i in range(0, n_samples_ev, batchsize):
            x = torch.tensor(features_ev[i : i + batchsize], device=dev)
            t = torch.tensor(labels_ev[i : i + batchsize], device=dev, dtype=torch.long)
            y = model(x)
            y = y.to('cpu').detach().numpy().copy()
            t = t.to('cpu').detach().numpy().copy()
            n_failed += np.count_nonzero(np.argmax(y, axis=1) - t)
            del y
            del x
            del t
        acc = (n_samples_ev - n_failed) / n_samples_ev
        print('  accuracy = {0:.2f}%'.format(100 * acc), file=sys.stderr)

        # 現状態の可視化
        if visualization_interval > 0 and (e + 1) % visualization_interval == 0:
            visualizer.show(model, device=dev, samples=data, title='Epoch {0}'.format(e + 1)) # グラフを表示

        print('', file=sys.stderr)

    print('', file=sys.stderr)


import os
import wget
import numpy as np

# Function for downloading data files from Zenodo
def download_zenodo():

   if os.path.exists("MatlabData"):
       pass
   else:
       print("Downloading files from Zenodo ... ")
       os.mkdir("MatlabData")
       # Powder Phantom Data
       wget.download("https://zenodo.org/record/5825464/files/Powder_phantom_180s_180Proj_sinogram.mat", out="MatlabData")
       wget.download("https://zenodo.org/record/5825464/files/Powder_phantom_30s_30Proj_sinogram.mat", out="MatlabData")
       wget.download("https://zenodo.org/record/5825464/files/Energy_axis.mat", out="MatlabData")
       print("\nFinished.")

def rmse_sing_chan(calculated,truth,errors):
    # Calculates RMSE for every channel of a single voxel
    for i in range(0,len(calculated)):
        errors[i] = np.sqrt(np.mean((calculated[i] - truth[i]) ** 2))
    print('Calculation Complete!')
    return errors

def cnr_spatial(mean_signal,std_signal,mean_bg,std_bg):
    # Need an ROI to do this
    ratio = (np.abs(mean_signal-mean_bg))/(std_signal+std_bg)
    print('Calculation Complete!')
    return ratio


from collections import Counter
items = ['YES', 'NO', 'NO', 'YES', 'EMPTY', 'YES', 'NO']
count = Counter()
for i in items:
    count[i]+=1
print(count)

# Another Sol
result = dict(zip(list(items),[list(items).count(i) for i in list(items)]))
print(f'Counter({result})')

200+ Exercises  Programming in Python/22- built-in modules/Ex 9.py


from typing import Optional, List, Dict, Tuple

import pandas as pd
from sklearn.preprocessing import KBinsDiscretizer

from monitoring.measurements import (
    TotalVarianceDistance,
    HellingerDistance,
    KullbackLeiblerDivergence,
)

class VirtualDrift:
    def __init__(
        self,
        bin_count: int,
        feature_cols: Optional[List[str]],
        prediction_col: Optional[str],
        label_col: Optional[str],
    ):
        self.feature_cols = feature_cols
        self.prediction_col = prediction_col
        self.label_col = label_col
        self.bin_count = bin_count
        self.discretizers: Dict[str, KBinsDiscretizer] = {}

    def compute_drift(
        self,
        first_dataset: pd.DataFrame,
        second_dataset: pd.DataFrame,
    ) -> Dict[str, float]:
        self.init_discritizers(first_dataset)
        self.discritize(first_dataset, second_dataset)
        return self.compute_drift_measures(first_dataset, second_dataset)

    def init_discritizers(self, base_data):
        continuous_features = base_data.select_dtypes(["float"])
        for feature in continuous_features.columns:
            if feature not in self.discretizers:
                self.discretizers[feature] = self.fit_discretizer(
                    feature, continuous_features
                )

    def fit_discretizer(
        self, feature_name: str, continuous_features: pd.DataFrame
    ) -> KBinsDiscretizer:
        discretizer = KBinsDiscretizer(
            n_bins=self.bin_count, encode="ordinal", strategy="uniform"
        )
        discretizer.fit(continuous_features.loc[:, feature_name].values.reshape(-1, 1))
        return discretizer

    def discritize(self, base_data, current_data):
        for feature, discretizer in self.discretizers.items():
            base_data[feature] = discretizer.transform(
                base_data.loc[:, feature].values.reshape(-1, 1)
            )
            current_data[feature] = discretizer.transform(
                current_data.loc[:, feature].values.reshape(-1, 1)
            )
            base_data[feature] = base_data[feature].astype("int")
            current_data[feature] = current_data[feature].astype("int")

    def compute_drift_measures(
        self,
        base_data,
        current_data,
    ) -> Dict[str, float]:
        feature_drift = self.compute_feature_drift(base_data, current_data)
        prediction_drift = self.compute_prediction_drift(base_data, current_data)
        label_drift = self.compute_label_drift(base_data, current_data)

        drift_measures = {**feature_drift, **label_drift, **prediction_drift}

        # Normalize inf values
        for key, value in drift_measures.items():
            if value == float("inf"):
                drift_measures[key] = 10

        return drift_measures

    def compute_feature_drift(
        self,
        base_data: pd.DataFrame,
        current_data: pd.DataFrame,
    ) -> Dict[str, float]:
        if self.feature_cols is None:
            return {}

        base_features = base_data[self.feature_cols]
        current_features = current_data[self.feature_cols]
        features_t, features_u = self.to_observations(base_features, current_features)

        return {
            "features_tvd": TotalVarianceDistance(features_t, features_u).compute(),
            "features_hd": HellingerDistance(features_t, features_u).compute(),
            "features_kld": KullbackLeiblerDivergence(features_t, features_u).compute(),
        }

    def compute_prediction_drift(
        self,
        base_data: pd.DataFrame,
        current_data: pd.DataFrame,
    ) -> Dict[str, float]:
        if self.prediction_col is None:
            return {}

        base_predictions = pd.DataFrame(base_data.loc[:, self.prediction_col])
        current_predictions = pd.DataFrame(current_data.loc[:, self.prediction_col])
        prediction_t, prediction_u = self.to_observations(
            base_predictions, current_predictions
        )

        return {
            "prediction_tvd": TotalVarianceDistance(
                prediction_t, prediction_u
            ).compute(),
            "prediction_hd": HellingerDistance(prediction_t, prediction_u).compute(),
            "prediction_kld": KullbackLeiblerDivergence(
                prediction_t, prediction_u
            ).compute(),
        }

    def compute_label_drift(
        self, base_data: pd.DataFrame, current_data: pd.DataFrame
    ) -> Dict[str, float]:
        if self.label_col is None:
            return {}

        base_labels = pd.DataFrame(base_data.loc[:, self.label_col])
        current_labels = pd.DataFrame(current_data.loc[:, self.label_col])
        labels_t, labels_u = self.to_observations(base_labels, current_labels)

        return {
            "prediction_tvd": TotalVarianceDistance(labels_t, labels_u).compute(),
            "prediction_hd": HellingerDistance(labels_t, labels_u).compute(),
            "prediction_kld": KullbackLeiblerDivergence(labels_t, labels_u).compute(),
        }

    @staticmethod
    def to_observations(
        t: pd.DataFrame, u: pd.DataFrame
    ) -> Tuple[pd.Series, pd.Series]:
        t = (
            t.apply(
                lambda row: f"{'_'.join([str(row[val]) for val in t.columns])}", axis=1
            )
            .value_counts()
            .sort_index()
        )
        u = (
            u.apply(
                lambda row: f"{'_'.join([str(row[val]) for val in u.columns])}", axis=1
            )
            .value_counts()
            .sort_index()
        )

        joined_uniques = pd.DataFrame([t, u]).T.fillna(0).sort_index()
        joined_uniques.columns = ["t", "u"]

        t_obs = joined_uniques.loc[:, "t"]
        u_obs = joined_uniques.loc[:, "u"]

        t_pdf = t_obs / t_obs.sum()
        u_pdf = u_obs / u_obs.sum()

        return t_pdf, u_pdf


# https://www.acmicpc.net/problem/2146
from sys import stdin
from collections import deque
input = stdin.readline

def bfs(r, c, group):
    groups[r][c] = group
    queue = deque([(r, c)])
    while queue:
        r, c = queue.popleft()
        for dx, dy in ((1,0),(0,1),(-1,0),(0,-1)):
            nx, ny = r+dx, c+dy
            if 0 <= nx < N and 0 <= ny < N and not groups[nx][ny] and matrix[nx][ny] == '1':
                groups[nx][ny] = group
                queue.append((nx, ny))

def dari(r, c, group):
    global answer
    visited = [[False]*N for _ in range(N)]
    visited[r][c] = True
    queue = deque([(r, c, 0)])
    while queue:
        r, c, length = queue.popleft()
        if answer < length: return 987654321
        if groups[r][c] and groups[r][c] != group:
            return length-1
        for dx, dy in ((1,0),(0,1),(-1,0),(0,-1)):
            nx, ny = r+dx, c+dy
            if 0 <= nx < N and 0 <= ny < N and not visited[nx][ny] and groups[nx][ny] != group:
                visited[nx][ny] = True
                queue.append((nx, ny, length+1))
    return 987654321

N = int(input())
matrix = [input().split() for _ in range(N)]

groups = [[0]*N for _ in range(N)]
group = 1
for r in range(N):
    for c in range(N):
        if matrix[r][c] == '0' or groups[r][c]: continue
        bfs(r, c, group)
        group += 1

answer = 987654321
for r in range(N):
    for c in range(N):
        if groups[r][c]:
            flag = False
            for dx, dy in ((1,0),(0,1),(-1,0),(0,-1)):
                nx, ny = r+dx, c+dy
                if 0 <= nx < N and 0 <= ny < N and matrix[nx][ny] == '0':
                    flag = True
                    break
            if flag: answer = min(answer, dari(r, c, groups[r][c]))
print(answer)


import signal
import functools
import logging

logger = logging.getLogger('awx.main.tasks.signals')

__all__ = ['with_signal_handling', 'signal_callback']

class SignalExit(Exception):
    pass

class SignalState:
    def reset(self):
        self.sigterm_flag = False
        self.sigint_flag = False

        self.is_active = False  # for nested context managers
        self.original_sigterm = None
        self.original_sigint = None
        self.raise_exception = False

    def __init__(self):
        self.reset()

    def raise_if_needed(self):
        if self.raise_exception:
            self.raise_exception = False  # so it is not raised a second time in error handling
            raise SignalExit()

    def set_sigterm_flag(self, *args):
        self.sigterm_flag = True
        self.raise_if_needed()

    def set_sigint_flag(self, *args):
        self.sigint_flag = True
        self.raise_if_needed()

    def connect_signals(self):
        self.original_sigterm = signal.getsignal(signal.SIGTERM)
        self.original_sigint = signal.getsignal(signal.SIGINT)
        signal.signal(signal.SIGTERM, self.set_sigterm_flag)
        signal.signal(signal.SIGINT, self.set_sigint_flag)
        self.is_active = True

    def restore_signals(self):
        signal.signal(signal.SIGTERM, self.original_sigterm)
        signal.signal(signal.SIGINT, self.original_sigint)
        # if we got a signal while context manager was active, call parent methods.
        if self.sigterm_flag:
            if callable(self.original_sigterm):
                self.original_sigterm()
        if self.sigint_flag:
            if callable(self.original_sigint):
                self.original_sigint()
        self.reset()

signal_state = SignalState()

def signal_callback():
    return bool(signal_state.sigterm_flag or signal_state.sigint_flag)

def with_signal_handling(f):
    """
    Change signal handling to make signal_callback return True in event of SIGTERM or SIGINT.
    """

    @functools.wraps(f)
    def _wrapped(*args, **kwargs):
        try:
            this_is_outermost_caller = False
            if not signal_state.is_active:
                signal_state.connect_signals()
                this_is_outermost_caller = True
            return f(*args, **kwargs)
        finally:
            if this_is_outermost_caller:
                signal_state.restore_signals()

    return _wrapped


from pyrogram import Client
from datetime import datetime
import pandas as pd
import time
import os
import dotenv

dotenv.load_dotenv()

api_id = os.getenv('API_ID')
api_hash = os.getenv('API_HASH')
channel_id = 'Spotted_DMI'

# Create a Pyrogram client
app = Client('session_name', api_id=api_id, api_hash=api_hash)
started = datetime.today()

print(" ######## app started successfully ########### ")
app.start()
i = 0
data_list = []
chat_history = app.get_chat_history(channel_id, limit=100,offset_id=16108)
for message in chat_history:
    i+=1

    # A) Possibility to get the posts with images AND video and getting the text under written.
    if message.text is None:
        print("\n##### Spot numero: " + str(i) + " ID : " + str(message.id))

        if message.photo:
            print(" ------------- Image of the Spot ------------------- ")
            # A) Download the images/video on the "downloads" directory.
            image = app.download_media(message.photo.file_id,f'image{message.id}.jpg')
            print(image)
        if message.video:
            print(" ------------- Video of the Spot ------------------- ")
            video = app.download_media(message.video.file_id,f'video{message.id}.mp4')
            print(video)
            if message.caption:
                print(" ------------- Text of the Spot ------------------- ")
                text_below = message.caption
                print(message.caption)

    if message.text is not None:
        print("\n##### Spot numero: " + str(i) + " ID : " + str(message.id))
        print(message.text)
        comments = []
        print("\n## Commenti del post con ID :" + str(message.id))
        for reply in app.get_discussion_replies(channel_id, message.id):

            # Q) Not sure if is saving the corret file, not visible from my laptop.

            # if reply.text is None:
            #     if reply.animation:
            #         print(" ------------- GIF of the comment ------------------- ")
            #         gif = app.download_media(reply.animation.file_id,f'animation{reply.id}.gif')
            #         print(gif)
            #     if reply.sticker:
            #         print(" ------------- Sticker of the comment ------------------- ")
            #         sticker = app.download_media(reply.sticker.file_id,f'sticker{reply.id}.jpeg')
            #         print(sticker)

                # A) Added the same concept as the post.
                if reply.photo:
                    print(" ------------- Image of the comment ------------------- ")
                    # A) Download the images/video on the "downloads" directory.
                    image = app.download_media(reply.photo.file_id,f'image{reply.id}.jpg')
                    print(image)
                if reply.video:
                    print(" ------------- Video of the comment ------------------- ")
                    video = app.download_media(reply.video.file_id,f'video{reply.id}.mp4')
                    print(video)

                    if reply.caption:
                        print(" ------------- Text of the comment ------------------- ")
                        text_below = reply.caption
                        print("- "+ message.caption)

        # A) If the message doesn't contain text it doesn't enter in the if (None = GIF,STICKER,PHOTO,VIDEO,VOICE MESSAGE(?) ).
        if reply.text is not None:
            print("- "+reply.text)
            comments.append(reply.text)
            time.sleep(2)

        data_list.append({
            "Message ID": message.id,
            "Spot": message.text,
            "Comments": comments
        })

app.stop()

df = pd.DataFrame(data_list)
df.to_csv("data.csv", index=False)


import numpy as np
import cv2

cat_cascade = cv2.CascadeClassifier('cascade.xml')

img = cv2.imread('Cat1.jpeg')
cats = cat_cascade.detectMultiScale(gray,1.01,7)
for(x,y,w,h) in cats:
    img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

cv2.imshow('cats',img)
cv2.waitKey(0)
cv2.destroyAllWindows()


"""empty message

Revision ID: 01b0cbb9a1a7
Revises: 37e499a6b25
Create Date: 2016-04-14 10:29:24.710604

"""

# revision identifiers, used by Alembic.
revision = '01b0cbb9a1a7'
down_revision = '37e499a6b25'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.add_column('time_place', sa.Column('latitude', sa.Float(), nullable=True))
    op.add_column('time_place', sa.Column('longitude', sa.Float(), nullable=True))
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('time_place', 'longitude')
    op.drop_column('time_place', 'latitude')
    ### end Alembic commands ###


#!/usr/bin/env python
# encoding: utf-8
#@author: jack
#@contact: 935650354@qq.com
#@site: https://www.cnblogs.com/jackzz
#@software: PyCharm
#@time: 2019/5/30 19:11

from django.http import HttpResponseForbidden

def simple_middleware(get_response): #参数固定
    print("一次性设置和初始化1")

    def middleware(request):
        user_agent = request.META['HTTP_USER_AGENT']
        if not 'chrome' in user_agent.lower():
            return HttpResponseForbidden()
        print('处理请求之前执行的代码2')

        response = get_response(request)

        print("处理请求、响应之后的代码5")
        return response
    return middleware

class SimpleMiddleWare:
    def __init__(self,get_response):
        self.get_response = get_response
        print("一次性设置和初始化0")

    def __call__(self, request):
        print('处理请求之前执行的代码3')

        response = self.get_response(request)

        print("处理请求、响应之后的代码4")
        return response


import os
import discord
from dotenv import load_dotenv
from datetime import datetime, timedelta

class Tsujigiri(discord.Client):
    async def on_ready(self):
        print(f'Logged on as {self.user}.')
        for guild in self.guilds:
            pruner = Pruner(guild)
            await pruner.make_list()
            await pruner.kick()
            del pruner

class Pruner:
    def __init__(self, guild):
        self.guild = guild
        self.period = int(os.getenv('PRUNING_PERIOD', 365))
        self.list = []

    async def make_list(self):
        for member in self.guild.members:
            if member.bot:
                continue
            if datetime.now() - member.joined_at < timedelta(days=self.period):
                continue

            prune = True
            for channel in self.guild.text_channels:
                entry = await channel.history().get(author__id=member.id)
                if not entry:
                    continue
                if datetime.now() - entry.created_at < timedelta(days=self.period):
                    prune = False
                    break
            if prune:
                self.list.append(member)

    async def kick(self):
        for member in self.list:
            try:
                await member.kick()
                print(f'Kicked {member} from {member.guild}')
            except (discord.errors.Forbidden, AttributeError) as error_content:
                print(f'Failed to kick {member}: {error_content}')

def main():
    load_dotenv()
    token = os.getenv('BOT_TOKEN')

    intents = discord.Intents.default()
    intents.members = True

    client = Tsujigiri(intents=intents)
    client.run(token)

if __name__ == '__main__':
    main()


from sympy import Mul, Pow, Integer
from compartor.compartments import Moment, Expectation
import itertools

# -------------------------------------------------
def __getMomentPowers(expr):
    """
    Decompose a product of powers of moments to list [(Moment, power)]

    :param expr: product of powers of Moments
    :return: list of tuples (Moment, power)
    """
    if expr.func == Mul:
        moments = [__getMomentPowers(arg) for arg in expr.args]
        return list(itertools.chain(*moments))
    elif expr.func == Pow and expr.args[0].func == Moment and issubclass(expr.args[1].func, Integer):
        return [(expr.args[0], expr.args[1])]
    elif expr.func == Moment:
        return [(expr, 1)]
    elif expr.is_number: #test
        return [] #test
    else:
        raise TypeError("Unexpected expression " + str(expr))

# -------------------------------------------------
def gamma_closure(expr):
    """
    Try to compute gamma closure for expectation of expr.

    :param expr: product of powers of moments
    :return: gamma closure of <expr>
    """

    def __closure1(moment_powers):
        moment = moment_powers[0][0]
        if 3 in moment.args:
            i = moment.args.index(3)
            j = i
        else:
            i = moment.args.index(2)
            j = moment.args.index(1)

        def m(a, b):
            gamma = [0] * len(moment.args)
            gamma[i] += a
            gamma[j] += b
            return Expectation(Moment(*gamma))

        expr = 2 * m(2, 0) * m(1, 1) / m(1, 0) - m(2, 0) * m(0, 1) / m(0, 0)
        return expr

    def __closure2(moment_powers):
        m_xi = moment_powers[0][0]
        if len(moment_powers) == 1:
            m_gamma = m_xi
        else:
            m_gamma = moment_powers[1][0]
        expr = 2 * (Expectation(m_gamma ** 2) * Expectation(m_gamma * m_xi)) / Expectation(m_gamma) - Expectation(
            m_gamma ** 2) * Expectation(m_xi)
        return expr

    # get tuples(M, pow) in expr
    moment_powers = __getMomentPowers(expr)
    # sort by ascending pow
    moment_powers = sorted(moment_powers, key=lambda x: x[1])

    if len(moment_powers) == 1 and moment_powers[0][1] == 1 and moment_powers[0][0].order() == 3:
        return __closure1(moment_powers)
    elif len(moment_powers) == 1 and moment_powers[0][1] == 3:
        return __closure2(moment_powers)
    elif len(moment_powers) == 2 and moment_powers[0][1] == 1 and moment_powers[1][1] == 2:
        return __closure2(moment_powers)
    else:
        raise ValueError("Could not derive Gamma closure for " + str(expr) + " (Not implemented yet).")

# -------------------------------------------------
def gamma_closures(expressions, could_not_close=None):
    """
    Try to compute gamma closure for each of expressions.

    :param expressions: list of moment expressions, where each expression is a product of
            powers of moments
    :param could_not_close: a list that will be filled with expressions that could not be closed.
            If this optional argument is not specified, then a ValueError will be raised if an
            expression cannot be closed.
    :return: list of tuples of (expr, gamma_closure(expr))
    """
    closures = []
    for expr in expressions:
        try:
            closure = gamma_closure(expr)
            closures.append((expr, closure))
        except ValueError:
            if could_not_close is not None:
                could_not_close.append(expr)
            else:
                raise
    return closures

# -------------------------------------------------
def meanfield_closure(expr):
    """
    Compute meanfield closure for expectation of expr.

    :param expr: product of powers of moments
    :return: meanfield closure of <expr>
    """

    def __product(list):
        r = 1
        for x in list:
            r *= x
        return r

    # get tuples(M, pow) in expr
    moment_powers = __getMomentPowers(expr)
    # sort by ascending pow
    moment_powers = sorted(moment_powers, key=lambda x: x[1])

    return  __product([Expectation(moment_power[0])**moment_power[1] for moment_power in moment_powers])

# -------------------------------------------------
def meanfield_closures(expressions):
    """
    Compute meanfield closure for each of expressions.

    :param expressions: list of moment expressions, where each expression is a product of powers of moments
    :return: list of tuples of (expr, meanfield_closure(expr))
    """
    return [(expr, meanfield_closure(expr)) for expr in expressions]

# -------------------------------------------------
def hybrid_closures(expressions):
    """
    Attempt gamma closure for each of expressions.
    For the expressions that could not be closed by gamma closure, do mean-field closure
    """
    could_not_close = []
    gamma = gamma_closures(expressions, could_not_close)
    meanfield = meanfield_closures(could_not_close)
    return gamma+meanfield

# -------------------------------------------------
def substitute_closures(equations, closures):
    """
    Take expectation of rhs in evolutions, and substitute closures.

    :param equations: list of pairs (fM, dfMdt). (as returned by compute_moment_equations)
    :param closures: list of tuples of (expr, closure(expr))
    :return: list of pairs (fM, dfMdt'), where dfMdt' is obtained by substituting closed moments into dfMdt
    """
    substitutions = {Expectation(m): c for m, c in closures}
    # print("Closures: %s" %(substitutions)) #debug
    closed_equations = [(fM, dfMdt.subs(substitutions)) for fM, dfMdt in equations]
    return closed_equations

def apply_substitutions(equations, substitutions):
    """
    Perform raw term substitutions.

    :param equations: list of pairs (fM, dfMdt). (as returned by compute_moment_equations)
    :param substitution: list of tuples of (expr, substitution(expr))
    :return: list of pairs (fM, dfMdt'), where dfMdt' is obtained by substituting closed moments into dfMdt
    """
    substitutions = {m: c for m, c in substitutions}
    # print("Substitutions: %s" %(substitutions)) #debug
    subs_equations = [(fM, dfMdt.subs(substitutions)) for fM, dfMdt in equations]
    return subs_equations

#eof


# -*- coding: utf-8 -*-
"""
Created on Mon Feb  1 10:32:11 2021

@author: LanTian
"""

import pandas as pd
def qx(x):
    x=x.replace('一汽-大众','一汽大众')
    return x

df = pd.read_csv('./car_complain.csv')
df['brand']=df['brand'].apply(qx)
df = df.drop('problem',axis=1).join(df.problem.str.get_dummies(','))
bresult = df.groupby(['car_model'])['id'].agg(['count'])
ptags=df.columns[7:]
bresult2 = df.groupby(['car_model'])[ptags].agg('sum')
bresult2 =bresult.merge(bresult2,left_index=True,right_index=True,how='left')
bresult2 = bresult2.sort_values('count',ascending = False)
print(bresult2)#输出按照车型统计的问题总数
bresult3 = bresult2.sort_values('A14',ascending = False)
bresult3.reset_index(inplace=True)
bresult3= bresult3[['car_model','A14']]
print(bresult3)#输出问题A14的车型排序
#print(bresult3)


import math
import pygame

from isec.app import Resource
from isec.environment import Entity, Sprite

from game.objects.game.player import Player

class RopeRangeIndicator(Entity):
    MAX_ARC_WIDTH = 25  # degrees
    MIN_ARC_CUTOFF = 0.1  # degrees
    MAX_VISIBILITY_THRESHOLD = 15  # pixels
    VISIBILITY_RANGE_CUTOFF = 15  # pixels
    BELOW_ARC_REDUCTION = 0.5  # ratio

    def __init__(self,
                 player: Player):

        self.range = Resource.data["objects"]["player"]["UTILS"]["ROPE_MAX_LENGTH"]
        surface = pygame.Surface((self.range * 2, self.range * 2), pygame.SRCALPHA)
        self.player = player
        super().__init__(position=self.player.position,
                         sprite=Sprite(surface, "static"),
                         linked_scene=self.player.linked_scene,
                         linked_instance=self.player.linked_instance)

    def update(self,
               delta: float) -> None:
        super().update(delta)
        self.update_surface()

    def update_surface(self):
        cursor_pos = pygame.Vector2(pygame.mouse.get_pos())
        center_pos = pygame.Vector2(Resource.data["engine"]["window"]["size"]) / 2
        cursor_vec = (cursor_pos-center_pos)

        angle = cursor_vec.angle_to(pygame.Vector2(1, 0))

        distance_from_center = cursor_vec.length()
        delta_radius = abs(distance_from_center - self.range)

        self.sprite.surface.fill((0, 0, 0, 0))

        if delta_radius > self.MAX_VISIBILITY_THRESHOLD + self.VISIBILITY_RANGE_CUTOFF:
            return

        if delta_radius > self.MAX_VISIBILITY_THRESHOLD:
            multiplier = 1-((delta_radius - self.MAX_VISIBILITY_THRESHOLD)/self.VISIBILITY_RANGE_CUTOFF)
            arc_width = self.MAX_ARC_WIDTH * multiplier

        else:
            arc_width = self.MAX_ARC_WIDTH

        i = 0
        while arc_width > self.MIN_ARC_CUTOFF:
            half_arc_width = arc_width / 2
            pygame.draw.arc(self.sprite.surface,
                            Resource.data["colors"][7],
                            pygame.Rect(i, i, (self.range-i) * 2, (self.range-i) * 2),
                            math.radians(angle-half_arc_width),
                            math.radians(angle+half_arc_width),
                            1)

            i += 1
            arc_width *= self.BELOW_ARC_REDUCTION


'''
Created on Oct 4, 2013

@author: Ryan
'''

import sys
import MapReduce

mr = MapReduce.MapReduce()

def mapper(record):
    sequence_id = record[0]
    nucleotides = record[1]

    # Trim the last 10 characters off the nucleotides
    nucleotides = nucleotides[:-10]

    # Use the resulting nucleotides string as the key because we only want unique values.
    mr.emit_intermediate(nucleotides, sequence_id)

def reducer(key, list_of_values):
    mr.emit(key)

if __name__ == '__main__':
    inputdata = open(sys.argv[1])
    mr.execute(inputdata, mapper, reducer)


from typing import Tuple
import csv
import regex

def read_ngs_references(path: str) -> dict:
    """Function reads the csv file containing the reference sequences with their
    respective names and returns a dictionary with the sequence coupled to the name."""
    ngs_references = {}
    with open(path, newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            ngs_references[row["sequence"]] = row["name"]
    return ngs_references

def complement_reverse_sequence(sequence: str) -> str:
    """Function creates a complementary sequence and reverses the sequence."""
    complement = {"A": "T", "T": "A", "C": "G", "G": "C"}
    # Create a list containing the complement bases
    complement_seq = [complement[base] for base in sequence]
    # Reverse the list
    complement_seq = complement_seq[::-1]
    complement_seq = "".join(complement_seq)
    return complement_seq

def clean_ngs_reference_sequences(ngs_references_dict: dict, prefix_info: dict, suffix_info: dict) -> dict:
    """Function goes over every reference sequence in a dict. Finds the
    complement for that sequence and reverses it. Then it cleans this sequences
    by removing the prefix and suffix. The cleaned sequence is then stored in a dictionary,
    where the sequence is the key and the value is the name of the reference sequence.\n
    \n
    args:\n
    ngs_references_dict: (dict) a dictionary where the key is a reference sequence and the value is the name of this sequence.\n
    suffix: (str) sequence of the suffix which should be removed.\n
    \n
    return values:\n
    cleaned_ngs_references: (dict) a dictionary where the key is a cleaned reference sequence and the value is the name of this sequence.
    """
    cleaned_ngs_references = {}
    for reference_seq in ngs_references_dict:
        reversed_seq = complement_reverse_sequence(reference_seq)
        prefix_seq, _ = determine_pattern(reversed_seq, prefix_info)
        suffix_seq, _ = determine_pattern(reversed_seq, suffix_info)
        cleaned_seq = clean_sequence(reversed_seq, prefix_seq, suffix_seq)
        cleaned_ngs_references[cleaned_seq] = ngs_references_dict[reference_seq]
    return cleaned_ngs_references

def create_ngs_references_patterns(ngs_references_dict: dict) -> dict:
    """Function compiles every sequence in the dictionary into a regex object.
    This is done so that during the database insertion, no compilation has to been done
    every time we want to check for a reference sequence."""
    patterns_dict = {}
    for seq in ngs_references_dict:
        patterns_dict[regex.compile(
            fr"(?e)({seq}){{e<=1}}")] = ngs_references_dict[seq]
    return patterns_dict

def reference_seq(sequence: str, ngs_references_dict: dict):
    """Function returns the name of the reference sequence or the string 'NULL'"""
    for reference_seq in ngs_references_dict.keys():
        match = reference_seq.search(sequence)
        if match:
            # True
            return ngs_references_dict[reference_seq]
    # False
    return None

def determine_pattern(sequence: str, patterns_info: dict) -> Tuple[str, str, int]:
    """Function loops over all the patterns in patterns_info. The patterns_info should either contain the sequences of the prefixes
    or suffixes. While looping over the patterns it checks whether there is a match of this pattern in the sequence.
    If this is the case, it returns the matched sequence and the name of the pattern that matched.\n
    args:\n
    sequence: (str) DNA sequence in which you want to check for a pattern.\n
    patterns_info: (dict) key should be a compiled regex pattern and the value should be the name of the regex pattern. Example:\n
    {regex.compile(r"(?e)(ACAAAACAAAAC){e<=1}"): "Z", regex.compile(r"(?e)(AAACAAACAAA){e<=1}"): "W", regex.compile(r"(?e)(CTTTTCCGTATATCTCGCCAG){e<=1}"): "A"}\n
    \n
    return values:\n
    pattern_seq: (str) the matched sequence to the pattern, the regex pattern can allow for errors, so this is the actual matched sequence.\n
    pattern_name: (str) name of the pattern.
    """
    for pattern in patterns_info:
        pattern_match = pattern.search(sequence)
        if bool(pattern_match):
            pattern_name = patterns_info[pattern]
            pattern_seq = pattern_match.group()
            mutated_pattern = 0
            # # If there is a substitution/insertion/deletion, the pattern is "mutated"
            # if sum(pattern_match.fuzzy_counts) > 0:
            #     mutated_pattern = 1
            return pattern_seq, pattern_name  # , mutated_pattern
    return None, None  # , None

def determine_clvd_prefix(prefix_name, clvd_prefix_name="Z", unclvd_prefix_name="W"):
    """Function returns whether a sequence matches with a cleaved or uncleaved prefix sequences.\n
    args:\n
    prefix_name: (str) name of the prefix.\n
    clvd_prefix_name: (str) name of the prefix that indicates cleavage.\n
    unclvd_prefix_name: (str) name of the prefix that indicates no cleavage took place.\n
    \n
    return values:\n
    clvd_prefix: (int) indicates whether the prefix indicates cleavage. Yes(1)/No(0)/Don't know(2)"""
    if prefix_name is None:
        clvd_prefix = 2
    elif prefix_name.lower() == clvd_prefix_name.lower():
        clvd_prefix = 1
    elif prefix_name.lower() == unclvd_prefix_name.lower():
        clvd_prefix = 0
    else:
        clvd_prefix = 2
    return clvd_prefix

def retrieve_barcode(sequence: str, prefix: str) -> str:
    if prefix is not None:
        prefix_match = regex.search(prefix, sequence)
        return sequence[:prefix_match.start()]
    else:
        return None

def clean_sequence(sequence: str, prefix: str, suffix: str) -> str:
    if prefix is not None and suffix is not None:
        prefix_match = regex.search(prefix, sequence)
        suffix_match = regex.search(suffix, sequence)
        if not bool(suffix_match):
            return None
        return sequence[prefix_match.end():suffix_match.start()]
    return None


import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from ProgressScreen import QProgressScreen
from PracticeScreen import QDiffGame

class QDiffScreen(QWidget):                         #MAIN SCREEN
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Type Faster")
        self.label = QLabel(self)
        self.label.setGeometry(QRect(0, 0, 900, 600))
        self.label.setPixmap(QPixmap("../Typing Practice Application/images/NINJA-TYPING.png"))
        self.label.setScaledContents(True)
        self.Button1 = QPushButton('\n  Easy  \n', self)
        self.Button1.move(380, 100)
        self.Button1.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.Button2 = QPushButton("\n  Medium  \n", self)
        self.Button2.move(380, 200)
        self.Button3 = QPushButton("\n  Difficult  \n", self)
        self.Button3.move(380, 300)
        self.Button4 = QPushButton("\n  View Progress  \n", self)
        self.Button4.move(380, 400)
        self.Button1.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.Button2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.Button3.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor))
        self.main_body()

    def main_body(self):                             #MODES
        x = 'Easy'
        self.Button1.clicked.connect(lambda x = x : self.Mode_set('Easy'))
        self.Button2.clicked.connect(lambda x = x : self.Mode_set('Normal'))
        self.Button3.clicked.connect(lambda x = x : self.Mode_set('Difficult'))
        self.Button4.clicked.connect(self.View_Progress)

    def View_Progress(self):
        Prog = QApplication(sys.argv)
        Prog_win = QProgressScreen()
        Prog_win.setGeometry(200, 200, 500, 600)
        Prog_win.show()
        while True:
            Prog.processEvents()

    def Mode_set(self, s):                            #JUMP TO NEW WINDOW FOR MAIN GAME
        #print(s)
        Main_Game = QApplication(sys.argv)
        Main_Game_win = QDiffGame(s)
        Main_Game_win.show()
        while True:
            Main_Game.processEvents()

def main() :
    Diff = QApplication(sys.argv)
    Diff_win = QDiffScreen()
    Diff_win.setGeometry(200, 200, 900, 600)
    Diff_win.show()
    sys.exit(Diff.exec_())

main()


class FreqStack:
    # O(1), O(N)
    def __init__(self):
        from collections import defaultdict
        self.c = Counter()
        self.stack = defaultdict(list)
        self.maxfreq = 0

    def push(self, x: int) -> None:
        self.c[x] +=1
        self.maxfreq = max(self.maxfreq, self.c[x])
        self.stack[self.c[x]].append(x)

    def pop(self) -> int:
        cand = self.stack[self.maxfreq].pop()
        self.c[cand] -= 1
        if not self.stack[self.maxfreq]:
            self.maxfreq -=1
        return cand

# Your FreqStack object will be instantiated and called as such:
# obj = FreqStack()
# obj.push(x)
# param_2 = obj.pop()


# is this just simply about building all of the combinations? can even use pythong library since n is so small
# we can simply sort and then first math.ceil(n / 2) will be our best combination, so we can even use math to find those combinations
# this problem seems super simple, what am I missing
import sys
import math
try:
    sys.stdin = open('06.in')
except:
    pass

def factorial(n, memo={}):
    if n <= 1:
        return 1
    if n in memo:
        return memo[n]
    memo[n] = factorial(n-1) * n
    return memo[n]

T = int(input())
for _ in range(T):
    words = input().split()
    words.sort(key=lambda x: len(x))
    n = len(words)
    r = math.ceil(n/2)
    ans = int((factorial(n) / (factorial(n-r) * factorial(r))))
    print(ans, ' '.join(sorted(words[:r])), sep=':')


# https://www.acmicpc.net/problem/1546

n = int(input())

score = list(map(int, input().split()))
max = max(score)
new_score = []
sum = 0

for i in score:
    x = i / max * 100
    new_score.append(x)
    sum += x

print(sum / n)