import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots

def interactive_visulization(points, labels, qcharges=None, rmsd=None, molecules=None, bg=None, bb=None, width=400, height=1000):
    """
    points: [num_frames, 2]
    molecules: [num_frames, 3, num_atoms]
    """

    # Preparing figure object
    if molecules is not None:
        fig = make_subplots(
            rows=1,
            cols=2,
            specs=[[{"type": "xy"}, {"type": "scene"}]],
        )
    else:
        fig = make_subplots(
            rows=1,
            cols=1,
            specs=[[{"type": "xy"}]],
        )
    if rmsd is not None and qcharges is not None:
        hovertext = list(map(str, zip(np.arange(points.shape[0]), qcharges, rmsd)))
    elif qcharges is not None:
        hovertext = list(map(str, zip(np.arange(points.shape[0]), qcharges)))
    elif rmsd is not None:
        hovertext = list(map(str, zip(np.arange(points.shape[0]), rmsd)))
    else:
        hovertext = np.arange(points.shape[0])

    points_plot = go.Scatter(
        x=points[:, 0],
        y=points[:, 1],
        hovertext=hovertext,
        #hovertext=np.arange( )
            mode="markers",
            name="latent_points",
            marker=dict(
                color=labels,
            )

    )

    fig.add_trace(points_plot, row=1, col=1)

    if molecules is not None:
        molecule_3d_plot = go.Scatter3d(
            x = molecules[0, 0, :],
            y = molecules[0, 1, :],
            z = molecules[0, 2, :],
            mode="markers",
            marker=dict(
                size=3,
            ),
            name="molecule",
        )

        fig.add_trace(molecule_3d_plot, row=1, col=2)

    layout = fig.layout
        # layout["xaxis"]["range"] = [-2.2, 2.2]
        # layout["yaxis"]["range"] = [-2.2, 2.2]
        # layout["zaxis"]["range"] = [-2.2, 2.2]

    if bg is not None:
        from PIL import Image
        from matplotlib import cm

        energy_array = np.load(bg)
        # energy_img = Image.fromarray(energy_array)
        energy_array = (energy_array - energy_array.min()) / \
                       (energy_array.max() - energy_array.min())

        energy_img = Image.fromarray(np.uint8(cm.viridis(energy_array)*255))
        # from matplotlib import pyplot as plt
        # plt.imshow(np.array(energy_img))
        # plt.show()

        x1,y1,x2,y2 = np.load(bb)
        fig.add_layout_image(
        dict(
            source=energy_img,
            #xref="x",
            #yref="y",
            x=x1,
            y=y2,
            sizex=x2-x1,
            sizey=y2-y1,
            sizing="stretch",
            opacity=0.5
            )
        #layer="below")
        )
    # fig.update_layout(template="plotly_white")
    fig.update_layout(
        width = width,
        height = height,
     )
    # Preparing interactive widget

    if molecules is not None:
        widget = go.FigureWidget([points_plot, molecule_3d_plot], layout=layout)
        molecule_3d_plot = widget.data[1]
    else:
        widget = go.FigureWidget([points_plot], layout=layout)

    points_plot = widget.data[0]

    # widget.layout.hovermode = 'closest'

    # Defining callback with 3 parameters: trace = graphical object with some changes, points and selector
    def callback(trace, points, selector):
        # A list with the size of the points, all of them have the same size
        # s = [5] * N # list(points_plot.marker.size)

        # Iteration over indexes, we want only one of the points
        for i in points.point_inds:
            # Imitating selection of the particular point
            # s[i] = 10

            # Go into batch_update for buffering

            with widget.batch_update():
                # coordinates of i frame
                molecule_3d_plot.x = molecules[i, 0, :]
                molecule_3d_plot.y = molecules[i, 1, :]
                molecule_3d_plot.z = molecules[i, 2, :]

                # changing sizes of all the points, it is necessary to make another list to make it work
                # points_plot.marker.size = s

            return

    # registring callback, possible modes (on_cxlick), (on_selection), etc
    if molecules is not None:
        points_plot.on_hover(callback)

    # Widget visualization
    return widget


# -*- coding: utf-8 -*
"""
Created on Fri Sep 24 12:30:15 2021
@author: Aashish Rana

kpi =  only returns and points

strategy = breakout of prvious day high(pdh) and previous day low(pdl)

entry logic  = long if current candle high is greater than pdh
               short if current candle low is lower than pdl

stop loss(fixed) = if long, sl will be pdl
                   if short, sl will be pdh
                   if sl didn't trigger, exit at 15:26'
"""

# import necessary liabraries
import pandas as pd
import numpy as np
from openpyxl import load_workbook
import matplotlib.pyplot as plt

# read the trade log file
df = pd.read_excel('E:\\breakout_pdh_pdl\\breakout_pdh_pdl_trade_log.xlsx',sheet_name='main',parse_dates =['Entry_date'],index_col = 'Entry_date')

# group the trade log points annually
Annual_points = df.groupby(pd.Grouper(freq = 'Y'))['points','returns'].sum()

#saving the annual points and returns to existing file which is trade_log
path = 'E:\\breakout_pdh_pdl\\breakout_pdh_pdl_trade_log.xlsx'
book = load_workbook(path)
writer = pd.ExcelWriter(path,engine = 'openpyxl')
writer.book = book
Annual_points.to_excel(writer,sheet_name = 'points and returns')
writer.save()
writer.close()

Annual_points.to_excel('breakout_pdh_pdl_trade_log.xlsx',sheet_name = 'points and returns')

# group the trade log points annually
Annual_points = df.groupby(pd.Grouper(freq = 'Y'))['points'].sum()

# plotting the charts of annual points
Annual_points.plot(kind = 'bar',xlabel = 'year',ylabel = 'points',figsize = (9,3),title = 'NIFTY FUTURES')


# -*- coding: utf-8 -*-

from odoo import models, fields, api, _
from odoo.exceptions import UserError

class CrmsaleEstimateWizard(models.Model):
    _name = 'crmsale.estimate.wizard.cust'
    _description = 'CRM Sale Estimate Wizard'

    partner_id = fields.Many2one(
        'res.partner',
        string='Customer',
        required=True,
    )

    def prepare_sales_estimate_vals_custom(self, crm_id):
        return {
            'partner_id': self.partner_id.id,
            'pricelist_id': self.partner_id.property_product_pricelist.id,
            'payment_term_id': self.partner_id.property_payment_term_id.id,
            'team_id': crm_id.team_id.id,
            'crm_custom_id': crm_id.id
        }

    def prepare_sale_estimate_line_vals_custom(self, line, sale_estimate):
        return {
            'product_id': line.product_id.id,
            'product_uom_qty': line.product_uom_qty,
            'product_uom': line.product_uom.id,
            'price_unit': line.price_unit,
            'product_description': line.product_description,
            'estimate_id': sale_estimate.id
        }

    def create_sale_estimate_custom(self):
        self.ensure_one()
        sale_estimate_obj = self.env['sale.estimate']
        sale_estimate_line_obj = self.env['sale.estimate.line']
        crm_id = self.env['crm.lead'].browse(self._context.get('crm_id'))
        sale_estimate_list = []
        if not crm_id.estimate_line_custom_ids:
            raise UserError(_('No estimate lines are found.'))

        # if all(line.is_estimate_created for line in crm_id.estimate_line_custom_ids):
        #     raise UserError(_('All estimate lines are created.'))

        estimate_vals = self.prepare_sales_estimate_vals_custom(crm_id)
        sale_estimate = sale_estimate_obj.create(estimate_vals)

        sale_estimate_list.append(sale_estimate.id)

        for line in crm_id.estimate_line_custom_ids:
            # if line.is_estimate_created != True:
            estimate_line_vals = self.prepare_sale_estimate_line_vals_custom(line,sale_estimate)
            sale_estimate_line = sale_estimate_line_obj.create(estimate_line_vals)
            line.is_estimate_created = True
            line.estimate_line_custom_id = sale_estimate_line.id
            line.estimate_custom_id = sale_estimate.id


print('=' * 30)
print(f'{"CAIXA ELETRÔNICO":^30}')
print('=' * 30, ' \n')

valor = int(input('Quanto deseja sacar? R$'))
val = valor
ced = 50
totced = 0

while True:
    if val >= ced:
        val -= ced
        totced += 1

    else:
        if totced > 0:
            print(f'Total de {totced} cédulas de R${ced}')

        if ced == 50:
            ced = 20

        elif ced == 20:
            ced = 10

        elif ced == 10:
            ced = 1
        totced = 0

        if val == 0:
            break

print('=' * 30)
print('OBRIGADO. Volte Sempre!!!')


import fastapi.routing
from sqlalchemy.orm import Session
from sqlalchemy.sql import select

from impressive_strawberry.database import tables
from impressive_strawberry.web import crud
from impressive_strawberry.web import deps
from impressive_strawberry.web import models
from impressive_strawberry.web import responses
from impressive_strawberry.web.errors import DuplicatingUnrepeatableUnlock, NotUnlockable
from impressive_strawberry.webhooks import notify_unlock

app_router = fastapi.routing.APIRouter(
    prefix="/api/unlock/v1",
    tags=[
        "Unlock v1",
    ],
)

group_router = fastapi.routing.APIRouter(
    prefix="/api/unlock-group/v1",
    tags=[
        "Unlock v1",
    ]
)

token_router = fastapi.routing.APIRouter(
    prefix="/api/unlock-direct/v1",
    tags=[
        "Unlock v1",
    ]
)

@group_router.get(
    "/",
    summary="List unlocked achievements obtained by a certain user in a certain group, both belonging to the same application you're authenticating as.",
    response_model=list[models.full.UnlockFull],
)
async def group_unlock_list(
        *,
        session: Session = fastapi.Depends(deps.dep_dbsession),
        group: tables.Group = fastapi.Depends(deps.dep_group_thisapp),
        user: tables.User = fastapi.Depends(deps.dep_user_thisapp),
):
    data = session.execute(
        select(tables.Unlock).where(tables.Unlock.user == user).join(tables.Achievement).where(tables.Achievement.group == group)
    ).all()
    return list(map(lambda d: d[0], data))

@app_router.post(
    "/",
    summary="Adds a certain achievement of a group to a user, both belonging to the same application you're authenticating as.",
    response_model=models.full.UnlockFull,
    status_code=201,
)
async def unlock_create(
        *,
        session: Session = fastapi.Depends(deps.dep_dbsession),
        achievement: tables.Achievement = fastapi.Depends(deps.dep_achievement_thisapp),
        user: tables.User = fastapi.Depends(deps.dep_user_thisapp),
):
    if not achievement.unlockable:
        raise NotUnlockable()
    if achievement in [u.achievement for u in user.unlocks] and not achievement.repeatable:
        raise DuplicatingUnrepeatableUnlock()
    unlock = crud.quick_create(session, tables.Unlock(achievement_id=achievement.id, user_id=user.id))
    await notify_unlock(group=achievement.group, unlock=unlock)
    return unlock

@app_router.delete(
    "/{unlock}",
    summary="Removes an unlock of an user belonging to the application you're authenticating as.",
    status_code=204,
)
async def unlock_delete(
        *,
        unlock: tables.Unlock = fastapi.Depends(deps.dep_unlock_thisapp),
        session: Session = fastapi.Depends(deps.dep_dbsession),
):
    session.delete(unlock)
    session.commit()
    return responses.raw.NO_CONTENT

@token_router.post(
    "/",
    summary="Adds a certain achievement of a group to a user, both belonging to the same application, using a token.",
    status_code=201,
)
async def direct_unlock_create(
        *,
        session: Session = fastapi.Depends(deps.dep_dbsession),
        achievement: tables.Achievement = fastapi.Depends(deps.dep_achievement_token),
        user: tables.User = fastapi.Depends(deps.dep_user_token)
):
    if not achievement.unlockable:
        raise NotUnlockable()
    if achievement in [u.achievement for u in user.unlocks] and not achievement.repeatable:
        raise DuplicatingUnrepeatableUnlock()
    unlock = crud.quick_create(session, tables.Unlock(achievement_id=achievement.id, user_id=user.id))
    await notify_unlock(group=achievement.group, unlock=unlock)
    return unlock


