import csv
from matplotlib import pyplot as plt
from datetime import datetime

# Pull precip values from file.
filename = 'tucson_tia_precip_2019.csv'

with open(filename) as file:
    reader = csv.reader(file)
    header_row = next(reader)

    precipitation, dates = [], []
    for row in reader:
        current_date = datetime.strptime(row[2], "%m/%d/%Y")
        dates.append(current_date)

        value = float(row[3])
        precipitation.append(value)

# Plot data.
fig = plt.figure(dpi=128, figsize=(10, 4))
plt.plot(dates, precipitation, c='blue', alpha=0.7)
plt.fill_between(dates, precipitation, 0, facecolor="blue", alpha=0.5)

# Format plot.
plt.title('Precipitation totals, Tucson 2019', fontsize=18)
plt.xlabel('', fontsize=12)
fig.autofmt_xdate()
plt.ylabel('Precipitation (inches)', fontsize=12)
plt.tick_params(axis='both', which='major', labelsize=12)

plt.savefig('tucson_precip_2019.png')

Project 2 - Data Visualization/Chapter 16 - Downloading Data/16-3 Rainfall.py


#Source: https://stackoverflow.com/questions/31940285/plot-a-polar-color-wheel-based-on-a-colormap-using-python-matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
import matplotlib as mpl

fig = plt.figure(figsize=(10.24,10.24))

display_axes = fig.add_axes([0.01,0.01,0.98,0.98], projection='polar')
display_axes._direction = 2*np.pi ## This is a nasty hack - using the hidden field to
                                  ## multiply the values such that 1 become 2*pi
                                  ## this field is supposed to take values 1 or -1 only!!

norm = mpl.colors.Normalize(0.0, 2*np.pi)

# Plot the colorbar onto the polar axis
# note - use orientation horizontal so that the gradient goes around
# the wheel rather than centre out
quant_steps = 2048
cb = mpl.colorbar.ColorbarBase(display_axes, cmap=cm.get_cmap('hsv',quant_steps),
    norm=norm, orientation='horizontal')

# aesthetics - get rid of border and axis labels
cb.outline.set_visible(False)
display_axes.set_axis_off()

#plt.show()
plt.savefig('color-wheel.png', transparent=True)
display_axes.set_rlim([-20,1]) # radius limit [min,max]: ring thickness = max/(-min)
plt.savefig('color-ring.png', transparent=True)


import socket
import subprocess

ip = input("ENTER YOUR IP ADDRESS ")
port = int(input("ENTER YOUR PORT NUMBER "))

try:
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect((ip,port))
    cmdlet = input("$")

    while cmdlet!='quit':

         s.send(cmdlet.encode())
         result = s.recv(2048).decode()
         print(result)
         cmdlet = input("$")
    s.close()

except:
    print("something went wrong ")


'''      ######
         #                       #####
         #  ###  ### #####       #
         #    #  ###   #         #####   #### #####
         ######  ###   #             #   ####   #
                                 #####   ####   #
   Author name :      Tarun Sharma
   Problem Statement: Reversal algorithm for rotating  the array

'''
def reverse_array(left,right,arr):
    while(left < right):
        temp=arr[left]
        arr[left]=arr[right]
        arr[right]=temp
        left=left+1
        right=right-1
    return arr
def rotate(arr,d,n):
    reverse_array(0,d-1,arr)
    reverse_array(d,n-1,arr)
    reverse_array(0,n-1,arr)

    return arr
print(rotate([1,2,3,4,5,6],2,6))


l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

ex1 = [variavel for variavel in l1]

ex2 = [v*2 for v in l1]
ex3 = [(v, v2) for v in l1 for v2 in range(3)]

l2 = ["Luiza", "Mauro", "Maria"]
ex4 = [v.replace("a", "@").upper() for v in l2]

tupla = (("chave1", "valor1"), ("chave2", "valor2"))
ex5 = [(y, x) for x, y in tupla]
ex5 = dict(ex5)
#print(ex5)

l3 = list(range(100))

ex6 = [num for num in l3 if num % 3 == 0 if num % 8 == 0]
print(ex6)

