import html

from htbuilder import H, HtmlElement, styles
from htbuilder.units import unit

# Only works in 3.7+: from htbuilder import div, span
div = H.div
span = H.span

# Only works in 3.7+: from htbuilder.units import px, rem, em
px = unit.px
rem = unit.rem
em = unit.em

# Colors from the Streamlit palette.
# These are red-70, orange-70, ..., violet-70, gray-70.
PALETTE = [
    "#ff4b4b",
    "#ffa421",
    "#ffe312",
    "#21c354",
    "#00d4b1",
    "#00c0f2",
    "#1c83e1",
    "#803df5",
    "#808495",
]

OPACITIES = [
    "33", "66",
]

def annotation(body, label="", background=None, color=None, **style):
    """Build an HtmlElement span object with the given body and annotation label.
    The end result will look something like this:
        [body | label]
    Parameters
    ----------
    body : string
        The string to put in the "body" part of the annotation.
    label : string
        The string to put in the "label" part of the annotation.
    background : string or None
        The color to use for the background "chip" containing this annotation.
        If None, will use a random color based on the label.
    color : string or None
        The color to use for the body and label text.
        If None, will use the document's default text color.
    style : dict
        Any CSS you want to apply to the containing "chip". This is useful for things like
    Examples
    --------
    Produce a simple annotation with default colors:
    >>> annotation("apple", "fruit")
    Produce an annotation with custom colors:
    >>> annotation("apple", "fruit", background="#FF0", color="black")
    Produce an annotation with crazy CSS:
    >>> annotation("apple", "fruit", background="#FF0", border="1px dashed red")
    """

    color_style = {}

    if color:
        color_style['color'] = color

    if not background:
        label_sum = sum(ord(c) for c in label)
        background_color = PALETTE[label_sum % len(PALETTE)]
        background_opacity = OPACITIES[label_sum % len(OPACITIES)]
        background = background_color + background_opacity

    return (
        span(
            style=styles(
                background=background,
                border_radius=rem(0.33),
                padding=(rem(0.125), rem(0.5)),
                overflow="hidden",
                white_space="pre",
                **color_style,
                **style,
            ))(

            body,

            span(
                style=styles(
                    padding_left=rem(0.5),
                    text_transform="uppercase",
                ))(
                span(
                    style=styles(
                        font_size=em(0.67),
                        opacity=0.5,
                    ))(
                    label,
                ),
            ),
        )
    )

def get_annotated_html(args):
    """Writes text with annotations into an HTML string.
    Parameters
    ----------
    *args : see annotated_text()
    Returns
    -------
    str
        An HTML string.
    """

    out = div()

    for arg in args:
        if isinstance(arg, str):
            out(arg)

        elif isinstance(arg, HtmlElement):
            out(arg)

        elif isinstance(arg, tuple):
            out(annotation(*arg))

        else:
            raise Exception("Oh noes!")

    return str(out)


from collections import Counter

class Solution:
    def frequencySort(self, s: str) -> str:
        # cCounter = Counter(s)
        # countDict = dict()
        # countOrder = set()
        # retVal = ''
        # for _key, _count in cCounter.items():
        #     countOrder.add(_count)
        #     if _count in countDict:
        #         countDict[_count].append(_key)
        #     else:
        #         countDict[_count] = [_key]
        # countOrder = sorted(list(countOrder), reverse=True)
        # for _count in countOrder:
        #     for c in countDict[_count]:
        #         retVal += c*_count
        # return retVal
        l = Counter(s)
        retVal = ''
        for char, count in (sorted(l.items(), key=lambda item: item[1], reverse=True)):  # sort dict items based on value (letter count)
            retVal += char*count
        return retVal

Coding_Challenges/30 Day Coding Challenge May/Week 4/Day 22) Sort Characters By Frequency.py


from quadratic_equation import QuadraticEquation

if __name__ == '__main__':
    file = "input03.txt"
    with open(file) as f:
        eqs_0 = []
        eqs_1 = []
        eqs_2 = []
        eqs_inf = []

        for line in f:
            try:
                a, b, c = map(int, line.split())
                eq = QuadraticEquation(a, b, c)
                solutions = eq.solve()
                if solutions == QuadraticEquation.INF:
                    eqs_inf.append(eq)
                elif len(solutions) == 0:
                    eqs_0.append(eq)
                elif len(solutions) == 1:
                    eqs_1.append(eq)
                else:
                    eqs_2.append(eq)
            except ValueError:
                pass

        print("Solutions 0:")
        for equation in eqs_0:
            equation.show()
        print("=====")
        print("Solutions 1:")
        for equation in eqs_1:
            equation.show()
        print("=====")
        print("Solutions 2:")
        for equation in eqs_2:
            equation.show()
        print("=====")
        print("Solutions inf:")
        for equation in eqs_inf:
            equation.show()

        if eqs_1:
            minsol = float("inf")
            min_eq = None
            maxsol = float("-inf")
            max_eq = None
            for equation in eqs_1:
                solution = equation.solve()[0]
                if solution < minsol:
                    minsol = solution
                    min_eq = equation
                if solution > maxsol:
                    maxsol = solution
                    max_eq = equation

            print("Рівняння з найменшим розв'язком: ")
            min_eq.show()
            print(minsol)
            print("Рівняння з найбільшим розв'язком: ")
            max_eq.show()
            print(maxsol)
        else:
            print("Немає рівнянь з одним розв'язком")


from math import pi, log, sqrt
import pandas as pd
import numpy as np
from math import pi, log, exp
import matplotlib as mpl; mpl.use("Qt5Agg")
import matplotlib.pyplot as plt

plt.rcParams.update({'font.size': 16})

def collectCoeffsSimple(pressure, temperature):

    # pressure in GPa
    # temperature in degK
    # Cottrell et al 2009

    coeffs = {
        'alpha': 0,
          'beta': 0,
          'chi': 0,
          'delta': 0,
          'epsilon': 0
    }

    if 0 <= pressure <= 3:
        coeffs['alpha'] = 1.11
        coeffs['beta'] = -1.18
        coeffs['chi'] = -0.85
        coeffs['delta'] = 1680
        coeffs['epsilon'] = 487

    elif 3 < pressure:
        coeffs['alpha'] = 1.05
        coeffs['beta'] = -1.10
        coeffs['chi'] = -0.84
        coeffs['delta'] = 3588
        coeffs['epsilon'] = -102

    return coeffs

def partition(pressure, temperature, deltaIW):
    nbo_t = 2.6
    coeffs = collectCoeffsSimple(pressure=pressure, temperature=temperature)
    alpha = coeffs['alpha']
    beta = coeffs['beta']
    chi = coeffs['chi']
    delta = coeffs['delta']
    epsilon = coeffs['epsilon']
    logD = alpha + (beta * deltaIW) + (chi * nbo_t) + (delta * (1/temperature)) + (epsilon * (pressure/temperature))
    D = 10**logD
    return D

def adiabat(current_depth, current_temperature, depth_increment, depth, gravity, thermal_expansion, heat_capacity,
            depth_gradient, adiabat_gradient):
    current_depth += depth_increment
    # dT/dh = (alpha * g * T) / c_p
    current_temperature += ((thermal_expansion * gravity * current_temperature) / heat_capacity) * depth_increment
    adiabat_gradient.append(current_temperature)
    depth_gradient.append(current_depth / 1000)
    if current_depth < depth:  # recursion!
        return adiabat(current_depth, current_temperature, depth_increment, depth, gravity, thermal_expansion,
                       heat_capacity, depth_gradient, adiabat_gradient)
    else:
        return depth_gradient, adiabat_gradient

def hydrostatic(current_depth, depth_increment, depth, gravity, density_melt, current_pressure, depth_gradient,
                pressure_gradient):
    current_depth += depth_increment
    # dP/dh = rho * g
    current_pressure += (density_melt * gravity) * depth_increment
    pressure_gradient.append(current_pressure * (10**(-9)))  # gPa
    depth_gradient.append(current_depth / 1000)
    if current_depth < depth:
        return hydrostatic(current_depth, depth_increment, depth, gravity, density_melt, current_pressure, depth_gradient,
                pressure_gradient)
    else:
        return depth_gradient, pressure_gradient

def calcNumTotalDroplets(core_radius, droplet_radius):
    core_volume = (4 / 3) * pi * (core_radius ** 3)
    droplet_volume = (4 / 3) * pi * (droplet_radius ** 3)
    num_droplets = core_volume / droplet_volume
    return num_droplets

def iterReverseD(obj_concs, cell_concs, index=0, iterReverseDList=[]):
    if index < len(list(obj_concs)):
        obj = list(obj_concs)[index]
        cell_concs_range = list(cell_concs)[0:index + 1]
        avg_cell_concs_range = sum(cell_concs_range) / (len(cell_concs_range))
        # print(cell_concs[index], avg_cell_concs_range)
        avg_D = obj / avg_cell_concs_range
        iterReverseDList.append(avg_D)
        return iterReverseD(obj_concs=obj_concs, cell_concs=cell_concs, index=(index + 1),
                            iterReverseDList=iterReverseDList)
    else:
        return iterReverseDList

def forIterReverseD(obj_concs, cell_concs):
    iterReverseDList = []
    for index in range(len(list(obj_concs))):
        if index + 1 < len(list(obj_concs)):
            obj = list(obj_concs)[index]
            cell_concs_range = list(cell_concs)[0:index + 1]
            avg_cell_concs_range = sum(cell_concs_range) / (len(cell_concs_range))
            # print(cell_concs[index], avg_cell_concs_range)
            avg_D = obj / avg_cell_concs_range
            iterReverseDList.append(avg_D)
        else:
            return iterReverseDList

def calcDiffusionLength(chem_diffusivity, droplet_radius, settling_velocity):
    l = sqrt((2 * chem_diffusivity * droplet_radius) / settling_velocity)
    return l

def meltLengthWidth(diff_length, droplet_radius):
    length_width = (2 * droplet_radius) + (2 * diff_length)
    return length_width

def recalcConcentration(predicted_d, original_moles_silicate, original_moles_metal, volume_mesh, radius_object):
    volume_obj = (4 / 3) * pi * (radius_object ** 3)

    original_conc_silicate = original_moles_silicate / volume_mesh
    original_conc_metal = original_moles_metal / volume_obj
    concs_mesh = [original_conc_silicate]
    concs_objs = [original_conc_metal]
    moles_mesh = [original_moles_silicate]
    moles_objs = [original_moles_metal]
    verify_D = [concs_objs[0] / concs_mesh[0]]
    for index, d in enumerate(list(predicted_d)):
        old_moles_obj = moles_objs[index - 1]
        old_moles_cell = moles_mesh[index - 1]

        adj_matrix = (old_moles_cell /
                      (1 + (3 * volume_mesh * (
                                  (4 * pi * (radius_object ** 3) * d) ** (-1)))))
        adj_object = (old_moles_obj /
                      (1 + (4 * pi * (radius_object ** 3) * d) * (
                                  (3 ** (-1)) * (volume_mesh**(-1)))))
        adj_moles = adj_matrix - adj_object

        # adjust the moles of the element in the object and matrix, respectively
        new_moles_obj = old_moles_obj + adj_moles
        new_moles_cell = old_moles_cell - adj_moles
        new_obj_conc = new_moles_obj / volume_obj
        new_mesh_conc = new_moles_cell / volume_mesh
        check_D = new_obj_conc / new_mesh_conc
        moles_objs.append(new_moles_obj)
        moles_mesh.append(new_moles_cell)
        concs_mesh.append(new_mesh_conc)
        concs_objs.append(new_obj_conc)
        verify_D.append(check_D)

    return concs_mesh, concs_objs, moles_mesh, moles_objs, verify_D

earth_magma_ocean_depth = 520 * 1000
earth_magma_ocean_depth_increment = 260 * 10
earth_surface_gravity = 9.8

vesta_magma_ocean_depth = 262.8 * 1000
vesta_magma_ocean_depth_increment = 400
vesta_surface_gravity = 0.25

silicate_density = 3750
metal_density = 7800
w_diffusivity = 10**-8
thermal_expansivity = 6 * 10**(-5)
heat_capacity = 10**3

earth_adiabatic_depths, earth_adiabatic = adiabat(
    current_depth=0 / 1000,  # begin at surface
    current_temperature=2000,  # degrees K
    depth_increment=earth_magma_ocean_depth_increment,  # 10 km interval
    depth=earth_magma_ocean_depth,  # to depth of 250 km
    gravity=earth_surface_gravity,  # m/s^2, Vesta
    thermal_expansion=thermal_expansivity,
    heat_capacity=heat_capacity,
    depth_gradient=[0],  # returns this list at index=0
    adiabat_gradient=[2000],  # returns this list at index=1
)

earth_hydrostatic_depths, earth_hydrostat = hydrostatic(
    current_depth=0 / 1000,
    depth_increment=earth_magma_ocean_depth_increment,
    depth=earth_magma_ocean_depth,
    gravity=earth_surface_gravity,
    current_pressure=0,
    density_melt=silicate_density,
    depth_gradient=[0],
    pressure_gradient=[0],
)

