#!/usr/bin/env python

import logging
import types
from logging import Logger

LEVELS = { "debug" : logging.DEBUG,
           "info" : logging.INFO,
           "warning" : logging.WARNING,
           "error" : logging.ERROR,
           "critical" : logging.CRITICAL
       }

DEFAULT_LEVEL = logging.ERROR
MSG_FORMAT = "%(levelname)s:%(funcName)s: %(message)s"

class Singleton(type):
    def __init__(cls, name, bases, dict_):
        super(Singleton, cls).__init__(name, bases, dict_)
        cls.instance = None

    def __call__(cls, *args, **kw):
        if cls.instance is None:
            cls.instance = super(Singleton, cls).__call__(*args, **kw)
        return cls.instance

class RavelLogger(Logger, object):
    __metaclass__ = Singleton

    def __init__(self):
        Logger.__init__(self, "ravel")
        ch = logging.StreamHandler()
        formatter = logging.Formatter(MSG_FORMAT)
        ch.setFormatter(formatter)
        self.addHandler(ch)
        self.setLogLevel()

    def setLogLevel(self, levelname=None):
        level = DEFAULT_LEVEL
        if levelname is not None:
            if levelname not in LEVELS:
                raise Exception("Unknown log level {0}".format(levelname))
            else:
                level = LEVELS.get(levelname, level)

        self.setLevel(level)

logger = RavelLogger()


from typing import Set
from datetime import datetime
import re

from sqlalchemy import String
from sqlalchemy import ForeignKey, PrimaryKeyConstraint
from sqlalchemy import UniqueConstraint
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import relationship

__all__ = ["Base", "Tag", "Autoresponse"]

import sqlalchemy.types as types

class Regex(types.TypeDecorator):
    """Prefixes Unicode values with "PREFIX:" on the way in and
    strips it off on the way out.
    """

    impl = types.String

    cache_ok = True

    def process_bind_param(self, value: str, dialect) -> re.Pattern:
        return re.compile(pattern=value)

    def process_result_value(self, value: re.Pattern, dialect) -> str:
        return value.pattern

    def copy(self, **kw):
        return Regex(self.impl.length)  # type: ignore

class Base(DeclarativeBase):
    pass

class Tag(Base):
    __tablename__ = "tag"

    name: Mapped[str] = mapped_column(String(100))
    server_id: Mapped[int] = mapped_column(index=True)
    author_id: Mapped[int] = mapped_column()
    content: Mapped[str] = mapped_column(String(2000))

    time_created: Mapped[datetime] = mapped_column(default=datetime.now())
    time_updated: Mapped[datetime] = mapped_column(
        default=datetime.now(), onupdate=datetime.now()
    )

    UniqueConstraint(server_id, name)
    PrimaryKeyConstraint(server_id, name)

    autoresponses: Mapped[Set["Autoresponse"]] = relationship(
        back_populates="tag",
        primaryjoin="and_(Tag.name==foreign(Autoresponse.tag_name), "
        "Tag.server_id==foreign(Autoresponse.server_id))",
    )

    def __repr__(self) -> str:
        return f"Tag(name={self.name!r}, server_id={self.server_id!r}, author_id={self.author_id!r})"

class Autoresponse(Base):
    __tablename__ = "autoresponse"

    autoresponse_name: Mapped[str] = mapped_column(String(100), primary_key=True)
    server_id: Mapped[int] = mapped_column(
        ForeignKey("tag.server_id"), primary_key=True
    )
    tag_name: Mapped[str] = mapped_column(ForeignKey("tag.name"), primary_key=True)

    regex: Mapped[re.Pattern] = mapped_column(Regex(4000))
    author_id: Mapped[int] = mapped_column()

    tag: Mapped["Tag"] = relationship("Tag", back_populates="autoresponses",
        primaryjoin="and_(Tag.name==foreign(Autoresponse.tag_name), "
        "Tag.server_id==foreign(Autoresponse.server_id))",)

    def __repr__(self) -> str:
        return f"Autoresponse(tag={self.tag.name if self.tag else None!r}, server_id={self.server_id!r}, author_id={self.author_id!r})"


class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        count_zero = nums.count(0)
        idx = 0
        while idx < len(nums)-count_zero:
            if nums[idx] == 0:
                nums.pop(idx)
                nums.append(0)
            else:
                idx += 1


import logging
import smtplib
import time
from abc import ABC
from abc import abstractmethod
from email.mime.text import MIMEText
from functools import reduce
from typing import List

from vdk.internal.builtin_plugins.notification.notification_configuration import (
    SmtpConfiguration,
)
from vdk.internal.core import errors

log = logging.getLogger(__name__)

class LoggingSMTP(smtplib.SMTP):
    """
    Subclass to replace the print statements with logging statements so that debug output can be captured
    """

    def _print_debug(self, *args):
        message = reduce((lambda msg1, msg2: str(msg1) + str(msg2)), iter(args))
        log.debug(message)

class INotification(ABC):
    @abstractmethod
    def notify(self, title, body):
        """
        Sends a message to recipients using a predefined channel.
        Both the receivers and the channel are specified in config.ini.
        :param title: message title
        :param body: message content
        """
        pass