from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

PATH_LIST = {
    "Windows": 'phantomjs-windows/bin/phantomjs.exe',
    "Linux": 'phantomjs-linux/bin/phantomjs',
    "Darwin": 'phantomjs-macos/bin/phantomjs'
}

def get_driver(os_system):
    dcap = dict(DesiredCapabilities.PHANTOMJS)
    dcap["phantomjs.page.settings.userAgent"] = (
        "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/53 "
        "(KHTML, like Gecko) Chrome/15.0.87"
    )
    path = PATH_LIST[os_system]
    driver = webdriver.PhantomJS(path, desired_capabilities=dcap)
    # driver = webdriver.Chrome('chromedriver.exe')
    driver.set_window_size(1920, 950)
    driver.implicitly_wait(10)
    return driver


import sys

if len(sys.argv) != 3:
    print("Usage: python filter_named_entities.py <char_tagged_transcription> <output_file>")
    print("<tagged_char_transcription>: Input file with char-level tagged transcription.")
    print("<output_file>: File which will store the line ID and the sequence of tagging symbols in its transcription.")

def is_tag(c):
    if "<" in c and c != "<space>":
        return True
    else:
        return False

input_file = open(sys.argv[1], 'r')
output_file = open(sys.argv[2], 'w')

for l in input_file.readlines():
    l_id, transc = l.split(" ", maxsplit=1)
    transc = list(filter(is_tag, transc.split()))
    if len(transc) > 0: #Only write lines with tags
        out_str = "{} {}\n".format(l_id, " ".join(transc))
        output_file.write(out_str)

input_file.close()
output_file.close()


import fire
import requests

from multiprocessing import Pool

URL_TEMPLATE = "http://info.dla.go.th/public/surveyInfo.do?cmd=surveyForm&orgInfoId={key}"

YEARS = [2015, 2016, 2017, 2018, 2019]
YINDX = dict(zip(YEARS, range(3, 3 + len(YEARS))))
ORG_IDS_FILE = "./data/local-governor-ids.txt"

BASE_DIR = "./outputs/budgets"

def _build_key(year, org_id):
    return "%s%s" % (year, "%04d" % int(org_id))

def scrape_years(years, trial=None, dry_run=False, pool_size=10):
    for y in years:
        print("Working on Y=%s" % y)
        scrape_year(y, trial=trial, dry_run=dry_run, pool_size=pool_size)

def scrape_year(year, trial=None, dry_run=False, pool_size=5):
    with open(ORG_IDS_FILE, "r") as f:
        org_ids = f.readlines()[:trial]

    year_org_ids = map(lambda x: (year, x.strip()), org_ids)

    with Pool(pool_size) as p:
        p.map(do_job, year_org_ids)

    return p.join()

def do_job(args):
    year, org_id = args
    text = scrape_year_org(year, org_id)

    with open("%s/%s/%s.html" % (BASE_DIR, year, org_id), "w") as f:
        f.write(text)

def scrape_year_org(year, org_id):
    yidx = YINDX[year]
    url = URL_TEMPLATE.format(key=_build_key(yidx, org_id))

    print("Scraping %s" % url)

    r = requests.get(url)

    return r.text

if __name__ == "__main__":
    fire.Fire({
        "years": scrape_years,
        "year": scrape_year,
        "year-org": scrape_year_org
    })


class Solution(object):
    def majorityElement(self, nums):
        size = len(nums)
        tracer = dict()
        for i in range(size):
            if tracer.get(nums[i],-1) == -1:
                tracer[nums[i]] = 1
            else:
                tracer[nums[i]]+=1
        for k in tracer:
            if tracer[k] > size//2:
                return k


"""
124. 二叉树中的最大路径和
路径 被定义为一条从树中任意节点出发，沿父节点-子节点连接，达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点，且不一定经过根节点。

路径和 是路径中各节点值的总和。

给你一个二叉树的根节点 root ，返回其 最大路径和 。

示例 1：

输入：root = [1,2,3]
输出：6
解释：最优路径是 2 -> 1 -> 3 ，路径和为 2 + 1 + 3 = 6
示例 2：

输入：root = [-10,9,20,null,null,15,7]
输出：42
解释：最优路径是 15 -> 20 -> 7 ，路径和为 15 + 20 + 7 = 42

提示：

树中节点数目范围是 [1, 3 * 104]
-1000 <= Node.val <= 1000
通过次数143,991提交次数326,083

树 深度优先搜索 动态规划 二叉树
背诵, 后续遍历
"""

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    max_value = float('-inf')

    def maxPathSum(self, root: TreeNode) -> int:
        self._maxPathSum(root)
        return self.max_value

    def _maxPathSum(self, root: TreeNode):
        if root is None:
            return 0
        # 和0对比，如果0更大，意味着不经过子节点
        left_max = max(self._maxPathSum(root.left), 0)
        right_max = max(self._maxPathSum(root.right), 0)
        self.max_value = max(self.max_value, left_max + right_max + root.val)

        # 返回经过我自己的最大的值，但是不一定经过我的子节点
        return max(left_max, right_max) + root.val

if __name__ == '__main__':
    # root = TreeNode(1, TreeNode(2), TreeNode(3))
    # root = [-10, 9, 20, None, None, 15, 7]
    # root = TreeNode(-10, TreeNode(9),TreeNode(20, TreeNode(15), TreeNode(7)))
    # [-1,-2,10,-6,null,-3,-6]
    root = TreeNode(-1, TreeNode(-2), TreeNode(10))
    s = Solution()
    print(s.maxPathSum(root))


from graphics import *
from m_zones import *

import m_file

def delay(d):
    for i in range(d):
        for i in range(100):
            pass

def field_setup(cell_size, border, info_area):
    # cell_size: how many square pixels each cell will occupy
    # border: the size of the area surrounding the field (in cells)
    # info_area: the size (in cells) of the area text will be displayed.
    cs = cell_size
    b = border
    ia = info_area

    # define the colors of the different field areas
    field_c = color_rgb(40, 100, 40)
    border_c = color_rgb(130, 80, 5)
    info_c = color_rgb(40, 50, 70)
    line_c = color_rgb(130, 180, 130)

    # set the field size using the coordinates of the
    # top right corner of the end zone
    fw = field['EZ'][1][0]
    fh = field['EZ'][1][1]

    # set the overall window size
    w = ((b * 2) + fw) * cs
    h = ((b * 2) + ia + fh) * cs
    print('setting window to {} by {}'.format(w, h))

    # create the window
    win = GraphWin('The Ultimater Field', w, h)
    win.setBackground(border_c)

    # draw the playing area
    top_left = Point(b * cs, b * cs)
    bottom_right = Point((fw + b) * cs, (fh + b) * cs)
    field_rect = Rectangle(top_left, bottom_right)
    field_rect.setFill(field_c)
    field_rect.draw(win)
    print('field area is at: {} {}'.format(top_left, bottom_right))

    # draw the info area
    top_left = Point(b * cs, (fh + b) * cs)
    bottom_right = Point((fw + b) * cs, h - (b * cs))
    info_rect = Rectangle(top_left, bottom_right)
    info_rect.setFill(info_c)
    info_rect.draw(win)
    print('info area is at: {} {}'.format(top_left, bottom_right))

    # draw the zones on the field
    for zone in field:
        top_left =     Point((field[zone][0][0] + b) * cs,
                             (field[zone][0][1] + b) * cs)
        bottom_right = Point((field[zone][1][0] + b) * cs,
                             (field[zone][1][1] + b) * cs)
        rect = Rectangle(top_left, bottom_right)
        rect.setOutline(line_c)
        rect.draw(win)
        text = Text(rect.getCenter(), zone)
        text.setTextColor(line_c)
        text.draw(win)
        print('{} is at: {} {}'.format(zone, top_left, bottom_right))
    return win

def bouncing_circle_test(win):
    # movement tester
    # based on https://www.youtube.com/watch?v=Rk7Q_VADBRQ
    p2 = win.getMouse()
    xmove = 8
    ymove = 10
    pt = Point(300, 260)
    c = Circle(pt, 50)
    c.setFill(color_rgb(250,200,50))
    c.draw(win)
    keep_going = True
    while keep_going == True:
        # delay(1)
        c.move(xmove, ymove)
        center = c.getCenter()
        p2 = win.checkMouse()
        if ((center.getX() < 60) or center.getX() > 1360):
            xmove =- xmove
        if ((center.getY() < 60) or center.getY() > 410):
            ymove =- ymove
        p3 = win.checkMouse()
        if p3 != p2:
            keep_going = False

def load_game_record(path, generation, away_team_num, home_team_num):
    p = path
    gen = generation
    a = away_team_num
    h = home_team_num
    file_name = ('GEN-' + gen + '_' + a + '_vs_' +
                 'GEN-' + gen + '_' + h)
    os.chdir(path)
    return m_file.read(file_name)

# turns a tuple into a point, and adjusts for cell size
def mk_pt(tup, cell_size, border_size):
    pt = Point((tup[0] + border_size) * cell_size,
               (tup[1] + border_size) * cell_size)
    return pt

def view_game(game_record, cell_size, border_size, win):
    r = game_record
    c = cell_size
    b = border_size
    circle_size = c
    home_color = color_rgb(250, 150, 15)
    away_color = color_rgb(180, 80, 240)
    label_color = color_rgb(40, 50, 70)
    # find the starting positions for each player
    home_left_loc =   mk_pt(r['Start_Spots']['home_left'],   c, b)
    home_center_loc = mk_pt(r['Start_Spots']['home_center'], c, b)
    home_right_loc =  mk_pt(r['Start_Spots']['home_right'],  c, b)
    away_left_loc =   mk_pt(r['Start_Spots']['away_left'],   c, b)
    away_center_loc = mk_pt(r['Start_Spots']['away_center'], c, b)
    away_right_loc =  mk_pt(r['Start_Spots']['away_right'],  c, b)
    print('home_left_loc point = {}'.format(home_left_loc))
    # make the circles for each player
    hl_circle = Circle(home_left_loc, circle_size)
    hl_circle.setFill(home_color)
    hl_circle.draw(win)
    hl_label = Text(hl_circle.getCenter(), 'HL')
    hl_label.setTextColor(label_color)
    hl_label.draw(win)

    hc_circle = Circle(home_center_loc, circle_size)
    hc_circle.setFill(home_color)
    hc_circle.draw(win)
    hc_label = Text(hc_circle.getCenter(), 'HC')
    hc_label.setTextColor(label_color)
    hc_label.draw(win)

    hr_circle = Circle(home_right_loc, circle_size)
    hr_circle.setFill(home_color)
    hr_circle.draw(win)
    hr_label = Text(hr_circle.getCenter(), 'HR')
    hr_label.setTextColor(label_color)
    hr_label.draw(win)

    al_circle = Circle(away_left_loc, circle_size)
    al_circle.setFill(away_color)
    al_circle.draw(win)
    al_label = Text(al_circle.getCenter(), 'AL')
    al_label.setTextColor(label_color)
    al_label.draw(win)

    ac_circle = Circle(away_center_loc, circle_size)
    ac_circle.setFill(away_color)
    ac_circle.draw(win)
    ac_label = Text(ac_circle.getCenter(), 'AC')
    ac_label.setTextColor(label_color)
    ac_label.draw(win)

    ar_circle = Circle(away_right_loc, circle_size)
    ar_circle.setFill(away_color)
    ar_circle.draw(win)
    ar_label = Text(ar_circle.getCenter(), 'AR')
    ar_label.setTextColor(label_color)
    ar_label.draw(win)

    win.getMouse() # pause for click in window before we play the moves

    # actually move the circles
    for time in range(r['Duration']):
        print('t = {}'.format(time))
        t = str(time)
        for move in r[t]['Moves']:
            if move == 'home_left':
                x = r[t]['Moves']['home_left']['offset'][0] * c
                y = r[t]['Moves']['home_left']['offset'][1] * c
                hl_circle.move(x, y)
                hl_label.move(x, y)
                print('Moving {} ({}, {})'.format(move, x, y))
            elif move == 'home_center':
                x = r[t]['Moves']['home_center']['offset'][0] * c
                y = r[t]['Moves']['home_center']['offset'][1] * c
                hc_circle.move(x, y)
                hc_label.move(x, y)
                print('Moving {} ({}, {})'.format(move, x, y))
            elif move == 'home_right':
                x = r[t]['Moves']['home_right']['offset'][0] * c
                y = r[t]['Moves']['home_right']['offset'][1] * c
                hr_circle.move(x, y)
                hr_label.move(x, y)
                print('Moving {} ({}, {})'.format(move, x, y))
            elif move == 'away_left':
                x = r[t]['Moves']['away_left']['offset'][0] * c
                y = r[t]['Moves']['away_left']['offset'][1] * c
                al_circle.move(x, y)
                al_label.move(x, y)
                print('Moving {} ({}, {})'.format(move, x, y))
            elif move == 'away_center':
                x = r[t]['Moves']['away_center']['offset'][0] * c
                y = r[t]['Moves']['away_center']['offset'][1] * c
                ac_circle.move(x, y)
                ac_label.move(x, y)
                print('Moving {} ({}, {})'.format(move, x, y))
            elif move == 'away_right':
                x = r[t]['Moves']['away_right']['offset'][0] * c
                y = r[t]['Moves']['away_right']['offset'][1] * c
                ar_circle.move(x, y)
                ar_label.move(x, y)
                print('Moving {} ({}, {})'.format(move, x, y))