ex7 = [num if num % 3 == 0 and num % 8 == 0 else 0 for num in l3]
print(ex7)


import re
import struct
import pdg
import basf2
import pybasf2
import uproot

import numpy as np

def _bitwiseConversion(value, i='f', o='i'):
    """
    Bitwise conversion between to python types
    This is equivalently to
    union {
        Type_i i;
        Type_o o;
    } conversion;
    conversion.i = input;
    return conversion.o
    @param i input data type (e.g. f for float)
    @param o output data type (e.g. i for integer)
    """
    s = struct.pack('>' + i, value)
    return struct.unpack('>' + o, s)[0]

def _decayHashFloatToInt(decayHash, decayHashExtended):
    """
    Convert decayHash and decayHashExtended 32 bit floats to an 64 bit integer
    """
    decayHashInt = _bitwiseConversion(np.float32(decayHash))
    decayHashExtendedInt = _bitwiseConversion(np.float32(decayHashExtended))
    decayHashFullInt = decayHashInt << 32
    decayHashFullInt += decayHashExtendedInt
    return decayHashFullInt

class DecayHashMap:
    """
    DecayHashMap using the C++ implementation of DecayTree and DecayNode
    """

    def __init__(self, rootfile, removeRadiativeGammaFlag=False):
        """Constructor"""
        # Always avoid the top-level 'import ROOT'.
        import ROOT  # noqa
        with uproot.open(rootfile) as rf:
            trees = rf.keys()
            assert len(trees) == 1
            ntuple = rf[trees[0]].arrays(library='np')
        # self._removeGammaFlag = removeRadiativeGammaFlag
        #: Dict Int -> DecayStrings
        self._string = {}
        #: Dict Int -> Reconstructed DecayTree
        self._forest = {}
        for decayHash, decayHashExtended, decayString in zip(
                ntuple['decayHash'], ntuple['decayHashExtended'], ntuple['decayString']):
            decayInt = ROOT.Belle2.DecayForest.decayHashFloatToInt(decayHash, decayHashExtended)
            if decayInt in self._string:
                continue
            self._string[decayInt] = decayString
            self._forest[decayInt] = ROOT.Belle2.DecayForest(decayString, True, removeRadiativeGammaFlag)

    def get_string(self, decayHash, decayHashExtended):
        """
        Return DecayString given the decayHash and decayHashExtended
        @param decayHash output of extraInfo(decayHash)
        @param decayHashExtended output of extraInfo(decayHashExtended)
        """
        # Always avoid the top-level 'import ROOT'.
        import ROOT  # noqa
        return self._string[ROOT.Belle2.DecayForest.decayHashFloatToInt(decayHash, decayHashExtended)]

    def get_original_decay(self, decayHash, decayHashExtended):
        """
        Return original (MC) DecayTree given the decayHash and decayHashExtended
        @param decayHash output of extraInfo(decayHash)
        @param decayHashExtended output of extraInfo(decayHashExtended)
        """
        # Always avoid the top-level 'import ROOT'.
        import ROOT  # noqa
        return self._forest[ROOT.Belle2.DecayForest.decayHashFloatToInt(decayHash, decayHashExtended)].getOriginalTree()

    def get_reconstructed_decay(self, decayHash, decayHashExtended):
        """
        Return reconstructed DecayTree given the decayHash and decayHashExtended
        @param decayHash output of extraInfo(decayHash)
        @param decayHashExtended output of extraInfo(decayHashExtended)
        """
        # Always avoid the top-level 'import ROOT'.
        import ROOT  # noqa
        return self._forest[ROOT.Belle2.DecayForest.decayHashFloatToInt(decayHash, decayHashExtended)].getReconstructedTree()

    def print_hash(self, decayHash, decayHashExtended):
        """
        Print the DecayString in a fancy way given the decayHash and decayHashExtended
        @param decayHash output of extraInfo(decayHash)
        @param decayHashExtended output of extraInfo(decayHashExtended)
        """
        entry = self.get_string(decayHash, decayHashExtended)
        entries = entry.split('|')
        all_particles = re.findall(r"(-?[0-9]+)", entries[0])

        if len(all_particles) != len(entries) - 1:
            print(entry)
            raise RuntimeError("Bad format of decay string: " +
                               str(len(all_particles)) + " " + str(len(entries)) + " " + str(entries))

        table = []
        table.append(["Decay ", prettify_pdg_codes(entries[0])])
        for particle, mc_decay_string in zip(all_particles, entries[1:]):
            table.append([prettify_pdg_codes(particle), prettify_pdg_codes(mc_decay_string)])

        basf2.pretty_print_table(table, column_widths=[6, '*'])