class EmailNotification(INotification):
    def __init__(
        self,
        recipients: List[str],
        cc: List[str],
        smtp_cfg: SmtpConfiguration,
        sender: str,
    ):
        """
        :param recipients: list of emails
        :param sender: sender email
        :param cc: list of emails
        """
        log.debug(
            f"New EmailNotification prepared: sender: {sender}; cc: {cc}; recipeints: {recipients}"
        )
        self._sender = sender
        self._cc = [] if cc is None else cc
        self._smtp_cfg = smtp_cfg
        self._recipients = recipients

    def notify(self, subject, body):
        """
        Sends an email to the specified recipients. If there are no valid recipient addresses, it sends the email
        to the CC'd addresses, assuming at least one of them is valid. If none of them are, an appropriate error is
        logged, and no email is sent.

        :param subject: The subject of the email
        :param body: The email job
        """
        valid_recipients = ",".join(self._get_valid_recipients())
        if valid_recipients:
            email_message = self._build_message(subject, body, valid_recipients)
            self._send_message(email_message)
        else:
            valid_cc = ",".join(self._get_valid_cc())
            if valid_cc:
                logging.getLogger(__name__).warning(
                    "No valid recipient address is given"
                )
                email_message = self._build_message(
                    subject,
                    (
                        "This message is sent to the list of CC'd addresses "
                        "because none of the listed recipient addresses are valid, or none were provided.\n\n"
                    )
                    + body,
                    valid_cc,
                )
                self._send_message(email_message)
            elif (not valid_cc) and self._cc:
                logging.getLogger(__name__).warning(
                    "No valid recipients or CC addresses given"
                )
            else:
                logging.getLogger(__name__).debug("Empty list of recipients is given")

    def _send_message(self, msg):
        log.debug(f"Send message {msg}")
        s = self.__smtp_server()
        s.send_message(msg)
        s.quit()

    def _build_message(self, subject, body, recipients):
        msg = MIMEText(body, "html")
        msg["Subject"] = subject
        msg["From"] = self._sender
        msg["To"] = recipients
        msg["Cc"] = ",".join(self._get_valid_cc())
        return msg

    def _email_address_exists(self, email_address):
        """
        Checks if a particular email address is valid or not. The reason for this is that if an attempt to send
        an email to a non-valid address is made, that attempt will fail and no email will be sent to any of the
        specified addresses, regardless is any of the rest were valid or not.

        :param email_address: The email address in string form
        :return: a boolean specifying if the address is valid or not
        """
        s = self.__smtp_server()
        try:
            s.helo()
            s.mail(self._sender)
            resp = s.rcpt(email_address)
            return resp[0] == 250
        except smtplib.SMTPServerDisconnected as e:
            log.warning(
                "SMTP connection error while checking if email address exists: %s", e
            )
            return True
        finally:
            s.quit()

    def __smtp_server(self):
        s = LoggingSMTP(self._smtp_cfg.get_host(), port=self._smtp_cfg.get_port())
        if self._smtp_cfg.get_use_tls():
            s.starttls()
        if self._smtp_cfg.get_login_username():
            s.login(
                self._smtp_cfg.get_login_username(), self._smtp_cfg.get_login_password()
            )
        s.set_debuglevel(self._smtp_cfg.get_debug_level())
        return s

    def _get_valid_recipients(self):
        return [x.strip() for x in self._recipients if self._email_address_exists(x)]

    def _get_valid_cc(self):
        return [x.strip() for x in self._cc if self._email_address_exists(x)]

class EmailNotificationMessageBuilder(ABC):
    def __init__(self, job_name, job_log_url_template):
        self._job_name = job_name

        self.JOB_LOG_URL_TEMPLATE = job_log_url_template

        self.NOTIFICATION_MSG_TEMPLATE = """
Dear Versatile Data Kit user,

   Last {exec_type} of your data job {job_name} has {result}.

   {result_msg}

The sender mailbox is not monitored, please do not reply to this email.

Best,
Versatile Data Kit team
"""

        self.USER_ERROR_TEMPLATE = """
Details:

{error_msg}

{job_log_link}

For more information please visit the user wiki.
"""

        self.INFRA_ERROR_MSG = """
Details:

{error_msg}
"""

        self.NOTIFICATION_MSG_SUBJECT_TEMPLATE = (
            "[{result}][data job {exec_type}] {job_name}"
        )

    @abstractmethod
    def build(self, exec_type, msg, op_id):
        """
        Builds a (subject, body) tuple to be used as input for EmailNotification.notify
        :param op_id: execution id of the data job
        :param msg: string to be included into the message template
        :param exec_type: 'run' or 'deploy'
        :return: (subject, body) tuple
        """
        pass

    def _get_job_log_url(self, op_id):
        now = int(round(time.time() * 1000))
        hour = 60 * 60 * 1000
        start_time_ms = now - 24 * hour
        end_time_ms = now + hour
        return self.JOB_LOG_URL_TEMPLATE.format(
            op_id=op_id, start_time_ms=start_time_ms, end_time_ms=end_time_ms
        )

    def _get_job_log_chunk(self, op_id):
        return (
            '
You can find full logs of the job execution  here .
'.format(
                self._get_job_log_url(op_id.strip())
            )
            if op_id
            else ""
        )

    def _get_subject(self, result, exec_type):
        return self.NOTIFICATION_MSG_SUBJECT_TEMPLATE.format(
            result=result, exec_type=exec_type, job_name=self._job_name
        )

class UserErrorEmailNotificationMessageBuilder(EmailNotificationMessageBuilder):
    def build(self, exec_type, msg="", op_id=""):
        user_error = self.USER_ERROR_TEMPLATE.format(
            error_msg=msg, job_log_link=self._get_job_log_chunk(op_id)
        )
        subject = self._get_subject("user error", exec_type)
        html_body = self.NOTIFICATION_MSG_TEMPLATE.format(
            exec_type=exec_type,
            job_name=self._job_name,
            result="failed",
            result_msg=user_error,
        )
        return subject, html_body