path = '/Users/testuser/Projects/ultimater/data/teams/test/games'
record = load_game_record(path, 'TEST3', '004', '003')
print('game record is:\n{}'.format(record))
print('game record 0 is:\n{}'.format(record['0']))

def main():
    cell_size = 10
    border_size = 1
    info_area = 5
    win = field_setup(cell_size, border_size, info_area)

    # bouncing_circle_test(win)
    view_game(record, cell_size, border_size, win)

    win.getMouse() # pause for click in window
    win.close()

main()


# напишите здесь функцию print_shopping_list(),
# подобрав уникальные названия продуктов и сложив значения

def print_shopping_list(a, b):
    product_a=set(a)
    spisok = product_a.union(b)
    d = {}
    for key in spisok:
        if key in a:
            if key in b:
                c=a[key]+b[key]
                d[key]=c
            else: d[key]=a[key]
        elif key in b:
            d[key]=b[key]
    for key in d:
        print(str(key)+': '+str(d[key]))

pizza = {'мука, кг': 1,
         'помидоры, кг': 1.5,
         'шампиньоны, кг': 1.5,
         'сыр, кг': 0.8,
         'оливковое масло, л': 0.1,
         'дрожжи, г': 50}
salad = {'огурцы, кг': 1,
         'перцы, кг': 1,
         'помидоры, кг': 1.5,
         'оливковое масло, л': 0.1,
         'листья салата, кг': 0.4}

print_shopping_list(pizza, salad)


from django.contrib import admin
from .models import TravelRequest, TrTravelRequest, AgentTravelRequest, TravelNotes, Attachment, Others
from contacts.models import Contact, IndividualRole, Zone, Center
from django.core.exceptions import ObjectDoesNotExist
from utils.filters import RelatedDropdownFilter, ChoiceDropdownFilter
from django.shortcuts import render
from django.utils import formats
from datetime import date, timedelta
from ipcaccounts.models import RCOAccountsMaster, VoucherDetails, AccountTypeMaster,EntityMaster,RCOVoucherStatusMaster,ExpensesTypeMaster, VoucherMaster
from django.contrib import messages
import json
from config.models import Configuration, SmartModel
from django.http import HttpResponse, HttpResponseNotFound, Http404,  HttpResponseRedirect
from AasaanUser.models import AasaanUserContact, AasaanUserZone
from django.contrib.auth.models import User
from django.utils import timezone
from .forms import TravelForm, TravelOtherDetailsInlineFormset

class OthersInline(admin.TabularInline):
    formset = TravelOtherDetailsInlineFormset
    model = Others
    extra = 0
    max_num = 10

class AttachmentInline(admin.StackedInline):
    model = Attachment
    extra = 1
    max_num = 5

class TravelNotesInline(admin.StackedInline):
    model = TravelNotes
    extra = 0
    fields = ['note', ]

    def has_change_permission(self, request, obj=None):
        return False

class TravelNotesInline1(admin.StackedInline):

    model = TravelNotes
    extra = 0
    readonly_fields = ['note',]

    fieldsets = [
        ('', {'fields': ('note',), }),
        ('Hidden Fields',
         {'fields': ['created_by',], 'classes': ['hidden']}),
    ]

    def has_add_permission(self, request):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

class BaseTravelAdmin(admin.ModelAdmin):

    date_hierarchy = 'onward_date'
    inlines = [OthersInline, TravelNotesInline1, TravelNotesInline, AttachmentInline]

    def save_related(self, request, form, formsets, change):
        for formset in formsets:
            for fs in formset:
                if isinstance(fs.instance, TravelNotes) and fs.cleaned_data:
                    if fs.instance.pk is None:
                        fs.instance.travel_request = form.instance
                        fs.instance.created_by = request.user.username
                        fs.instance.note = fs.instance.note + ' - created_by : ' + request.user.username + ' created at : ' + timezone.now().strftime(
                            "%b %d %Y %H:%M:%S")
                        fs.instance.save()
        super(BaseTravelAdmin, self).save_related(request, form, formsets, change)

    class Media:
        js = ('/static/aasaan/travels/travels.js',)