def _pdg_to_name(x):
    """
    Convert PDG code to a name
    @param a pdg code
    """
    selected = False
    if x[0] == '^':
        selected = True
        x = x[1:]

    pdg_code = int(x)
    pdg_string = str(pdg_code)
    try:
        pdg_string = pdg.to_name(pdg_code)
    except BaseException:
        pass

    if selected:
        if pybasf2.LogPythonInterface.terminal_supports_colors():
            return '\x1b[31m' + pdg_string + '\x1b[0m'
        else:
            return '^' + pdg_string
    return pdg_string

def prettify_pdg_codes(text):
    """
    Prettifiy a string containing PDG codes by replacing PDG codes
    with their corresponding names.
    @param text the text
    """
    text = re.sub(r"(\^?-?[0-9]+)", lambda x: _pdg_to_name(x.group(0)), text)
    text = text.replace('gamma', 'g').replace('--> ', '').replace('anti-', 'a-')
    text = text.replace('Upsilon', 'Y').replace(') ', ')').replace(' (', '(')
    return text


import numpy as np

import Game.selectors as s
import Game.constants as c

def select_is_player_token_winning_line(list_of_winning_lines, winning_line_size, player_token):
    for winning_lines in list_of_winning_lines:
        winning_token = s.select_winning_token_by_winning_lines(winning_lines, winning_line_size)
        if winning_token == player_token: return True
    return False

def select_player_has_winning_move(game, board_parameters, player_token):
    board_size, _, winning_line_size, _, _ = board_parameters
    for y in range(board_size):
        for x in range(board_size):
            if not s.select_is_empty_position(game.current_state[y][x]): continue
            future_game_state = game.current_state.copy()
            future_game_state[y][x] = player_token
            columns = s.select_columns(future_game_state, board_size)
            rows = s.select_rows(future_game_state, board_size)
            diagonals = s.select_board_diagonals(future_game_state)
            if select_is_player_token_winning_line([columns, rows, diagonals], winning_line_size,
                                                   player_token):
                return True
    return False

def select_player_is_winning(game, board_parameters, player_token):
    board_size, _, winning_line_size, _, _ = board_parameters
    columns = s.select_columns(game.current_state, board_size)
    rows = s.select_rows(game.current_state, board_size)
    diagonals = s.select_board_diagonals(game.current_state)
    if select_is_player_token_winning_line([columns, rows, diagonals], winning_line_size,
                                           player_token):
        return True
    return False

def select_distance_between_coordinates(p1, p2):
    distance = np.linalg.norm(np.array(p1) - np.array(p2))
    return distance

def select_min_max_center_score_differential(game, board_parameters):
    board_size, _, _, _, _ = board_parameters
    max_token, min_token = s.select_max_min_tokens_from_player_turn(game.player_turn)
    max_center_score = 0
    min_center_score = 0
    center_position = (board_size / 2, board_size / 2)
    for y in range(board_size):
        for x in range(board_size):
            position_token = game.current_state[y][x]
            if position_token != min_token and position_token != max_token: continue
            distance_from_center = select_distance_between_coordinates((x, y), center_position)
            if position_token == min_token:
                min_center_score += 1 / distance_from_center if distance_from_center != 0 else 1
            if position_token == max_token:
                max_center_score += 1 / distance_from_center if distance_from_center != 0 else 1
    max_center_score_differential = max_center_score - min_center_score
    return max_center_score_differential

def select_is_move_on_board(board_size, move):
    x, y = move
    if -1 < y < board_size and -1 < x < board_size: return True
    return False