class InfraErrorEmailNotificationMessageBuilder(EmailNotificationMessageBuilder):
    def build(self, exec_type, msg="", op_id=""):
        if exec_type == "deploy":
            error_msg = errors.ErrorMessage(
                "There has been a platform error. The error will be resolved by the Versatile Data Kit team. "
                "Here are the details:",
                "Last deploy of your data job has failed",
                "There has been a platform error.",
                "Your new/updated job was not deployed. Your job will run its latest "
                "successfully deployed version (if any) as scheduled.",
                "The Versatile Data Kit team is working on the issue and will redeploy your job.",
            ).to_html()
        elif exec_type == "run":
            error_msg = errors.ErrorMessage(
                "There has been a platform error. The error will be resolved by the Versatile Data Kit team. "
                "Here are the details:",
                "Last run of your data job has failed",
                "There has been a platform error.",
                "Job will be restarted automatically on failure up to 3 times.",
                "No customer action is required. If the 3 restarts fail, Versatile Data Kit team will investigate the "
                "error and ensure job will continue to run as expected. If you want to receive notification on "
                "successful job execution, you can set it up in config.ini",
            ).to_html()
        else:
            logging.getLogger(__name__).warning(
                "Unknown exec_type [{}]".format(
                    exec_type if exec_type is not None else "None"
                )
            )
            exec_type = ""
            error_msg = "There has been a platform error. The error will be resolved by the Versatile Data Kit team."

        subject = self._get_subject("platform error", exec_type)
        html_body = self.NOTIFICATION_MSG_TEMPLATE.format(
            exec_type=exec_type,
            job_name=self._job_name,
            result="failed",
            result_msg=self.INFRA_ERROR_MSG.format(error_msg=error_msg),
        )
        return subject, html_body

class SuccessEmailNotificationMessageBuilder(EmailNotificationMessageBuilder):
    def build(self, exec_type, msg="", op_id=""):
        additional_info = self._get_job_log_chunk(op_id)
        subject = self._get_subject("success", exec_type)
        html_body = self.NOTIFICATION_MSG_TEMPLATE.format(
            exec_type=exec_type,
            job_name=self._job_name,
            result="succeeded",
            result_msg=additional_info,
        )
        return subject, html_body


import locale
from tkinter import font as tk_font

import PySimpleGUI as sg
from tracking.tracker import TrackerState

from . import popup
from .events import Events, Keys
from .localization import TXT
from .theme import TH
from .tracker_widget import TrackerWidget

# locale parser info for printing date
locale.setlocale(locale.LC_TIME, TXT.locale_setting)  # date in correct language

class TrackerWidgetsHandler:
    def __init__(self, window, trackers, splash):
        self.widgets = []
        self.trackers = trackers

        self.widgets_frame = window[Keys.all_tracker_widgets]
        self.old_trackers = window[Keys.old_tracker_widgets]
        self.new_trackers = window[Keys.new_tracker_widgets]
        self.widget_menu = window[Keys.menu]
        self.archives_button = window[Events.archives]
        self.refresh_button = window[Events.refresh]
        self.deleted_button = window[Events.trash]
        self.its_empty = window[Keys.its_empty]

        self.archives_updated()
        self.deleted_updated()

        n_trackers = len(trackers.trackers)
        for i, tracker in enumerate(trackers.trackers):
            splash.update(f"{TXT.tracker_creation} {i + 1}/{n_trackers}")
            self._create_widget(window, tracker, new=False)

        self.update_window_size(window)
        self.recenter(window, True)

    def _create_widget(self, window, tracker, new=False):
        widget = TrackerWidget(tracker)
        self.widgets.append(widget)

        where = self.new_trackers if new else self.old_trackers
        window.extend_layout(where, widget.create_layout())

        # finalize only shown trackers to speed up startup
        if widget.tracker.state == TrackerState.shown:
            widget.finalize(window)
            widget.update(window)

    def new(self, window):
        popup_edit = popup.Edit(
            TXT.new, "", TXT.new, [], self.trackers.couriers_handler, window
        )
        ok, *tracker_params = popup_edit.loop()
        if ok:
            tracker = self.trackers.new(*tracker_params)
            self._create_widget(window, tracker, new=True)

    def _get_widgets_with_state(self, state):
        return [widget for widget in self.widgets if widget.tracker.state == state]

    def _get_sorted(self, widgets):
        return self.trackers.sort(widgets, get_tracker=lambda widget: widget.tracker)

    def _choose(self, window, title, state, ok_name, added_button=None):
        widgets = self._get_sorted(self._get_widgets_with_state(state))
        w_desc = (
            max(len(widget.get_description()) for widget in widgets) if widgets else 0
        )
        w_date = (
            max(len(widget.get_creation_date()) for widget in widgets) if widgets else 0
        )

        choices = []
        for widget in widgets:
            color = TH.ok_color if widget.get_delivered() else TH.warn_color
            date = f"{widget.get_creation_date()},".ljust(w_date + 1)
            txt = f"{date} {widget.get_description().ljust(w_desc)} - {widget.get_idship()}"
            choices.append((txt, color))

        popup_choices = popup.Choices(choices, title, window, ok_name, added_button)
        exit_result, chosen = popup_choices.loop()
        return exit_result, [widgets[i] for i in chosen]

    def show_archives(self, window):
        exit_result, chosen = self._choose(
            window, TXT.unarchive, TrackerState.archived, ok_name=TXT.unarchive
        )
        if exit_result:
            for widget in chosen:
                widget.unarchive(window)

    def show_deleted(self, window):
        def_delete_button_key = "-definitly delete-"
        def_delete_button = dict(
            txt=TXT.delete_definitly,
            mouse_over_color=TH.warn_color,
            key=def_delete_button_key,
        )
        exit_result, chosen = self._choose(
            window,
            TXT.restore,
            TrackerState.deleted,
            ok_name=TXT.restore,
            added_button=def_delete_button,
        )
        if exit_result == def_delete_button_key and chosen:
            w_desc = max(len(widget.get_description()) for widget in chosen)
            txt = "\n".join(
                f"{widget.get_description().ljust(w_desc)} - {widget.get_idship()}"
                for widget in chosen
            )
            popup_warn = popup.AskConfirmation(
                TXT.delete_definitly,
                txt,
                window,
            )
            definitly_delete = popup_warn.loop()
            if definitly_delete:
                for widget in chosen:
                    widget.definitly_delete(window)

        else:
            for widget in chosen:
                widget.undelete(window)

    def archives_updated(self):
        n_archives = self.trackers.count_state(TrackerState.archived)
        color = TH.archives_color if n_archives else TH.archives_color_empty
        self.archives_button.update(
            f"{TXT.archives}({n_archives})", button_color=(color, None)
        )

    def deleted_updated(self):
        n_deleted = self.trackers.count_state(TrackerState.deleted)
        color = TH.trash_color if n_deleted else TH.trash_color_empty
        self.deleted_button.update(
            f"{TXT.trash}({n_deleted})", button_color=(color, None)
        )

    def update(self, window):
        for widget in self._get_widgets_with_state(TrackerState.shown):
            widget.update(window)

    def _count_has_something_to_update(self):
        shown = self._get_widgets_with_state(TrackerState.shown)
        return [widget.has_something_to_update for widget in shown].count(True)

    def updating_changed(self):
        n_has_something_to_update = self._count_has_something_to_update()
        self.refresh_button.update(disabled=n_has_something_to_update == 0)

    def _set_min_width(self, min_width):
        for widget in self._get_widgets_with_state(TrackerState.shown):
            widget.set_min_width(min_width)

    def update_window_size(self, window):
        shown = self._get_widgets_with_state(TrackerState.shown)

        # needed to get the actual sizes
        window.refresh()  # or visibility_changed() that produces different glitches

        self.widgets_frame.contents_changed()
        self.its_empty.update(visible=not shown)

        menu_w = self.widget_menu.Widget.winfo_reqwidth()
        menu_h = self.widget_menu.Widget.winfo_reqheight()
        self._set_min_width(menu_w)

        # wanted size
        scrollbar = self.widgets_frame.vsb
        if shown:
            w = max(widget.get_pixel_width() for widget in shown)
            h = sum(widget.get_pixel_height() for widget in self.widgets) + menu_h + 5

            # need a scrollbar ?
            screen_w, screen_h = window.get_screen_size()
            max_h = screen_h - TH.window_height_screen_margin

            if h > max_h:
                scrollbar.pack(side=sg.tk.RIGHT, fill="y")
                w += scrollbar.winfo_width()

            else:
                scrollbar.pack_forget()

            window.size = min(w, screen_w), min(h, max_h)
            self.recenter(window)

        else:
            scrollbar.pack_forget()

            # needed to set height because the scrollbar missing prevents the right height computation in pySimpleGUI
            window.size = (
                menu_w,
                menu_h
                + self.its_empty.Widget.winfo_reqheight()
                + self.its_empty.Pad[1] * 2,
            )

            # add spaces in its_empty to fit w
            wfont = tk_font.Font(self.its_empty.ParentForm.TKroot, self.its_empty.Font)
            n_spaces = round(menu_w / wfont.measure(" "))
            self.its_empty.update(TXT.empty.center(n_spaces))

    @staticmethod
    def recenter(window, force=False):
        W, H = window.get_screen_size()
        w, h = window.size
        x, y = window.current_location()
        if force:
            x = max(0, int((W - w) * 0.5))
            y = max(0, int((H - h) * 0.5))
        else:
            y = max(0, int((H - h) * 0.5)) if y + h > H else y
        window.move(x, y)