class TravelRequestAdmin(BaseTravelAdmin):
    form = TravelForm
    list_display = ('status_flag', 'ticket_number', '__str__', 'source', 'destination', 'onward_date', 'zone', 'status', 'invoice_no', 'created_by')
    list_editable = ('status',)
    list_display_links = ['status_flag', '__str__', 'ticket_number']
    list_filter = ('created',('travel_mode', ChoiceDropdownFilter), ('status', ChoiceDropdownFilter), ('zone', RelatedDropdownFilter), )
    search_fields = ('source', 'destination', 'teacher__first_name', 'teacher__last_name', 'created_by__first_name', 'invoice_no', 'ticket_number')
    fieldsets = (
        ('', {
            'fields': ('ticket_number', 'source', 'destination', 'onward_date', 'travel_mode', 'travel_class', 'zone', 'teacher', 'is_others')

        }),
        ('Booking details', {
            'fields': ('status', 'booked_date', 'invoice_no', 'amount', 'attachments', 'invoice', 'refund_amount'),
            'classes': ('collapse', 'open')
        }),
    )
    filter_horizontal = ('teacher',)

    def create_voucher(self, request, queryset):
        accounts_voucher = RCOAccountsMaster()
        accounts_voucher.account_type = AccountTypeMaster.objects.get(id=3)
        amount = 0
        for tr in list(queryset):
            if tr.status=='VC' or tr.status=='CL' or tr.status=='PD' or tr.status=='IP':
                self.message_user(request, "Voucher already created or processed or Inprogress. Update booking details to create vouchers", level=messages.WARNING)
                return
            accounts_voucher.zone = tr.zone
            amount += tr.amount
            cft = Configuration.objects.get(configuration_key='IPC_ACCOUNTS_TRACKING_CONST')
            data = json.loads(cft.configuration_value)
            prefix = data[accounts_voucher.zone.zone_name]['prefix']
            accounts_voucher.budget_code = 'Teachers budget '+prefix
            accounts_voucher.save()
            bank_voucher = VoucherDetails()
            bank_voucher.voucher_type = 'BV'
            bank_voucher.nature_of_voucher = VoucherMaster.objects.get(id=4)
            bank_voucher.head_of_expenses = ExpensesTypeMaster.objects.get(id=5)
            bank_voucher.expenses_description = 'Booked Teachers Tickets'
            bank_voucher.party_name = 'Kathir Travel Line'
            bank_voucher.amount = amount
            bank_voucher.accounts_master = accounts_voucher
            bank_voucher.save()

            journal_voucher= VoucherDetails()
            journal_voucher.voucher_type = 'JV'
            journal_voucher.nature_of_voucher = VoucherMaster.objects.get(id=3)
            journal_voucher.head_of_expenses = ExpensesTypeMaster.objects.get(id=5)
            journal_voucher.expenses_description = 'Booked tickets for Teachers'
            journal_voucher.party_name = 'Kathir Travel Line'
            journal_voucher.amount = amount
            journal_voucher.accounts_master = accounts_voucher
            journal_voucher.save()

            for tr in list(queryset):
                tr.status = 'VC'
                tr.voucher = accounts_voucher
                tr.save()

        return HttpResponseRedirect('/admin/ipcaccounts/rcoaccountsmaster/'+str(accounts_voucher.id)+'/change/')

    create_voucher.short_description = "Create Vouchers"

    def email_ticket_passanger(self, request, queryset):
        pass

    email_ticket_passanger.short_description = "Email ticket to Teacher"

    def make_email(self, request, queryset):
        pass

    make_email.short_description = "Send Email to Travel Agency"

    def view_passanger_details(self, request, queryset):
        all_tickets = []

        for tr in list(queryset):
            ticket_request = {}
            ticket_request['tracking_no'] = 'TR' + str(tr.id).zfill(6)
            ticket_request['zone'] = tr.zone.zone_name
            ticket_request['source'] = tr.source
            ticket_request['destination'] = tr.destination
            onward_date = formats.date_format(tr.onward_date, "DATE_FORMAT")
            ticket_request['onward_date'] = onward_date
            ticket_request['travel_mode'] = tr.get_travel_mode_display()
            ticket_request['remarks'] = tr.remarks
            traveller_details = list(tr.teacher.all())
            t_list = []
            for index, t in enumerate(traveller_details):
                age = 'Age not known'
                if t.date_of_birth:
                    age = (date.today() - t.date_of_birth) // timedelta(days=365.2425)
                t_dict = {}
                t_dict['SNo'] = str(index + 1)
                t_dict['full_name'] =t.full_name
                t_dict['age'] = t.get_gender_display() + ' - ' + str(age)
                t_dict['primary_mobile'] =t.primary_mobile
                t_list.append(t_dict)
            ticket_request['travellers'] = t_list
            all_tickets.append(ticket_request)

        return render(request,
                      'travels/view_details.html',
                      context={'travel_request':all_tickets})

    view_passanger_details.short_description = "View Passanger Details"

    actions = [make_email, view_passanger_details, create_voucher, email_ticket_passanger]

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):

        if not request.user.is_superuser and db_field.name == 'zone':
            user_zones = [x.zone.id for x in request.user.aasaanuserzone_set.all()]
            kwargs["queryset"] = Zone.objects.filter(pk__in=user_zones)
        return super(TravelRequestAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        if db_field.name == 'teacher':

            try:
                teacher_role = IndividualRole.objects.get(role_name='Teacher', role_level='ZO')
                _teacher_list = Contact.objects.filter(individualcontactrolezone__role=teacher_role)
                kwargs["queryset"] = _teacher_list.distinct()
            except ObjectDoesNotExist:
                kwargs["queryset"] = Contact.objects.none()
            return super(TravelRequestAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

    # filter tickets records based on user permissions
    def get_queryset(self, request):
        qs = super(TravelRequestAdmin, self).get_queryset(request)
        if request.user.is_superuser:
            return qs
        if 'Teacher' in [x.name for x in request.user.groups.all()]:
            return TravelRequest.objects.filter(created_by=request.user)
        else:
            user_zones = [x.zone for x in request.user.aasaanuserzone_set.all()]
            return TravelRequest.objects.filter(zone__in=user_zones)

    def save_model(self, request, obj, form, change):
        if not obj.id:
            obj.created_by = request.user
        obj.save()

    def get_actions(self, request):
        actions = super(TravelRequestAdmin, self).get_actions(request)
        if request.user.is_superuser:
            return actions
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

class TeachersTravelRequestAdmin(BaseTravelAdmin):
    list_editable = []
    list_filter = []
    list_display = ('status_flag', 'ticket_number', '__str__', 'source', 'destination', 'onward_date', 'status')
    search_fields = []
    list_display_links = ['status_flag', '__str__', 'ticket_number']

    def get_actions(self, request):
        actions = super(TeachersTravelRequestAdmin, self).get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

    fieldsets = (
        ('', {
            'fields': ('ticket_number', 'source', 'destination','onward_date', 'travel_mode', 'travel_class', 'zone')
        }),
    )

    def get_queryset(self, request):
        return TravelRequest.objects.filter(created_by=request.user, status__in=['IP', 'BO','BK', 'CL', 'CB'])

    def save_model(self, request, obj, form, change):
        login_user = User.objects.get(username=request.user.username)
        contact = AasaanUserContact.objects.get(user=login_user)
        obj.created_by = request.user
        obj.save()
        obj.teacher.add(contact.contact)

    def get_form(self, request, obj=None, **kwargs):
        login_user = User.objects.get(username=request.user.username)
        try:
            AasaanUserContact.objects.get(user=login_user)
        except AasaanUserContact.DoesNotExist:
            self.message_user(request,
                              "Contact is not mapped to User. Contact aasaan admin",
                              level=messages.WARNING)
        try:
            AasaanUserZone.objects.get(user=login_user)
        except AasaanUserZone.DoesNotExist:
            self.message_user(request,
                              "Zone is not mapped to User. Contact aasaan admin",
                              level=messages.WARNING)

        return super(TeachersTravelRequestAdmin, self).get_form(request, obj=None, **kwargs)

class AgentTravelRequestAdmin(BaseTravelAdmin):
    date_hierarchy = 'created'
    list_display = ('status_flag', 'ticket_number', '__str__', 'source', 'destination', 'onward_date', 'zone', 'status', 'created_by')
    list_editable = ('status',)
    list_display_links = ['status_flag', '__str__', 'ticket_number']
    list_filter = ('onward_date', ('travel_mode', ChoiceDropdownFilter), ('status', ChoiceDropdownFilter),
                   ('zone', RelatedDropdownFilter),)
    search_fields = ('source', 'destination', 'teacher__first_name', 'teacher__last_name', 'created_by__first_name','invoice_no', 'ticket_number')
    fieldsets = (
        ('', {
            'fields': ('ticket_number','source', 'destination', 'onward_date', 'travel_mode', 'travel_class', 'zone', 'remarks')

        }),
        ('Passanger details', {
            'fields': ('teacher', )
        }),
        ('Booking details', {
            'fields': ('status', 'booked_date', 'invoice_no', 'amount', 'attachments', 'invoice', 'refund_amount'),
            'classes': ('collapse', 'open')
        }),
    )
    readonly_fields = ['source', 'destination', 'teacher', 'onward_date', 'travel_mode', 'travel_class', 'zone', 'remarks']

    def get_queryset(self, request):
       return TravelRequest.objects.filter(status__in=['BO', 'BK', 'CL', 'CB'])

    def get_actions(self, request):
        actions = super(AgentTravelRequestAdmin, self).get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

    def has_delete_permission(self, request, obj=None):
        return False

admin.site.register(TravelRequest, TravelRequestAdmin)
admin.site.register(TrTravelRequest, TeachersTravelRequestAdmin)
admin.site.register(AgentTravelRequest, AgentTravelRequestAdmin)


#Строковые занчения
'{} {}'.format('one', 'two') #one two

#Числовые значения
'{} {}'.format(1, 2) #1 2

#порядок значений можно указывать
'{1} {0}'.format('one', 'two') #two one

#Можно так же подставлять значения классов
class Data(object):

    def __str__(self):
        return 'str'

    def __repr__(self):
        return 'repr'

'{0!s} {0!r}'.format(Data()) #str repr

#Отступы и выравнивания
#по правому краю
'{:>10}'.format('test') #      test

#по левому краю
'{:_<10}'.format('test') #test______

#по центру
'{:^10}'.format('test') #   test

#срезы
'{:.5}'.format('xylophone') #xylop

#срезы и отступы
'{:10.5}'.format('xylophone') #xylop

#числа
'{:d}'.format(42) #42
'{:f}'.format(3.141592653589793) #3.141593

#числа и отступы
'{:4d}'.format(42) #  42
'{:06.2f}'.format(3.141592653589793) #003.14
'{:04d}'.format(42) # 0042

#знаковые числа
'{:+d}'.format(42) #+42
'{: d}'.format((- 23)) #-23
'{: d}'.format(42) # 42
'{:=5d}'.format((- 23)) #-  23
'{:=+5d}'.format(23) #+  23

#можно вставлять значения по именам
data = {'first': 'Hodor', 'last': 'Hodor!'}
'{first} {last}'.format(**data) #Hodor Hodor!
'{first} {last}'.format(first='Hodor', last='Hodor!') #Hodor Hodor!

#Формат даты и времени
from datetime import datetime
'{:%Y-%m-%d %H:%M}'.format(datetime(2001, 2, 3, 4, 5)) #2001-02-03 04:05


from celery import shared_task

from helper.celery import app

@shared_task
def create_dedup_event(data, dedup_key, task_pair_id):
    from helper.models import DedupEvent # avoid recursive import.
    return DedupEvent.objects.get_or_create(
        task_pair_id=task_pair_id, key=data[dedup_key])[1]

@shared_task
def dedup_effect_wrapper(data, dedup_key, task_pair_id, effect):
    from helper.models import DedupEvent # avoid recursive import.
    if DedupEvent.objects.get_or_create(task_pair_id=task_pair_id,
                                        key=data[dedup_key])[1]:
        effect.apply_async(
            (data,), link_error=remove_from_dedup_cache_on_error.s(
                dedup_key, task_pair_id, data))
        return data

@shared_task
def remove_from_dedup_cache_on_error(task_id, dedup_key, task_pair_id, data):
    from helper.models import DedupEvent # avoid recursive import.
    DedupEvent.objects.filter(task_pair_id=task_pair_id,
                              key=data[dedup_key]).delete()


# -*- coding: utf-8 -*-
from typing import Optional

from somali import aiorequests, config

class AI:
    base_url = config.ai_url
    key = config.ai_key

    @classmethod
    async def nlu(cls, text: str) -> Optional[dict]:
        url = f"{cls.base_url}/model/parse"
        params = {"token": cls.key}
        data = {"text": text}
        return await aiorequests.post(url, params=params, json=data)

    @classmethod
    async def predict(cls, text: str) -> dict:
        response = cls.nlu(text)
        intent: str = response["intent"]["name"]
        entity: Optional[str] = response["entities"][0]["value"] if response["entities"] else ""
        confidence: float = response["intent"]["confidence"]
        if intent == "nlu_fallback":
            intent = None
        elif entity and entity.startswith(
            ("o ", "a ", "do ", "da ", "no ", "na ", "em ")
        ):
            entity = entity.split(maxsplit=1)[1]
        return {"intent": intent, "entity": entity, "confidence": confidence}

    @staticmethod
    def small_talk(intent: str) -> Optional[str]:
        if intent == "ping":
            return "estou aqui"
        elif intent == "greet":
            return "oi"
        elif intent == "how_are_you":
            return "estou bem"
        elif intent == "who_are_you":
            return 'eu sou um bot, veja meus comandos digitando "%help"'
        elif intent == "praise":
            return "ðŸ˜Š"
        elif intent == "swear":
            return "ðŸ–•"


# Simple introduction to python

import numpy as np
import pandas as pd

def variables():
  x = "Hello world"   # String
  print(x)

  b = True # Boolean
  print(b)

  i = 123 # Integer
  print(i)

  f = 2.34  # Float
  print(f)

  c = "ABC 123"
  print(c)

def add(a, b):
  return a +b

def dataStructures():
  t = (1, 2, 3) # tuple
  print(t)
  print(t[0])

  l = [2, 3, 4] # list
  print(l)
  print(l[2])

  d = { "a":1, "b":2, "c":3 } # dictionary
  print(d)
  print(d['b'])

def numpyDataStructures():
  print('\n\nNumpy Data Structures')
  a = np.array([1, 2, 3])
  print(a)
  print(a[0])

  range = np.arange(1, 6)
  print(range)

  m = np.matrix([
    [1, 2, 3],
    [4, 5, 6]
  ])
  print(m)
  print(m[0, 1])

def pandasDataStructures():
  print('\n\nPandas Data Structures')
  df = pd.DataFrame(
    columns = ["Name", "How_Many", "Is_Pet"],
    data=[
      ["Cat", 5, True],
      ["Dog", 10, True],
      ["Cow", 15, False],
      ["Pig", 20, False]
    ]
  )
  print(df)
  print(df.iloc[0, 1]) # Middle column of Cat row
  print('\n', df.iloc[0, :]) # Entire cat row
  print('\n', df.iloc[:, 0]) # Name column for all rows
  print('\n', df.loc[:, "How_Many"]) # Entire How_Many column for all rows, by name

  # Subsetting
  print(df.iloc[[1, 3], :]) # Grab all columns of rows 1 *and* 3
  print('\n', [df.iloc[1:4, :]]) # Grab rows 1-3 (sequence)
  print(df.iloc[[True, False, True, False], :]) # Individual test each row for inclusion
  print(df[df.Is_Pet == True]) # General test for inclusion
  print(df[df.How_Many > 12])
  print(df[df.Name.isin(["Cow", "Cat"])])

def matrices():
  print('\n\nMatrices')
  # Named parameters
  m1 = np.matrix(
    data = [
      [1, 2],
      [3, 4]
    ],
    dtype = "float"
  )
  # ordered parameters
  m2 = np.matrix(
    [[1, 2], [3, 4]],
    "float"
  )
  # All matrix operations yield a matrix
  # including equality
  print(m1 == m2)

def main():
  variables()
  print(add(1, 2))
  dataStructures()
  numpyDataStructures()
  pandasDataStructures()
  matrices()

if __name__ == "__main__":
  main()


from markdown import Markdown
from os import path,listdir
from Blask.errors import PageNotExistError
import math
import os

class BlogRenderer:
    """
    Class BlogRenderer: This class provides the feature for render posts from Markdown to HTML and search features.
    :Author: Zerasul <suarez.garcia.victor@gmail.com>
    Date: 2018-05-05
    Version: 0.1.0
    """
    postdir = None
    """
    Posts Directory
    """

    def __init__(self, postdir):
        """
        This is the constructor of the blog renderer.
        :param postdir: Posts Directory. See Settings py for more information.
        """
        self.postdir = postdir

    def renderfile(self, filename, abstract=None):
        """
            Render a markdown and returns the blogEntry.
        :param filename: Number of the file without extension.
        :return: BlogEntry.
        :raises PageNotExistError Raise this error if file does not exists.
        """
        filepath = path.join(self.postdir, filename + ".md")
        if not path.exists(filepath):
            raise PageNotExistError("{} does not exists".format(filename))
        with open(filepath, 'r', encoding='UTF-8') as content_file:
            content = content_file.read()
            if abstract is not None:
                content = content[:max(450, len(content)//10)]

            entry = self.rendertext(filename, content)
        return entry

    def rendertext(self,filename, text):
        """
         Render a Markdown Text and returns the BlogEntry.
        :param filename: filename or title of the post.
        :param text: Text write in Markdown.
        :return: BlogEntry.
        """
        md = Markdown(extensions=['full_yaml_metadata', 'codehilite', 'markdown.extensions.toc', 'mdx_math',
                                  'markdown_fenced_code_tabs'],
                      extension_configs={
                          'mdx_math': {'add_preview': True},
                          'markdown_fenced_code_tabs':{
                                'single_block_as_tab': False,
                                'active_class': 'active',
                                'template': 'default',
                            }
                      })
        entry = BlogEntry(filename, md, text)
        return entry

    def get_info(self, query=""):
        file = self.postdir + '/info.md'
        with open(file, 'r', encoding='UTF-8') as content_file:
            content = content_file.read()
        md = Markdown(extensions=['full_yaml_metadata', 'codehilite', 'markdown.extensions.toc', 'mdx_math'])
        content = md.convert(content)
        meta = md.Meta
        if meta is not None:
            return meta.get(query).split(",")

    def list_posts(self, tags=[], exclusions=["plda_algo.md", "404.md"], search="", category="", author=""):
        """
        Search a list of Posts returning a list of BlogEntry.
        :param tags: list of tags for searching.
        :param exclusions: list of name of posts with exclusions.
        :param search: string with the content what we want of search.
        :param category: list of category of the entry.
        :return: List of BlogEntry.
        """
        files = list(filter(lambda l: l.endswith('.md') and l not in exclusions, listdir(self.postdir)))
        mapfilter = list(map(lambda l: path.splitext(l)[0], files))
        entries = list(map(lambda l: self.renderfile(l), mapfilter))
        if tags:
            for tag in tags:
                entries = list(filter(lambda l: tag in l.tags, entries))
        if category:
            entries = list(filter(lambda c: c.category == category, entries))
        if author:
            entries = list(filter(lambda a: a.author == author, entries))
        if search:
            entries = list(filter(lambda l: search in l.content, entries))

        return entries

    def generatetagpage(self, postlist):
        """
        Get a HTML with links of the entries.
        :param postlist: List with BlogEntry.
        :return: String with the HTML list.
        """
        if postlist == []:
            return '
        Oops! seems like you get a bug.
'
        else:
            content = '
Search Result:
'
            content += '
'
            for post in postlist:
                entrycontent = "
{}
".format(post.name, post.name)
                content += entrycontent
            content += "
"
            return content

    def generate_abstract(self, entries, files):
        contents = []
        names = []
        dates = []
        for file in files:
            entry = self.renderfile(file, abstract=True)
            contents.append(entry.content)
            names.append(entry.name)
            dates.append(entry.date)
        entries.contents = contents
        entries.names = names
        entries.date = dates
        entries.type = 'index'
        entries.zip_datas = zip(dates, contents, names)
        return entries

    def get_recent_five_post(self, page):
        postdir = self.postdir
        ex = ['info.md']

        files = [s for s in os.listdir(postdir)
                 if os.path.isfile(os.path.join(postdir, s))]
        files = list(set(files).difference(set(ex)))
        print(files)
        page_num = math.ceil(len(files) / 5)
        print(page_num)
        files.sort(key=lambda s: os.path.getmtime(os.path.join(postdir, s)))
        files = files[::-1]
        files = files[(page-1)*5:(page-1)*5+5]
        fs = []
        for file in files:
            f = file[:-3]
            fs.append(f)
        files = fs
        return files, page_num

class BlogEntry:
    """"
    This class has the information about the Blog Posts.
    Author: Zerasul
    Version: 0.0.1.
    """
    content = None
    """Content of the post."""
    date = None
    """ Date of post creation"""
    tags = []
    """List of tags of the blog entry."""
    author = None
    """Author of the post"""
    category = None
    """category of the post"""
    template = None
    """Name of the template file"""
    name = None
    """ Name of the post"""
    type = None

    def __init__(self, name, md, content):
        """
        Default constructor
        :param name: name of the post
        :param md: Markdown information
        :param content: String with the Content in HTML.
        """
        self.content = md.convert(content)
        self.name = name
        meta = md.Meta
        if md.toc is not None:
            self.toc = md.toc
        if meta is not None:
            self.date = meta.get('date')
            self.tags = meta.get('tags').split(",")
            self.template = meta.get('template')
            self.category = meta.get('category')
            self.author = meta.get('author')
            self.type = meta.get('type')

    def __str__(self):
        string = "['content': {}, 'name': {}, 'date': {}, 'tags':[{}], 'author': {}, 'category': {}, template': {}]".format(self.content,self.name,self.date,self.tags,self.author,self.category,self.template)
        return string


import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
from apachelogs import LogParser
from pathlib import Path
from ip2geotools.databases.noncommercial import DbIpCity

#function to ingest apache logs and parse out fields
def logFileParse(paths):
    for path in paths:
        path_in_str = str(path)
        with open(path_in_str) as fp:
            for entry in parser.parse_lines(fp):

                host = entry.directives["%h"]
                logName = (str(entry.directives["%l"]) == 'None' and '-') or str(entry.directives["%l"])
                user = (str(entry.directives["%u"]) == 'None' and '-') or str(entry.directives["%u"])
                time = str(entry.request_time)
                request = entry.directives["%r"]
                status = entry.directives["%>s"]
                bytesSent = entry.directives["%O"]

                lst.append([host,logName,user,time,request,status,bytesSent])

#function to call ip2geotools api and get country code by IP address
def getCountryByIP(lst):
    for i in lst:
        response = DbIpCity.get(i[0], api_key='free')
        i[0] = response.country

#define variables
projectLocation = '/home/jshivers/projects/apache-log-anonymizer'
parser = LogParser("%h %l %u %t \"%r\" %>s %O")
lst = []
paths = Path(projectLocation + '/logs').glob('*.log.*')
cols = ['host', 'logName', 'user', 'time', 'request', 'status', 'bytesSent']

#call ingest and transformation functions
logFileParse(paths)
getCountryByIP(lst)

#create pandas dataframe
df = pd.DataFrame(lst, columns=cols)

#create numpy array in case of further analysis
#a = np.array(lst)
#a[:,0]

#print cleaned data to txt file
with open(projectLocation + '/output/out.txt', 'w', encoding="utf-8") as x:
    for sub_list in lst:
        for item in sub_list:  #Since attempt to write whole giv error
            x.write(str(item) + ' ')
        x.write("\n")

#print dataframe to parquet file
table = pa.Table.from_pandas(df)
pq.write_table(table, projectLocation + '/output/out.parquet')

#read parquet file
#table2 = pq.read_table('C:/projects/apache-log-anonymizer/output/example.parquet')
#table2.to_pandas()


import os
import json
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy.util as util
import argparse
import webbrowser
from dlimg import download
import math
import figlet_wrapper as f

def write_to_album_file(album_title, artist, img_url, album_url):
    with open('top_albums.json', 'r+') as f:
        data = json.load(f)
        t = {
            "name": album_title,
            "artist": artist,
            "img": img_url,
            "url": album_url
        }

        data['albums'].append(t)
        f.seek(0)
        json.dump(data, f, indent=4)
        f.truncate()

def write_to_artists_file(artist, artist_url, img_url, genres, popularity):
    with open('top_artists2.json', 'r+') as f:
        data = json.load(f)
        t = {
            "artist": artist,
            "artist_url": artist_url,
            "img_url": img_url,
            "genres": genres,
            "popularity": popularity
        }

        data['artists'].append(t)
        f.seek(0)
        json.dump(data, f, indent=4)
        f.truncate()

def open_img_url(url):
    webbrowser.open(url)

# Using spotify credentials to access API and returns the general info about artist
def get_artist_info(name):
    spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
    results = spotify.search(q='artist:' + name, type='artist')
    items = results['artists']['items']
    if len(items) > 0:
        return items
    else:
        return {}

# Function for getting the background image of the artist
def get_background(name):
    items = get_artist_info(name)

    try:

        if len(items) > 0:
            artist = items[0]
            return artist['images'][0]['url']
        else:
            return 'Something Went Wrong'
    except:
        return 'No Artist Found'

def get_artist_url(name):
    items = get_artist_info(name)

    try:
        if len(items) > 0:
            artist = items[0]
            return artist['external_urls']['spotify']
        else:
            return 'Something Went Wrong'
    except:
        return 'No Artist Found'

#def get_album_url(name):

# Function for getting the genres of the artist
def get_genres(name):
    items = get_artist_info(name)

    try:
        if len(items) > 0:
            artist = items[0]
            return artist['genres']
        else:
            return 'Something Went Wrong'

    except:
        return 'Artist Not Found'

# Function for getting the number of followers that the artist has
def get_followers(name):
    items = get_artist_info(name)

    try:
        if len(items) > 0:
            artist = items[0]

            return artist['followers']['total']
        else:
            return 'Something Went Wrong'

    except:
        return 'Artist Not Found'

# Function for getting the uri of the artist (good for getting more info about them)
def get_uri(name):
    items = get_artist_info(name)

    try:
        if len(items) > 0:
            artist = items[0]

            return artist['uri']
        else:
            return False
    except:
        return False

def get_popularity(name):
    items = get_artist_info(name)

    try:
        if len(items) > 0:
            artist = items[0]
            return artist['popularity']
        else:
            print('Something went wrong')
            return False
    except:
        print('Artist Not Found')
        return False

def get_albums(name):
    uri = get_uri(name)
    if (not uri):
        print('Bad Name')
        exit(1)

    spotify = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())

    results = spotify.artist_albums(uri, album_type='album')

    a = results['items']
    albums = []
    for i in a:
        new_album = {}
        new_album['name'] = i['name']
        new_album['num_tracks'] = i['total_tracks']
        new_album['cover'] = i['images'][0]['url']
        new_album['artist'] = i['artists'][0]['name']
        new_album['id'] = i['id']
        new_album['url'] = i['external_urls']['spotify']
        albums.append(new_album)

    return albums

# Getting image url
def find_album(artist, album):
    albums = get_albums(artist)
    if (not albums):
        return False

    albs = set([a['name'] for a in albums])

    for i in albums:
        if i['name'].lower() == album.lower():
            return i

    print('Album not found. Choose from this list:')

    index = 0
    for a in albs:
        print('[{0}] {1}'.format(index, a))
        index += 1

    choose = ' '
    while not isinstance(choose, int):
        try:
            inp = input('\n>')
            if (inp == 'q'):
                break
            choose = int(inp)
        except:
            print('Choose number')
            continue

    if (choose == ' '):
        return False

    chosen_album = list(albs)[choose]

    if (chosen_album):
        for i in albums:
            if i['name'].lower() == chosen_album.lower():
                return i

    return False

def input_for_album_cover():
    artist = input('Artist: ')
    print(get_albums(artist))
    album = input('Album: ')

    album = find_album(artist, album)
    download(album['cover'], album['name'])

    if (not album):
        return False

    print('image url: ', album['cover'])

def artist_info(artist):
    p = get_popularity(artist)
    albums = get_albums(artist)
    followers = get_followers(artist)
    genres = get_genres(artist)
    print(artist)
    print('Popularity: {0}\n====='.format(p))
    print('Followers: {0}'.format(followers))
    print('=====\nGenres: ')
    for genre in genres:
        print(genre, end=', ')
    print('\n=====\nAlbums: ')
    for album in albums:
        print(' - ' + album['name'])

# Loading in secret to the OS env in order to access spotify API
def load_secret():
    with open('secret.json') as f:
        data = json.load(f)
    os.environ['SPOTIPY_CLIENT_ID'] = str(data['SPOTIPY_CLIENT_ID'])
    os.environ['SPOTIPY_CLIENT_SECRET'] = data['SPOTIPY_CLIENT_SECRET']
    os.environ['SPOTIPY_REDIRECT_URI'] = data['SPOTIPY_REDIRECT_URI']
    print('Credentials Correct!\n')

def append_album():
    artist = input('Artist: ')
    album_choice = input('Album: ')
    album = find_album(artist, album_choice)
    if album:
        write_to_album_file(album['name'], album['artist'], album['cover'], album['url'])

    another = input('Another? (y/n)')
    if another == 'y':
        append_album()

def append_artist():
    artist = input('Artist: ')

    url = get_artist_url(artist)
    bg = get_background(artist)
    genres = get_genres(artist)
    popularity = get_popularity(artist)

    write_to_artists_file(artist, url, bg, genres, popularity)

    append_artist()

# This requires scope = 'user-read-playback-state'
def current(to_write=False):
    username = 'Avery Biskup'
    scope = 'user-read-playback-state'
    playlist_scope = 'playlist-read-private'
    library_scope = 'user-library-read'
    follow_scope = 'user-follow-read'
    top_scope = 'user-top-read'

    with open('secret.json') as secret:
        j = json.load(secret)
        SPOTIPY_CLIENT_ID = j['SPOTIPY_CLIENT_ID']
        SPOTIPY_CLIENT_SECRET = j['SPOTIPY_CLIENT_SECRET']
        SPOTIPY_REDIRECT_URI = j['SPOTIPY_REDIRECT_URI']
    token = util.prompt_for_user_token(username,
                                   scope,
                                   SPOTIPY_CLIENT_ID,
                                   SPOTIPY_CLIENT_SECRET,
                                   SPOTIPY_REDIRECT_URI)

    s = spotipy.Spotify(auth=token)
    os.system('clear')

    p = s.current_playback()

    if not p:
        print('No song playing')
        return 0

    device = p['device']['name']
    volume = p['device']['volume_percent']
    volume_percentage = math.floor(int(volume)/2)
    artist = p['item']['artists'][0]['name']
    album = p['item']['album']['name']
    track = p['item']['name']
    progress = p['progress_ms']
    duration = p['item']['duration_ms']
    img_url = p['item']['album']['images'][0]['url']
    link = p['item']['album']['external_urls']['spotify']

    artists = []
    for i in p['item']['artists']:
        artists.append(i['name'])

    if len(artists) > 1:
        maybe_plural_artist = 'Artists'
    else:
        maybe_plural_artist = 'Artist'

    artist_list = ', '.join(artists)

    percentage = math.floor((progress / duration)*50)
    progress_bar = '[' + ('=' * percentage) + ('-' * (50 - percentage)) + ']'

    duration_min = math.floor((int(duration)/1000)/60)
    duration_sec = math.floor((int(duration)/1000)%60)
    time = '{}:{}'.format(duration_min, duration_sec)

    volume_bar = '[' + ('=' * volume_percentage) + ('-' * (50 - volume_percentage)) + ']'

    print(f.p('Track: ', None, 'yellow') + f.p(track, None, 'purple'))
    print(f.p('{}: '.format(maybe_plural_artist), None, 'yellow') + f.p(artist_list, None, 'purple'))
    print(f.p('Album: ', None, 'yellow') + f.p(album, None, 'purple'))
    print(f.p('{} {}%'.format(volume_bar, volume), None, 'red'))
    print(f.p('{} {}'.format(progress_bar, time), None, 'cyan'))

    def write(data, filename='albums.json'):
        print('writing to file')
        with open(filename, 'w') as f:
            json.dump(data, f, indent=4)
    if to_write:
        with open('albums.json') as album_file:
            data = json.load(album_file)

            old = data['albums']

            new = {'name': album, 'artist': artist, 'img': img_url, 'url': link  }

            old.append(new)

        write(data)

if __name__ == '__main__':
    load_secret()

    parser = argparse.ArgumentParser()
    parser.add_argument('-a', '--album-cover', dest='album',
                              action='store_true',
                              help='Get album cover by artist, and album name')
    parser.add_argument('-p', '--popularity', dest='pop',
                              action='store_true',
                              help='Get the popularity of an artist')
    parser.add_argument('-ai', '--artist-info', dest='ai',
                              action='store_true',
                              help='Get information about a given artist')
    parser.add_argument('-c', '--current', dest='cur',
                              action='store_true',
                              help='Print what you are currently listening to')
    parser.add_argument('-ap', '--append', dest='app',
                              action='store_true',
                              help='Append album to top_albums file')
    parser.add_argument('-sa', '--save-artist', dest='art',
                              action='store_true',
                              help='Append artist to top_artists file')

    args = parser.parse_args()

    if (args.album):
        input_for_album_cover()
    elif (args.pop):
        artist = input('Artist: ')
        p = get_popularity(artist)
        if p:
            print('Popularity: ', p)
        else:
            print('Artist not found')
    elif (args.ai):
        artist = input('Artist: ')
        artist_info(artist)
    elif (args.cur):
        current()
    elif (args.app):
        append_album()
    elif (args.art):
        append_artist()
    else:
       print('No args given, -h for help')


#!/usr/bin/env python3

import rospy
from geometry_msgs.msg import Twist
from geometry_msgs.msg import PointStamped
from nav_msgs.msg import Odometry

class Movimento:
    def __init__(self):
        rospy.init_node('movimento_carro', anonymous=True)
        rospy.Subscriber('sonar_data', PointStamped, self.movimentarCarro)
        rospy.Subscriber('odom', Odometry, self.posicaoCarro)
        self.pubMovimentacao = rospy.Publisher('cmd_vel', Twist, queue_size=10)
        self.radar = PointStamped()
        self.posicaoRelativaCarros = PointStamped()
        self.posicaoCarro = PointStamped()

    def posicaoCarro(self,odom):

        rate = rospy.Rate(500)

        self.posicaoCarro.point.x = odom.pose.pose.position.x
        self.posicaoCarro.point.y = odom.pose.pose.position.y
        self.posicaoCarro.point.z = odom.pose.pose.position.z

        rate.sleep()

    def direcaoLado(self, posicaoCarro , distancia):
        if(abs(distancia) > 3.0):
            posicaoCarroVerde = posicaoCarro + distancia
            if(posicaoCarroVerde < posicaoCarro):
             return 0 - 1.5
            else:
             return 1.5
        else:
            return 0.0

    def direcaoFrente(self, posicaoCarro , distancia):
        if(abs(distancia) > 3.0):
            posicaoCarroVerde = posicaoCarro + distancia
            if(posicaoCarroVerde > posicaoCarro):
             return 1.5
            else:
             return 0 - 1.5
        else:
            return 0.0

    def movimentarCarro(self,sonar):

        rate = rospy.Rate(500)

        v = Twist()
        v.linear.x = self.direcaoLado(self.posicaoCarro.point.x, sonar.point.x)
        v.linear.y = self.direcaoFrente(self.posicaoCarro.point.y, sonar.point.y)
        v.linear.z = 0.0

        v.angular.x = 0.0
        v.angular.y = 0.0

        v.angular.z = 0.0

        self.pubMovimentacao.publish(v)

        rate.sleep()

if __name__ == '__main__':
    try:
        t = Movimento()
        rospy.spin()
    except rospy.ROSInterruptException:
        pass


# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser. #http://127.0.0.1:8050/

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
from joblib import load

app = dash.Dash(__name__)

report = load('./report.joblib')
fig_report = go.Figure(data=[go.Table(
    header=dict(values=list(report.columns),
                fill_color='paleturquoise',
                align='left'),
    cells=dict(values=report.transpose().values.tolist(),
               fill_color='lavender',
               align='left'))
])

result = load('./model_result.joblib')
history = pd.DataFrame(result['model_history'])
history['epoch'] = [i for i in range(1,history.shape[0]+1)]
fig_history =px.line(history, x=history.epoch, y=['loss', 'precision','accuracy','val_loss','val_precision','val_accuracy'])

app.layout = html.Div(children=[
    html.H1(children='Model Evaluation'),

    html.H5(children=' Classification report'),
    dcc.Graph(
        id='classification_report',
        figure=fig_report
    ),

    html.H5(children='parameters vs epoch'),
    dcc.Graph(
        id='model history',
        figure=fig_history
    )

])

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


import torch
import torch.nn as nn
import copy

## (Conditional) Variational Autoencoder class and encoder/decoder class

class VAE(nn.Module):
    def __init__(self, x_dim, y_dim, latent_dim, encoder_layersizes, decoder_layersizes, normparams, conditional=False):
        super().__init__()

        if conditional:
            assert y_dim > 0

        assert type(latent_dim) == int
        assert type(x_dim) == int

        self.latent_dim = latent_dim

        self.encoder = Encoder(x_dim, y_dim, latent_dim, conditional, encoder_layersizes, normparams)
        self.decoder = Decoder(x_dim, y_dim, latent_dim, conditional, decoder_layersizes, normparams)
        self.clamp = [-4, 15]

    def inference(self, z, y=None):
        recon_x = self.decoder(z, y)
        return recon_x

class Encoder(nn.Module):
    def __init__(self, x_dim, y_dim, latent_dim, conditional, encoder_layersizes, normparams):
        """
        Args:
            x_dim (int): e.g., x variable (to be reconstructed) dimension
            y_dim (int): e.g., y variable (if x is conditioned by y) dimension
            latent_dim (int): latent dimension
            conditional (bool): whether to use conditional VAE, if conditional then x is conditioned by y
        """
        super().__init__()

        self.conditional = conditional
        self.normparams = normparams

        layer_sizes = copy.deepcopy(encoder_layersizes)
        layer_sizes.insert(0, x_dim)
        if self.conditional:
            layer_sizes[0] += y_dim

        self.MLP = nn.Sequential()

        for i, (in_size, out_size) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):
            self.MLP.add_module(
                name="L{:d}".format(i), module=nn.Linear(in_size, out_size))
            self.MLP.add_module(name="A{:d}".format(i), module=nn.ReLU())

        self.liner_means = nn.Linear(layer_sizes[-1], latent_dim)
        self.linear_log_var = nn.Linear(layer_sizes[-1], latent_dim)

class Decoder(nn.Module):
    def __init__(self, x_dim, y_dim, latent_dim, conditional, decoder_layersizes, normparams):
        """
        Args:
            x_dim (int): e.g., x variable (to be reconstructed) dimension
            y_dim (int): e.g., y variable (if x is conditioned by y) dimension
            latent_dim (int): latent dimension
            conditional (bool): whether to use conditional VAE, if conditional then x is conditioned by y
        """
        super().__init__()

        self.conditional = conditional
        self.normparams = normparams

        layer_sizes = copy.deepcopy(decoder_layersizes)
        layer_sizes.insert(0, latent_dim)
        if self.conditional:
            layer_sizes[0] += y_dim

        layer_sizes.append(x_dim)

        self.MLP = nn.Sequential()

        for i, (in_size, out_size) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):
            self.MLP.add_module(
                name="L{:d}".format(i), module=nn.Linear(in_size, out_size))
            if i + 1 < len(layer_sizes[:-1]):
                self.MLP.add_module(name="A{:d}".format(i), module=nn.ReLU())
            else:
                self.MLP.add_module(name="sigmoid", module=nn.Sigmoid())

    def forward(self, z, y=None):
        if self.conditional:
            y = idx2onehot(y, 5)
            z = torch.cat((z, y), dim=-1)
        x = self.MLP(z)
        return x

## GAN class definition and corresponding Generator and Discriminator

class GAN(nn.Module):
     def __init__(self, sample_dim, latent_dim, generator_layersizes, discriminator_layersizes):
        super().__init__()

        assert type(sample_dim) == int
        assert type(latent_dim) == int
        self.sample_dim = sample_dim
        self.latent_dim = latent_dim
        self.generator_layersizes = generator_layersizes
        self.discriminator_layersizes = discriminator_layersizes

     def weights_init(self, m):
        classname = m.__class__.__name__
        if classname.find('Conv') != -1:
            nn.init.normal_(m.weight.data, 0.0, 0.02)
        elif classname.find('BatchNorm') != -1:
            nn.init.normal_(m.weight.data, 1.0, 0.02)
            nn.init.constant_(m.bias.data, 0)

     def initialize_generator(self, device):
        generator = Generator(self.latent_dim, self.sample_dim, self.generator_layersizes)
        generator.apply(self.weights_init)
        generator.to(device)
        return generator

     def generate_samples(self, generator, num_samples, latent_dim, device):
        noise = torch.randn(num_samples, latent_dim, device=device)
        generator.eval()
        samples = generator(noise)
        samples = samples.detach().numpy()
        return samples

class Generator(nn.Module):
  """
    DCGan Generator
  """
  def __init__(self, input_dim, out_dim, generator_layersizes):
    super().__init__()

    layer_sizes = copy.deepcopy(generator_layersizes)
    layer_sizes.insert(0, input_dim)
    layer_sizes.append(out_dim)

    self.MLP = nn.Sequential()

    for i, (in_size, out_size) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):
        self.MLP.add_module(
            name="L{:d}".format(i), module=nn.Linear(in_size, out_size))
        if i + 1 < len(layer_sizes[:-1]):
            self.MLP.add_module(name="A{:d}".format(i), module=nn.LeakyReLU())
        else:
            self.MLP.add_module(name="sigmoid", module=nn.Sigmoid())

  def forward(self, x):
    """Forward pass"""
    return self.MLP(x)
    # return self.layers(x)