def select_surrounding_moves(x, y):
    return [(x - 1, y - 1), (x, y - 1), (x + 1, y - 1), (x - 1, y), (x + 1, y),
            (x - 1, y + 1), (x, y + 1), (x + 1, y + 1)]

def select_surrounding_moves_from_position_score(board, position_coordinates, board_size):
    connection_count = 0
    (x, y) = position_coordinates
    for move in select_surrounding_moves(x, y):
        x_surrounding, y_surrounding = move
        if not select_is_move_on_board(board_size, move): continue
        if board[y_surrounding][x_surrounding] == board[y][x]:
            connection_count += 1
    return connection_count

def select_connect_groups_score_differential(game, board_parameters):
    board_size, _, _, _, _ = board_parameters
    max_token, min_token = s.select_max_min_tokens_from_player_turn(game.player_turn)
    min_connected_group_score = 0
    max_connected_group_score = 0
    for y in range(board_size):
        for x in range(board_size):
            position_token = game.current_state[y][x]
            if position_token == min_token:
                min_connected_group_score += select_surrounding_moves_from_position_score(
                    game.current_state, (x, y), board_size)
            if position_token == max_token:
                max_connected_group_score += select_surrounding_moves_from_position_score(
                    game.current_state, (x, y), board_size)
    return max_connected_group_score - min_connected_group_score

def select_player_heuristic_id_from_player_turn(game):
    player_turn = game.player_turn
    if player_turn == c.X_TOKEN:
        return game.heuristics[0]
    else:
        return game.heuristics[1]

def select_surrounding_position_cardinality_contribution(game_board, move, player_token,
                                                         other_player_token, board_size):
    x_surrounding, y_surrounding = move
    if not select_is_move_on_board(board_size, move): return -3
    surrounding_position_token = game_board[y_surrounding][x_surrounding]
    if surrounding_position_token == c.BLOCK_TOKEN: return -1
    if surrounding_position_token == other_player_token: return 0
    if surrounding_position_token == c.EMPTY_TOKEN: return 1
    if surrounding_position_token == player_token: return 3

def select_position_cardinality_score(game_board, coordinate, token, board_size):
    (x, y) = coordinate
    cardinality_score = 0
    other_player_token = s.select_opposite_player(token)
    for move in select_surrounding_moves(x, y):
        cardinality_score += select_surrounding_position_cardinality_contribution(game_board, move,
                                                                                token,
                                                                                other_player_token,
                                                                                board_size)
    return cardinality_score

def select_max_move_cardinalities_differential(game, board_parameters):
    board_size, _, _, _, _ = board_parameters
    max_token, min_token = s.select_max_min_tokens_from_player_turn(game.player_turn)
    game_board = game.current_state
    max_cardinality_score, min_cardinality_score = 0, 0
    for y in range(board_size):
        for x in range(board_size):
            position_token = game_board[y][x]
            if position_token == c.EMPTY_TOKEN or position_token == c.BLOCK_TOKEN: continue
            if position_token == max_token:
                position_score = select_position_cardinality_score(game_board, (x, y), max_token,
                                                                   board_size)
                max_cardinality_score += position_score
            if position_token == min_token:
                position_score = select_position_cardinality_score(game_board, (x, y), min_token,
                                                                   board_size)
                min_cardinality_score += position_score
    return max_cardinality_score - min_cardinality_score


from sqlalchemy.orm import Session
import models, schemas

# Diet Create Utility Function
def create_pet_diet(db: Session, diet: schemas.DietCreate, pet_id: int):
    db_diet = models.Diet(**diet.dict(), owner_id=pet_id)
    db.add(db_diet)
    db.commit()
    db.refresh(db_diet)
    return db_diet

# Diet READ utility functions
def get_diet(db: Session, diet_id: int, pet_id: int):
    return (
        db.query(models.Diet)
        .filter(models.Diet.owner_id == pet_id)
        .filter(models.Diet.id == diet_id)
        .first()
    )