vesta_adiabatic_depths, vesta_adiabatic = adiabat(
    current_depth=0 / 1000,  # begin at surface
    current_temperature=2000,  # degrees K
    depth_increment=vesta_magma_ocean_depth_increment,  # 10 km interval
    depth=vesta_magma_ocean_depth,  # to depth of 250 km
    gravity=vesta_surface_gravity,  # m/s^2, Vesta
    thermal_expansion=thermal_expansivity,
    heat_capacity=heat_capacity,
    depth_gradient=[0],  # returns this list at index=0
    adiabat_gradient=[2000],  # returns this list at index=1
)

vesta_hydrostatic_depths, vesta_hydrostat = hydrostatic(
    current_depth=0 / 1000,
    depth_increment=vesta_magma_ocean_depth_increment,
    depth=vesta_magma_ocean_depth,
    gravity=vesta_surface_gravity,
    current_pressure=0,
    density_melt=silicate_density,
    depth_gradient=[0],
    pressure_gradient=[0],
)

droplet_radius = 0.0185
earth_droplet_radius = 0.002957762
diff_length = calcDiffusionLength(chem_diffusivity=10**-8, settling_velocity=0.2580697580112788, droplet_radius=droplet_radius)
earth_diff_length = calcDiffusionLength(chem_diffusivity=10**-8, settling_velocity=0.646064514, droplet_radius=earth_droplet_radius)
vesta_z_eq_1_thru_4 = 240
vesta_z_eq_5_thru_8 = 600
vesta_vol_mesh_1_thru_4 = ((2 * (droplet_radius + diff_length))**2) * vesta_z_eq_1_thru_4
vesta_vol_mesh_5_thru_8 = ((2 * (droplet_radius + diff_length))**2) * vesta_z_eq_5_thru_8
earth_z_eq_1_thru_4 = 25
earth_z_eq_5_thru_8 = 65
earth_vol_mesh_1_thru_4 = ((2 * (earth_droplet_radius + earth_diff_length))**2) * earth_z_eq_1_thru_4
earth_vol_mesh_5_thru_8 = ((2 * (earth_droplet_radius + earth_diff_length))**2) * earth_z_eq_5_thru_8

vesta_1 = pd.read_csv("thesis_model_outputs/Vesta_1.csv")
vesta_2 = pd.read_csv("thesis_model_outputs/Vesta_2.csv")
vesta_3 = pd.read_csv("thesis_model_outputs/Vesta_3.csv")
vesta_4 = pd.read_csv("thesis_model_outputs/Vesta_4.csv")
vesta_5 = pd.read_csv("thesis_model_outputs/Vesta_5.csv")
vesta_6 = pd.read_csv("thesis_model_outputs/Vesta_6.csv")
vesta_7 = pd.read_csv("thesis_model_outputs/Vesta_7.csv")
vesta_8 = pd.read_csv("thesis_model_outputs/Vesta_8.csv")

depth_vesta_1 = [i / 1000 for i in [0] + list(vesta_1['z-depth'])]
depth_vesta_2 = [i / 1000 for i in [0] + list(vesta_2['z-depth'])]
depth_vesta_3 = [i / 1000 for i in [0] + list(vesta_3['z-depth'])]
depth_vesta_4 = [i / 1000 for i in [0] + list(vesta_4['z-depth'])]
depth_vesta_5 = [i / 1000 for i in [0] + list(vesta_5['z-depth'])]
depth_vesta_6 = [i / 1000 for i in [0] + list(vesta_6['z-depth'])]
depth_vesta_7 = [i / 1000 for i in [0] + list(vesta_7['z-depth'])]
depth_vesta_8 = [i / 1000 for i in [0] + list(vesta_8['z-depth'])]