import gradio as gr
import glob
import torch
from transformers import VisionEncoderDecoderModel
from transformers import TrOCRProcessor
import uuid

model_path = "models/20231014-18-19"

processor = TrOCRProcessor.from_pretrained("microsoft/trocr-small-printed")
model = VisionEncoderDecoderModel.from_pretrained(model_path)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)

def process_image(image):
    pixel_values = processor(image, return_tensors="pt").pixel_values.to(device)
    generated_ids = model.generate(pixel_values)
    text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
    image.save(f"data/{str(uuid.uuid4())}_{text}.png")
    return text.split("_")[0]

demo = gr.Interface(
    fn=process_image,
    inputs=gr.inputs.Image(type="pil"),
    outputs="text",
    examples=list(glob.glob("examples/*.png")),
)

demo.launch(share=True)


class Animal():
    def __init__(self, w, a, name):
        self.weight = w
        self.age = a
        self.name = name

    def h():
        print('hello')

ki = Animal(50, 5, 'koko')
print(ki.age)
fi = Animal(70, 10, 'lulu')
print(fi.name)
# def fi.h(): # Можно ли переопределить метод класса для объекта?


def birthday(s, d, m):
    res = 0
    for i in range(len(s) - m + 1):
        som = 0
        for j in range(m):
            som += s[i + j]
        if som == d:
            res += 1
    return res

if __name__ == '__main__':
    n = int(input().strip())

    s = list(map(int, input().rstrip().split()))

    dm = input().rstrip().split()

    d = int(dm[0])

    m = int(dm[1])

    result = birthday(s, d, m)

    print(str(result) + '\n')