# Diet DELETE utility functions
def delete_diet(db: Session, diet_id: int, pet_id: int):
    (
        db.query(models.Diet)
        .filter(models.Diet.owner_id == pet_id)
        .filter(models.Diet.id == diet_id)
        .delete(synchronize_session=False)
    )
    db.commit()

    return "Successfully Deleted"


#from __future__ import absolute_import

from models_utility.param_gp import Param
from models_utility.function_gp import  cholesky, lt_log_determinant
from models_utility.likelihoods import Gaussian
from torch import triangular_solve

from models.gp import gpr
import numpy as np
import torch
import torch.nn as nn

import torch
from torch.autograd import Variable
import numpy as np

#torch.set_default_tensor_type(torch.DoubleTensor)
torch.set_default_tensor_type(torch.FloatTensor)

jitter = 1e-8
class gp_vfe(gpr):

    def __init__(self, kernel, likelihood , device, param_dict):
        super(gp_vfe,self).__init__(kernel, likelihood, device ,param_dict)
        self.device = torch.device("cuda") if device else torch.device('cpu')
        #self.jitter = torch.tensor(1e-8).to(self.device)
        self.x = None
        self.y = None

    def _set_data(self, batch_x, batch_y):
        self.x = batch_x
        self.y = batch_y
        return

    def _set_inducing_pt(self,num_inducing):
        assert(self.x is not None)
        self.num_inducing_pt = num_inducing
        idx = np.random.choice(len(self.x),num_inducing)
        self.inducing_pt = Param(torch.tensor(self.x[idx]).to(self.device), requires_grad=True, requires_transform=False, param_name = 'inducing_pt')
        return

    def compute_loss(self,batch_x,batch_y,kl_option):
        num_inducing_pt = self.num_inducing_pt
        dim_output = batch_y.shape[1]
        num_data = batch_x.shape[0]

        K_ff_diag = self._compute_Kxx_diag(self.x)
        K_uf = self._compute_Kxs(self.inducing_pt, self.x)
        K_uu = self._compute_Kxx(self.inducing_pt)

        L = cholesky(K_uu)
        A = triangular_solve(K_uf, L, upper=False)[0]
        A_At = A.matmul(A.t()).div(self.likelihood.variance.transform()**2)
        B = A_At + torch.eye(int(num_inducing_pt)).to(self.device)
        L_B = cholesky(B)
        C = triangular_solve(A.matmul(self.y), L_B, upper=False)[0].div(self.likelihood.variance.transform()**2)

        Elbo = 0.
        Elbo += torch.tensor([-0.5 * dim_output * num_data * np.log(2 * np.pi)]).to(self.device)
        Elbo -= dim_output * L_B.diag().log().sum()
        Elbo -= 0.5 * dim_output * num_data * 2*self.likelihood.variance
        Elbo -= (0.5 / (self.likelihood.variance.transform()**2)) * (self.y.pow(2).sum() + dim_output * K_ff_diag.sum())
        Elbo += 0.5 * C.pow(2).sum()
        Elbo += 0.5 * dim_output * A_At.diag().sum()

        return -Elbo.squeeze()

    def _predict(self, inputs_new, diag = True):
        if isinstance(inputs_new, np.ndarray):
            inputs_new = torch.Tensor(inputs_new).to(self.device)

        num_inducing_pt = self.num_inducing_pt
        dim_output = self.y.shape[1]

        K_ff_diag = self._compute_Kxx_diag(self.x)
        K_uf = self._compute_Kxs(self.inducing_pt, self.x)
        K_uu = self._compute_Kxx(self.inducing_pt)
        K_us = self._compute_Kxs(self.inducing_pt, inputs_new)

        L = cholesky(K_uu)
        A = triangular_solve(K_uf, L, upper=False)[0]
        A_At = A.matmul(A.t()).div(self.likelihood.variance.transform()**2)
        B = A_At + torch.eye(int(num_inducing_pt)).to(self.device)
        L_B = cholesky(B)
        C = triangular_solve(A.matmul(self.y), L_B, upper=False)[0].div(self.likelihood.variance.transform()**2)

        temp1 = triangular_solve(K_us, L, upper=False)[0]
        temp2 = triangular_solve(temp1, L_B, upper=False)[0]
        mean_f = temp2.t().matmul(C)

        if diag:
            var = self._compute_Kxx_diag(inputs_new) + temp2.t().pow(2).sum(1) - temp1.pow(2).sum(0).squeeze() +  (self.likelihood.variance.transform()**2).diag().diag()
        else:
            var = self._compute_Kxx(inputs_new) + temp2.t().matmul(temp2) - temp1.t().matmul(temp1) +  self.likelihood.variance.transform()**2
        return mean_f, var