class Discriminator(nn.Module):
  """
    DCGan Discriminator
  """
  def __init__(self, input_dim, out_dim, discriminator_layersizes):
    super().__init__()

    assert(out_dim==1)
    layer_sizes = copy.deepcopy(discriminator_layersizes)
    layer_sizes.insert(0, input_dim)
    layer_sizes.append(out_dim)

    self.MLP = nn.Sequential()

    for i, (in_size, out_size) in enumerate(zip(layer_sizes[:-1], layer_sizes[1:])):
        self.MLP.add_module(
            name="L{:d}".format(i), module=nn.Linear(in_size, out_size))
        if i + 1 < len(layer_sizes[:-1]):
            self.MLP.add_module(name="A{:d}".format(i), module=nn.LeakyReLU())
            self.MLP.add_module(name="Dropout{:d}".format(i), module=nn.Dropout(0.3))
        else:
            self.MLP.add_module(name="sigmoid", module=nn.Sigmoid())

  def forward(self, x):
    """Forward pass"""
    return self.MLP(x)
    # return self.layers(x)

## Additional functions

def idx2onehot(idx, n):
    assert torch.max(idx).item() < n

    if idx.dim() == 1:
        idx = idx.unsqueeze(1)
    onehot = torch.zeros(idx.size(0), n).to(idx.device)
    onehot.scatter_(1, idx, 1)

    return onehot