# -*- coding: utf-8 -*-
"""
Created on Wed May 10 18:50:46 2023

@author: mattw
"""
import light
import camera
import glm
class Scene:
    '''
    Class the manages all the objects in the scene.
    ----------
    ctx : ModerGl.Context
        The current context.
    win_size : list
        The window size
    meshes : list of Mesh
        The list of the all the meshes to be rendered.
    skybox : Skybox
        The skybox object to render
    camera : Camera
        The camera in the scene.
    backround color : list
        The color of the backround.

    '''

    def __init__(self, ctx, win_size, backround_color = [.2, .2, .2]):
        self.ctx = ctx
        self.win_size = win_size # Probably want to refactor remove this as an attribute.
        self.meshes = [] # Add two lists, one render mesh, another non-render mesh list so spawning objects can be added.
        self.skybox = None
        self.camera = camera.Camera(ctx, win_size, [0, 0, 0])
        self.backround_color =  backround_color #RGB

    def add_skybox(self, skybox):
        """
        Method that adds the skybox to the scene.

        Parameters
        ----------
        skybox : Skybox
            SkyBox object to add to the scene.

        Returns
        -------
        None.

        """
        self.skybox = skybox
        skybox.program['proj_mat'].write(self.camera.get_proj_mat())

    def add_mesh_arr(self, mesh_arr):
        """
        Method that appends an array of meshes to the meshes property.

        Parameters
        ----------
        mesh_arr : list of Mesh
            The list of meshes to add.

        Returns
        -------
        None.

        """
        for mesh in mesh_arr:
            mesh.program['proj_mat'].write(self.camera.get_proj_mat())
            self.meshes.append(mesh)

    def add_light(self, light_pos, light_color):
        """
        Method to add a light to the scene.

        Parameters
        ----------
        light_pos : list
            The postion of the light in world space.
        light_color : list
            The color of the light.

        Returns
        -------
        None.

        """
        self.light = light.Light(light_pos, light_color)

    def update_camera_specs(self, in_pos, fov=60.0, near=.1, far=100.0, yaw=-90, pitch=0):
        """
        Method that updates the camera.

        Parameters
        ----------
        in_pos : list
            The initail positon of the camera.
        fov : float, optional
            The field of view of the camera. The default is 60.0.
        near : float, optional
            The near clipping plane of the camera The default is .1.
        far : float, optional
            The far clipping plane of the camera. The default is 100.0.
        yaw : float, optional
            The yaw angle of the camera. The default is -90.
        pitch : flaot, optional
            The pitch angle of the camera. The default is 0.

        Returns
        -------
        None.

        """
        mounted_idx = self.camera.mounted_phobject_index
        self.camera = camera.Camera(self.ctx, self.win_size, in_pos, fov=fov,
                                    near=near, far=far, yaw=yaw, pitch=pitch)
        self.camera.mounted_phobject_index = mounted_idx

        if len(self.meshes) != 0:
            for mesh in self.meshes:
                mesh.program['proj_mat'].write(self.camera.get_proj_mat())

        self.skybox.program['proj_mat'].write(self.camera.get_proj_mat())

    def destroy(self):
        """
        Garbage collection

        Returns
        -------
        None.

        """
        [mesh.destroy() for mesh in self.meshes]

    def render(self, dt, phobject_mat):
        """
        Renders the meshes, light, and skybox in the scene

        Parameters
        ----------
        dt : float
            Change in time from last frame.
        phobject_mat : ndarray
            The portion of the phobject matrix that holds the phobject info.

        Returns
        -------
        None.

        """

        self.camera.update(dt, phobject_mat)

        # Changing the postion of the light to the suns.
        self.light.pos = phobject_mat[0, 0:3]

        ### Probably one of the largest bottlenecks, if someone finds a way to run the shaders
        ### without using a python loop then the number of renderable objects will increase.
        for i, mesh in enumerate(self.meshes):

            mesh.update_mesh_state(phobject_mat[i, :3])
            mesh.program['view_mat'].write(self.camera.get_view_mat())

            # The Sun shader does not use these, so this is my dirty solution (I am sorry)
            if i > 0:
                mesh.program['camera_position'].write(self.camera.position)

                mesh.program['light_position'].value = glm.vec3(self.light.pos)
                mesh.program['light_color'].value = glm.vec3(self.light.color)
            mesh.render()

            if self.skybox:
                self.skybox.program['view_mat'].write(glm.mat4(glm.mat3(self.camera.get_view_mat())))
                self.skybox.render()


# Importing Stuff
import pygame
import math
from queue import PriorityQueue