#calculator v0.1.py
#Simple calculator

from graphics import *
from math import *

def main():

    #create window
    win = GraphWin("Calculator",500,200)
    win.setBackground('light blue')

    #create objects
    basicCalculator = Text(Point(250,20),"Basic Calculator")
    basicCalculator.setSize(20)
    basicCalculator.draw(win)

    enterText = Text(Point(250,75),"Enter equation with spaces in between numbers and operators.")
    enterText.setSize(12)
    enterText.draw(win)

    equationBox = Entry(Point(250,120),20)
    equationBox.draw(win)

    readyButton = Rectangle(Point(200,150),Point(300,175))
    readyButton.setFill('black')
    readyButton.draw(win)

    calculateText = Text(Point(250,162.5),"Calculate")
    calculateText.setTextColor('white')
    calculateText.draw(win)

    #calculate equation on GUI

    win.getMouse()

    #math

    equationText = equationBox.getText()

    equationList = equationText.rsplit()
    print(equationList)

    while True:
        multiplyDivideFlag = 0
        try:
            multiplyPosition = equationList.index("*")
        except ValueError:
            multiplyPosition = 9999
        try:
            dividePosition = equationList.index("/")
        except ValueError:
            dividePosition = 9999
        try:
            addPosition = equationList.index("+")
        except ValueError:
            addPosition = 9999
        try:
            subtractPosition = equationList.index("-")
        except ValueError:
            subtractPosition = 9999

        print(multiplyPosition)
        print(dividePosition)
        print(addPosition)
        print(subtractPosition)

        if dividePosition > multiplyPosition:
            print("Multiply")
            multiplyDivideFlag = 1
            number1 = equationList[multiplyPosition - 1]
            #print(number1)
            number2 = equationList[multiplyPosition + 1]
            #print(number2)
            number3 = float(number1) * float(number2)
            #print(number3)
            #print(equationList)
            del equationList[multiplyPosition - 1: multiplyPosition + 2]
            #print(equationList)
            print("inserting " + str(number3) + "at index " + str(multiplyPosition - 1))
            equationList.insert(multiplyPosition - 1,number3)
            print(equationList)
            #print("the list is now" + str(equationList))
            if len(equationList) == 1:
                #print("this should be right")
                print(equationList)
                break
        elif multiplyPosition > dividePosition:
            print("Divide")
            multiplyDivideFlag = 1
            number1 = equationList[dividePosition - 1]
            #print(number1)
            number2 = equationList[dividePosition + 1]
            #print(number2)
            number3 = float(number1) / float(number2)
            #print(number3)
            del equationList[dividePosition - 1: dividePosition + 2]
            print("inserting " + str(number3) + "at index " + str(dividePosition - 1))
            equationList.insert(dividePosition - 1,number3)
            print(equationList)
            if len(equationList) == 1:
                print(equationList)
                break

        if multiplyDivideFlag != 1:

            if  subtractPosition > addPosition:
                print("Add")
                number1 = equationList[addPosition - 1]
                #print(number1)
                number2 = equationList[addPosition + 1]
                #print(number2)
                number3 = float(number1) + float(number2)
                #print(number3)
                del equationList[addPosition - 1: addPosition + 2]
                print("inserting " + str(number3) + "at index " + str(addPosition - 1))
                equationList.insert(addPosition - 1,number3)
                print(equationList)
                if len(equationList) == 1:
                    print(equationList)
                    break
            elif addPosition > subtractPosition:
                print("Subtract")
                number1 = equationList[subtractPosition - 1]
                #print(number1)
                number2 = equationList[subtractPosition + 1]
                #print(number2)
                number3 = float(number1) - float(number2)
                #print(number3)
                del equationList[subtractPosition - 1: subtractPosition + 2]
                print("inserting " + str(number3) + "at index " + str(subtractPosition - 1))
                equationList.insert(subtractPosition - 1,number3)
                print(equationList)
                if len(equationList) == 1:
                    print(equationList)
                    break

    #calculate equation on GUI

    calculateText.undraw()
    readyButton.undraw()

    answerText = Text(Point(250,162.5),"The answer is " + str(number3))
    answerText.draw(win)