concs_mesh_vesta_1, concs_objs_vesta_1, moles_mesh_vesta_1, moles_objs_vesta_1, verify_D_vesta_1 = recalcConcentration(predicted_d=vesta_1['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=0, volume_mesh=vesta_vol_mesh_1_thru_4, radius_object=droplet_radius)
concs_mesh_vesta_2, concs_objs_vesta_2, moles_mesh_vesta_2, moles_objs_vesta_2, verify_D_vesta_2 = recalcConcentration(predicted_d=vesta_2['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=0, volume_mesh=vesta_vol_mesh_1_thru_4, radius_object=droplet_radius)
concs_mesh_vesta_3, concs_objs_vesta_3, moles_mesh_vesta_3, moles_objs_vesta_3, verify_D_vesta_3 = recalcConcentration(predicted_d=vesta_3['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=0, volume_mesh=vesta_vol_mesh_1_thru_4, radius_object=droplet_radius)
concs_mesh_vesta_4, concs_objs_vesta_4, moles_mesh_vesta_4, moles_objs_vesta_4, verify_D_vesta_4 = recalcConcentration(predicted_d=vesta_4['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=0, volume_mesh=vesta_vol_mesh_1_thru_4, radius_object=droplet_radius)
concs_mesh_vesta_5, concs_objs_vesta_5, moles_mesh_vesta_5, moles_objs_vesta_5, verify_D_vesta_5 = recalcConcentration(predicted_d=vesta_5['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=0, volume_mesh=vesta_vol_mesh_5_thru_8, radius_object=droplet_radius)
concs_mesh_vesta_6, concs_objs_vesta_6, moles_mesh_vesta_6, moles_objs_vesta_6, verify_D_vesta_6 = recalcConcentration(predicted_d=vesta_6['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=0, volume_mesh=vesta_vol_mesh_5_thru_8, radius_object=droplet_radius)
concs_mesh_vesta_7, concs_objs_vesta_7, moles_mesh_vesta_7, moles_objs_vesta_7, verify_D_vesta_7 = recalcConcentration(predicted_d=vesta_7['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=0, volume_mesh=vesta_vol_mesh_5_thru_8, radius_object=droplet_radius)
concs_mesh_vesta_8, concs_objs_vesta_8, moles_mesh_vesta_8, moles_objs_vesta_8, verify_D_vesta_8 = recalcConcentration(predicted_d=vesta_8['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=0, volume_mesh=vesta_vol_mesh_5_thru_8, radius_object=droplet_radius)

reverse_D_vesta_1 = forIterReverseD(obj_concs=concs_objs_vesta_1, cell_concs=concs_mesh_vesta_1)
reverse_D_vesta_2 = forIterReverseD(obj_concs=concs_objs_vesta_2, cell_concs=concs_mesh_vesta_2)
reverse_D_vesta_3 = forIterReverseD(obj_concs=concs_objs_vesta_3, cell_concs=concs_mesh_vesta_3)
reverse_D_vesta_4 = forIterReverseD(obj_concs=concs_objs_vesta_4, cell_concs=concs_mesh_vesta_4)
reverse_D_vesta_5 = forIterReverseD(obj_concs=concs_objs_vesta_5, cell_concs=concs_mesh_vesta_5)
reverse_D_vesta_6 = forIterReverseD(obj_concs=concs_objs_vesta_6, cell_concs=concs_mesh_vesta_6)
reverse_D_vesta_7 = forIterReverseD(obj_concs=concs_objs_vesta_7, cell_concs=concs_mesh_vesta_7)
reverse_D_vesta_8 = forIterReverseD(obj_concs=concs_objs_vesta_8, cell_concs=concs_mesh_vesta_8)

earth_1 = pd.read_csv("thesis_model_outputs/Earth_1.csv")
earth_2 = pd.read_csv("thesis_model_outputs/Earth_2.csv")
earth_3 = pd.read_csv("thesis_model_outputs/Earth_3.csv")
earth_4 = pd.read_csv("thesis_model_outputs/Earth_4.csv")
earth_5 = pd.read_csv("thesis_model_outputs/Earth_5.csv")
earth_6 = pd.read_csv("thesis_model_outputs/Earth_6.csv")
earth_7 = pd.read_csv("thesis_model_outputs/Earth_7.csv")
earth_8 = pd.read_csv("thesis_model_outputs/Earth_8.csv")

depth_earth_1 = [i / 1000 for i in [0] + list(earth_1['z-depth'])]
depth_earth_2 = [i / 1000 for i in [0] + list(earth_2['z-depth'])]
depth_earth_3 = [i / 1000 for i in [0] + list(earth_3['z-depth'])]
depth_earth_4 = [i / 1000 for i in [0] + list(earth_4['z-depth'])]
depth_earth_5 = [i / 1000 for i in [0] + list(earth_5['z-depth'])]
depth_earth_6 = [i / 1000 for i in [0] + list(earth_6['z-depth'])]
depth_earth_7 = [i / 1000 for i in [0] + list(earth_7['z-depth'])]
depth_earth_8 = [i / 1000 for i in [0] + list(earth_8['z-depth'])]

num_droplets_vesta = calcNumTotalDroplets(core_radius=113*1000, droplet_radius=droplet_radius)
num_droplets_earth = calcNumTotalDroplets(core_radius=113*1000, droplet_radius=earth_droplet_radius)

moles_per_droplet_earth_1 = (moles_objs_vesta_1[-1] * num_droplets_vesta) / num_droplets_earth
moles_per_droplet_earth_2 = (moles_objs_vesta_2[-1] * num_droplets_vesta) / num_droplets_earth
moles_per_droplet_earth_3 = (moles_objs_vesta_3[-1] * num_droplets_vesta) / num_droplets_earth
moles_per_droplet_earth_4 = (moles_objs_vesta_4[-1] * num_droplets_vesta) / num_droplets_earth
moles_per_droplet_earth_5 = (moles_objs_vesta_5[-1] * num_droplets_vesta) / num_droplets_earth
moles_per_droplet_earth_6 = (moles_objs_vesta_6[-1] * num_droplets_vesta) / num_droplets_earth
moles_per_droplet_earth_7 = (moles_objs_vesta_7[-1] * num_droplets_vesta) / num_droplets_earth
moles_per_droplet_earth_8 = (moles_objs_vesta_8[-1] * num_droplets_vesta) / num_droplets_earth

concs_mesh_earth_1, concs_objs_earth_1, moles_mesh_earth_1, moles_objs_earth_1, verify_D_earth_1 = recalcConcentration(predicted_d=earth_1['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=moles_per_droplet_earth_1, volume_mesh=earth_vol_mesh_1_thru_4, radius_object=earth_droplet_radius)
concs_mesh_earth_2, concs_objs_earth_2, moles_mesh_earth_2, moles_objs_earth_2, verify_D_earth_2 = recalcConcentration(predicted_d=earth_2['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=moles_per_droplet_earth_2, volume_mesh=earth_vol_mesh_1_thru_4, radius_object=earth_droplet_radius)
concs_mesh_earth_3, concs_objs_earth_3, moles_mesh_earth_3, moles_objs_earth_3, verify_D_earth_3 = recalcConcentration(predicted_d=earth_3['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=moles_per_droplet_earth_3, volume_mesh=earth_vol_mesh_1_thru_4, radius_object=earth_droplet_radius)
concs_mesh_earth_4, concs_objs_earth_4, moles_mesh_earth_4, moles_objs_earth_4, verify_D_earth_4 = recalcConcentration(predicted_d=earth_4['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=moles_per_droplet_earth_4, volume_mesh=earth_vol_mesh_1_thru_4, radius_object=earth_droplet_radius)
concs_mesh_earth_5, concs_objs_earth_5, moles_mesh_earth_5, moles_objs_earth_5, verify_D_earth_5 = recalcConcentration(predicted_d=earth_5['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=moles_per_droplet_earth_5, volume_mesh=earth_vol_mesh_5_thru_8, radius_object=earth_droplet_radius)
concs_mesh_earth_6, concs_objs_earth_6, moles_mesh_earth_6, moles_objs_earth_6, verify_D_earth_6 = recalcConcentration(predicted_d=earth_6['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=moles_per_droplet_earth_6, volume_mesh=earth_vol_mesh_5_thru_8, radius_object=earth_droplet_radius)
concs_mesh_earth_7, concs_objs_earth_7, moles_mesh_earth_7, moles_objs_earth_7, verify_D_earth_7 = recalcConcentration(predicted_d=earth_7['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=moles_per_droplet_earth_7, volume_mesh=earth_vol_mesh_5_thru_8, radius_object=earth_droplet_radius)
concs_mesh_earth_8, concs_objs_earth_8, moles_mesh_earth_8, moles_objs_earth_8, verify_D_earth_8 = recalcConcentration(predicted_d=earth_8['D'],
                              original_moles_silicate=0.27950089725326804, original_moles_metal=moles_per_droplet_earth_8, volume_mesh=earth_vol_mesh_5_thru_8, radius_object=earth_droplet_radius)

reverse_D_earth_1 = forIterReverseD(obj_concs=concs_objs_earth_1, cell_concs=concs_mesh_earth_1)
reverse_D_earth_2 = forIterReverseD(obj_concs=concs_objs_earth_2, cell_concs=concs_mesh_earth_2)
reverse_D_earth_3 = forIterReverseD(obj_concs=concs_objs_earth_3, cell_concs=concs_mesh_earth_3)
reverse_D_earth_4 = forIterReverseD(obj_concs=concs_objs_earth_4, cell_concs=concs_mesh_earth_4)
reverse_D_earth_5 = forIterReverseD(obj_concs=concs_objs_earth_5, cell_concs=concs_mesh_earth_5)
reverse_D_earth_6 = forIterReverseD(obj_concs=concs_objs_earth_6, cell_concs=concs_mesh_earth_6)
reverse_D_earth_7 = forIterReverseD(obj_concs=concs_objs_earth_7, cell_concs=concs_mesh_earth_7)
reverse_D_earth_8 = forIterReverseD(obj_concs=concs_objs_earth_8, cell_concs=concs_mesh_earth_8)

cottrell_model_vesta = []
cottrell_model_earth = []
fO2_list = [-0.8, -1.10, -2.25, -2.45]
for i in fO2_list:
    temp_d_vesta = []
    temp_d_earth = []
    for index, t in enumerate(vesta_hydrostatic_depths):
        pressure = vesta_hydrostat[index]
        temperature = vesta_adiabatic[index]
        d = partition(pressure=pressure, temperature=temperature, deltaIW=i)
        temp_d_vesta.append(d)
    for index, t in enumerate(earth_hydrostatic_depths):
        pressure = earth_hydrostat[index]
        temperature = earth_adiabatic[index]
        d = partition(pressure=pressure, temperature=temperature, deltaIW=i)
        temp_d_earth.append(d)
    cottrell_model_vesta.append(temp_d_vesta)
    cottrell_model_earth.append(temp_d_earth)

# adiabatic/hydrostatic gradient figure
fig1 = plt.figure()
ax1_0 = fig1.add_subplot(111)
ax1_1 = fig1.add_subplot(211)
ax1_2 = fig1.add_subplot(212)
ax1_1.plot(vesta_adiabatic_depths, vesta_adiabatic, linewidth=2.0, color='black', label='Vesta')
ax1_2.plot(earth_adiabatic_depths, earth_adiabatic, linewidth=2.0, color='black', label='Earth')
# Turn off axis lines and ticks of the big subplot
ax1_0.spines['top'].set_color('none')
ax1_0.spines['bottom'].set_color('none')
ax1_0.spines['left'].set_color('none')
ax1_0.spines['right'].set_color('none')
ax1_0.tick_params(labelcolor='w', top='off', bottom='off', left='off', right='off')
ax1_0.xaxis.labelpad = 20
ax1_0.yaxis.labelpad = 20
ax1_0.set_xlabel("Depth (km)")
ax1_0.set_ylabel("Temperature ($\degree$K)")
ax1_0.set_title("Adiabatic Temperature Profile for Vestian and Earth Magma Ocean")
ax1_1.grid()
ax1_2.grid()
ax1_1.legend(loc='upper left')
ax1_2.legend(loc='upper left')
ax1_1.set_xlim(0, max(vesta_adiabatic_depths))
ax1_2.set_xlim(0, max(earth_adiabatic_depths))

# cottrell partition models for Vesta
fig2 = plt.figure()
ax2_0 = fig2.add_subplot(111)
ax2_1 = fig2.add_subplot(211)
ax2_2 = fig2.add_subplot(212)
# Turn off axis lines and ticks of the big subplot
ax2_0.spines['top'].set_color('none')
ax2_0.spines['bottom'].set_color('none')
ax2_0.spines['left'].set_color('none')
ax2_0.spines['right'].set_color('none')
ax2_0.tick_params(labelcolor='w', top='off', bottom='off', left='off', right='off')
ax2_0.xaxis.labelpad = 20
ax2_0.yaxis.labelpad = 20
ax2_0.set_xlabel("Depth (km)")
ax2_0.set_ylabel("D")
ax2_0.set_title("Predicted Partition Coefficients for a Vestian Magma Ocean")
ax2_1.plot(vesta_hydrostatic_depths, cottrell_model_vesta[0], color='black')
ax2_1.plot(vesta_hydrostatic_depths, cottrell_model_vesta[1], color='black')
ax2_1.fill_between(vesta_hydrostatic_depths, cottrell_model_vesta[0], cottrell_model_vesta[1], color='red', alpha=0.4,
                   label="Vesta Oxidizing Model")
ax2_1.grid()
ax2_1.legend(loc='upper right')
ax2_2.plot(vesta_hydrostatic_depths, cottrell_model_vesta[2], color='black')
ax2_2.plot(vesta_hydrostatic_depths, cottrell_model_vesta[3], color='black')
ax2_2.fill_between(vesta_hydrostatic_depths, cottrell_model_vesta[2], cottrell_model_vesta[3], color='red', alpha=0.4,
                   label="Vesta Reducing Model")
ax2_2.grid()
ax2_2.legend(loc='upper right')

# cottrell partition models for Earth
fig3 = plt.figure()
ax3_0 = fig3.add_subplot(111)
ax3_1 = fig3.add_subplot(211)
ax3_2 = fig3.add_subplot(212)
# Turn off axis lines and ticks of the big subplot
ax3_0.spines['top'].set_color('none')
ax3_0.spines['bottom'].set_color('none')
ax3_0.spines['left'].set_color('none')
ax3_0.spines['right'].set_color('none')
ax3_0.tick_params(labelcolor='w', top='off', bottom='off', left='off', right='off')
ax3_0.xaxis.labelpad = 20
ax3_0.yaxis.labelpad = 20
ax3_0.set_xlabel("Depth (km)")
ax3_0.set_ylabel("D")
ax3_0.set_title("Predicted Partition Coefficients for an Earth Magma Ocean")
ax3_1.plot(earth_hydrostatic_depths, cottrell_model_earth[0], color='black')
ax3_1.plot(earth_hydrostatic_depths, cottrell_model_earth[1], color='black')
ax3_1.fill_between(earth_hydrostatic_depths, cottrell_model_earth[0], cottrell_model_earth[1], color='red', alpha=0.4,
                   label="Earth Oxidizing Model")
ax3_1.grid()
ax3_1.legend(loc='upper right')
ax3_2.plot(earth_hydrostatic_depths, cottrell_model_earth[2], color='black')
ax3_2.plot(earth_hydrostatic_depths, cottrell_model_earth[3], color='black')
ax3_2.fill_between(earth_hydrostatic_depths, cottrell_model_earth[2], cottrell_model_earth[3], color='red', alpha=0.4,
                   label="Earth Reducing Model")
ax3_2.grid()
ax3_2.legend(loc='upper right')

# eta = 10^-3.5 model mapped to earth
fig4 = plt.figure()
ax4_0 = fig4.add_subplot(111)
ax4_1 = fig4.add_subplot(211)
ax4_2 = fig4.add_subplot(212)
# Turn off axis lines and ticks of the big subplot
ax4_0.spines['top'].set_color('none')
ax4_0.spines['bottom'].set_color('none')
ax4_0.spines['left'].set_color('none')
ax4_0.spines['right'].set_color('none')
ax4_0.tick_params(labelcolor='w', top='off', bottom='off', left='off', right='off')
ax4_0.xaxis.labelpad = 20
ax4_0.yaxis.labelpad = 20
ax4_0.set_xlabel("Depth (km)")
ax4_0.set_ylabel("D")
ax4_0.set_title("Predicted Partition Coefficients for an Earth Magma Ocean ($\eta$=10$^{-3.5}$)")
ax4_1.plot(earth_hydrostatic_depths, cottrell_model_earth[0], color='black')
ax4_1.plot(earth_hydrostatic_depths, cottrell_model_earth[1], color='black')
ax4_1.fill_between(earth_hydrostatic_depths, cottrell_model_earth[0], cottrell_model_earth[1], color='red', alpha=0.4,
                   label="Earth Oxidizing Model")
ax4_1.fill_between(earth_hydrostatic_depths, [list(vesta_1['D'])[-1] for i in earth_hydrostatic_depths],
                   [list(vesta_2['D'])[-1] for i in earth_hydrostatic_depths], color='blue', label='Final D on Vesta')
ax4_1.fill_between(earth_hydrostatic_depths, [verify_D_earth_1[0] for i in earth_hydrostatic_depths], [verify_D_earth_2[0] for i in earth_hydrostatic_depths], alpha=0.2, color='green', label='Initial D on Earth')
ax4_1.grid()
ax4_1.legend(loc='upper right')
ax4_2.plot(earth_hydrostatic_depths, cottrell_model_earth[2], color='black')
ax4_2.plot(earth_hydrostatic_depths, cottrell_model_earth[3], color='black')
ax4_2.fill_between(earth_hydrostatic_depths, cottrell_model_earth[2], cottrell_model_earth[3], color='red', alpha=0.4,
                   label="Earth Reducing Model")
ax4_2.fill_between(earth_hydrostatic_depths, [list(vesta_3['D'])[-1] for i in earth_hydrostatic_depths],
                   [list(vesta_4['D'])[-1] for i in earth_hydrostatic_depths], color='blue', label='Final D on Vesta')
ax4_2.fill_between(earth_hydrostatic_depths, [verify_D_earth_3[0] for i in earth_hydrostatic_depths], [verify_D_earth_4[0] for i in earth_hydrostatic_depths], alpha=0.2, color='green', label='Initial D on Earth')
ax4_2.grid()
ax4_2.legend(loc='upper right')

fig5 = plt.figure()
ax5_0 = fig5.add_subplot(111)
ax5_1 = fig5.add_subplot(211)
ax5_2 = fig5.add_subplot(212)
# Turn off axis lines and ticks of the big subplot
ax5_0.spines['top'].set_color('none')
ax5_0.spines['bottom'].set_color('none')
ax5_0.spines['left'].set_color('none')
ax5_0.spines['right'].set_color('none')
ax5_0.tick_params(labelcolor='w', top='off', bottom='off', left='off', right='off')
ax5_0.xaxis.labelpad = 20
ax5_0.yaxis.labelpad = 20
ax5_0.set_xlabel("Depth (km)")
ax5_0.set_ylabel("D")
ax5_0.set_title("Predicted Partition Coefficients for an Earth Magma Ocean ($\eta$=10$^{-1.0}$)")
ax5_1.plot(earth_hydrostatic_depths, cottrell_model_earth[0], color='black')
ax5_1.plot(earth_hydrostatic_depths, cottrell_model_earth[1], color='black')
ax5_1.fill_between(earth_hydrostatic_depths, cottrell_model_earth[0], cottrell_model_earth[1], color='red', alpha=0.4,
                   label="Earth Oxidizing Model")
ax5_1.fill_between(earth_hydrostatic_depths, [list(vesta_1['D'])[-1] for i in earth_hydrostatic_depths],
                   [list(vesta_2['D'])[-1] for i in earth_hydrostatic_depths], color='blue', label='Final D on Vesta')
ax5_1.fill_between(earth_hydrostatic_depths, [verify_D_earth_5[0] for i in earth_hydrostatic_depths], [verify_D_earth_6[0] for i in earth_hydrostatic_depths], alpha=0.2, color='green', label='Initial D on Earth')
ax5_1.grid()
ax5_1.legend(loc='upper right')
ax5_2.plot(earth_hydrostatic_depths, cottrell_model_earth[2], color='black')
ax5_2.plot(earth_hydrostatic_depths, cottrell_model_earth[3], color='black')
ax5_2.fill_between(earth_hydrostatic_depths, cottrell_model_earth[2], cottrell_model_earth[3], color='red', alpha=0.4,
                   label="Earth Reducing Model")
ax5_2.fill_between(earth_hydrostatic_depths, [list(vesta_3['D'])[-1] for i in earth_hydrostatic_depths],
                   [list(vesta_4['D'])[-1] for i in earth_hydrostatic_depths], color='blue', label='Final D on Vesta')
ax5_2.fill_between(earth_hydrostatic_depths, [verify_D_earth_7[0] for i in earth_hydrostatic_depths], [verify_D_earth_8[0] for i in earth_hydrostatic_depths], alpha=0.2, color='green', label='Initial D on Earth')
ax5_2.grid()
ax5_2.legend(loc='upper right')

plt.show()


import os
import time
import datetime
from pathlib import Path
from typing import Dict, Optional, List, Tuple
import pandas as pd

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import NoSuchElementException
from webdriver_manager.chrome import ChromeDriverManager
from htmldate import find_date

USRNME = 'BocarBa'

def selenium_driver_helper(main_url: str):
    """
    Create driver object using chrome driver and selenium.
    :param main_url: string with link to main website
    :return driver: selenium driver object
    """
    # path to the chromedriver executable
    chromedriver = "C:/Users/robal/Downloads/chromedriver_win32chromedriver/chromedriver.exe"
    os.environ["webdriver.chrome.driver"] = chromedriver

    options = webdriver.ChromeOptions()
    options.add_argument('--disable-blink-features=AutomationControlled')
    options.add_argument("--incognito")
    options.add_experimental_option("excludeSwitches", ["enable-automation"])

    driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
    driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
    driver.get(main_url)

    return driver

def enter_text_helper(driver: webdriver.Chrome, xpath: str, text: str):
    """
    Helper function to enter text into a web field using selenium
    :param driver: selenium driver object
    :param xpath: the xpath of the element to enter text into
    :param text: the text to be entered
    :result: enters text into element
    """
    inp = driver.find_element_by_xpath(xpath)
    inp.send_keys(USRNME)

def click_button_helper(driver: webdriver.Chrome, xpath: str):
    """
    Helper function to click web element using selenium
    :param driver: selenium driver object
    :param xpath: the xpath of the element to enter text into
    :return bool: whether clicking the element was successful
    :result: clicks web element
    """
    try:
        element = driver.find_element_by_xpath(xpath)
        element.click()
        return True
    except:
        return False

def download_fsearch_page_csv(driver: webdriver.Chrome, main_page_window):
    """
    Handles downloading a single page from foundation search as csv
    :param driver: selenium driver object
    :param main_page_window: the window_handle of the main page
    :return bool: whether clicking the next page was successful
    :result: downloads csv of data in page, and clicks to next page if possible
    """
    export_csv_xpath = '//*[@id="ctl00_ctl00_TabContentPlaceHolder_FindFundersContentPlaceHolder_ExportLink"]/span'
    click_button_helper(driver, export_csv_xpath)

    popup_window = driver.window_handles[1]
    driver.switch_to.window(popup_window)

    time.sleep(2)

    select_all_xpath = '/html/body/form/div[4]/table[2]/tbody/tr/td[1]/a[1]'
    download_csv_xpath = '/html/body/form/div[4]/div[2]/table/tbody/tr/td[1]/a[1]'
    exit_popup_xpath = '/html/body/form/div[3]/div/a/span[1]'

    # download csv in popup window
    click_button_helper(driver, select_all_xpath)
    click_button_helper(driver, download_csv_xpath)

    # close popup window and return to main page
    time.sleep(2)
    click_button_helper(driver, exit_popup_xpath)
    driver.switch_to.window(main_page_window)

    # click next page - DOES NOT CURRENTLY WORK
    time.sleep(10)

    return click_button_helper(driver, '//*[@id="ctl00_ctl00_TabContentPlaceHolder_FindFundersContentPlaceHolder_ctl00_listView_ctl01_btnNext"]')

def scrape_foundations_search():
    """
    Handles downloading data from foundations search
    :result: downloads csvs of from each page of data
    """
    url = 'https://www.foundationsearch.com/FindFunders/GrantVisualizer.aspx?searchid=5430205'
    driver = selenium_driver_helper(url)

    usrnme_xpath =  '/html/body/form/div[3]/main/div[4]/div/div/div/div[1]/div/div/div[1]/div[2]/input'
    pwrd_xpath = '/html/body/form/div[3]/main/div[4]/div/div/div/div[1]/div/div/div[2]/div[2]/input'
    submit_xpath = '/html/body/form/div[3]/main/div[4]/div/div/div/div[1]/div/div/div[4]/div[2]/a/span'

    # login page
    time.sleep(2)
    enter_text_helper(driver, usrnme_xpath, USRNME)
    enter_text_helper(driver, pwrd_xpath, USRNME)
    time.sleep(2)
    click_button_helper(driver, submit_xpath)

    main_page_window = driver.window_handles[0]

    # download csvs
    new_page = True
    while new_page:
        new_page = download_fsearch_page_csv(driver, main_page_window)


import google
import google.auth.transport.requests
from google.oauth2 import id_token

def verify_google_idtoken(idtoken: str, audience="iap.googleapis.com",
                          jwk_url="https://www.googleapis.com/oauth2/v3/certs"):
    """
      Verifies the obtained Google id token. This is done at the receiving end of the OIDC endpoint.
      The most common use case for verifying the ID token is when you are protecting
      your own APIs with IAP. Google services already verify credentials as a platform,
      so verifying ID tokens before making Google API calls is usually unnecessary.

    Args:
        idtoken: The Google ID token to verify.

        audience: The service name for which the id token is requested. Service name refers to the
            logical identifier of an API service, such as "iap.googleapis.com".

        jwk_url: To verify id tokens, get the Json Web Key endpoint (jwk).
            OpenID Connect allows the use of a "Discovery document," a JSON document found at a
            well-known location containing key-value pairs which provide details about the
            OpenID Connect provider's configuration.
            For more information on validating the jwt, see:
            https://developers.google.com/identity/protocols/oauth2/openid-connect#validatinganidtoken

            Here, we validate Google's token using Google's OpenID Connect service (jwkUrl).
            For more information on jwk,see:
            https://auth0.com/docs/secure/tokens/json-web-tokens/json-web-key-sets
    """

    request = google.auth.transport.requests.Request()
    # Set the parameters and verify the token.
    # Setting "certs_url" is optional. When verifying a Google ID token, this is set by default.
    result = id_token.verify_token(idtoken, request, audience, clock_skew_in_seconds=10)

    # Verify that the token contains subject and email claims.
    # Get the User id.
    if not result["sub"] is None:
        print(f"User id: {result['sub']}")
    # Optionally, if "INCLUDE_EMAIL" was set in the token options, check if the
    # email was verified.
    if result['email_verified'] == "True":
        print(f"Email verified {result['email']}")

# [END auth_cloud_verify_google_idtoken]


#Ingrese por teclado 10 letras, indique cuantas de ellas son vocales y cuántas son consonantes

vocales = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
vocales_contador = 0
consonantes = 0

for i in range(10):
    letras = input("ingrese una letra: ")
    if letras in vocales:
        vocales_contador += 1
    else:
        consonantes += 1
print(f"Hay {vocales_contador} vocales y {consonantes} consonantes. ")

Programación de Algoritmos Duoc/Primer semestre/Clase 3/ejercicio 2.py


# concierge-nlp-cluster/concierge_nlp_cluster/database.py
import logging
import redis
import pandas as pd

from redis.commands.search.query import Query
from concierge_nlp_cluster.utils.database.redis import NUM_VECTORS

# Logging set up
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def process_doc(doc: dict) -> dict:
    """
    Process document to handle vector_score and bytes data.

    Args:
    doc: dict: Document to be processed.

    Returns:
    dict: Processed document.
    """
    d = doc.__dict__
    if "vector_score" in d:
        d["vector_score"] = 1 - float(d["vector_score"])

    if isinstance(d["document_name"], bytes):
        d["document_name"] = d["document_name"].decode("utf-8", errors="ignore")
    if isinstance(d["text_chunks"], bytes):
        d["text_chunks"] = d["text_chunks"].decode("utf-8", errors="ignore")

    return d

def index_documents(redis_conn: redis.Redis, df: pd.DataFrame, prefix: str):
    """
    Index documents in Redis.

    Args:
    redis_conn: redis.Redis: Redis connection.
    df: pd.DataFrame: DataFrame containing documents to be indexed.
    prefix: str: Prefix to be used for document keys.

    """
    pipe = redis_conn.pipeline()
    for index, row in df.iterrows():
        key = f"{prefix}:{row['vector_id']}"
        document_data = {
            "document_name": row["document_name"],
            "text_chunks": row["text_chunks"],
            "text_embeddings": row["text_embeddings"].tobytes(),
        }
        pipe.hset(key, mapping=document_data)
        logger.info(f"Indexing document: {key}, document_data: {document_data}")
    pipe.execute()

def load_documents(redis_conn: redis.Redis, df: pd.DataFrame, prefix: str):
    """
    Load documents into Redis.

    Args:
    redis_conn: redis.Redis: Redis connection.
    df: pd.DataFrame: DataFrame containing documents to be loaded.
    prefix: str: Prefix to be used for document keys.

    """
    logger.info(f"Indexing {len(df)} Documents")
    index_documents(redis_conn, df, prefix)
    logger.info("Redis Vector Index Created!")

def list_docs(
    redis_conn: redis.Redis,
    index_name: str,
    k: int = NUM_VECTORS,
) -> list[dict]:
    """
    List documents from Redis index.

    Args:
    redis_conn: redis.Redis: Redis connection.
    index_name: str: Name of the index to fetch documents from.
    k: int: Maximum number of documents to fetch.

    Returns:
    list[dict]: List of documents from Redis index.

    """
    base_query = "*"
    return_fields = ["document_name", "text_chunks"]
    query = Query(base_query).paging(0, k).return_fields(*return_fields).dialect(2)
    results = redis_conn.ft(index_name).search(query)
    return [process_doc(doc) for doc in results.docs]

def delete_index(redis_conn: redis.Redis, index_name: str):
    """
    Delete a specific index from Redis.

    Args:
    redis_conn: redis.Redis: Redis connection.
    index_name: str: Name of the index to be deleted.

    """
    try:
        redis_conn.execute_command("FT.DROPINDEX", index_name)
        logger.info(f"Index {index_name} has been deleted.")
    except redis.exceptions.ResponseError as e:
        if "Unknown index name" in str(e):
            logger.info(f"Index {index_name} does not exist.")
        else:
            raise e

def clear_cache(redis_conn: redis.Redis):
    """
    Clear cache in Redis.

    Args:
    redis_conn: redis.Redis: Redis connection.

    """
    redis_conn.flushdb()
    logger.info("Cache cleared")


"""Command-line tool for making self-extracting Python file.

Call this program from your command line with one argument:
  (1) the file that you want to pack and compress
  (2) the output will be a file with a pyw ending
The output can run on Windows where Python is installed."""

################################################################################

import sys
import os.path
import bz2
import zlib
import base64

################################################################################

def main():
    "Extract the command-line arguments and run the packer."
    try:
        pack(sys.argv[1])
    except (IndexError, AssertionError):
        print('Usage: {} <filename>'.format(os.path.basename(sys.argv[0])))

def pack(path):
    "Get the source, compress it, and create a packed file."
    data = read_file(path)
    builder, data = optimize(data)
    with open(os.path.splitext(path)[0] + '.pyw', 'w') as file:
        builder(os.path.basename(path), base64.b64encode(data), file)

def read_file(path):
    "Read the entire file content from path in binary mode."
    assert os.path.isfile(path)
    with open(path, 'rb') as file:
        return file.read()

def optimize(data):
    "Compress the data and select the best method to write."
    bz2_data = bz2.compress(data, 9)
    zlib_data = zlib.compress(data, 9)
    sizes = tuple(map(len, (data, bz2_data, zlib_data)))
    smallest = sizes.index(min(sizes))
    if smallest == 1:
        return build_bz2_extractor, bz2_data
    if smallest == 2:
        return build_zlib_extractor, zlib_data
    return build_b64_extractor, data

################################################################################

def build_bz2_extractor(filename, data, file):
    "Write a Python program that uses bz2 data compression."
    print("import base64, bz2, os", file=file)
    print("data =", data, file=file)
    print("with open({!r}, 'wb') as file:".format(filename), file=file)
    print("    file.write(bz2.decompress(base64.b64decode(data)))", file=file)
    print("os.startfile({!r})".format(filename), file=file)

def build_zlib_extractor(filename, data, file):
    "Pack data into a self-extractor with zlib compression."
    print("import base64, zlib, os", file=file)
    print("data =", data, file=file)
    print("with open({!r}, 'wb') as file:".format(filename), file=file)
    print("    file.write(zlib.decompress(base64.b64decode(data)))", file=file)
    print("os.startfile({!r})".format(filename), file=file)

def build_b64_extractor(filename, data, file):
    "Create a Python file that may not utilize compression."
    print("import base64, os", file=file)
    print("data =", data, file=file)
    print("with open({!r}, 'wb') as file:".format(filename), file=file)
    print("    file.write(base64.b64decode(data))", file=file)
    print("os.startfile({!r})".format(filename), file=file)

################################################################################

if __name__ == '__main__':
    main()

# Small Program Version

# import bz2,base64 as a,os.path as b,sys,zlib;c=sys.argv[1]
# with open(c,'rb') as d:d=d.read();e,f=bz2.compress(d),zlib.compress(d,9);g=list(map(len,(d,e,f)));g,h,i,j,k,l=g.index(min(g)),'import base64 as a,os','\nwith open({0!r},"wb") as b:b.write(','.decompress(','a.b64decode({1}))',';os.startfile({0!r})'
# if g==1:d,e=e,h+',bz2'+i+'bz2'+j+k+')'+l
# elif g==2:d,e=f,h+',zlib'+i+'zlib'+j+k+')'+l
# else:e=h+i+k+l
# with open(b.splitext(c)[0]+'.pyw','w') as f:f.write(e.format(b.basename(c),a.b64encode(d)))


# coding:utf-8
# 第1种解法
'''
线性扫描：对bits数组从左到右扫描来判断最后一位是否为一比特字符。当扫描到第 i位时，
如果bits[i]=1，那么说明这是一个两比特字符，将 i的值增加 2。
如果bits[i]=0，那么说明这是一个一比特字符，将 i的值增加 1。
如果 i最终落在了 bits.length−1 的位置，那么说明最后一位一定是一比特字符。
时间复杂度：O(n)、空间复杂度O(1)
'''
def isOneBitCharacter(bits):
    i = 0
    while i < len(bits)-1:
        i += bits[i] + 1
    return i == len(bits) - 1

# 第2种解法
'''
三种字符分别为0,10,11，那么bits 数组中出现的所有 0 都表示一个字符的结束位置（无论其为一比特还是两比特）。
因此最后一位是否为一比特字符，只和他左侧出现的连续的 1 的个数（即它与倒数第二个 0 出现的位置之间的 1 的个数，
如果 bits 数组中只有 1 个 0，那么就是整个数组的长度减一）有关。如果 1 的个数为偶数个，
那么最后一位是一比特字符，如果 1 的个数为奇数个，那么最后一位不是一比特字符。
'''
def isOneBitCharacter2(bits):
    parity = bits.pop()
    while bits and bits.pop(): parity ^= 1
    return parity == 0
print(isOneBitCharacter2([1,1,1,0]))


SIZE = 50
table = []
parent = [[] for _ in range(SIZE)]

# 조상을 찾는다.
def find_ancestor(r, c):
    if [r, c] != parent[r][c]:
        parent[r][c] = find_ancestor(*parent[r][c])
    return parent[r][c]

# 해당 위치에 저장된 데이터가 중요한게 아니다. 조상의 데이터를 조회한다.
def get_data(r, c):
    ar, ac = find_ancestor(r, c)
    return table[ar][ac]

# old인지 확인하기 위해서 table[r][c]로 찾지 마라.
# 부모의 값이 일치하는지 찾는게 진짜로 병합된 셀 값 바꾸는 방법이다.
def update_by_value(old, new):
    for r in range(SIZE):
        for c in range(SIZE):
            if get_data(r, c) == old:
                pr, pc = find_ancestor(r, c)
                table[pr][pc] = new

# 그 위치의 값을 업데이트 할거지만, 역시나 조상의 값을 바꿔야 한다.
def update_by_pos(r, c, value):
    r, c = int(r) - 1, int(c) - 1
    ar, ac = find_ancestor(r, c)
    table[ar][ac] = value

# 진짜로 병합하기
def merge(r1, c1, r2, c2):
    if r1 == r2 and c1 == c2:
        return
    r1, c1, r2, c2 = r1 - 1, c1 - 1, r2 - 1, c2 - 1

    ar1, ac1 = find_ancestor(r1, c1)
    ar2, ac2 = find_ancestor(r2, c2)

    if table[ar1][ac1] is None:
        parent[ar1][ac1] = [ar2, ac2]
    else:
        parent[ar2][ac2] = [ar1, ac1]

# 병합 해제하기
# 처음에는 각 위치별 자손의 위치를 저장했는데 그냥 2중 for문 돌면서 자식 찾아내면 됨
def unmerge(r, c):
    r, c = r - 1, c - 1
    ar, ac = find_ancestor(r, c)
    value = table[ar][ac]

    seperates = []

    for row in range(SIZE):
        for col in range(SIZE):
            if [ar, ac] == find_ancestor(*parent[row][col]):
                seperates.append((row, col))

    for row, col in seperates:
        parent[row][col] = [row, col]
        table[row][col] = None

    table[r][c] = value
    parent[r][c] = [r, c]

# 역시나 조상을 찾고 그 조상의 값을 출력해야함
def print_cell(r, c):
    r, c = r - 1, c - 1
    ar, ac = find_ancestor(r, c)
    return table[ar][ac] if table[ar][ac] is not None else "EMPTY"

def solution(commands):
    global table
    answer = []
    table = [[None] * SIZE for _ in range(SIZE)]
    for r in range(SIZE):
        for c in range(SIZE):
            parent[r].append([r, c])

    for command in commands:
        command = command.split()
        order = command.pop(0)
        if order == "UPDATE":
            if len(command) == 2:
                update_by_value(*command)
            else:
                update_by_pos(*command)
        elif order == "MERGE":
            merge(*map(int, command))
        elif order == "UNMERGE":
            unmerge(*map(int, command))
        elif order == "PRINT":
            answer.append(print_cell(*map(int, command)))

    return answer


import sys
import time
import numpy as np
import xlsxwriter
from insertion_sort import insertionSort
from merge_sort import merge_sort
from quick_select_pivot_first import quick_select_pivot_first
from quick_select_three_median import quick_select_three_median
sortTypes = {
    'merge-sort':['merge-sort',3],
    'insertion-sort':['insertion-sort',3],
    'quick-first':['quick-first',3],
    'quick-median':['quick-median',3]
}

printCases=['Random Array','Worst Case','Best Case']

filename=sys.argv[1]
condition=sys.argv[2]
kthElement=9
row=0
column=0

def writeColumnTitles(worksheet,row,column,condition):
    for i in range(1,sortTypes[condition][1]+1):
        worksheet.write(row,column+i,printCases[i-1])
def saveArray(arrayType,i_size,condition,array):
    saveString='arrays/'
    cases=['random-array_','best-case_','worst-case_']
    if(condition==sortTypes['insertion-sort'][0]):
        saveString=saveString+'insertion-sort/'
    elif(condition==sortTypes['merge-sort'][0]):
        saveString=saveString+'merge-sort/'
    elif(condition==sortTypes['quick-first'][0]):
        saveString=saveString+'quick-first/'
    elif(condition==sortTypes['quick-median'][0]):
        saveString=saveString+'quick-median/'
    for i in range(len(array)):
        saveStringNew=saveString+arrayType+'/'+cases[i]+arrayType+'-size-'+str(i_size)+'.txt'
        F=open(saveStringNew,'w')
        step=75
        lineEnd=step
        for j in range(len(array[i])):
            if j>=lineEnd:
                F.write('\n')
                lineEnd+=step
            F.write(str(array[i][j]))
            F.write('  ')
        F.close()

def prepareArraysForCases(i_size,condition):
    normal_array=np.random.random_integers(0,100000,size=(i_size))
    if(condition==sortTypes['insertion-sort'][0]):
        best_case=normal_array.copy()
        best_case=sorted(best_case)
        temp=best_case.copy()
        worst_case=list(reversed(temp)).copy()
        saveArray('input',i_size,condition,[normal_array,best_case,worst_case])
        return [[normal_array,9],[worst_case,9],[best_case,9]]
    elif(condition==sortTypes['merge-sort'][0]):
        best_case=sorted(normal_array.copy())
        worst_case=list(reversed(normal_array.copy()))
        saveArray('input',i_size,condition,[normal_array,best_case,worst_case])
        return [[normal_array,9],[worst_case,9],[best_case,9]]
    elif(condition==sortTypes['quick-first'][0]):
        best_case=normal_array.copy()
        best_case=sorted(best_case)
        temp=best_case.copy()
        #worst_case=list(reversed(temp))
        worst_case=best_case.copy()
        lnt=len(normal_array)
        halflnt=lnt//2
        saveArray('input',i_size,condition,[normal_array,best_case,worst_case])
        return [[normal_array,9],[worst_case,1],[best_case,1]]
    elif(condition==sortTypes['quick-median'][0]):
        best_case=normal_array.copy()
        best_case=sorted(best_case)
        temp=best_case.copy()
        worst_case=list(reversed(temp))
        lnt=len(normal_array)
        halflnt=lnt//2
        saveArray('input',i_size,condition,[normal_array,best_case,worst_case])
        return [[normal_array,9],[worst_case,len(normal_array)-1],[best_case,1]]
def runFunction(condition,alist,k):
    if condition == sortTypes['insertion-sort'][0]:
        start_time=time.time()
        kthElement=insertionSort(alist,k)
        end_time=time.time()
    elif condition == sortTypes['merge-sort'][0]:
        start_time=time.time()
        kthElement=merge_sort(alist,k)
        end_time=time.time()
    elif condition == sortTypes['quick-first'][0]:
        start_time=time.time()
        kthElement=quick_select_pivot_first(alist,k)
        end_time=time.time()
    elif condition == sortTypes['quick-median'][0]:
        start_time=time.time()
        kthElement=quick_select_three_median(alist,k)
        end_time=time.time()
    return end_time-start_time

rowCount=0
workbook=xlsxwriter.Workbook('out/'+filename)
worksheet=workbook.add_worksheet()

writeColumnTitles(worksheet,row,column,condition)
count=0
cases=[]
step=10000
for input_size in range(101000,111000,step):
    rowCount+=1
    worksheet.write(row+rowCount,column,str(input_size))
    endStr=''
    cases=prepareArraysForCases(input_size,condition)
    print("Test cases generated")
    numOfCases=len(cases)
    print('Array size = '+str(input_size),end=' ---> ')
    for i in cases:
        totaltime=runFunction(condition,i[0],i[1])
        if(count==numOfCases-1):
            endStr='\n'
        else:
            endStr='\n                              '
        print(printCases[count]+": %f"%totaltime,end=endStr)
        worksheet.write(row+rowCount,column+count+1,totaltime)

        count+=1
        count=count%numOfCases
    saveArray('output',input_size,condition,[cases[0][0],cases[1][0],cases[2][0]])
workbook.close()
exit()


from __future__ import unicode_literals

import json

from django.http import HttpResponse
from django.shortcuts import render
from django.template import loader
from django.views.decorators.csrf import ensure_csrf_cookie

@ensure_csrf_cookie
def root(request):
    user = request.user if request.user.is_authenticated() else None

    payload = {}

    if user:
        user = user.to_user()

        payload = {
            'session': {
                'currentUser': user,
            },
            'browse': {
                'feed': [],
                'users': {
                    'list': [],
                    'current': {}
                }
            }
        }

    return render(request, 'partials/root.html', {'payload': json.dumps(payload)})


import pandas as pd
from Data.AddEntry import AddEntry
from Data.AddEntry import match_id_to_name

class ExcelReader:
    """Reads rows from an excel sheet and uploads them to the respective JSON file."""

    df = pd.read_excel(r'C:\Users\james\OneDrive\Desktop\Points Coordinator\Winter 2021.xlsx',
                       sheet_name='Points Tracking')

    def __init__(self):
        """Initialize the ExcelReader."""

    def add_tournament_data(self):
        """Takes in data from excel spreadsheet for debate tournament results and adds them as competitive points."""

        for x in range(len(self.df['Name'])):
            debater_id = int(self.df.loc[x]['Debater ID'])
            semester = "Winter 2021"
            new_entry = AddEntry(debater_id, semester)

            tournament_tier = self.df.loc[x]['Tier']
            tournament_name = self.df.loc[x]['Tournament']
            judging = self.df.loc[x]['Judging']

            if judging == 'Yes':
                if self.df.loc[x]['Judge Break'] == 'Yes':
                    break_judge = True
                else:
                    break_judge = False

                new_entry.tournament_judging(tournament_tier, tournament_name, break_judge)

            else:
                size = self.df.loc[x]['No. of Teams']
                team_place = self.df.loc[x]['Team Place']
                speaker_place = self.df.loc[x]['Speaker Place']
                new_entry.tournament_debating(tournament_tier, tournament_name, size, team_place, speaker_place)

    def check_name_to_id(self) -> None:
        """Check if the name and ID match. If not, print the occurrence."""
        for x in range(len(self.df['Name'])):
            debater_id = int(self.df.loc[x]['Debater ID'])
            name_excel = self.df.loc[x]['Name']
            name_system = match_id_to_name(debater_id)

            if name_excel != name_system:
                print(name_excel + ' : ' + str(debater_id))

        print('Finished!')

file = ExcelReader()
file.add_tournament_data()


import tensorflow as tf
from PIL import Image
import matplotlib.pyplot as plt

def load_image(image_path):
    img = tf.io.read_file(image_path)
    img = tf.io.decode_jpeg(img, channels=3)
    img = tf.keras.layers.Resizing(299, 299)(img)
    img = tf.keras.applications.inception_v3.preprocess_input(img)
    return img

def show_image(image_path, height=10, weight=10):
    img = Image.open(image_path)
    plt.figure(figsize=(height, weight))
    plt.imshow(img)
    plt.show()

def post_processing(text):
    words_to_remove = ['<bos>', '<eos>', '[UNK]']
    for word in words_to_remove:
        text = text.replace(word, "")
    return text


from __future__ import with_statement, print_function
import os
import imp
import cPickle
import json

def rule_encode(rule):
    return buffer(cPickle.dumps(rule))

def rule_decode(rule):
    return cPickle.loads(str(rule))

class CBuilder(object):
    def __init__(self, compiler=None, cflags=None, libs=None):
        if compiler is None:
            compiler = 'gcc'
        self.compiler = compiler
        if cflags is None:
            cflags = ['-Wall']
        self.cflags = cflags
        if libs is None:
            libs = []
        self.libs = libs

    def prepend(self, cflags=[], libs=[]):
        return CBuilder(self.compiler, cflags + self.cflags, libs + self.libs)

    def get_compile(self, src):
        srco = src + '.o'
        return srco, [self.compiler, '-c', src, '-o', srco] + self.cflags

    def get_link(self, exename, objs, extralibs):
        return [self.compiler, '-o', exename] + self.cflags + objs + extralibs + self.libs

class Environment(object):
    def __init__(self):
        self._buildbysuffix = dict()
        self.register_builder('.c', CBuilder())

    def register_builder(self, suffix, builder):
        self._buildbysuffix[suffix] = builder

    def get_builder(self, source):
        suffix = os.path.splitext(source)[1]
        return self._buildbysuffix[suffix]

class ExeHelper(object):
    def __init__(self, reghelper, exeid):
        self._reghelper = reghelper
        self._exeid = exeid

    def test(self, testname, func, args):
        return self._reghelper.test(self._exeid, testname, func, args)

class RegHelper(object):
    def __init__(self, env, db, dirid):
        self._db = db
        self._dirid = dirid
        self._env = env

    def executable(self, sources, exename=None, extralibs=[]):
        if isinstance(sources, str):
            sources = [sources]
        if exename is None:
            exename = os.path.splitext(sources[0])[0]
        mainbuilder = self._env.get_builder(sources[0])
        objids = []
        objnames = []
        for src in sources:
            srcid = self._db.add_file(self._dirid, src)
            builder = self._env.get_builder(src)
            objname, rule = builder.get_compile(src)
            objid = self._db.add_file(self._dirid, objname, ghost=True)
            qrule = rule_encode(rule)
            self._db.add_rule(self._dirid, qrule, [srcid], [objid])
            objids.append(objid)
            objnames.append(objname)
        link = mainbuilder.get_link(exename, objnames, extralibs)
        qlink = rule_encode(link)
        exeid = self._db.add_file(self._dirid, exename, ghost=True)
        self._db.add_rule(self._dirid, qlink, objids, [exeid])
        return ExeHelper(self, exeid)

    def test(self, exeid, testname, func, args):
        testid = self._db.add_test(self._dirid, testname)
        rule = rule_encode((testname, func, args))
        self._db.add_rule(self._dirid, rule, [exeid], [testid])

class Registrar(object):
    def __init__(self, env, db):
        self._env = env
        self._db = db

    def walk(self, path, pbtfile='pbtfile.py'):
        for root, dirs, files in os.walk('tmp'):
            if pbtfile not in files:
                raise RuntimeError('No pbtfile.py at %s' % root)
            sub = imp.load_source('pbt_register', os.path.join(root, pbtfile))
            dirid = self._db.dir(root)
            reg = RegHelper(self._env, self._db, dirid)
            sub.register(reg)


import joblib
import numpy as np
from main import get_depth, depth2coor
from matplotlib import pyplot as plt

def draw_unICP(coor1_x: np.array, coor1_y: np.array, coor2_x: np.array, coor2_y: np.array, index: int = None):
    assert len(coor1_x) == len(coor2_x) == len(coor1_y) == len(coor2_y)
    frame1 = plt.scatter(coor1_x, coor1_y, s=1, c='red')
    frame2 = plt.scatter(coor2_x, coor2_y, s=1, c='green')

    for j in range(len(coor1_x)):
        plt.plot([coor2_x[j], coor1_x[j]], [coor2_y[j], coor1_y[j]], c='g', linewidth=0.4)

    plt.legend([frame1, frame2], ['Old', 'Current'], scatterpoints=2, loc='upper left')
    if index is None:
        plt.title("test")
    else:
        plt.title("Frame{}&{}_unICP".format(str(index), str(index - 1)))
    plt.show()

# para1 Init(frame0) para2 Source(frame index+1) para ICPed
def draw(coor1_x: np.array, coor1_y: np.array, coor2_x: np.array, coor2_y: np.array, coor3_x: np.array,
         coor3_y: np.array, index_: int):
    frame1 = plt.scatter(coor1_x, coor1_y, s=1, c='red')
    frame2 = plt.scatter(coor2_x, coor2_y, s=1, c='green')
    frame3 = plt.scatter(coor3_x, coor3_y, s=1, c='blue')

    plt.legend([frame1, frame2, frame3], ['Init', 'UnICP_frame{}'.format(index_), 'ICPed_frame{}'.format(index_)], scatterpoints=3, loc='upper left')
    plt.show()

def readMatrix(path='./TransformMatrix/1&0'):
    m = joblib.load(path)
    return m

def readMatrixByIndex(index_: int = 1):
    m = joblib.load('./TransformMatrix/{}&{}'.format(index_, index_ - 1))
    return m

if __name__ == '__main__':
    index = 1
    matrixs = list()
    for i in range(index):
        matrixs.append(readMatrixByIndex(i+1))

    depth_data = get_depth("hw1_data/data.txt")
    coordinate_data = depth2coor(depth_data)

    # Init frame
    left0_x = [coordinate_data[0][p][0] for p in range(360)]
    left0_y = [coordinate_data[0][p][1] for p in range(360)]

    # Source frame
    lefts_x = [coordinate_data[index][p][0] for p in range(360)]
    lefts_y = [coordinate_data[index][p][1] for p in range(360)]

    # Current frame
    left2_x = [coordinate_data[index][p][0] for p in range(360)]
    left2_y = [coordinate_data[index][p][1] for p in range(360)]

    for j in range(360):
        for i in range(index):
            left2_x[j], left2_y[j], _ = np.array(np.matmul(matrixs[-1-i], np.mat([left2_x[j], left2_y[j], 1]).T).T)[0]

    draw(left0_x, left0_y, lefts_x, lefts_y, left2_x, left2_y, index)


PLATOS_INTERMEDIO = 5
PLATOS_EXPERTO = 15
PRECIO_BOCADILLO = 50
LLEGADA_CLIENTES = 3000
PROPINA = 10
TIEMPO_ESPERA_RELAJADO = 15
PROB_RELAJADO = 0.3
TIEMPO_ESPERA_APURADO = 10
PROB_APURADO = 0.7
DINERO_INICIAL = 400
REPUTACION_INICIAL = 3
CHEFS_INICIALES = 1
MESAS_INICIALES = 2
CLIENTES_INICIALES = 10
VEL_MOVIMIENTO = 8
LARGO_MAPA = 550  # x
ANCHO_MAPA = 370  # y
FALLAR_NUMERAODR = 0.3
FALLAR_DENOMINADOR = 1
EXP_PRINCIPIANTE = 1
EXP_INTERMEDIO = 2
EXP_EXPERTO = 3
PREPARACION_DESDE = 0
PREPARCION_HASTA = 15
PREPARACION_CHEF = 2
CALIDAD_DESDE = 0
CALIDAD_NUM1 = 1
CALIDAD_NUM2 = 0.05
CALIDAD_NUM3 = 3
REPUTACION_DESDE1 = 0
REPUTACION_DESDE2 = 5
REPUTACION_M = 4
REPUR = 2
CANTIDAD_CLIENTES_M = 5
CANTIDAD_CLIENTES_S = 1
DINERO_TRAMPA = 300
REPUTACION_TRAMPA = 2
X_INICIAL = 180
Y_INICIAL = 480
PATH_MAPA = "mapa.csv"
PATH_DATOS = "datos.csv"
CHEF_X = 60
CHEF_Y = 70
MESA_X = 25
MESA_Y = 55
MESERO_X = 32
MESERO_Y = 32
CLIENTE_X = 25
CLIENTE_Y = 25
CLIENTE_X_ENOJADO = 50
CLIENTE_Y_ENOJADO = 50
PATH_VENTANA_INICIAL = "VentanaInicio.ui"
PATH_VENTANA_PRINCIPAL = "Ventana_Principal.ui"
PATH_VENTANA_FINAL = "Ventana_Final.ui"
PATH_BOCADILLO = "sprites/bocadillos/bocadillo_09.png"
PATH_VENTANA_PERDEDOR = "Ventana_Perdedor.ui"


"""Script to prepare amos dataset."""

import logging

from pathlib import Path
import random

from transoar.utils.io import get_config, set_root_logger, load_json
from transoar.data.preprocessor_luna16 import PreProcessor

if __name__ == "__main__":
    # Set config of root logger
    set_root_logger('./logs/prepare_dataset.log')
    logging.info('Started preparing dataset.')

    # Load data config
    preprocessing_config = get_config('preprocessing_luna16')
    data_config = get_config(preprocessing_config['dataset_config'])

    print(preprocessing_config)
    print(data_config)

    random.seed(preprocessing_config['seed'])  # Set arbitrary seed to make experiments reproducible

    dataset_name = preprocessing_config['dataset_name']
    fold = preprocessing_config['fold']
    path_dataset = Path(preprocessing_config['path_to_dataset'])   # complete dataset
    path_to_splits = Path(f"{preprocessing_config['path_to_split']}/{dataset_name}_{fold}")
    split_file = Path(f"{preprocessing_config['path_to_dataset']}/preprocessed/splits_final.json")
    logging.info(f'path_dataset: {path_dataset}')
    logging.info(f'path_to_splits: {path_to_splits}')
    logging.info(f'fold: {fold}')
    logging.info(f'dataset_name: {dataset_name}')

    split_info = load_json(split_file)[fold]

    # Create test, val, and train split
    train_set = split_info['train']
    val_set = split_info['val']
    test_set = split_info['val']

    logging.info(f'Preparing dataset {dataset_name}_{fold}.')
    logging.info(f'len train: {len(train_set)}, len val: {len(val_set)}, len test: {len(test_set)}.')

    # Prepare dataset based on dataset analysis
    logging.info(f"Starting dataset preprocessing. Target shape: {preprocessing_config['resize_shape']}.")
    preprocessor = PreProcessor(
        train_set, val_set, test_set, path_dataset, path_to_splits, preprocessing_config, data_config
    )
    preprocessor.run()
    logging.info(f'Succesfully finished dataset preprocessing.')


def part1():
    with open("day1.txt", "r") as inFile:
        count = 0
        previous = None
        for line in inFile:
            value = int(line.strip())
            if previous and value > previous:
                count += 1
            previous = value

    print("Nbr of increasing item = %i " % count)

def part2():

    previous = 0
    count = 0
    sums = [0, 0, 0]
    with open("day1.txt", "r") as inFile:
        line1 = inFile.readline()
        line2 = inFile.readline()
        value1 = int(line1.strip())
        value2 = int(line2.strip())

        sums[0] += value1
        sums[0] += value2
        sums[1] += value2

        index = 0

        for line in inFile:
            value = int(line.strip())

            for i in range(3):
                sums[i] += value

            if previous and sums[index] > previous:
                count += 1

            previous = sums[index]
            sums[index] = 0

            index += 1
            index %= 3

    print("Nb of increasing sums = %i" % count)

part2()


"""Bill Greene's credit scoring data."""
from statsmodels.datasets import utils as du

__docformat__ = 'restructuredtext'

COPYRIGHT   = """Used with express permission of the original author, who
retains all rights."""
TITLE       = __doc__
SOURCE      = """
William Greene's `Econometric Analysis`

More information can be found at the web site of the text:
http://pages.stern.nyu.edu/~wgreene/Text/econometricanalysis.htm
"""

DESCRSHORT  = """William Greene's credit scoring data"""

DESCRLONG   = """More information on this data can be found on the
homepage for Greene's `Econometric Analysis`. See source.
"""

NOTE        = """::

    Number of observations - 72
    Number of variables - 5
    Variable name definitions - See Source for more information on the
                                variables.
"""

def load_pandas():
    """Load the credit card data and returns a Dataset class.

    Returns
    -------
    Dataset
        See DATASET_PROPOSAL.txt for more information.
    """
    data = _get_data()
    return du.process_pandas(data, endog_idx=0)

def load():
    """Load the credit card data and returns a Dataset class.

    Returns
    -------
    Dataset
        See DATASET_PROPOSAL.txt for more information.
    """
    return load_pandas()

def _get_data():
    return du.load_csv(__file__, 'ccard.csv', convert_float=True)


import pytest
import os
import python_c_sockets.rx as pcs

CI = bool(os.environ.get("CI"))

@pytest.mark.usefixtures("unicast_sender")
@pytest.mark.skipif(CI, reason="Many CI's don't have IPv6")
def test_listener():
    port = 2000
    addr = "::1"

    pcs.udpunicast(addr, port, N=1000)


from datetime import date

from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage
from django.http import HttpResponse
from django.views.generic import DetailView
from django.views import View
from .models import *
from .forms import *
from django.db.models import Q
import random
# from utils.pdf import render_to_pdf
from .decorators import allowed_users

# pdf
from django.http import HttpResponse
from django.template.loader import get_template
from xhtml2pdf import pisa
from django.shortcuts import get_object_or_404

# Email
from django.core.mail import send_mail
from django.conf import settings
from django.shortcuts import render

@login_required(login_url='login')
def render_pdf_view(request, *args, **kwargs):
    pk = kwargs.get('pk')
    certificate = get_object_or_404(Certificate, pk=pk)
    activities = Activity.objects.all()
    template_path = '../templates/pdf.html'
    context = {
        'certificate': certificate,
        'activities': activities,

    }
    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'filename="report.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response)
    # if error then show some funny view
    if pisa_status.err:
        return HttpResponse('We had some errors
' + html + '
')
    return response

@login_required(login_url='login')
def indexView(request):
    organizations = Organization.objects.all()
    hosts = Host.objects.all()
    activities = Activity.objects.all()
    participants = Participant.objects.all()

    selected_activities = []
    while len(selected_activities) < 3:
        activity = random.choice(activities)
        if activity not in selected_activities:
            selected_activities.append(activity)

    selected_hosts = []
    while len(selected_hosts) < 3:
        host = random.choice(hosts)
        if host not in selected_hosts:
            selected_hosts.append(host)

    selected_participants = []
    while len(selected_participants) < 3:
        participant = random.choice(participants)
        if participant not in selected_participants:
            selected_participants.append(participant)

    selected_organizations = []
    while len(selected_organizations) < 3:
        organization = random.choice(organizations)
        if organization not in selected_organizations:
            selected_organizations.append(organization)

    context = {
        'participants': participants,
        'activities': activities,
        'selected_activities': selected_activities,
        'selected_hosts': selected_hosts,
        'selected_participants': selected_participants,
        'organizations': organizations,
        'selected_organizations': selected_organizations,
        'hosts': hosts,
    }
    return render(request, 'index.html', context)

@login_required(login_url='login')
def activityView(request):
    paginator = Paginator(Activity.objects.filter(active=True), 4)
    page_number = request.GET.get('page', 1)
    page_obj = paginator.get_page(page_number)

    context = {
        'activities': Activity.objects.all(),
        'organizations': Organization.objects.all(),
        'participants': Participant.objects.all(),
        'host': Host.objects.all(),
        'page_obj': page_obj
    }
    return render(request, 'activities.html', context)

@login_required(login_url='login')
def activity_view_with_category(request, slug, *args, **kwargs):
    activity = Organization.objects.get(slug=slug)
    activities = activity.activity_set.filter(active=True)
    context = {
        'activities': activities,
        'host': Host.objects.all()
    }
    return render(request, 'activities_slog.html', context)

@login_required(login_url='login')
def activityDetail(request, slug):
    activity = Activity.objects.get(slug=slug)
    activities = Activity.objects.all()
    context = {
        'activity': activity,
        'activities': activities
    }
    return render(request, 'activity_detail.html', context)

# @login_required(login_url='login')
class Contactview(View):
    def get(self, request, *args, **kwargs):
        context = {
            'form': ContactForm()
        }
        return render(request, 'basarili.html', context)

    def post(self, request, *args, **kwargs):
        form = ContactForm(request.POST or None)
        if form.is_valid():
            c_form = form.save(commit=False)
            c_form.save()
            return render(request, 'basarili.html', context={'form': ContactForm()})

def send_email(request):
    if request.method == 'POST':
        fullname = request.POST.get('fullname')
        email = request.POST.get('email')
        subject = request.POST.get('subject')
        description = request.POST.get('description')
        data = {
            'fullname': fullname,
            'email': email,
            'subject': subject,
            'description': description,
        }
        print(data)

        message = '''
        New Message: {}
        From: {}
        '''.format(data['description'], data['email'])
        send_mail(data['subject'], description, settings.EMAIL_HOST_USER, ['gapparmustafa@gmail.com'], fail_silently=False)

        return HttpResponse('Thanks')

@login_required(login_url='login')
def decoratorView(request):
    return render(request, 'decorators.html')

@login_required(login_url='login')
def participantsView(request):
    participants = Participant.objects.all()
    participantss = Participant.objects.all()
    activities = Activity.objects.all()
    context = {
        'participants': participants,
        'participantss': participantss,
        'activities': activities
    }
    return render(request, 'participant.html', context)

@login_required(login_url='login')
def participantView(request, id, *args, **kwargs):
    certificate = Certificate.objects.filter(active=True, activity_name=id)
    participant = Participant.objects.filter(activity_name=id)
    activities = Activity.objects.all()
    participants = Participant.objects.all()
    context = {
        'participants': participant,
        'activities': activities,
        'participantss': participants,
        'certificates': certificate,
    }
    return render(request, 'participant.html', context)

@login_required(login_url='login')
def hostView(request):
    context = {
        'hosts': Host.objects.all()
    }
    return render(request, 'host.html', context)

@login_required(login_url='login')
def organizationView(request):
    context = {
        'organizations': Organization.objects.all()
    }
    return render(request, 'organization.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def certificateView(request, id, *args, **kwargs):

    certificate = Certificate.objects.filter(active=True, cer_code=id)
    context = {
        'participants': Participant.objects.filter(activity_name=id),
        'certificates': certificate,
    }
    return render(request, 'certificates.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def certificatesView(request):

    certificates = Certificate.objects.all()
    context = {
        'certificates': certificates
    }
    return render(request, 'certificates.html', context)

@login_required(login_url='login')
@allowed_users(allowed_roles=['admin'])
def certificalar(request):
    context = {}
    activities = Activity.objects.all()
    participants = Participant.objects.all()
    certificate = Certificate.objects.all()
    keyword = request.GET.get("keyword")
    print(keyword)
    if keyword:
        # participant_name__phone_number__contains = keyword,
        participants = Participant.objects.filter(Q(name__contains=keyword) | Q(phone_number = keyword))
        print(participants)
        return render(request, "certificalar.html", {'participants': participants, 'activities': activities, 'certificates': certificate})

    context = {
        'certificates': certificate,
        'activities': activities,
        'participants': participants
    }
    return render(request, 'certificalar.html', context)

# @login_required(login_url='login')
# @allowed_users(allowed_roles=['admin'])
def qr_code_view(request):
    obj = Website.objects.all()
    objects = Product.objects.all()
    google_forms = GoogleForm.objects.all()
    keyword = request.GET.get("keyword")
    if keyword:
        objs = Website.objects.filter(name__contains=keyword)
        return render(request, "qr_code.html", {'objs': objs})
    context = {
        'objs': obj,
        'objects': objects,
        'google_forms': google_forms,
    }
    return render(request, 'qr_code.html', context)

@login_required(login_url='login')
def qr_pdf_view(request, *args, **kwargs):
    pk = kwargs.get('pk')
    objs = get_object_or_404(Website, pk=pk)
    template_path = '../templates/qr_code_pdf.html'
    context = {
        'objs': objs,
    }
    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/qr')
    response['Content-Disposition'] = 'filename="qr.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response)
    # if error then show some funny view
    if pisa_status.err:
        return HttpResponse('We had some errors
' + html + '
')
    return response

@login_required(login_url='login')
def barcode_pdf_view(request, *args, **kwargs):
    pk = kwargs.get('pk')
    objs = get_object_or_404(Product, pk=pk)
    template_path = '../templates/barcode.html'
    context = {
        'objs': objs,
    }
    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/barcode')
    response['Content-Disposition'] = 'filename="barcode.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response)
    # if error then show some funny view
    if pisa_status.err:
        return HttpResponse('We had some errors
' + html + '
')
    return response

@login_required(login_url='login')
def googleForm_pdf_view(request, *args, **kwargs):
    pk = kwargs.get('pk')
    objs = get_object_or_404(GoogleForm, pk=pk)
    template_path = '../templates/google_forms_pdf.html'
    context = {
        'objs': objs,
    }
    # Create a Django response object, and specify content_type as pdf
    response = HttpResponse(content_type='application/qr')
    response['Content-Disposition'] = 'filename="qr.pdf"'
    # find the template and render it.
    template = get_template(template_path)
    html = template.render(context)

    # create a pdf
    pisa_status = pisa.CreatePDF(
        html, dest=response)
    # if error then show some funny view
    if pisa_status.err:
        return HttpResponse('We had some errors
' + html + '
')
    return response


"""informal manual test of interception"""

import logging
import lolog
import lolog.iclogging

log = logging.getLogger()

def main():
    logging.basicConfig(level=logging.DEBUG)
    log.info("info to root before interception")

    cfg = lolog.init()
    icept = lolog.iclogging.Interceptor(cfg, logging.Logger)
    icept.intercept()

    log.info("info message to root logger")

    logging.getLogger("foo").debug("debug message to foo")
    logging.getLogger("foo.bar").info("info message with arg %s", "meep")
    logging.getLogger("foo.baz").debug("debug with arg %s and kwargs %(bar)s",
                                       "blip", bar=42)

    icept.undo()

    log.info("info to root after undo")

main()


import numpy as np
import torch

import utils

from torch import nn
from torch.nn import functional as F, init

def get_mask(in_features, out_features, autoregressive_features, mask_type=None):
    max_ = max(1, autoregressive_features - 1)
    min_ = min(1, autoregressive_features - 1)

    if mask_type == 'input':
        in_degrees = torch.arange(1, autoregressive_features + 1)
        out_degrees = torch.arange(out_features) % max_ + min_
        mask = (out_degrees[..., None] >= in_degrees).float()

    elif mask_type == 'output':
        in_degrees = torch.arange(in_features) % max_ + min_
        out_degrees = utils.tile(
            torch.arange(1, autoregressive_features + 1),
            out_features // autoregressive_features
        )
        mask = (out_degrees[..., None] > in_degrees).float()

    else:
        in_degrees = torch.arange(in_features) % max_ + min_
        out_degrees = torch.arange(out_features) % max_ + min_
        mask = (out_degrees[..., None] >= in_degrees).float()

    return mask

class MaskedLinear(nn.Linear):
    def __init__(self, in_features, out_features, autoregressive_features, kind=None, bias=True):
        super().__init__(in_features=in_features, out_features=out_features, bias=bias)
        mask = get_mask(in_features, out_features, autoregressive_features,
                        mask_type=kind)
        self.register_buffer('mask', mask)

    def forward(self, x):
        return F.linear(x, self.weight * self.mask, self.bias)

class MaskedResidualBlock(nn.Module):
    def __init__(self, features, autoregressive_features, activation=F.relu,
                 zero_initialization=True, dropout_probability=0., use_batch_norm=False):
        super().__init__()
        self.features = features
        self.activation = activation

        self.use_batch_norm = use_batch_norm
        if use_batch_norm:
            self.batch_norm_layers = nn.ModuleList([
                nn.BatchNorm1d(features, eps=1e-3)
                for _ in range(2)
            ])
        self.layers = nn.ModuleList([
            MaskedLinear(features, features, autoregressive_features)
            for _ in range(2)
        ])
        self.dropout = nn.Dropout(p=dropout_probability)
        if zero_initialization:
            init.zeros_(self.layers[-1].weight)
            init.zeros_(self.layers[-1].bias)

    def forward(self, inputs):
        temps = inputs
        if self.use_batch_norm:
            temps = self.batch_norm_layers[0](temps)
        temps = self.activation(temps)
        temps = self.layers[0](temps)
        if self.use_batch_norm:
            temps = self.batch_norm_layers[1](temps)
        temps = self.activation(temps)
        temps = self.dropout(temps)
        temps = self.layers[1](temps)
        return temps + inputs

class MADE(nn.Module):
    def __init__(self, input_dim, n_hidden_layers, hidden_dim, output_dim_multiplier,
                 conditional=False, conditioning_dim=None, activation=F.relu):
        super().__init__()
        self.input_dim = input_dim
        self.output_dim_multiplier = output_dim_multiplier
        self.conditional = conditional

        self.initial_layer = MaskedLinear(
            input_dim,
            hidden_dim,
            input_dim,
            kind='input'
        )
        if conditional:
            assert conditioning_dim is not None, 'Dimension of condition variables must be specified.'
            self.conditional_layer = nn.Linear(conditioning_dim, hidden_dim)
        self.hidden_layers = nn.ModuleList(
            [MaskedLinear(hidden_dim, hidden_dim, input_dim)
             for _ in range(n_hidden_layers)]
        )
        self.final_layer = MaskedLinear(
            hidden_dim, input_dim * output_dim_multiplier,
            input_dim,
            kind='output'
        )

        self.activation = activation

    def forward(self, inputs, conditional_inputs=None):
        temps = self.initial_layer(inputs)
        if self.conditional:
            temps += self.conditional_layer(conditional_inputs)
        temps = self.activation(temps)
        for layer in self.hidden_layers:
            temps = layer(temps)
            temps = self.activation(temps)
        outputs = self.final_layer(temps)
        return outputs

class ResidualMADE(nn.Module):
    def __init__(self, input_dim, n_residual_blocks, hidden_dim,
                 output_dim_multiplier, conditional=False, conditioning_dim=None,
                 activation=F.relu, use_batch_norm=False,
                 dropout_probability=None, zero_initialization=True):
        super().__init__()
        self.input_dim = input_dim
        self.output_dim_multiplier = output_dim_multiplier
        self.conditional = conditional

        self.initial_layer = MaskedLinear(
            input_dim,
            hidden_dim,
            input_dim,
            kind='input'
        )
        if conditional:
            assert conditioning_dim is not None, 'Dimension of condition variables must be specified.'
            self.conditional_layer = nn.Linear(conditioning_dim, hidden_dim)
        self.blocks = nn.ModuleList(
            [MaskedResidualBlock(
                features=hidden_dim,
                autoregressive_features=input_dim,
                activation=activation,
                use_batch_norm=use_batch_norm,
                dropout_probability=0 if dropout_probability is None else dropout_probability,
                zero_initialization=zero_initialization
            )
                for _ in range(n_residual_blocks)]
        )
        self.final_layer = MaskedLinear(
            hidden_dim,
            input_dim * output_dim_multiplier,
            input_dim,
            kind='output'
        )

        self.activation = activation

    def forward(self, inputs, conditional_inputs=None):
        temps = self.initial_layer(inputs)
        del inputs  # free GPU memory
        if self.conditional:
            temps += self.conditional_layer(conditional_inputs)
        for block in self.blocks:
            temps = block(temps)
        temps = self.activation(temps)
        outputs = self.final_layer(temps)
        return outputs

def check_connectivity():
    input_dim = 3
    output_dim_multiplier = 3
    n_residual_blocks = 2
    hidden_dim = 256
    conditional = False
    model = ResidualMADE(
        input_dim=input_dim,
        n_residual_blocks=n_residual_blocks,
        hidden_dim=hidden_dim,
        output_dim_multiplier=output_dim_multiplier,
        conditional=conditional,
        activation=F.relu
    )
    inputs = (torch.rand(1, input_dim) > 0.5).float()
    inputs.requires_grad = True
    res = []
    for k in range(input_dim * output_dim_multiplier):
        outputs = model(inputs)
        outputs[0, k].backward()
        depends = (inputs.grad.data[0].numpy() != 0).astype(np.uint8)
        depends_ix = list(np.where(depends)[0])
        is_valid = k // output_dim_multiplier not in depends_ix
        res.append((len(depends_ix), k, depends_ix, is_valid))

    res.sort()
    for _, k, ix, is_valid in res:
        print('Output {} depends on inputs {} : {}'.format(k, ix, is_valid))

def check_masks():
    input_dim = 3
    hidden_dim = 6
    output_dim_multiplier = 2
    n_residual_blocks = 2

    made = ResidualMADE(
        input_dim=input_dim,
        n_residual_blocks=n_residual_blocks,
        hidden_dim=hidden_dim,
        output_dim_multiplier=output_dim_multiplier
    )

    for module in made.modules():
        if isinstance(module, MaskedLinear):
            print(module.mask.t())

def check_conditional():
    input_dim = 3
    n_hidden_layers = 1
    hidden_dim = 6
    output_dim_multiplier = 2
    conditional = True
    conditional_dim = 4
    made = ResidualMADE(
        input_dim,
        n_hidden_layers,
        hidden_dim,
        output_dim_multiplier,
        conditional,
        conditional_dim
    )
    batch_size = 16
    inputs = torch.randn(batch_size, input_dim)
    conditional_inputs = torch.randn(batch_size, conditional_dim)
    outputs = made(inputs, conditional_inputs)
    print(outputs)

def main():
    check_connectivity()
    check_masks()
    check_conditional()

if __name__ == '__main__':
    main()


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

# # Make_dictionary
# - 의료 급여 비급여 명칭데이터를 통해 사전을 구축

# 형태소분석기 관련 설치
get_ipython().system('pip install JPype1')
get_ipython().system('pip install rhinoMorph')

import pandas as pd
import numpy as np
import re
import rhinoMorph

def Make_Dictionary(path): # 사전 만들기(csv 파일)
    df = pd.read_csv(path, encoding = 'cp949')   # 파일 불러오기
    df_list = df.명칭.to_list()  # 명칭만 해당하는 데이터를 리스트로 변환
    dic = []
    for i in range(len(df_list)):  # 특수기호 제거
        text = re.sub('[-_=+,/\?:^.*·''""(\)[\]<\>「\」|`~!%βⅡ°\ © ® ° α β γ δ ε ζ η θ ι κ λ μ π ο φ χ ψ ω Ф Э ф • ⁿ ‥ … € Ⅰ Ⅱ Ⅲ Ⅳ Ⅴ Ⅵ ⅦⅧ ™ Ω ⅓ ⅔ ℃ ℓ → ← ∙ ① ② ③ ④ ⑤ ⑥ ⑦ ⑧ ⑨ ⑩ ■ □ ▲ △ ▶ ◆◇ ◈ ◎ ○ ● ◐ ◑ ★ ☆ ♠ ♡ ♣ ♤ ♥ 〮 ㎀ ㎁ ㎂ ㎃ ㎄ ㎈ ㎉ ㎊ ㎋ ㎌ ㎍㎎ ㎕ ㎖ ㎗ ㎘ ㎚ ㎛ ㎜ ㎝ ㎞ ㎟ ㎠ ㎡ ㎢ ㎣ ㎤ ㎥ ㎦ ㎧ ㎼ ㎽ ㎾ ￠ ￡ ～ ︒ ︓ ⅓™αμΦ×,Ⅲ∥Ⅰ~ⅣΙ®ⅤⅥⅦ㎛*Øⓜ＊ㆍ?◈°ⅠⅡⅢⅣΙΙβ]', '', df_list[i])
        dic.append(text)
    rn = rhinoMorph.startRhino()   # 형태소분석기 객체 생성
    morphed_data = ''
    for data_each in dic:      # 전체 데이터 Tokenizer
        morphed_data_each = rhinoMorph.onlyMorph_list(
            rn, data_each[:-1], pos =['NNG', 'NNP' ,'SL'], eomi = True)
        joined_data_each = ' '. join(morphed_data_each)  # 문자열 하나로 연결
        if joined_data_each:                              # 내용이 있는 경우만 저장
            morphed_data += joined_data_each + '\t'
    data = morphed_data.replace('\t',' ')   # tab 제거
    data = data.split(' ')    # 공백을 기준으로 나눠 리스트로 저장
    set_list = set(data)
    final_list = list(set_list)   # 최종적으로 중복값 제거
    return final_list

path = "Dict_list.csv"   # 급여 사전 구축
dict = Make_Dictionary(path)
print(dict)

path_non = "Dict_list_non.csv"  # 비급여 사전 구축
dict_non = Make_Dictionary(path_non)
print(dict_non)

with open('insurance.txt', 'w', encoding = 'UTF-8') as f:  # 급여사전을 txt로 저장
    for name in dict:
        f.write(name+'\t')

with open('insurance_non.txt', 'w', encoding = 'UTF-8') as f: # 비급여사전을 txt로 저장
    for name in dict_non:
        f.write(name+'\t')

데이터 청년 캠퍼스 최종 결과물 제출/code+visualization/MakeDictionary/Make_dictionary.py


from typing import Dict, List
import core.config as config
from core.context import Context
import core.error as error
from core.parse.jumps import SectionMeta

from core.profile.profile import Profile

def gather_instructions_by_section(program, sections: Dict[str, SectionMeta]):
    chunks = {x:list() for x in sections.keys()}

    for line_obj in program:
        chunks[line_obj.section.name].append(line_obj)
    return chunks

def get_adress_offset(current_line_obj, profile: Profile):
    if profile.adressing.mode == 'align':
        return max(profile.arguments_len.values())
    elif profile.adressing.mode == 'packed':
        return int(profile.arguments_len[list(current_line_obj.parsed_command.keys())[0]])
    raise RuntimeError("Logic Error")

def get_address(current_chunk_physical_adress, profile: Profile):
    return current_chunk_physical_adress//profile.adressing.bin_len+profile.adressing.offset

def get_adressable_word_count(current_chunk_physical_adress, profile: Profile):
    return current_chunk_physical_adress//profile.adressing.bin_len

def find_key_by_value(dict: dict, value):
    output = []
    for key, val in dict.items():
        if val == value:
            output.append(key)
    return output

def calculate_addresses(chunks: dict, sections: Dict[str, SectionMeta], profile: Profile, labels: dict):
    used_addresses = dict()
    chunk_labels_physical_adresses = dict()
    chunk_labels = dict()
    entrypoints = profile.entrypoints

    def handle_labels(i, chunk_physical_adress):
        label = find_key_by_value(labels, i)
        if len(label) != 0:
            for lab in label:
                chunk_labels_physical_adresses[lab] = chunk_physical_adress
                chunk_labels[lab] = i
    def find_last_used_address(section_name):
        if len(used_addresses) == 0:
            return 0
        return max(address for address, section in used_addresses.items() if section == section_name)

    def add_address(chunk_physical_adress, section):
        if chunk_physical_adress in used_addresses:
            raise error.CompilerError(None, f"Cannot solve sections addresses: {section} overlaps with {last_section}")
        used_addresses[chunk_physical_adress] = section

    last_section = 'default'

    i = 1
    for section_name, chunk in chunks.items():
        section = sections[section_name]
        offset = section.offset
        write = section.write

        if offset == None:
            offset = find_last_used_address(last_section)+1

        current_chunk_physical_adress = 0

        # Calculate physical address for each command (relative to section)
        for line_obj in chunk:

            chunk_physical_adress = get_address(current_chunk_physical_adress, profile)+offset

            command_bit_count = get_adress_offset(line_obj, profile)

            handle_labels(i, chunk_physical_adress)

            for off in range(get_adressable_word_count(command_bit_count, profile)):
                add_address(chunk_physical_adress+off, section.name)

            current_chunk_physical_adress += command_bit_count

            line_obj.physical_adress = chunk_physical_adress

            i += 1
        last_section = section_name
    return used_addresses, chunk_labels_physical_adresses, chunk_labels

def stick_chunks(chunks, used_addresses, chunk_labels):
    output = list()

    for val in chunks.values():
        output.extend(val)

    program = sorted(output, key = lambda x: x.physical_adress)

    return program

def solve_sections(program, context: Context):
    labels = context.labels
    profile: Profile = context.get_profile()
    sections: Dict[str, SectionMeta] = context.sections

    chunks = gather_instructions_by_section(program, sections)

    used_addresses, chunk_labels_physical_adresses, chunk_labels = calculate_addresses(chunks, sections, profile, labels)

    context.physical_adresses = {key:val for key, val in chunk_labels_physical_adresses.items()}
    context.chunk_adreses = chunk_labels
    context.used_addresses = used_addresses
    context.namespace = None
    context.use_phisical_adresses = True

    program = stick_chunks(chunks, used_addresses, chunk_labels)

    return program, context


# Write a method that takes a string with one or more space separated words and returns a hash that shows the number of words of different sizes.

# Words consist only alphabet characters that do not include a space.

'''
Input: a string

Output: a dictinoary with keys the length of words, and values the occurances of that length

Rules

Data structure / Algorithms
    split the sentence into words by space
    create an empty hash
    iterate through the words
        remove the word of non-alphabet characters
        set the hash's key to the length of the current word, and value += 1, starting at 0
    return the hash

'''

def word_sizes(string):
    words = string.split()
    hash = {}

    for word in words:
        word_length = 0
        for char in word:
            if char.isalpha():
                word_length += 1

        hash[word_length] = hash.setdefault(word_length, 0) + 1

    return hash

print(word_sizes('Four score and seven.') == { 3 : 1, 4 : 1, 5 : 2 })
print(word_sizes('Hey diddle diddle, the cat and the fiddle!') == { 3 : 5, 6 : 3 })
print(word_sizes("What's up doc?") == { 5 : 1, 2 : 1, 3 : 1 })
print(word_sizes('') == {})


from time import sleep
cores = {'padrao': '\033[m',
         'azul': '\033[1;34m'}

def deco():
    print('{}-{}'.format(cores['azul'], cores['padrao'])*70)

deco()
print('{}LISTAGEM DE PREÇÕS | LOJA PYTHONCELL'.format('\033[1m').center(72))
deco()

lista = ('Samsung A22', 1200, 'Samsung A32', 1500, 'Samsung A52', 1700, 'Samsung A72', 2000,
         'Samsung S20 FE', 2300, 'Samsung S20', 3500, 'Samsung S21', 4000, 'Samsung 21 Ultra',
         6000, 'Samsung S22', 5400, 'Samsung S22 Ultra', 8400)

for posicao in range(0, len(lista)):
    if posicao % 2 == 0:
        print('{:.<60}'.format(lista[posicao]), end='')

    else:
        print(f'R$: {lista[posicao]}')
        sleep(0.5)

deco()