# Pygame window
WIDTH = 700
ROWS = 40
WIN = pygame.display.set_mode((WIDTH-WIDTH//ROWS, WIDTH-WIDTH//ROWS))
pygame.display.set_caption("A* Path Finding Algorithm")

# Colors
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
GREY = (168, 159, 158)
RED = (255, 0, 0)
BLUE = (50, 119, 168)
ORANGE = (245, 185, 66)
PURPLE = (87, 76, 245)
TURQUOISE = (76, 217, 245)

# Frame
frame = 60
clock = pygame.time.Clock()

# Class which takes care of each node
class Node:
    # taking args
    def __init__(self, row, col, width, total_rows):
        self.row = row
        self.col = col
        self.x = row * width
        self.y = col * width
        self.color = WHITE
        self.neighbours = []
        self.width = width
        self.total_rows = total_rows

    # the current position of the node
    def get_pos(self):
        return self.row, self.col

    # check if node is closed (already looked through)
    def is_closed(self):
        return self.color == RED

    # checking if node is open (we can still check)
    def is_open(self):
        return self.color == GREEN

    # checking if the node is a barrier
    def is_barrier(self):
        return self.color == BLACK

    # checking if the node is the start node
    def is_start(self):
        return self.color == ORANGE

    # checking if node is the end node
    def is_end(self):
        return self.color == TURQUOISE

    # changing node to white (default color)
    def reset(self):
        self.color = WHITE

    # making the current node closed (already looked through)
    def make_closed(self):
        self.color = RED

    # making the node a barrier (black node)
    def make_barrier(self):
        self.color = BLACK

    # making the node the start node
    def make_start(self):
        self.color = ORANGE

    def make_open(self):
        self.color = GREEN

    # def making the node the end node
    def make_end(self):
        self.color = TURQUOISE

    # making the node to a color of the path
    def make_path(self):
        self.color = PURPLE

    # to draw rectangle on the screen
    def draw(self, win):
        pygame.draw.rect(
            win, self.color, (self.x, self.y, self.width, self.width))

    # These are all the neighbours of the current node

    def update_neighbours(self, grid):
        self.neighbours = []
        # Down
        if self.row < self.total_rows - 1 and not grid[self.row + 1][self.col].is_barrier():
            self.neighbours.append(grid[self.row + 1][self.col])

        # Up
        if self.row > 0 and not grid[self.row - 1][self.col].is_barrier():
            self.neighbours.append(grid[self.row - 1][self.col])

        # Right
        if self.col < self.total_rows - 1 and not grid[self.row][self.col+1].is_barrier():
            self.neighbours.append(grid[self.row][self.col+1])

        # Left
        if self.row > 0 and not grid[self.row][self.col-1].is_barrier():
            self.neighbours.append(grid[self.row][self.col-1])

    def __lt__(self, other):
        return False

# Estimated distance between two nodes (Manhattan distance)
def h(p1, p2):
    x1, y1 = p1
    x2, y2 = p2

    return abs(x1 - x2) + abs(y1-y2)

# Draws the path between the start point and end point
def reconstruct_path(came_from, current, start, draw):
    while current in came_from:
        current = came_from[current]
        current.make_path()
        draw()

    start.make_start()

def algorithm(draw, grid, start, end):
    # var to keep count of queue
    count = 0
    print(count)
    open_set = PriorityQueue()
    open_set.put((0, count, start))

    came_from = {}
    g_score = {node: float("inf") for row in grid for node in row}
    g_score[start] = 0

    f_score = {node: float("inf") for row in grid for node in row}
    f_score[start] = h(start.get_pos(), end.get_pos())

    open_set_hash = {start}
    # print(open_set_hash)

    # looping runnning untlt the priorityqueue is empty
    while not open_set.empty():
        # option to quit
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

        current = open_set.get()[2]
        # print(current.row, current.col)
        open_set_hash.remove(current)

        # Found the path
        if current == end:
            end.make_end()
            start.make_start()
            reconstruct_path(came_from, end, start, draw)
            return True

        for neighbour in current.neighbours:

            temp_g_score = g_score[current] + 1

            if temp_g_score < g_score[neighbour]:
                came_from[neighbour] = current
                g_score[neighbour] = temp_g_score
                f_score[neighbour] = temp_g_score + \
                    h(neighbour.get_pos(), end.get_pos())

                if neighbour not in open_set_hash:
                    count += 1
                    open_set.put((f_score[neighbour], count, neighbour))
                    open_set_hash.add(neighbour)
                    neighbour.make_open()

        draw()

        if current != start:
            current.make_closed()

    return False

# making the grid
def make_grid(rows, width):
    grid = []
    gap = width // rows

    for i in range(rows):
        grid.append([])
        for j in range(rows):
            node = Node(i, j, gap, rows)
            grid[i].append(node)

    return grid

# drawing the grid
def draw_grid(win, rows, width):
    # width of each node
    gap = width // rows
    for i in range(rows):
        # for vertical lines
        pygame.draw.line(win, GREY, (0, i*gap), (width, i*gap))
        # for horizontal lines
        for j in range(rows):
            pygame.draw.line(win, GREY, (j*gap, 0), (j*gap, width))

# draws all the stuff on the screen
def draw(win, grid, rows, width):
    # refilling white color on screen every frame
    win.fill(WHITE)

    # drawing each node
    for row in grid:
        for node in row:
            node.draw(win)

    draw_grid(win, rows, width)
    clock.tick(frame)
    pygame.display.update()

# getting the position
def get_clicked_pos(pos, rows, width):
    gap = width // rows
    y, x = pos

    row = y // gap
    col = x // gap

    return row, col

# main loop
def main(win, width):
    grid = make_grid(ROWS, width)

    start = None
    end = None

    run = True

    while run:
        draw(win, grid, ROWS, width)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

            if pygame.mouse.get_pressed()[0]:
                pos = pygame.mouse.get_pos()
                row, col = get_clicked_pos(pos, ROWS, width)
                node = grid[row][col]

                if not start and node != end:
                    start = node
                    start.make_start()

                elif not end and node != start:
                    end = node
                    end.make_end()

                elif node != end and node != start:
                    node.make_barrier()

            elif pygame.mouse.get_pressed()[2]:
                pos = pygame.mouse.get_pos()
                row, col = get_clicked_pos(pos, ROWS, width)
                node = grid[row][col]

                node.reset()
                if node == start:
                    start = None
                elif node == end:
                    end = None

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE and start and end:
                    for row in grid:
                        for node in row:
                            node.update_neighbours(grid)

                    algorithm(lambda: draw(win, grid, ROWS, width),
                              grid, start, end)

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    start = end = None
                    grid = make_grid(ROWS, width)

    pygame.quit()

main(WIN, WIDTH)


from random import randint
def cheese_and_crackers(cheese_count, boxes_of_crackers): #defines the function cheese_and_crackers with the cheese_count and boxes_of_crackers as arguments
    print("You have %d cheeses!" % cheese_count) #prints a string that gives us the number of cheese
    print("You have %d boxes of crackers" % boxes_of_crackers) #prints a string that gives us the number of crackers
    print("Man that's enough for a party!") #just prints a string
    print("Get a blanket. \n")#just prints a string and makes a new line

print("We can just give the function numbers directly") #prints a string
cheese_and_crackers(20,30) #runs the function cheese_and crackers with 20 as the cheese_count arguments and 30 as the boxes_of crackers argument

print("OR, we can use variables from our script") #prints a string
amount_of_cheese = 10 #creates a variable that stores an int 10
amount_of_crackers = 50#creates a variable that stores an int 10

#runs the function cheese_and crackers with the variableas amount_of cheese as the cheese_count argument and amount_of_crackers as the boxes_of crackers argument
cheese_and_crackers(amount_of_cheese, amount_of_crackers)

print("We can even do math inside too:") # prints a string
cheese_and_crackers(10+20, 5+6) #runs the function cheese_and crackers with 20+10 as the cheese_count arguments and 5+6 as the boxes_of crackers argument

print("And we can combine the two, variables and math:") # prints a string
#runs the function cheese_and_crackers with amount_of_cheese + 100 as the cheese_count arguments and amount_of_crackers + 1000 as the boxes_of crackers argument
cheese_and_crackers(amount_of_cheese+ 100, amount_of_crackers + 1000)

def pastaAndSauce(pastaAmount, sauceAmount):
    print("you have %d grams of pasta" % pastaAmount)
    print("you have %d liters of sauce" % sauceAmount)
    print("That's a ton of sauce or pasta i don't know xDD")

pastaAndSauce(1000, 1)
Pasta_count = 500
Sauce_count = 0.5

pastaAndSauce(Pasta_count, Sauce_count)
pastaAndSauce(50 + 10, 0.1 + 0.2)
pastaAndSauce(Pasta_count+ 10, Sauce_count + 5)
Pasta = int(input("Grams of pasta: "))
Sauce = int(input("Liters of sauce: "))
pastaAndSauce(Pasta_count + Pasta, Sauce_count + Sauce)
pastaAndSauce(Pasta + 10, Sauce + 1)
pastaAndSauce(Pasta * 2, Sauce * 2)
pastaAndSauce(Pasta_count * 2, Sauce_count * 2)
pastaAndSauce(randint(1, 10000), randint(1, 100))
pastaAndSauce(randint(1, 100) + 100, randint(1, 10) + 50)
pastaAndSauce(randint(1,100) + Pasta, randint(1,10) + Sauce)


from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from userapp.models import Userextension
from .models import Dishes
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .serializers import DishListSerializer
from rest_framework.response import Response
from rest_framework.decorators import api_view
# Create your views here.

@login_required
def select_restaurant(request):
    currentuserobj = Userextension.objects.filter(user_id = request.user.id).first()
    if currentuserobj.usertype == "C":
        restaurants = []
        alluserobj = Userextension.objects.filter(usertype='R').all()
        for i in alluserobj:
            name = User.objects.filter(id = i.user_id).first().first_name
            user_id = User.objects.filter(id = i.user_id).first().id
            restaurants.append([name,user_id])
        context = {"restaurants":restaurants}
        return render(request, 'dishapp/selectrest.html',context=context)
    if currentuserobj.usertype == "R":
        # restaurants = []
        # alluserobj = Userextension.objects.filter(usertype='R').all()
        # for i in alluserobj:
        #     name = User.objects.filter(id = i.user_id).first().first_name
        #     user_id = User.objects.filter(id = i.user_id).first().id
        #     restaurants.append([name,user_id])
        # context = {"restaurants":restaurants}
        return render(request, 'myorderapp/restallorders.html',context={"restro":"yes"})

@login_required
@api_view(['POST'])
def get_dishes(request):
    print("Hello I not am here")
    if request.method == 'POST':
        all_dish_objects = Dishes.objects.filter(user_id = request.data['id']).all()
        restauro = User.objects.filter(id=request.data['id']).first()
        restauroname = restauro.first_name
        request.session['restauro_id'] = restauro.id
        alluserobj = Userextension.objects.filter(usertype='R').all()
        restaurants = []
        for i in alluserobj:
            name = User.objects.filter(id = i.user_id).first().first_name
            user_id = User.objects.filter(id = i.user_id).first().id
            restaurants.append([name,user_id])
        context = {"restaurants":restaurants,"dishes":all_dish_objects,"restauro":restauroname}
        return render(request, 'dishapp/selectrest.html',context=context)
    else:
        messages.success(request ,"Some thing went wrong")
        return redirect('restaurant')

# @login_required
# @api_view(['POST'])
# def placeorder(request):
#     if request.method == 'POST':
#         restaurant_code = request.data
#         all_dish_objects = Dishes.objects.filter(user_id = restaurant_code).all()
#         for i in all_dish_objects:
#             print(i.dishname)
#         return Response({"status":200,"message":"all good"})
#     else:
#         return Response({"status":400,"message":"It seems you are trying wrong type of request"})


import pygame

from data.modules.helper import read_from_json
from data.modules.player import Player
from data.modules.settings import SCREEN_HEIGHT, SCREEN_WIDTH
from data.modules.tile_list import TileList

class Level:
	def __init__(self, level_name):
		self.level_name = level_name

		self.tiles = None
		self.player = None

		self.scroll = pygame.Vector2(0, 0)

		self.initialize_level()

	def initialize_level(self):
		json = read_from_json(self.level_name)

		self.tiles = TileList((json["width"], json["height"]), json["tiles"])

		self.player = Player((json["player_x"], json["player_y"]))

	def get_scroll(self, delta):
		target_x = self.player.rect.center[0] - SCREEN_WIDTH / 2
		target_y = self.player.rect.center[1] - SCREEN_HEIGHT / 2

		self.scroll += pygame.Vector2(round((target_x - self.scroll.x) / 10, 3), round((target_y - self.scroll.y) / 10, 3)) * delta

		if self.scroll.x < 0:
			self.scroll.x = 0
		if self.scroll.y > 0:
			self.scroll.y = 0

	def update(self, delta):
		self.get_scroll(delta)

		self.player.update(delta, self.tiles.list)

	def draw(self, screen):
		self.tiles.draw(screen, self.scroll)

		self.player.draw(screen, self.scroll)


import torch
import torch.nn as nn

import torch.nn.functional as f

from ..layers import APPNPConv
from ..data import NodeBlocks

class APPNP(nn.Module):
    """
    APPNP model with simple APPNPConv layers at all layers
    """

    def __init__(self,
                 features_dim,
                 hidden_dim,
                 num_classes,
                 num_layers,
                 activation,
                 layer=APPNPConv,
                 dropout=0,
                 input_norm=False,
                 layer_norm=False,
                 *args,
                 **kwargs):

        super().__init__()

        self.num_layers = num_layers
        self.layers = nn.ModuleList()

        self.layer_type = layer

        self.dropout = nn.Dropout(p=dropout)
        self.activation = activation
        self.batch_norm = nn.BatchNorm1d(features_dim, affine=False)
        self.input_fc = nn.Linear(features_dim, hidden_dim)
        self.output_fc = nn.Linear(hidden_dim, num_classes)

        for i in range(num_layers):
            self.layers.append(layer(hidden_dim, hidden_dim,))

    def forward(self, x, adjs):

        h = x
        adj = adjs

        h = self.activation(self.input_fc(self.batch_norm(h)))
        h_0 = h.clone()

        gcn_cnt = 0

        for i, layer in enumerate(self.layers):

            if type(layer) == self.layer_type:

                if type(adjs) == NodeBlocks:
                    adj = adjs[gcn_cnt]
                    gcn_cnt += 1

                h = layer(adj, h, h_0)

            else:
                h = layer(h)

        h = self.dropout(h)
        h = self.output_fc(h)

        return h


import sys
import os
import collections
import glob
import json
import re
import math

import pandas as pd

from program_synthesis.common.tools import saver

from program_synthesis.karel import arguments
from program_synthesis.karel import dataset
from program_synthesis.karel import models

from program_synthesis.karel.dataset import parser_for_synthesis
from program_synthesis.karel.dataset import executor
from program_synthesis.karel.models import karel_trace_model

def load_model(model_dir, model_type, step=None):
    args = saver.ArgsDict(model_dir=model_dir, model_type=model_type, step=step)
    saver.restore_args(args)
    arguments.backport_default_args(args)
    dataset.set_vocab(args)
    m = models.get_model(args)
    eval_dataset = dataset.get_eval_dataset(args, m)
    m.model.eval()
    the_executor = executor.get_executor(args)()
    return m, eval_dataset, the_executor

parser = parser_for_synthesis.KarelForSynthesisParser()
tracer = karel_trace_model.KarelTracer(parser.karel)

def get_traces(code, tests):
    result = []
    prog = parser.parse(code)
    for test in tests:
        tracer.reset(indices=test['input'])
        prog()
        result.append(tracer.actions)
    return result

def check_correct(code, tests, e):
    res = executor.evaluate_code(code, None, tests, e)
    return res['correct'] == len(tests)

def load_report(report, ds, executor, traces=True):
  result = []
  idx = 0
  total_correct = 0
  for ex in ds.dataset:
    seq = report['beam_outputs'][idx][0]
    match = seq == ex.code_sequence
    if traces:
      gt_traces = get_traces(ex.code_sequence, ex.input_tests)
      inferred_traces = []
      # inferred_traces = [[ev.type for ev in test['trace'].events] for test in ex.input_tests]
    else:
      gt_traces, inferred_traces = [], []
    input_correct = check_correct(seq, ex.input_tests, executor.execute)
    all_correct = check_correct(seq, ex.input_tests + ex.tests, executor.execute)
    result.append((' '.join(ex.code_sequence), ' '.join(seq), gt_traces, inferred_traces, match, input_correct, all_correct))
    total_correct += 1 if all_correct else 0
    idx += 1
  print(float(total_correct) / len(result))
  return result

def show_stratified_report(reports):
  def length_to_key(l):
    if l < 15:
        return '0-15'
    elif l < 30:
        return '15-30'
    else:
        return '30+'
  result = []
  for rows in reports:
    total_by_length, correct_by_length = collections.defaultdict(int), collections.defaultdict(int)
    for r in rows:
        l = len(r[0].split(' ') if isinstance(r[0], str) else r[0])
        key = length_to_key(l)
        total_by_length[key] += 1
        if r[-1]:
            correct_by_length[key] += 1

    q = []
    for l in sorted(total_by_length.keys()):
      q.append((
            l, total_by_length[l] / len(rows),
            float(correct_by_length[l]) / total_by_length[l],
            correct_by_length[l], total_by_length[l]))
    def contain_and_not(seq, contain, not_contain):
        has_contain = False if contain else True
        has_not_contain = False
        for x in contain:
            if x in seq:
                has_contain = True
                break
        for x in not_contain:
            if x in seq:
                has_not_contain = True
                break
        return has_contain and not has_not_contain

    stats = collections.defaultdict(lambda: [0, 0])
    keys = [
        ('COND', ['IF', 'IFELSE'], ['REPEAT', 'WHILE']),
        ('LOOP', ['REPEAT', 'WHILE'], ['IF', 'IFELSE']),
        ('NONE', [], ['IF', 'IFELSE', 'REPEAT', 'WHILE']),
        ('COND_LOOP', ['IF', 'IFELSE', 'REPEAT', 'WHILE'], [])
    ]
    for r in rows:
        for key, contain, not_contain in keys:
            if contain_and_not(r[0], contain, not_contain):
                stats[key][0] += 1
                if r[-1]:
                    stats[key][1] += 1
        key = 'LOOP-%d' % (r[0].count('REPEAT') + r[0].count('WHILE'))
        stats[key][0] += 1
        if r[-1]:
            stats[key][1] += 1

    for key in sorted(list(stats.keys())):
        q.append((
            key, stats[key][0] / len(rows),
            float(stats[key][1]) / stats[key][0], stats[key][1],
            stats[key][0]))
    result.append(q)
  return result

if __name__ == "__main__":
    m, eval_dataset, the_executor = load_model(
        '/home/ubuntu/karel-io-trace-code/logdirs/20180321/karel-code-trace-ioshuf-interleave-nogrid',
        'karel-code-trace', step=300100)
    orig_report = json.load(open('/home/ubuntu/karel-io-trace-code/logdirs/20180321/karel-code-trace-ioshuf-interleave-nogrid/report-20180321-val-bs43-300100.jsonl'))
    baseline_report = json.load(open('/home/ubuntu/karel-io-trace-code/baseline-msr.eval2.json'))
    iotracecode_result = load_report(orig_report, eval_dataset, the_executor, True)
    baseline_result = load_report(baseline_report, eval_dataset, the_executor)
    report = show_stratified_report([baseline_result, iotracecode_result])
    for rows in report:
        for row in rows:
            print('\t'.join([str(x) for x in row]))


import os
from setuptools import setup, find_packages

def read(filename):
    return open(os.path.join(os.path.dirname(__file__), filename)).read()

setup(
    name='Gears',
    version='0.7.2',
    license='ISC',
    description='Compiles and concatenates JavaScript and CSS assets.',
    long_description=read('README.rst'),
    url='https://github.com/gears/gears',
    author='Mike Yumatov',
    author_email='mike@yumatov.org',
    packages=find_packages(exclude=['tests', 'tests.*']),
    include_package_data=True,
    install_requires=[
        'glob2',
    ],
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: ISC License (ISCL)',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.6',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.3',
    ],
)