main()


# DSC510
# Week 8
# Programming Assignment Week 8
# Author Ammy Theobald
# 10/25/2020

# Change#:1
# Change(s) Made: Initial Program
# Date of Change: 10/25/2020
# Author: Ammy Theobald
# Change Approved by: N/A
# Date Moved to Production: 10/25/2020

import string

# add_word function increments word counter by 1 if word in dict, else adds to dict with count of 1
def add_word(word,dict):
    if word in dict:
        dict[word] += 1
    else:
        dict[word] = 1
# process_line function strips leading characters and punctuation,splits lines into separate words, and calls the add_word function
def process_line(line, dict):
    line = line.strip()
    linesplit = line.split()
    for word in linesplit:
        if word != '--':
            word = word.lower()
            word = word.strip(string.punctuation)
            add_word(word, dict)

# pretty_print function formats the output into a desirable format
def pretty_print(dict):
    resultslist = []
    for letters,num in dict.items():
        resultslist.append((num, letters))
    resultslist.sort(reverse=True)
    print('{:13}{:13}'.format('Word','Count'))
    print('__'*12)
    for num,letters in resultslist:
        print('{:14s} {:d}'.format(letters,num))

# main function pulls all of the functions together to process and format the file
def main():
    dict={}
    gba_file = open('gettysburg.txt','r')
    for line in gba_file:
        process_line(line,dict)
    print('Length of the Dictionary:', len(dict))
    pretty_print(dict)

print(main())


from contextlib import AsyncExitStack
from datetime import datetime

from google.protobuf.message import Message as ProtoBufMessage
from google.protobuf.struct_pb2 import Struct
from google.protobuf.timestamp_pb2 import Timestamp

from grpc_stubs.kafkacomms.producer_pb2 import SampleMsg
from producer.exceptions import NotSerialisable
from producer.kafka import KafkaProducer

BOOTSTRAP_SERVERS = ['127.0.0.1:9092']

def serialise(msg: ProtoBufMessage) -> bytes:
	""" Serialises a protobuf message """
	if not isinstance(msg, ProtoBufMessage):
		raise NotSerialisable()
	return msg.SerializeToString()

async def run() -> None:
	async with AsyncExitStack() as stack:

		# Create a Kafka producer client
		print(f"Running Kafka producer at: {BOOTSTRAP_SERVERS}")

		kafka_producer = await stack.enter_async_context(
			KafkaProducer(
				max_request_size=10000,
				bootstrap_servers=BOOTSTRAP_SERVERS,
				request_timeout_ms=10000,
			)
		)

		# Create a GRPC message
		msg_other_data = Struct()
		msg_other_data.update({
			'key_1': 'val_1',
			'key_2': 'val_2',
		})

		kafka_grpc_msg = SampleMsg(
			msg_no=1,
			msg_body='my text',
			msg_date=Timestamp(),
			msg_other_data=msg_other_data,
		)

		# Send the message to the Kafka broker
		await kafka_producer.send_and_wait(
			'my_topic',
			value=serialise(kafka_grpc_msg),
			key=bytes('my_key', 'utf-8'),
			headers=[
				('my_header_name', b'my_header_value')
			],
		)

		print(f"Sent message: {kafka_grpc_msg}")


array = [7,5,9,0,3,1,6,2,4,8]
# 방법1
array.sort()
# 방법2
result = sorted(array)
print(result)

array2 = [('바나나', 2), ('사과', 5), ('당근', 3)]
array2.sort(key=lambda x: x[1])
print(array2)

정렬/정렬내장함수.py