# 기끔씩 이론과 현실사이에 괴리가 생길때가 있죠. 그때는 현실부정을 하면 됩니다. 그래서 만들엇습니다. 주작버전. 데이터를 마음껏(그러나 걸리지 않게 조심조심) 조작하십시오!

# 주작버전. A_B_Angle 값을 이용한 계산을 통해 그림을 그리지만, 벡터의 크기, 각의 크기 등 표시는 직접 입력하는거.
# https://www.youtube.com/watch?v=QUXKib-jfEM 처럼 유투브 링크 있는데에다가는 뭘 넣어도 상관없음. 걍 표시용이라. 유튜브 링크 대신 원하는 숫자를 넣으면 됨.
# 아 글고 저 노래들은내가 개인적으로 좋아하는 노래들임. 그 외에는 별 의미 없음. 뭘 넣어도 된다는것을 보여주기 위한거.

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import math

X = np.array((0))
Y= np.array((0))

#------여기 아래에 값 넣으면 됨----------

a = 49.5 # 벡터 1 의 x 성분. 여기서는 49.5. 계산에 쓰이는 숫자.
b = 0    # 벡터 1 의 y 성분. 걍 0으로 두자....제바ㄹ
# 참고로 b =! 0 이면 터질수도 있음. 실험 안해봤고 해보기도 싫어. 코드 고치기 그ㅟ찮아앙

Vector_2_Length = 49.8 # 벡터 2 의 크기. 여기서는 49.8. 계산에 쓰이는 숫자.

A_B_Angle = 120 # 벡터 1과 벡터 2 사이 각. 계산에 쓰이는 숫자.
A_C_Angle = '요루시카 - 비와 카푸치노: https://www.youtube.com/watch?v=PWbRleMGagU'  # 벡터 1과 벡터 3 사이 각. 표시용이라 뭐든지 들어가도 됨
B_C_Angle = '술탄 오브 더 디스코 - 사라지는 꿈: https://www.youtube.com/watch?v=7fsavq0mU2k'  # 벡터 2와 벡터 3 사이 각. 표시용이라 뭐든지 들어가도 됨

label_1 = '달의하루 - 염라: https://www.youtube.com/watch?v=jv543Nk5s18' # 벡터 1 이름.
label_2 = '달의하루 - 너로피어오라 https://www.youtube.com/watch?v=3vhA8njtoQg' # 벡터 2 이름.
label_3 = '요루시카 - 그래서 나는 음악을 그만두었다. : https://www.youtube.com/watch?v=KTZ-y85Erus' # 벡터 3 이름. 글고 이름들은 ' ' 안에 넣어야함.

# x,y 축 최대. 최소 표시값. 그래프 잘리면 늘리고 너무 크면 좀 줄여. -80,80/ -60,60 하면 엔간한건 그려짐.
# 고치기 귀찮으면 실행시 뜨는 그래프에서 우클릭+드래그 하면 확대/축소됨.
xmin = -80
xmax = 80
ymin = -60
ymax = 60

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

c = Vector_2_Length*(math.cos(math.radians(A_B_Angle)))
d = Vector_2_Length*(math.sin(math.radians(A_B_Angle)))

e = a + c
f = b + d

def calculateDistance(x1,y1,x2,y2):
     dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
     ansdist = round(dist,2)
     return ansdist

def angle_of_vectors(A,B,C,D):

     dotProduct = A*C + B*D
     modOfVector1 = math.sqrt(A*A + B*B)*math.sqrt(C*C + D*D)
     angle = dotProduct/modOfVector1
     angleInDegree = math.degrees(math.acos(angle))
     return angleInDegree

angle_1 = round(float(angle_of_vectors(a,b,c,d)),2)
angle_2 = round(float(angle_of_vectors(a,b,-e,-f)),2)
angle_3 = round(float(angle_of_vectors(c,d,-e,-f)),2)

angle_plot_1 = mpatches.Arc([0, 0], 15, 15, 0, 0, angle_1)

angle_plot_21 = mpatches.Arc([0, 0], 13, 13, -angle_2, 0, angle_2)
angle_plot_22 = mpatches.Arc([0, 0], 11, 11, -angle_2, 0, angle_2)

angle_plot_31 = mpatches.Arc([0, 0], 9, 9, angle_1, 0, angle_3)
angle_plot_32 = mpatches.Arc([0, 0], 10, 10, angle_1, 0, angle_3)
angle_plot_33 = mpatches.Arc([0, 0], 11, 11, angle_1, 0, angle_3)

fig, ax = plt.subplots()
q = ax.quiver(X, Y, a, b, units='xy' ,scale=1, color= 'r', label=label_1)
r = ax.quiver(X, Y, c, d,units='xy' ,scale=1, color= 'b', label=label_2)
s = ax.quiver(X, Y, e, f,units='xy' ,scale=1, color = 'k') # 합벡터 안 그릴려면 이 줄 주석처리.
t = ax.quiver(X, Y, -e, -f,units='xy' ,scale=1, color = 'g', label=label_3)

ax.add_patch(angle_plot_1)
ax.add_patch(angle_plot_21)
ax.add_patch(angle_plot_22)
ax.add_patch(angle_plot_31)
ax.add_patch(angle_plot_32)
ax.add_patch(angle_plot_33)

text_1 = str(A_B_Angle) + '°'
text_2 = str(A_C_Angle) + '°'
text_3 = str(B_C_Angle) + '°'

plt.text(7,5, text_1) #벡터 1--2 각도 표시. 7,5,가 글씨의 x,y좌표. 알아서 옮겨
plt.text(7,-7, text_2) #벡터 1--3 각도 표시. 7,-7,가 글씨의 x,y좌표. 알아서 옮겨
plt.text(-20,2, text_3) #벡터 2--3 각도 표시. -20,2,가 글씨의 x,y좌표. 알아서 옮겨

x_1 = [a, e]
y_1 = [b, f]
x_2 = [c, e]
y_2 = [d, f]

plt.plot(x_1, y_1, 'k--', alpha = 0.7) # 합벡터에서 평햏사변형 점선 안 그리려면 이거 주석처리.
plt.plot(x_2, y_2, 'k--', alpha = 0.7) # 합벡터에서 평행사변형 점선 안 그리려면 이거도 주석처리.

major_ticks = np.arange(-100, 120, 20)
minor_ticks = np.arange(-100, 120, 5)

ax.set_xticks(major_ticks)
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(major_ticks)
ax.set_yticks(minor_ticks, minor=True)

ax.grid(which='both')

ax.grid(which='minor', alpha=0.2)
ax.grid(which='major', alpha=1)
ax.set_axisbelow(True)

plt.axis('equal')

plt.axis([xmin, xmax, ymin, ymax])

plt.gca().set_aspect("equal")

plt.legend(loc='upper left', fontsize= 8)

#plt.title('Run #1')

plt.show()

벡터그리는거 V3(결과주작용).py

벡터그리는거 V3(결과주작용).py


import os
import warnings

class FlowTestsBase(object):

    def _assert_equalish(self, a, b, e=0.05):
        delta = a * e
        diff = abs(a-b)
        if diff > delta:
            warnings.warn('runtimes differ by more than \"%f\" percent' % e)

    def _assert_only_expected_results_are_in_actual_results(self,
                                                           actual_result,
                                                           query_info):
        actual_result_set = []
        if actual_result.result_set is not None:
            actual_result_set = actual_result.result_set

        # Assert number of results.
        self.env.assertEqual(len(actual_result_set), len(query_info.expected_result))

        # Assert actual values vs expected values.
        for res in query_info.expected_result:
            self.env.assertIn(res, actual_result_set)

    def _assert_actual_results_contained_in_expected_results(self,
                                                             actual_result,
                                                             query_info,
                                                             num_contained_results):
        actual_result_set = actual_result.result_set

        # Assert num results.
        self.env.assertEqual(len(actual_result_set), num_contained_results)

        # Assert actual values vs expected values.
        expected_result = query_info.expected_result
        count = len([res for res in expected_result if res in actual_result_set])

        # Assert number of different results is as expected.
        self.env.assertEqual(count, num_contained_results)

    def _assert_resultset_and_expected_mutually_included(self, actual_result, query_info):
        actual_result_set = []
        if actual_result.result_set is not None:
            actual_result_set = actual_result.result_set

        # Assert number of results.
        self.env.assertEqual(len(actual_result_set), len(query_info.expected_result))

        # Assert actual values vs expected values.
        for res in query_info.expected_result:
            self.env.assertIn(res, actual_result_set)

        # Assert expected values vs actual values.
        for res in actual_result_set:
            self.env.assertIn(res, query_info.expected_result)

    def _assert_resultset_equals_expected(self, actual_result, query_info):
        actual_result_set = actual_result.result_set or []
        self.env.assertEqual(actual_result_set, query_info.expected_result)

    def _assert_run_time(self, actual_result, query_info):
            if actual_result.run_time_ms > query_info.max_run_time_ms:
                warnings.warn('Maximum runtime for query \"%s\" was: %s, but should be %s' %
                             (query_info.description, str(actual_result.run_time_ms), str(query_info.max_run_time_ms)))


#!/usr/bin/env python3

"""A script to enforce versioning requirements for python packages.

Parsing requirements.txt files for requirements is nontrivial, so we use the
python pip.req module to do it for us, then use this script to wrap around
that functionality.
"""
import glob
import sys
import pip.req
import traceback

# Scan all directories for files named requirements.txt
requirements_files = glob.glob('**/requirements.txt', recursive=True)

for req_file in requirements_files:
    try:
        for item in pip.req.parse_requirements(req_file, session="somesession"):
            if isinstance(item, pip.req.InstallRequirement):

                # To check whether or not we have versioning, we check if specifiers
                # exist for a given install requirement.
                if not item.specifier:
                    print('{} has no version specifiers.'.format(item))
                    sys.exit(1)
    except Exception as exc:
        print('Exception while trying to parse requirements file {}: {}'.format(
            req_file, exc))
        sys.exit(1)

sys.exit(0)


import requests
import json

def start_record(token):
    url = "https://apitesting.au.vbrickrev.com/api/v1/vc/start-recording"
    querystring = {"title": "Morning Call Recording", "sipAddress": "[insert sip address]"}
    headers = {
        'Authorization': "VBrick {}".format(token),
        'Content-Type': "application/json",
        'cache-control': "no-cache",
        'Postman-Token': "[insert token]"
    }
    response = requests.request("POST", url, headers=headers, params=querystring)
    print(response.text)
    return json.loads(response.text)["videoId"]


from key_value_pair_cache.client import client
import key_value_pair_cache.helper_functions.log_helper as log_helper
import configparser
import os
import sys
from collections import defaultdict
import marshal
import types
import re
from key_value_pair_cache.helper_functions.hash_fnv1a import fnv1a_32
import random
import urllib.request
import threading
import time
from reducer.word_count_reducer import word_count_reducer
from reducer.inverted_index_reducer import inverted_index_reducer
import subprocess

class reducer:
    config = configparser.ConfigParser()
    config.read('config.ini')
    LOG = log_helper._logger("map-reduce reducer")

    def send_reducer_output(self, reducer_output):
        try:
            self.LOG.log(50, 'Sending reducer out put for ' +
                         str(self.reducer_id)+" to key value store")
            msg_key = 'reducer_output' + str(self.reducer_id)
            for list_item in reducer_output:
                msg_val = str(list_item[0]+" "+str(list_item[1])+"\n")
                self.reducer_client.append_key(msg_key, msg_val)
            self.LOG.log(50, 'output for reducer ' +
                         str(self.reducer_id) + 'stored in key value store')
            return True
        except Exception as e:
            self.LOG.log(30, "Exception while running send_reducer_output")
            print(e, sys.exc_info())

    def run_serialized_reducer(self, input_list):
        try:
            self.LOG.log(
                50, 'Running supplied reducer on worker '+str(self.reducer_id))
            # with open(self.reducer_code_serialized, 'rb') as fd:
            #     code_string = fd.read()
            #     code = marshal.loads(code_string)
            #     user_defined_reduce_function = types.FunctionType(
            #         code, globals(), "user_defined_reducer_function"+str(self.reducer_id))
            if self.reducer_code_serialized == 'reducer/word_count_reducer_serialized':
                reducer_output = word_count_reducer(input_list)
            else:
                reducer_output = inverted_index_reducer(input_list)
            # reducer_output = user_defined_reduce_function(input_list)
            self.LOG.log(50, 'Reducer '+str(self.reducer_id) +
                         " has run reducer function")
            return reducer_output
        except Exception as e:
            self.LOG.log(30, "Exception while running run_serialized_reducer")
            print(e, sys.exc_info())

    def get_reducer_data(self):
        try:
            keys = self.reducer_client.get_keys("reducer"+str(self.reducer_id))
            data = ''
            for key in keys:
                data = self.reducer_client.get_key_lines(key)
                self.LOG.log(50, "reducer "+str(self.reducer_id) +
                             " received data "+str(len(data)))
                lines = data.split('\n')[1:]
                input_list = []
                # split from lines to list of tuples
                for line in lines:
                    words = line.split()
                    if len(words) == 2:
                        input_list.append((words[0], words[1]))
                self.LOG.log(50, "reducer "+str(self.reducer_id) +
                             " collected these keys data :"+str(len(input_list)))
                # runs serial reducer script
                reducer_output = self.run_serialized_reducer(input_list)
                self.send_reducer_output(reducer_output)
            if random.randrange(int(self.number_of_reducers)+1) == int(self.number_of_reducers) and self.test_reducer_fail == "True":
                self.LOG.log(30, "Creating an exception in reducer " +
                             str(self.reducer_id)+" for testing")
                raise Exception
            self.finished_checker = False
            self.reducer_client.set_key(
                'reducer_status'+str(self.reducer_id), 'finished')
            return True
        except Exception as e:
            self.LOG.log(30, "Exception while running get_reducer_data")
            print(e, sys.exc_info())
            self.LOG.log(50, "Reducer "+str(self.reducer_id)+" broke down")
            return False

    def get_reducer_id(self):
        # keys = self.reducer_client.get_keys('reducer_status')
        # for key in keys:
        #     val = self.reducer_client.get_key(key)
        #     if val.split(' \r\n')[1] == 'idle':
        #         id = val.split(' \r\n')[0].split()[1][len('reducer_status'):]
        req = urllib.request.Request(
            'http://metadata.google.internal/computeMetadata/v1/instance/hostname', headers={"Metadata-Flavor": "Google"})
        host_name = urllib.request.urlopen(req).read().decode().split('.')
        # host_name = ['reducer0', 'c', 'rishabh-gajra', 'internal']
        id = host_name[0][len('reducer'):]
        self.reducer_client.set_key(
            'reducer_status'+str(id), 'assigned')
        return int(id)

    def send_heartbeat(self):
        heart_beat_client = client(str(self.key_value_ip),
                                   int(self.config['app_config']['KeyValueServerPort']))
        while self.finished_checker:
            heart_beat_client.set_key(
                'reducer_status'+str(self.reducer_id), 'assigned')
            time.sleep(7)
        return True

    def reducer_clean_files(self):
        self.LOG.log(
            50, 'Cleaning previous files for reducer %d' % (self.reducer_id))
        msg_key = 'reducer_output' + str(self.reducer_id)
        self.reducer_client.clean_file_by_line(msg_key)
        return True

    def get_server_ip(self):
        output = subprocess.run(
            "gcloud compute instances describe key-value-server4 --zone=us-central1-a --format='get(networkInterfaces[0].accessConfigs[0].natIP)'", shell=True, check=True, stdout=subprocess.PIPE)
        ip = output.stdout.decode()[:-1]
        return ip

    def __init__(self, reducer_name, reducer_port):
        self.key_value_ip = str(self.get_server_ip())
        self.finished_checker = True
        self.reducer_port = reducer_port
        self.reducer_name = reducer_name
        self.reducer_client = client(str(self.key_value_ip),
                                     int(self.config['app_config']['KeyValueServerPort']))
        self.number_of_mappers = int(self.reducer_client.get_key(
            'NumberOfMappers').split(' ')[3])
        self.number_of_reducers = int(self.reducer_client.get_key(
            'NumberOfReducers').split(' ')[3])
        self.reducer_code_serialized = self.reducer_client.get_key(
            'ReducerCodeSerialized').split(' ')[3][2:]
        self.test_reducer_fail = self.reducer_client.get_key(
            'TestReducerFail').split(' ')[3][2:]
        self.reducer_id = self.get_reducer_id()
        self.LOG.log(50, "Booting up map-reduce reducer with id " +
                     str(self.reducer_id))
        heartbeat_thread = threading.Thread(
            target=self.send_heartbeat, args=(), daemon=True)
        heartbeat_thread.start()
        self.reducer_clean_files()
        self.LOG.log(50, 'reducer '+str(self.reducer_id)+" intialized")
        return


#Problem Link:- https://leetcode.com/problems/even-odd-tree/

"""A binary tree is named Even-Odd if it meets the following conditions:The root of the
binary tree is at level index 0, its children are at level index 1, their children are
at level index 2, etc.For every even-indexed level, all nodes at the level have odd integer
values in strictly increasing order (from left to right).For every odd-indexed level, all
nodes at the level have even integer values in strictly decreasing order (from left to
right).Given the root of a binary tree, return true if the binary tree is Even-Odd,
otherwise return false."""

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def isEvenOddTree(self, root: TreeNode) -> bool:
        if root is None:
            return
        que = [root]
        level = 0
        while que:
            count = len(que)
            if level % 2 == 0:
                prev = None
                for i in range(len(que)):
                    if que[i].val % 2 == 1 and prev == None:
                        prev = que[i].val
                    elif que[i].val % 2 == 1 and prev != None:
                        if que[i].val <= prev:
                            return False
                        else:
                            prev = que[i].val
                    else:
                        return False
            elif level % 2 == 1:
                prev = None
                for i in range(len(que)):
                    if que[i].val % 2  == 0 and prev == None:
                        prev = que[i].val
                    elif que[i].val % 2 == 0 and prev != None:
                        if que[i].val >= prev:
                            return False
                        else:
                            prev = que[i].val
                    else:
                        return False
            while count > 0:
                temp = que.pop(0)
                if temp.left:
                    que.append(temp.left)
                if temp.right:
                    que.append(temp.right)
                count -= 1
            level += 1
        return True


import json

class AppJSONDecoder(json.JSONDecoder):

    def __init__(self, file_name = None):
        json.JSONDecoder.__init__(self)
        self.FileName = file_name
        self.JSONData = {}

        try:
            f = open(self.FileName)
            self.JSONData = json.load(f)
        except:
            print("Failed to open %s for reading or JSON" % (self.FileName))
        return

    def GetDictionary(self, name = None):
        if (name == None) or name not in self.JSONData.keys():
            return
        else:
            return self.JSONData[name]

class AppJSONEncoder(json.JSONEncoder):
    def __init__(self):
        json.JSONEncoder.__init__(self)
        pass


from flask import Flask
from flask_restful import Api, Resource,reqparse,abort , fields,marshal_with
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
api = Api(app)

#configuration setting for db
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///database.db' #relative path
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class VideoModel(db.Model): #this is to craete instance of record that will be eventually inserted into a table.
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100),nullable=False) #maximum is 100
    views = db.Column(db.Integer,nullable=False)
    likes = db.Column(db.Integer, nullable=False)

    def __repr__(self):
        return f"Video(name)={self.name}, views={self.views},likes={self.likes}"

#to actually create DB
"""db.create_all()
"""
#we only create db once. So after creating db, you should comment this out. Otherwise, you will overwrite things

video_put_args = reqparse.RequestParser()
video_put_args.add_argument("name",type=str,help="Name of the video is required",required=True)
video_put_args.add_argument("views",type=int,help="Views of the video is required",required=True)
video_put_args.add_argument("likes",type=int,help="Likes on the video is required",required=True)

#If for some reason your data object doesn’t have an attribute in your fields list,
# you can specify a default value to return instead of None.
resource_fields = {
    "id" : fields.Integer,
    "name" : fields.String,
    "views" : fields.Integer,
    "likes" : fields.Integer
}
#what I'm doing here is ... making dictionary that defines the fields
#from the VideoModel class

class Video(Resource):
    #with marshal_with , when we return, take this return value and
    #serialize it using fields from resource_fields
    @marshal_with(resource_fields)
    def get(self,video_id):
        #gonna query database and return something that fits the query that we have.
        result = VideoModel.query.filter_by(id=video_id).first() #it can be all() as well.

        if not result:
            abort(404, message="Couldn't find video with that id")

        return result
        #this will be the result of __repr__

    @marshal_with(resource_fields)
    def put(self,video_id):
        args = video_put_args.parse_args()

        #check validity of the query(because we are not going to put in instance of which the key has been already inserted in db)
        query = VideoModel.query.filter_by(id=video_id).first()
        if query:
            abort(409,message ="Video_id(Primary key) has been already taken")

        #to create instance that will be put in the db
        video = VideoModel(id=video_id, name=args['name'], views=args['views'], likes=args['likes'])

        #to insert the instance to db
        db.session.add(video)

        #commit()
        db.session.commit()

        #to check if the data has been inserted into db,
        return video,201

    # def delete(self,video_id):
    #     abort_if_video_id_doesnt_exist(video_id)
    #     #in case you get a request for deleting stuff,
    #     del videos[video_id]
    #     return "",204

api.add_resource(Video,"/video/<int:video_id>")

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