#coding:utf8
import logging
import json
import datetime
from django.utils import timezone
from django.forms.models import model_to_dict

logger = logging.getLogger(__name__)

class Ret(object):
    """返回值 Interface
    包含错误码和错误原因
    """
    RET_OK = 0
    RET_AUTH_ERROR = 1
    RET_REQUEST_ERROR = 2
    RET_INSERT_ERROR = 3
    RET_DELETE_ERROR = 4
    RET_UPDATE_ERROR = 5
    RET_HANDLE_ERROR = 6
    RET_LOGOUT_ERROR = 7

    def __init__(self):
        self.ret = self.RET_OK
        self.reason = 'OK'
        self.ts = timezone.now()

class ComplexEncoder(json.JSONEncoder):
    """Json 序列化补完
    解决 json 无法序列化 datetime 类型的问题
    """

    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return timezone.localtime(obj).strftime('%Y-%m-%d %H:%M:%S')
        # elif isinstance(obj, date):
        #     return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)

def pack_list_response(objs, count = None, t = None):
    """打包数组数据
    """
    datas = []
    for obj in objs:
        d = model_to_dict(obj)
        datas.append(model_to_dict(obj))

    reason = {}
    reason['ret'] = 0
    reason['reason'] = 'OK'
    reason['data'] = datas
    if count is not None:
        reason['length'] = count
    if t is not None:
        reason['t'] = t

    return json.dumps(reason, cls = ComplexEncoder)

def pack_response(obj = None):
    """打包数据
    """
    if obj is not None:
        reason = {
                'ret': 0,
                'reason': 'OK',
                'data': model_to_dict(obj),
                }
    else:
        reason = {
                'ret': 0,
                'reason': 'OK',
                }

    return json.dumps(reason, cls = ComplexEncoder)

def pack_string_response(string):
    """打包字符串
    """
    reason = {
            'ret': 0,
            'reason': 'OK',
            'data': string,
            }
    return json.dumps(reason)

def pack_error_response(ret):
    """打包错误
    """
    reason = {
            'ret': ret.ret,
            'reason': ret.reason,
            }

    return json.dumps(reason)

def pack_logout_response():
    """未登录错误
    """
    ret = Ret()
    ret.ret = ret.RET_LOGOUT_ERROR
    ret.reason = "please login first"
    reason = {
            'ret': ret.ret,
            'reason': ret.reason,
            }

    return json.dumps(reason)


""" Based on frontend component of https://github.com/McAuley-Lab/RecWizard
"""
import sys
import streamlit as st
import requests
import json
from collections import defaultdict
from utils import img_to_html, create_graph, plotly_plot, plotly_timeline, strip_debug
import re

try:
    PORT = int(sys.argv[1])
except:
    PORT = 8000

def replace_url(match):
    url = match.group(1)
    # You can customize the replacement text based on the extracted URL here
    return f" [Retrieved image]({url}) "

@st.cache_data
def convert_to_json(chat_history):
    # IMPORTANT: Cache the conversion to prevent computation on every rerun
    return json.dumps(chat_history)

def chat_actions(user_key):
    st.session_state["chat_history"][user_key].append(
        {"role": "user", "content": st.session_state["chat_input"]},
    )

st.markdown(img_to_html('logo.png', 'Xray-Insight'), unsafe_allow_html=True)
st.write("#### Lets dive deeper into that Chest")
mode = st.sidebar.radio(label="Logging mode", options=["info", "debug"])
plot_type = None
show_details = None
PLOT_OPTIONS = ["timeline", "graph"]

if mode == "debug":
    plot_type = st.sidebar.radio(label="Plot Type", options=PLOT_OPTIONS)
    show_details = st.sidebar.checkbox("Show Details")
if "chat_history" not in st.session_state:
    st.session_state["chat_history"] = defaultdict(list)

metadata = st.sidebar.text_input("metadata (dict)", value="{}", key="metadata")
user_key = '0'
uploaded_file = st.file_uploader("Choose a file")
if uploaded_file is not None:
    # To read file as bytes:
    bytes_data = uploaded_file.getvalue()

prompt = st.chat_input("Enter your message",
                        on_submit=chat_actions,
                        args=(user_key,),
                        key="chat_input",
                        )
for i in st.session_state["chat_history"][user_key]:
    with st.chat_message(name=i["role"], avatar='logo.png' if i["role"]=="assistant" else None):
        st.image(bytes_data)
        if 'content' in i:
            st.write(i["content"])
        if 'debug_message' in i:
            if i["type"] == "json":
                st.json(i["debug_message"], expanded=False)
            else:
                st.write(i["debug_message"])

if prompt:
    history = st.session_state["chat_history"][user_key]
    if len(history) > 2:
        past = []
        for chat in history:
            if "content" in chat:
                if chat["role"] == "user":
                    past.append("User: " + chat["content"])
                else:
                    past.append("System: " + chat["content"])

    with st.spinner("generating..."):
        files = {"file": (uploaded_file.name, uploaded_file, "image/jpeg")}
        result = requests.post(f"http://localhost:{PORT}/predict/",
                                                                data={"query": prompt,
                                                                      "mode": mode},
                                                                files=files,
                                                                #headers = {"Content-Type": "multipart/form-data"}
                                                                ).json()
    if result:

        with st.chat_message(name="ai", avatar="logo.png"):
            output = result["response"]
            output = re.sub("(http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])",
                   replace_url,
                   output)
            if "links" in result["response"]:
                for name, link in result["response"]["links"].items():
                    if link:
                        output = output.replace(name, f"[{name}]({link})")
            print(output)
            formatted_resp = output.replace("System: ", "").replace("User: ", "").replace("<|endoftext|>", "")
            st.write(formatted_resp)
            st.session_state["chat_history"][user_key].append(
                {
                    "role": "assistant",
                    "content": formatted_resp,
                },
            )
            if result["graph"]:
                # Create a directed graph using NetworkX
                st.toast(f'## Total time: {round(result["graph"][-1]["time"], 3)}s')

                if plot_type == "graph":
                    G = create_graph(result)
                    fig = plotly_plot(G)
                    st.plotly_chart(fig, use_container_width=False)

                elif plot_type == "timeline":
                    fig = plotly_timeline(result["graph"])
                    st.plotly_chart(fig, use_container_width=False)

                st.session_state["chat_history"][user_key].append(
                    {
                        "role": "assistant",
                        "debug_message": fig,
                        "type": "figure"
                    },
                )
                if show_details:
                    st.write("details:")
                    st.json(result["graph"], expanded=False)
                    st.session_state["chat_history"][user_key].append(
                        {
                            "role": "assistant",
                            "debug_message": result["graph"],
                            "type": "json"
                        },
                    )
if st.sidebar.button("Refresh Chat"):
    del st.session_state["chat_history"][user_key]
    st.rerun()
st.sidebar.download_button("Download Chat History",
                        convert_to_json(strip_debug(st.session_state["chat_history"], user_key)),
                        file_name="chat_history.json")


from flask import abort, render_template, Response, Blueprint

from .. import config, crypto, http
from ..model.room import get_accessible_rooms
from . import auth, converters  # noqa: F401

from io import BytesIO

import qrcode

import PIL.Image

if hasattr(PIL.Image, 'Resampling'):
    NEAREST = PIL.Image.Resampling.NEAREST
else:
    NEAREST = PIL.Image.NEAREST

views = Blueprint('views', __name__)

@views.get("/")
def serve_index():
    """
    Publicly accessible URL that displays a list of public rooms to a web browser.  This isn't a
    normal SOGS client endpoint, but rather a convenience web page for people who follow a SOGS
    pseudo-URL.
    """
    rooms = get_accessible_rooms()
    if len(rooms) == 0:
        return render_template('setup.html')
    if not config.HTTP_SHOW_INDEX:
        abort(http.FORBIDDEN)
    return render_template(
        "index.html", url_base=config.URL_BASE, rooms=rooms, pubkey=crypto.server_pubkey_hex
    )

@views.get("/r/<Room:room>/")
def view_room(room):
    """
    Publicly accessible URL that displays a room (including recent messages) to a web browser.  This
    isn't a normal SOGS client endpoint, but rather a convenience web page for people who follow a
    SOGS pseudo-URL, that displays the SOGS URL and QR code along with a list of recent messages.
    """
    if not room.default_read:
        abort(http.FORBIDDEN)

    return render_template("view_room.html", room=room, show_recent=config.HTTP_SHOW_RECENT)

@views.get("/r/<Room:room>/invite.png")
def serve_invite_qr(room):
    """
    URL that generates a SOGS open group URL in QR code format for consumption by a mobile device.
    This isn't a normal SOGS client endpoint, but rather part of the a convenience web page for
    people who view the SOGS URL in a browser and want to scan the URL into another device (i.e.
    mobile Session).
    """
    if not room.default_read:
        abort(http.FORBIDDEN)

    img = qrcode.make(room.url)
    data = BytesIO()
    img = img.resize((512, 512), NEAREST)
    img.save(data, "PNG")
    return Response(data.getvalue(), mimetype="image/png")


#-*- coding: utf-8 -*-
import os

import tensorflow as tf
from models import SASRec, BERT4Rec
from util import data_partition

random_seed = 12345

flags = tf.flags
FLAGS = flags.FLAGS

flags.DEFINE_integer(
    "pool_size", 10,
    "multiprocesses pool size.")

flags.DEFINE_integer(
    "max_seq_length", 200,
    "max sequence length.")

flags.DEFINE_integer(
    "max_predictions_per_seq", 20,
    "max_predictions_per_seq.")

flags.DEFINE_float(
    "masked_lm_prob", 0.15,
    "Masked LM probability.")

flags.DEFINE_float(
    "mask_prob", 1.0,
    "mask probabaility")

flags.DEFINE_integer(
    "dupe_factor", 10,
    "Number of times to duplicate the input data (with different masks).")

flags.DEFINE_string(
    "data_dir", './data/',
    "data dir.")

flags.DEFINE_string(
    "output_dir", './result/',
    "output dir.")

flags.DEFINE_string(
    "dataset_name", 'ml-1m',
    "dataset name.")

model_map = {'sasrec': SASRec,
             'bert4rec': BERT4Rec}

# ===========================
# config_file, data_file, do_train, do_eval

def main():
  model_type = FLAGS.type
  data_dir = FLAGS.data_dir
  datafile = FLAGS.datafile
  output_dir = FLAGS.output_dir

  if not os.path.isdir(data_dir):
    print(data_dir + ' is not exist in {}'.format(os.getcwd()))
    exit(1)

  model = model_map[model_type](FLAGS)

  # if tf record exists, pass
  if not os.path.isfile(model.record_file):
    dataset = data_partition(output_dir + datafile)
    model.store_data_as_record(dataset)

  if FLAGS.do_train:
    model.train()
  else:
    model.predict()

if __name__ == "__main__":
    main()


from django.shortcuts import render, redirect, get_object_or_404
from .models import Job
from faker import Faker
from pprint import pprint
from decouple import config
import requests

def new(request):
    if request.method == 'GET':
        return render(request, 'jobs/new.html')
    else:
        name = request.POST.get('name')
        image = request.FILES.get('image')
        if not Job.objects.filter(name=name):
            job = Job()
            job.name = name
            fake = Faker()
            past_job = fake.job()
            job.past_job = past_job
            job.profile_image = image
            job.save()
        job = Job.objects.filter(name=name).first()
        KEY = config('KEY')
        url = 'http://api.giphy.com/v1/gifs/search?api_key=' + KEY + '&q=' + job.past_job +'&limit=1&lang=ko'
        datas = requests.get(url).json()
        data = datas.get("data")
        gif_url = ''
        if data:
            gif_url = data[0].get("images").get("original").get("url")
        context = {'job': job, 'gif_url' : gif_url}
        return render(request, 'jobs/result.html', context)


from django.conf.urls import include
from django.conf.urls import url

from django.conf import settings
from django.contrib import admin
from rest_framework import routers
from rest_framework_jwt.views import obtain_jwt_token
from rest_framework_jwt.views import refresh_jwt_token
from rest_framework_jwt.views import verify_jwt_token

from gale_user import views
from bills import views as bills_view
from authorization.views import (
    LoginView,
    RegisterView
)

router = routers.DefaultRouter()
urlpatterns = router.urls

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^api-token-auth/', obtain_jwt_token, name='create_token'),
    url(r'^api-token-refresh/', refresh_jwt_token),
    url(r'^api-token-verify/', verify_jwt_token)
]

urlpatterns += router.urls

urlpatterns += [
    url(r'^api/', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

urlpatterns += [
    url(r'^users/create/$', views.UserCreateView.as_view(), name="user_create"),
    url(r'^users/list/$', views.UsersListView.as_view(), name="users_list"),
    url(r'^users/(?P<pk>\d+)/detail/$', views.UserDetailView.as_view(), name="user_detail"),
    url(r'^users/(?P<pk>\d+)/update/$', views.UserUpdateView.as_view(), name="user_update"),
    url(r'^users/(?P<pk>\d+)/delete/$', views.UserDeleteView.as_view(), name="user_delete"),
    url(r'^users/mybills/$', views.my_bills, name="my_bills"),
]

urlpatterns += [
    url(r'^bill/create/$', bills_view.BillsCreateView.as_view(), name="bills_create"),
    url(r'^bill/list/$', bills_view.BillsListView.as_view(), name="bills_list"),
    url(r'^bill/(?P<pk>\d+)/detail/$', bills_view.BillsDetailView.as_view(), name="bills_detail"),
    url(r'^bill/(?P<pk>\d+)/update/$', bills_view.BillsUpdateView.as_view(), name="bills_update"),
    url(r'^bill/(?P<pk>\d+)/delete/$', bills_view.BillsDeleteView.as_view(), name="bills_delete"),
]

urlpatterns += [
    url(r'^user/login', LoginView.as_view()),
    url(r'^user/register', RegisterView.as_view())
]

if not settings.DEBUG:
    urlpatterns += (
        '',
        (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),)


from itertools import combinations
word = input()
N = len(word)
num = []
result = []
for i in range(1, N):
    num.append(i)
ncr = combinations(num, 2)

for item in ncr:
    a, b =item
    temp_word=list(word[0:a])
    temp_word.reverse()
    temp_word2=list(word[a:b])
    temp_word2.reverse()
    temp_word3=list(word[b:])
    temp_word3.reverse()
    #print(len(temp_word),len(temp_word2),len(temp_word3))
    temp_word.extend(temp_word2)
    temp_word.extend(temp_word3)
    re = "".join(temp_word)
    result.append(re)

print(sorted(result)[0])


from typing import Callable, Dict, Iterable, Iterator, Tuple, Union, Sequence

from spacy.tokens import Doc
import toolz as tlz

from textacy_corpora.typing import LabelledData

def to_labelled(collection: Dict[str, Sequence]) -> Iterator[LabelledData]:
    seq = flatten_collection(collection)
    (_, first), seq = tlz.peek(seq)

    labeller: Callable

    if isinstance(first, tuple):
        labeller = _from_record
    else:
        labeller = _from_scalar

    for label, data in seq:
        yield labeller(label, data)

def flatten_collection(collection: Dict[str, Sequence]) -> Iterator:
    for label, seq in collection.items():
        for item in seq:
            yield (label, item)

def _from_scalar(label: str, data: Union[str, Doc]) -> Tuple[str, Union[str, Doc]]:
    return label, data

def _from_record(label: str, data: Tuple[str, dict]) -> Tuple[str, str, dict]:
    return (label, *data)


from __future__ import annotations

from typing import Literal, Optional

import htmltools
from htmltools import Tag, TagAttrValue, TagChild, TagList

from .. import ui
from ..types import MISSING, MISSING_TYPE
from ..ui._layout_columns import BreakpointsUser
from ..ui.css import CssUnit
from . import _run
from ._recall_context import RecallContextManager, wrap_recall_context_manager

__all__ = (
    "set_page",
    "p",
    "div",
    "span",
    "pre",
    "sidebar",
    "layout_column_wrap",
    "layout_columns",
    "column",
    "row",
    "card",
    "accordion",
    "accordion_panel",
    "navset",
    "navset_card",
    "nav_panel",
    "page_fluid",
    "page_fixed",
    "page_fillable",
    "page_sidebar",
)

# ======================================================================================
# Page functions
# ======================================================================================
def set_page(page_fn: RecallContextManager[Tag]):
    """Set the page function for the current Shiny express app."""
    _run.replace_top_level_recall_context_manager(page_fn, force=True)

# ======================================================================================
# htmltools Tag functions
# ======================================================================================
p = wrap_recall_context_manager(htmltools.p)
div = wrap_recall_context_manager(htmltools.div)
span = wrap_recall_context_manager(htmltools.span)
pre = wrap_recall_context_manager(htmltools.pre)

# ======================================================================================
# Shiny layout components
# ======================================================================================
def sidebar(
    *,
    width: CssUnit = 250,
    position: Literal["left", "right"] = "left",
    open: Literal["desktop", "open", "closed", "always"] = "always",
    id: Optional[str] = None,
    title: TagChild | str = None,
    bg: Optional[str] = None,
    fg: Optional[str] = None,
    class_: Optional[str] = None,  # TODO-future; Consider using `**kwargs` instead
    max_height_mobile: Optional[str | float] = "auto",
    gap: Optional[CssUnit] = None,
    padding: Optional[CssUnit | list[CssUnit]] = None,
) -> RecallContextManager[ui.Sidebar]:
    """
    Sidebar element

    Create a collapsing sidebar layout. This function wraps :func:`~shiny.ui.sidebar`.

    Parameters
    ----------
    width
        A valid CSS unit used for the width of the sidebar.
    position
        Where the sidebar should appear relative to the main content.
    open
        The initial state of the sidebar. It can be `"desktop"` (the sidebar starts open
        on desktop screen, closed on mobile), `"open"` or `True` (the sidebar starts
        open), `"closed"` or `False` (the sidebar starts closed), or `"always"` or
        `None` (the sidebar is always open and cannot be closed).

        In :func:`~shiny.ui.update_sidebar`, `open` indicates the desired state of the
        sidebar. Note that :func:`~shiny.ui.update_sidebar` can only open or close the
        sidebar, so it does not support the `"desktop"` and `"always"` options.
    id
        A character string. Required if wanting to re-actively read (or update) the
        `collapsible` state in a Shiny app.
    title
        A character title to be used as the sidebar title, which will be wrapped in a
        `<div>` element with class `sidebar-title`. You can also provide a custom
        :class:`~htmltools.Tag` for the title element, in which case you'll
        likely want to give this element `class = "sidebar-title"`.
    bg,fg
        A background or foreground color.
    class_
        CSS classes for the sidebar container element, in addition to the fixed
        `.sidebar` class.
    max_height_mobile
        A CSS length unit (passed through :func:`~shiny.ui.css.as_css_unit`) defining
        the maximum height of the horizontal sidebar when viewed on mobile devices. Only
        applies to always-open sidebars that use `open = "always"`, where by default the
        sidebar container is placed below the main content container on mobile devices.
    gap
        A CSS length unit defining the vertical `gap` (i.e., spacing) between elements
        provided to `*args`.
    padding
        Padding within the sidebar itself. This can be a numeric vector (which will be
        interpreted as pixels) or a character vector with valid CSS lengths. `padding`
        may be one to four values. If one, then that value will be used for all four
        sides. If two, then the first value will be used for the top and bottom, while
        the second value will be used for left and right. If three, then the first will
        be used for top, the second will be left and right, and the third will be
        bottom. If four, then the values will be interpreted as top, right, bottom, and
        left respectively.

    Returns
    -------
    :
        A :class:`~shiny.ui.Sidebar` object.
    """
    return RecallContextManager(
        ui.sidebar,
        default_page=page_sidebar(),
        kwargs=dict(
            width=width,
            position=position,
            open=open,
            id=id,
            title=title,
            bg=bg,
            fg=fg,
            class_=class_,
            max_height_mobile=max_height_mobile,
            gap=gap,
            padding=padding,
        ),
    )

def layout_column_wrap(
    *,
    width: CssUnit | None | MISSING_TYPE = MISSING,
    fixed_width: bool = False,
    heights_equal: Literal["all", "row"] = "all",
    fill: bool = True,
    fillable: bool = True,
    height: Optional[CssUnit] = None,
    height_mobile: Optional[CssUnit] = None,
    gap: Optional[CssUnit] = None,
    class_: Optional[str] = None,
    **kwargs: TagAttrValue,
):
    """
    A grid-like, column-first layout

    Wraps a 1d sequence of UI elements into a 2d grid. The number of columns (and rows)
    in the grid dependent on the column `width` as well as the size of the display.
    This function wraps :func:`~shiny.ui.layout_column_wrap`.

    Parameters
    ----------
    width
        The desired width of each card. It can be a (unit-less) number between 0 and 1
        and should be specified as `1/num`, where `num` represents the number of desired
        columns. It can be a CSS length unit representing either the minimum (when
        `fixed_width=False`) or fixed width (`fixed_width=True`). It can also be `None`,
        which allows power users to set the `grid-template-columns` CSS property
        manually, either via a `style` attribute or a CSS stylesheet. If missing, a
        value of `200px` will be used.
    fixed_width
        When `width` is greater than 1 or is a CSS length unit, e.g. `"200px"`,
        `fixed_width` indicates whether that `width` value represents the absolute size
        of each column (`fixed_width=TRUE`) or the minimum size of a column
        (`fixed_width=FALSE`). When `fixed_width=FALSE`, new columns are added to a row
        when `width` space is available and columns will never exceed the container or
        viewport size. When `fixed_width=TRUE`, all columns will be exactly `width`
        wide, which may result in columns overflowing the parent container.
    heights_equal
        If `"all"` (the default), every card in every row of the grid will have the same
        height. If `"row"`, then every card in _each_ row of the grid will have the same
        height, but heights may vary between rows.
    fill
        Whether or not to allow the layout to grow/shrink to fit a fillable container
        with an opinionated height (e.g., :func:`~shiny.ui.page_fillable`).
    fillable
        Whether or not each element is wrapped in a fillable container.
    height
        Any valid CSS unit to use for the height.
    height_mobile
        Any valid CSS unit to use for the height when on mobile devices (or narrow
        windows).
    gap
        Any valid CSS unit to use for the gap between columns.
    class_
        A CSS class to apply to the containing element.
    **kwargs
        Additional attributes to apply to the containing element.

    Returns
    -------
    :
        A :class:`~htmltools.Tag` element.

    See Also
    --------
    * :func:`~shiny.express.layout.layout_columns` for laying out elements into a
      responsive 12-column grid.
    """
    return RecallContextManager(
        ui.layout_column_wrap,
        default_page=page_fillable(),
        kwargs=dict(
            width=width,
            fixed_width=fixed_width,
            heights_equal=heights_equal,
            fill=fill,
            fillable=fillable,
            height=height,
            height_mobile=height_mobile,
            gap=gap,
            class_=class_,
            **kwargs,
        ),
    )

def layout_columns(
    *,
    col_widths: BreakpointsUser[int] = None,
    row_heights: BreakpointsUser[CssUnit] = None,
    fill: bool = True,
    fillable: bool = True,
    gap: Optional[CssUnit] = None,
    class_: Optional[str] = None,
    height: Optional[CssUnit] = None,
    **kwargs: TagAttrValue,
):
    """
    Create responsive, column-based grid layouts, based on a 12-column grid.

    Parameters
    ----------
    col_widths
        The widths of the columns, possibly at different breakpoints. Can be one of the
        following:

        * `None` (the default): Automatically determines a sensible number of columns
          based on the number of children given to the layout.
        * A list or tuple of integers between 1 and 12, where each element represents
          the number of columns for the relevant UI element. Column widths are recycled
          to extend the values in `col_widths` to match the actual number of items in
          the layout, and children are wrapped onto the next row when a row exceeds 12
          column units. For example, `col_widths=(4, 8, 12)` allocates 4 columns to the
          first element, 8 columns to the second element, and 12 columns to the third
          element (which wraps to the next row). Negative values are also allowed, and
          are treated as empty columns. For example, `col_widths=(-2, 8, -2)` would
          allocate 8 columns to an element (with 2 empty columns on either side).
        * A dictionary of column widths at different breakpoints. The keys should be
          one of `"xs"`, `"sm"`, `"md"`, `"lg"`, `"xl"`, or `"xxl"`, and the values are
          either of the above. For example, `col_widths={"sm": (3, 3, 6), "lg": (4)}`.

    row_heights
        The heights of the rows, possibly at different breakpoints. Can be one of the
        following:

        * A numeric vector, where each value represents the
          [fractional unit](https://css-tricks.com/introduction-fr-css-unit/)
          (`fr`) height of the relevant row. If there are more rows than values
          provided, the pattern will be repeated. For example, `row_heights=(1, 2)`
          allows even rows to take up twice as much space as odd rows.
        * A list of numeric or CSS length units, where each value represents the height
          of the relevant row. If more rows are needed than values provided, the pattern
          will repeat. For example, `row_heights=["auto", 1]` allows the height of odd
          rows to be driven my it's contents and even rows to be
          [`1fr`](https://css-tricks.com/introduction-fr-css-unit/).
        * A single string containing CSS length units. In this case, the value is
          supplied directly to `grid-auto-rows`.
        * A dictionary of row heights at different breakpoints, where each key is a
          breakpoint name (one of `"xs"`, `"sm"`, `"md"`, `"lg"`, `"xl"`, or `"xxl"`)
          and where the values may be any of the above options.

    fill
        Whether or not to allow the layout to grow/shrink to fit a fillable container
        with an opinionated height (e.g., :func:`~shiny.ui.page_fillable`).

    fillable
        Whether or not each element is wrapped in a fillable container.

    gap
        Any valid CSS unit to use for the gap between columns.

    class_
        CSS class(es) to apply to the containing element.

    height
        Any valid CSS unit to use for the height.

    **kwargs
        Additional attributes to apply to the containing element.

    Returns
    -------
    :
        An :class:`~htmltools.Tag` element.

    See Also
    --------
    * :func:`~shiny.express.layout.layout_column_wrap` for laying out elements into a
      uniform grid.

    Reference
    --------
    * [Bootstrap CSS Grid](https://getbootstrap.com/docs/5.3/layout/grid/)
    * [Bootstrap Breakpoints](https://getbootstrap.com/docs/5.3/layout/breakpoints/)
    """
    return RecallContextManager(
        ui.layout_columns,
        kwargs=dict(
            col_widths=col_widths,
            row_heights=row_heights,
            fill=fill,
            fillable=fillable,
            gap=gap,
            class_=class_,
            height=height,
            **kwargs,
        ),
    )

def column(width: int, *, offset: int = 0, **kwargs: TagAttrValue):
    """
    Responsive row-column based layout

    This function wraps :func:`~shiny.ui.column`. See :func:`~shiny.ui.row` for more
    information.

    Parameters
    ----------
    width
        The width of the column (an integer between 1 and 12).
    offset
        The number of columns to offset this column from the end of the previous column.
    **kwargs
        Attributes to place on the column tag.

    Returns
    -------
    :
        A UI element.

    See Also
    -------
    :func:`~shiny.ui.row`
    """
    return RecallContextManager(
        ui.column,
        args=(width,),
        kwargs=dict(
            offset=offset,
            **kwargs,
        ),
    )

def row(**kwargs: TagAttrValue):
    """
    Responsive row-column based layout

    This function wraps :func:`~shiny.ui.row`. Layout UI components using Bootstrap's
    grid layout system. Use ``row()`` to group elements that should appear on the same
    line (if the browser has adequate width) and :func:`~shiny.ui.column` to define how
    much horizontal space within a 12-unit wide grid each on of these elements should
    occupy. See the [layout guide](https://shiny.posit.co/articles/layout-guide.html>)
    for more context and examples. (The article is about Shiny for R, but the general
    principles are the same.)

    Parameters
    ----------
    **kwargs
        Attributes to place on the row tag.

    Returns
    -------
    :
        A UI element.

    See Also
    -------
    :func:`~shiny.ui.column`
    """
    return RecallContextManager(ui.row, kwargs=kwargs)

def card(
    *,
    full_screen: bool = False,
    height: Optional[CssUnit] = None,
    max_height: Optional[CssUnit] = None,
    min_height: Optional[CssUnit] = None,
    fill: bool = True,
    class_: Optional[str] = None,
    **kwargs: TagAttrValue,
):
    """
    A Bootstrap card component

    This function wraps :func:`~shiny.ui.card`. A general purpose container for grouping
    related UI elements together with a border and optional padding. To learn more about
    `card()`s, see [this article](https://rstudio.github.io/bslib/articles/cards.html).

    Parameters
    ----------
    full_screen
        If `True`, an icon will appear when hovering over the card body. Clicking the
        icon expands the card to fit viewport size.
    height,max_height,min_height
        Any valid CSS unit (e.g., `height="200px"`). Doesn't apply when a card is made
        `full_screen` (in this case, consider setting a `height` in
        :func:`~shiny.experimental.ui.card_body`).
    fill
        Whether or not to allow the card to grow/shrink to fit a fillable container with
        an opinionated height (e.g., :func:`~shiny.ui.page_fillable`).
    class_
        Additional CSS classes for the returned Tag.
    wrapper
        A function (which returns a UI element) to call on unnamed arguments in `*args`
        which are not already card item(s) (like :func:`~shiny.ui.card_header`,
        :func:`~shiny.experimental.ui.card_body`, etc.). Note that non-card items are
        grouped together into one `wrapper` call (e.g. given `card("a", "b",
        card_body("c"), "d")`, `wrapper` would be called twice, once with `"a"` and
        `"b"` and once with `"d"`).
    **kwargs
        HTML attributes on the returned Tag.

    Returns
    -------
    :
        An :func:`~shiny.ui.tags.div` tag.
    """
    return RecallContextManager(
        ui.card,
        kwargs=dict(
            full_screen=full_screen,
            height=height,
            max_height=max_height,
            min_height=min_height,
            fill=fill,
            class_=class_,
            **kwargs,
        ),
    )

def accordion(
    *,
    id: Optional[str] = None,
    open: Optional[bool | str | list[str]] = None,
    multiple: bool = True,
    class_: Optional[str] = None,
    width: Optional[CssUnit] = None,
    height: Optional[CssUnit] = None,
    **kwargs: TagAttrValue,
):
    """
    Create a vertically collapsing accordion.

    This function wraps :func:`~shiny.ui.accordion`.

    Parameters
    ----------
    id
        If provided, you can use `input.id()` in your server logic to determine which of
        the :func:`~shiny.ui.accordion_panel`s are currently active. The
        value will correspond to the :func:`~shiny.ui.accordion_panel`'s
        `value` argument.
    open
        A list of :func:`~shiny.ui.accordion_panel` values to open (i.e.,
        show) by default. The default value of `None` will open the first
        :func:`~shiny.ui.accordion_panel`. Use a value of `True` to open
        all (or `False` to open none) of the items. It's only possible to open more than
        one panel when `multiple=True`.
    multiple
        Whether multiple :func:`~shiny.ui.accordion_panel` can be open at
        once.
    class_
        Additional CSS classes to include on the accordion div.
    width
        Any valid CSS unit; for example, height="100%".
    height
        Any valid CSS unit; for example, height="100%".
    **kwargs
        Attributes to this tag.

    Returns
    -------
    :
        Accordion panel Tag object.
    """
    return RecallContextManager(
        ui.accordion,
        kwargs=dict(
            id=id,
            open=open,
            multiple=multiple,
            class_=class_,
            width=width,
            height=height,
            **kwargs,
        ),
    )

def accordion_panel(
    title: TagChild,
    *,
    value: Optional[str] | MISSING_TYPE = MISSING,
    icon: Optional[TagChild] = None,
    **kwargs: TagAttrValue,
):
    """
    Single accordion panel.

    This function wraps :func:`~shiny.ui.accordion_panel`.

    Parameters
    ----------
    title
        A title to appear in the :func:`~shiny.ui.accordion_panel`'s header.
    value
        A character string that uniquely identifies this panel. If `MISSING`, the
        `title` will be used.
    icon
        A :class:`~htmltools.Tag` which is positioned just before the `title`.
    **kwargs
        Tag attributes to the `accordion-body` div Tag.

    Returns
    -------
    :
        `AccordionPanel` object.
    """
    return RecallContextManager(
        ui.accordion_panel,
        args=(title,),
        kwargs=dict(
            value=value,
            icon=icon,
            **kwargs,
        ),
    )

# ======================================================================================
# Nav components
# ======================================================================================

def navset(
    *,
    type: Literal["underline", "pill", "tab"] = "underline",
    id: Optional[str] = None,
    selected: Optional[str] = None,
    header: TagChild = None,
    footer: TagChild = None,
):
    """
    Render a set of nav items

    Parameters
    ----------
    *args
        A collection of nav items (e.g., :func:`shiny.ui.nav`).
    type
        The type of navset to render. Can be one of `"underline"`, `"pill"`, or `"tab"`.
    id
        If provided, will create an input value that holds the currently selected nav
        item.
    selected
        Choose a particular nav item to select by default value (should match it's
        ``value``).
    header
        UI to display above the selected content.
    footer
        UI to display below the selected content.
    """

    funcs = {
        "underline": ui.navset_underline,
        "pill": ui.navset_pill,
        "tab": ui.navset_tab,
    }

    func = funcs.get(type, None)
    if func is None:
        raise ValueError(f"Invalid navset type: {type!r}")

    return RecallContextManager(
        func,
        kwargs=dict(
            id=id,
            selected=selected,
            header=header,
            footer=footer,
        ),
    )

def navset_card(
    *,
    type: Literal["underline", "pill", "tab"] = "underline",
    id: Optional[str] = None,
    selected: Optional[str] = None,
    title: Optional[TagChild] = None,
    sidebar: Optional[ui.Sidebar] = None,
    header: TagChild = None,
    footer: TagChild = None,
):
    """
    Render a set of nav items inside a card container.

    Parameters
    ----------
    *args
        A collection of nav items (e.g., :func:`shiny.ui.nav`).
    type
        The type of navset to render. Can be one of `"underline"`, `"pill"`, or `"tab"`.
    id
        If provided, will create an input value that holds the currently selected nav
        item.
    selected
        Choose a particular nav item to select by default value (should match it's
        ``value``).
    sidebar
        A :class:`shiny.ui.Sidebar` component to display on every :func:`~shiny.ui.nav` page.
    header
        UI to display above the selected content.
    footer
        UI to display below the selected content.
    """

    funcs = {
        "underline": ui.navset_card_underline,
        "pill": ui.navset_card_pill,
        "tab": ui.navset_card_tab,
    }

    func = funcs.get(type, None)
    if func is None:
        raise ValueError(f"Invalid navset type: {type!r}")

    return RecallContextManager(
        func,
        kwargs=dict(
            id=id,
            selected=selected,
            title=title,
            sidebar=sidebar,
            header=header,
            footer=footer,
        ),
    )

def nav_panel(
    title: TagChild,
    *,
    value: Optional[str] = None,
    icon: TagChild = None,
):
    """
    Create a nav item pointing to some internal content.

    This function wraps :func:`~shiny.ui.nav`.

    Parameters
    ----------
    title
        A title to display. Can be a character string or UI elements (i.e., tags).
    value
        The value of the item. This is used to determine whether the item is active
        (when an ``id`` is provided to the nav container), programmatically select the
        item (e.g., :func:`~shiny.ui.update_navs`), and/or be provided to the
        ``selected`` argument of the navigation container (e.g.,
        :func:`~shiny.ui.navset_tab`).
    icon
        An icon to appear inline with the button/link.
    """
    return RecallContextManager(
        ui.nav_panel,
        args=(title,),
        kwargs=dict(
            value=value,
            icon=icon,
        ),
    )

# ======================================================================================
# Page components
# ======================================================================================
def page_fluid(
    *,
    title: Optional[str] = None,
    lang: Optional[str] = None,
    **kwargs: str,
) -> RecallContextManager[Tag]:
    """
    Create a fluid page.

    This function wraps :func:`~shiny.ui.page_fluid`.

    Parameters
    ----------
    title
        The browser window title (defaults to the host URL of the page). Can also be set
        as a side effect via :func:`~shiny.ui.panel_title`.
    lang
        ISO 639-1 language code for the HTML page, such as ``"en"`` or ``"ko"``. This
        will be used as the lang in the ``<html>`` tag, as in ``<html lang="en">``. The
        default, `None`, results in an empty string.
    **kwargs
        Attributes on the page level container.

    Returns
    -------
    :
        A UI element.
    """
    return RecallContextManager(
        ui.page_fluid,
        kwargs=dict(
            title=title,
            lang=lang,
            **kwargs,
        ),
    )

def page_fixed(
    *,
    title: Optional[str] = None,
    lang: Optional[str] = None,
    **kwargs: str,
) -> RecallContextManager[Tag]:
    """
    Create a fixed page.

    This function wraps :func:`~shiny.ui.page_fixed`.

    Parameters
    ----------
    title
        The browser window title (defaults to the host URL of the page). Can also be set
        as a side effect via :func:`~shiny.ui.panel_title`.
    lang
        ISO 639-1 language code for the HTML page, such as ``"en"`` or ``"ko"``. This
        will be used as the lang in the ``<html>`` tag, as in ``<html lang="en">``. The
        default, `None`, results in an empty string.
    **kwargs
        Attributes on the page level container.

    Returns
    -------
    :
        A UI element.
    """
    return RecallContextManager(
        ui.page_fixed,
        kwargs=dict(
            title=title,
            lang=lang,
            **kwargs,
        ),
    )

def page_fillable(
    *,
    padding: Optional[CssUnit | list[CssUnit]] = None,
    gap: Optional[CssUnit] = None,
    fillable_mobile: bool = False,
    title: Optional[str] = None,
    lang: Optional[str] = None,
    **kwargs: TagAttrValue,
):
    """
    Creates a fillable page.

    This function wraps :func:`~shiny.ui.page_fillable`.

    Parameters
    ----------
    padding
        Padding to use for the body. See :func:`~shiny.ui.css_unit.as_css_padding`
        for more details.
    fillable_mobile
        Whether or not the page should fill the viewport's height on mobile devices
        (i.e., narrow windows).
    gap
        A CSS length unit passed through :func:`~shiny.ui.css_unit.as_css_unit`
        defining the `gap` (i.e., spacing) between elements provided to `*args`.
    title
        The browser window title (defaults to the host URL of the page). Can also be set
        as a side effect via :func:`~shiny.ui.panel_title`.
    lang
        ISO 639-1 language code for the HTML page, such as ``"en"`` or ``"ko"``. This
        will be used as the lang in the ``<html>`` tag, as in ``<html lang="en">``. The
        default, `None`, results in an empty string.

    Returns
    -------
    :
        A UI element.
    """
    return RecallContextManager(
        ui.page_fillable,
        kwargs=dict(
            padding=padding,
            gap=gap,
            fillable_mobile=fillable_mobile,
            title=title,
            lang=lang,
            **kwargs,
        ),
    )

def page_sidebar(
    *,
    title: Optional[str | Tag | TagList] = None,
    fillable: bool = True,
    fillable_mobile: bool = False,
    window_title: str | MISSING_TYPE = MISSING,
    lang: Optional[str] = None,
    **kwargs: TagAttrValue,
):
    """
    Create a page with a sidebar and a title.

    This function wraps :func:`~shiny.ui.page_sidebar`.

    Parameters
    ----------
    sidebar
        Content to display in the sidebar.
    title
        A title to display at the top of the page.
    fillable
        Whether or not the main content area should be considered a fillable
        (i.e., flexbox) container.
    fillable_mobile
        Whether or not ``fillable`` should apply on mobile devices.
    window_title
        The browser's window title (defaults to the host URL of the page). Can also be
        set as a side effect via :func:`~shiny.ui.panel_title`.
    lang
        ISO 639-1 language code for the HTML page, such as ``"en"`` or ``"ko"``. This
        will be used as the lang in the ``<html>`` tag, as in ``<html lang="en">``. The
        default, `None`, results in an empty string.
    **kwargs
        Additional attributes passed to :func:`~shiny.ui.layout_sidebar`.

    Returns
    -------
    :
        A UI element.
    """
    return RecallContextManager(
        ui.page_sidebar,
        kwargs=dict(
            title=title,
            fillable=fillable,
            fillable_mobile=fillable_mobile,
            window_title=window_title,
            lang=lang,
            **kwargs,
        ),
    )


"""setup.py file for single_type_logit.c.

Note that since this is a numpy extension
we use numpy.distutils instead of
distutils from the python standard library.

Calling
$python setup.py build_ext --inplace
will build the extension library in the npufunc_directory.

Calling
$python setup.py build
will build a file that looks like ./build/lib*, where
lib* is a file that begins with lib. The library will
be in this file and end with a C library extension,
such as .so

Calling
$python setup.py install
will install the module in your site-packages file.

See the distutils section of
'Extending and Embedding the Python Interpreter'
at docs.python.org  and the documentation
on numpy.distutils for more information.
"""

def configuration(parent_package='', top_path=None):
    from numpy.distutils.misc_util import Configuration

    config = Configuration('np_sims',
                           parent_package,
                           top_path)
    config.add_extension('ufuncs', ['ufunc.c'])

    return config

if __name__ == "__main__":
    from numpy.distutils.core import setup
    setup(configuration=configuration)


n, s = map(int ,input().split())
arr = list(map(int, input().split()))
result = 0

def subset_sum(idx, sub_sum):
    global result

    if idx >= n:
        return

    sub_sum += arr[idx]

    if sub_sum == s:
        result += 1

    # 현재의 idx를 포함하지 않는 수열
    subset_sum(idx+1, sub_sum-arr[idx])

    # 현재의 idx를 포함하는 수열
    subset_sum(idx+1, sub_sum)

subset_sum(0, 0)
print(result)

백준/Silver/1182. 부분수열의 합/부분수열의 합.py


from reglang.dfa import dfa

#-----------------------#
delta = {  # DFA p.94 L&P (for minimization algo)
    (1, 'a') : 2,
    (1, 'b') : 4,
    (2, 'a') : 5,
    (2, 'b') : 3,
    (3, 'a') : 2,
    (3, 'b') : 6,
    (4, 'a') : 1,
    (4, 'b') : 5,
    (5, 'a') : 5,
    (5, 'b') : 5,
    (6, 'a') : 3,
    (6, 'b') : 5
}
dfa1 = dfa(delta=delta, start=1, finals={1, 3})
print('DFA that accepts (ab U ba)* is')
print(40*'-')
print(dfa1)
print(40*'-')

inputlist = ['', 'a', 'b', 'ab', 'ba', 'abbabaab', 'abaaba', 'bababa', 'babbab']
for inpstr in inputlist:
    if dfa1.accept(inpstr):
        print(f"'{inpstr}' accepted")
    else:
        print(f"'{inpstr}' not accepted")


__author__ = 'Zhenxin Lei'
import numpy as np
import pandas
import com.datautil.RiskCal.EqCVarCalImp as cVarCal

def rankReOverCvar(reMx, cvar ):
    '''

    :param reMx:
    :param cvar:
    :return:
        ranking result of stocks( column index)
    '''
    a=np.mean(reMx,0)/cvar

    array = np.array(a[0])
    for i in range(len(array)):

        if np.isnan(array[i]):

            array[i]=-float("inf")
    order = array.argsort()
    ranks = order.argsort()

    return ranks

def momRanking(reData, rankPers, holdPers, topPercent):
    """
    :param data:
        asset retrun dataframe
    :param rankPers:
    :param holdPers:
    :param topPercent:
    :return:
    """

    eqRe = reData.values
    [r, c] = np.shape(eqRe)
    date = []
    symbol = []
    alpha =0.06

    i = 0
    while i + rankPers - 1 <= r - 1:
        subperiod = eqRe[i:i + rankPers - 1, :]
        cVar = cVarCal.eqCVarCalImp(subperiod, alpha)
        print('return ', subperiod)
        print("c Var ",cVar)
        ranking = rankReOverCvar(subperiod, cVar)
        symbolindex = np.argsort(ranking)[::-1]

        symbolindex = symbolindex[:int(len(ranking) * topPercent / 100)]

        # date.append(i + rankPers)
        date.append(reData.index[i + rankPers])
        a=reData.axes[1][symbolindex]

        symbol.append(reData.axes[1][symbolindex])
        # date=date.append([reData.axes[0][i]])
        #symbol=symbol.append(reData.axes[1][symbolindex])
        if i+holdPers+rankPers>r-1:
            break
        i = i + holdPers

    rankindex = [i + 1 for i in range(int(c * topPercent / 100))]
    recomStkData = pandas.DataFrame(symbol, date, rankindex)
    print("recom stock ", recomStkData)
    #print(rankindex)

    return recomStkData


from mpl_toolkits.mplot3d import axes3d, Axes3D
import torch
import numpy as np
import matplotlib.pyplot as plt

obj_func = lambda x1, x2: x1 ** 2 + (x2-1)**2 + x1 + x2
x1 = torch.tensor(10.0, requires_grad=True)
x1_history = []
x2 = torch.tensor(5.0, requires_grad=True)
x2_history = []
y_history = []
eta1 = torch.tensor(-0.4)
eta2 = torch.tensor(-0.9)
thresh = 0.1

cnt = 0
while True:
    y = obj_func(x1, x2)
    y_history.append(y)
    x1_history.append(x1.item())
    x2_history.append(x2.item())
    if abs(y.item()) < thresh:
        break

    y.backward()
    x1 = torch.tensor(x1 + eta1 * x1.grad, requires_grad=True)
    x2 = torch.tensor(x2 + eta2 * x2.grad, requires_grad=True)
    cnt += 1
    if cnt > 1000:
        break

x1_plot = np.arange(-10, 10, 0.1)
x2_plot = np.arange(-10, 10, 0.1)
x1_mesh, x2_mesh = np.meshgrid(x1_plot, x2_plot)
print(x1_mesh.shape)
y_mesh = obj_func(x1_mesh, x2_mesh)

fig = plt.figure()
ax = Axes3D(fig)
ax.plot_wireframe(x1_mesh, x2_mesh, y_mesh)
ax.plot(x1_history, x2_history, y_history, color='red')
#plt.savefig("twodim.jpg")
plt.show()


# This calls the two functions defined in task 1d and displays the data

from floodsystem.geo import stations_by_river, rivers_with_station
from floodsystem.stationdata import build_station_list

def run():
    '''Requrements for Task 1D'''

    # Builds Stations List
    stations = build_station_list()

    # Compiles a list of rivers. prints the length and first ten
    riversWithStation = rivers_with_station(stations)
    print(len(riversWithStation))
    sortedList = sorted(riversWithStation)
    print(sortedList[:10])

    # Compiles a list of stations sorted by river and prints a list of stations on three rivers in particular
    stationsByRiver = stations_by_river(stations)
    riverAire = list()
    riverCam = list()
    riverThames = list()
    for station in stationsByRiver['River Aire']:
        riverAire.append(station.name)
        riverAire.sort()

    for station in stationsByRiver['River Cam']:
        riverCam.append(station.name)
        riverCam.sort()

    for station in stationsByRiver['River Thames']:
        riverThames.append(station.name)
        riverThames.sort()

    print(riverAire, '\n', riverCam, '\n', riverThames)

if __name__ == "__main__":
    run()


import meam_calculator as meamc
import numpy as np
from ase import Atoms, Atom
import matplotlib.pyplot as plt
import sys
from ase.build import bulk
from ase.visualize import view

def test_meam_potential():
  calc = meamc.setup_meam_calculator()
  #lengths = np.linspace(1, 5, 301)
  lengths = [5]
  potentials = []
  atomic_distances = []

  for i in range(len(lengths)):
    #atoms: Atoms = bulk('Zr', crystalstructure='hcp')
    #atoms.set_cell((atoms.get_cell().lengths() * i).tolist() + atoms.get_cell().angles().tolist(), scale_atoms=True)
    #print(atoms.get_cell())
    atoms = Atoms(2*'Zr', positions=[(0,0,0), (0, 0, lengths[i])])
    atoms.calc = calc
    potentials.append(atoms.get_potential_energy())
    atomic_distances.append(lengths[i])
  plt.plot(atomic_distances, potentials, color='green', linestyle='dashed')
  plt.xlabel("r Angstrom")
  plt.ylabel("Energy ev")
  plt.show()

  #Ni = bulk('Ni', cubic=True)
  #Fe = Atom('Fe', position=Ni.cell.diagonal()/2)
  #NiFe = Ni + Fe
  #NiFe.calc = calc
  #print("Energy ", NiFe.get_potential_energy())
  #Zr_1 = Atom('Fe', position=Zr.cell.diagonal()/2)
  #Zr2 = Zr + Zr_1
  #Zr2.calc = calc
  #print("Energy ", Zr2.get_potential_energy())

def main(argv):
  if argv[0] == "--test_meam":
    test_meam_potential()

if __name__ == "__main__":
  main(sys.argv[1:])


# Importing Libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Import dataset
dataset = pd.read_csv('Restaurant_Reviews.tsv', delimiter = '\t')
# library to clean data
import re

# Natural Language Tool Kit
import nltk

nltk.download('stopwords')

# to remove stopword
from nltk.corpus import stopwords

# for Stemming propose
from nltk.stem.porter import PorterStemmer

# Initialize empty array
# to append clean text
corpus = []

# 1000 (reviews) rows to clean
for i in range(0, 1000):

  # column : "Review", row ith
  review = re.sub('[^a-zA-Z]', ' ', dataset['Review'][i])

  # convert all cases to lower cases
  review = review.lower()

  # split to array(default delimiter is " ")
  review = review.split()

  #  #creating PorterStemmer object to
  #  #take main stem of each word
  ps = PorterStemmer()

  #  # loop for stemming each word
  #  # in string array at ith row
  review = [ps.stem(word) for word in review
         if not word in set(stopwords.words('english'))]

   # rejoin all string array elements
   # to create back into a string
  review = ' '.join(review)
  corpus.append(review)

from sklearn.feature_extraction.text import CountVectorizer

# To extract max 1500 feature.
# "max_features" is attribute to
# experiment with to get better results
cv = CountVectorizer(max_features = 1500)

#X contains corpus (dependent variable)
X = cv.fit_transform(corpus).toarray()

# y contains answers if review
# is positive or negative
y = dataset.iloc[:, 1].values

from sklearn.model_selection import train_test_split

# experiment with "test_size"
# to get better results
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.1,random_state = 0)
# Fitting Random Forest Classification
# to the Training set
from sklearn.ensemble import RandomForestClassifier

# n_estimators can be said as number of
# trees, experiment with n_estimators
# to get better results
model = RandomForestClassifier(n_estimators = 501,criterion = 'gini')

model.fit(X_train, y_train)
# Predicting the Test set results
y_pred = model.predict(X_test)

print(y_pred)
# Making the Confusion Matrix
from sklearn import metrics

cm = metrics.confusion_matrix(y_test, y_pred)
print(cm)

import seaborn as sns
sns.set(font_scale=1.4) # for label size
sns.heatmap(cm, annot=True, annot_kws={"size": 16}) # font size
plt.show()

print("Accuracy",metrics.accuracy_score(y_test, y_pred))
print("precision = ", metrics.precision_score(y_test,y_pred))
print("recall = ", metrics.recall_score(y_test,y_pred))


import random
from functools import partial

import torch
from ByrdLab.library.RandomNumberGenerator import RngPackage
from ByrdLab.library.dataset import DataPackage

from ByrdLab.library.initialize import RandomInitialize
from ByrdLab.library.measurements import multi_classification_accuracy
from ByrdLab.library.tool import adapt_model_type
from ByrdLab.tasks import Task

class softmaxRegression_model(torch.nn.Module):
    def __init__(self, feature_dimension, num_classes):
        super().__init__()
        self.linear = torch.nn.Linear(in_features=feature_dimension,
                                      out_features=num_classes, bias=True)
    def forward(self, features):
        features = features.view(features.size(0), -1)
        return self.linear(features)

def softmax_regression_loss(predictions, targets):
    loss = torch.nn.functional.cross_entropy(
                predictions, targets.type(torch.long).view(-1))
    return loss

def random_generator(dataset, batch_size=1, rng_pack: RngPackage=RngPackage()):
    while True:
        beg = rng_pack.random.randint(0, len(dataset)-1)
        if beg+batch_size <= len(dataset):
            yield dataset[beg:beg+batch_size]
        else:
            features, targets = zip(dataset[beg:beg+batch_size],
                                    dataset[0:(beg+batch_size) % len(dataset)])
            yield torch.cat(features), torch.cat(targets)

def order_generator(dataset, batch_size=1, rng_pack: RngPackage=RngPackage()):
    beg = 0
    while beg < len(dataset):
        end = min(beg+batch_size, len(dataset))
        yield dataset[beg:end]
        beg += batch_size

def full_generator(dataset, rng_pack: RngPackage=RngPackage()):
    while True:
        yield dataset[:]

class softmaxRegressionTask(Task):
    def __init__(self, data_package: DataPackage, batch_size=32):
        weight_decay = 0.01
        model = softmaxRegression_model(data_package.feature_dimension,
                                        data_package.num_classes)
        model = adapt_model_type(model)
        loss_fn = softmax_regression_loss
        test_fn = multi_classification_accuracy

        super_params = {
            'rounds': 100,
            'display_interval': 500,
            'batch_size': batch_size,
            'test_batch_size': 900,

            'lr': 9e-1,
        }

        test_set = data_package.test_set
        get_train_iter = partial(random_generator,
                                 batch_size=super_params['batch_size'])
        get_test_iter = partial(order_generator, dataset=test_set,
                                 batch_size=super_params['test_batch_size'])
        super().__init__(weight_decay, data_package, model,
                         loss_fn=loss_fn, test_fn=test_fn,
                         initialize_fn=RandomInitialize(),
                         get_train_iter=get_train_iter,
                         get_test_iter=get_test_iter,
                         super_params=super_params,
                         name=f'SR_{data_package.name}',
                         model_name='softmaxRegression')


import gym
import numpy as np
import random
import math
from gym import spaces, error

class enemy:
    def __init__(self, side, width, height):
        # 0:up, 1:down, 2:left, 3:right (from u,d,l,r)
        self.width = width
        self.height = height
        self.curve = 0
        if random.random() < 1/10 :
            self.curve = 1
        elif random.random() < 1/9 :
            self.curve = -1
        self.x = random.randrange(0,width)
        self.y = random.randrange(0,height)
        self.rad = math.pi/180
        self.angle = 0.
        if side == 0:
            self.y = 0
            self.angle = random.uniform(0, 180)
        elif side == 1:
            self.y = height
            self.angle = random.uniform(180, 360)
        elif side == 2:
            self.x = 0
            self.angle = random.uniform(-90, 90)
        elif side == 3:
            self.x = width
            self.angle = random.uniform(90, 270)
        self.dir_x = math.cos(self.angle * self.rad)
        self.dir_y = math.cos(self.angle * self.rad)
        self.speed = random.uniform(4,7)

    # move 1 timestep
    def move(self):
        self.angle += self.curve * random.uniform(-self.speed/4, self.speed/2)
        dx = self.speed * math.cos(self.angle * self.rad)
        dy = self.speed * math.sin(self.angle * self.rad)
        self.x = (self.x + dx) % self.width
        self.y = (self.y + dy) % self.height

    def getxy(self):
        return self.x, self.y

class Dodge(gym.Env):
    metadata = {'render.modes': ['human']
        , 'videos.frames_per_second': 30}

    # 30 fps
    def __init__(self):
        # Game Variables
        self.PAD_WIDTH = 400
        self.PAD_HEIGHT = 400
        self.MAN_SIZE = 10
        self.ENEMY_SIZE = 10
        self.ENEMY_NUM = 60
        self.SPEED = 6  # Player Speed

        # Gym Variables
        self.observation_size = 2 + self.ENEMY_NUM * 2
        self.action_space = spaces.Box(
            low = 0.,
            high = 1., shape=(1,),
            dtype=np.float32
        )
        self.observation_space = spaces.Discrete(self.observation_size)

        self.reset()

    # action : angle
    def step(self, action):
        self.score += 1
        angle = 2 * action * math.pi
        dx = self.SPEED * math.cos(angle)
        dy = self.SPEED * math.sin(angle)

        self.man_x += dx
        self.man_y += dy

        if self.man_x < 0:
            self.man_x = 0
        elif self.man_x > self.PAD_WIDTH - self.MAN_SIZE:
            self.man_x = self.PAD_WIDTH - self.MAN_SIZE
        if self.man_y < 0:
            self.man_y = 0
        elif self.man_y > self.PAD_HEIGHT - self.MAN_SIZE:
            self.man_y = self.PAD_HEIGHT - self.MAN_SIZE

        for enemy in self.enemies:
            enemy.move()

        if self.score >= 3000:
            self.done = True

        if self.check_crash():
            self.done = True

        state = self._get_game_state()
        reward = 1
        done = self.done
        score = self.score
        return state, reward, done, score

    def reset(self):
        self.man_x = self.PAD_WIDTH/2
        self.man_y = self.PAD_HEIGHT/2
        self.enemies = []
        for _ in range(self.ENEMY_NUM):
            self.enemies.append(enemy(random.randrange(0, 4), self.PAD_WIDTH, self.PAD_HEIGHT))

        self.screen = None
        self.score = 0
        self.done = False
        return self._get_game_state()

    def render(self, mode='human', close=False):
        try:
            import pygame
        except ImportError as e:
            raise error.DependencyNotInstalled(
                "{}. (HINT: install pygame using `pip install pygame`".format(e))
        if close:
            pygame.quit()
        else:
            # update render
            man_img = pygame.image.load('man.png')
            man_img = pygame.transform.scale(man_img, (self.MAN_SIZE, self.MAN_SIZE))
            enemy_img = pygame.image.load('enemy.png')
            enemy_img = pygame.transform.scale(enemy_img, (self.ENEMY_SIZE, self.ENEMY_SIZE))
            if self.screen is None:
                pygame.init()
                self.screen = pygame.display.set_mode((self.PAD_WIDTH, self.PAD_HEIGHT))
            clock = pygame.time.Clock()
            self.screen.fill((255, 255, 255))
            self.screen.blit(man_img, (self.man_x, self.man_y))
            for enemy in self.enemies:
                self.screen.blit(enemy_img, enemy.getxy())
            font = pygame.font.SysFont(None, 30)
            text = font.render('Score: {}'.format(self.score), True, (0, 0, 0))
            self.screen.blit(text, (self.PAD_WIDTH/2, 30))
            pygame.display.update()
            clock.tick(30)

    def close(self):
        pass

    # True : Crashed
    def check_crash(self):
        for enemy in self.enemies:
            # crash condition : man_x - ENEMY_SIZE < enemy.x < man_x + MAN_SIZE. (y is same)
            if (enemy.x > self.man_x - self.ENEMY_SIZE and
                    enemy.x < self.man_x + self.MAN_SIZE and
                    enemy.y > self.man_y - self.ENEMY_SIZE and
                    enemy.y < self.man_y + self.MAN_SIZE):
                return True
        return False

    def _get_game_state(self):
        state = []
        for enemy in self.enemies :
            x, y = enemy.getxy()
            state.append(x)
            state.append(y)
        state.append(self.man_x)
        state.append(self.man_y)

        return np.reshape(state, [1, self.observation_size])


# [BOJ] 2822. 점수 계산  2022-07-15

scores = [0] * 8
for i in range(8):
    scores[i] = int(input())

new_scores = sorted(scores)
ans = 0
idxs = []
for i in range(1, 6):
    ans += new_scores[-i]
    for j in range(8):
        if new_scores[-i] == scores[j]:
            idxs.append(j + 1)

new_idxs = sorted(idxs)

print(ans)
for i in new_idxs:
    print(i, end=" ")


import argparse
import json
import os
import shutil
import time
from typing import Dict

import pandas as pd

from ..preprocessing import preprocessor
from ..serving.predictor import BanditPredictor
from ..utils import feature_importance, model_constructors, model_trainers, utils

logger = utils.get_logger(__name__)

def num_float_dim(data):
    return len(data["X_float"].columns)

def train(
    training_df: pd.DataFrame,
    ml_config: Dict,
    feature_config: Dict,
    predictor_save_dir: str = None,
) -> BanditPredictor:

    start = time.time()

    utils.validate_ml_config(ml_config)

    logger.info("Checking schema of training data...")
    utils.validate_training_data_schema(training_df)

    if len(training_df) == 0:
        logger.error(f"Got no raws of training data. Training aborted.")
        return None

    logger.info(f"Got {len(training_df)} rows of training data.")
    logger.info(training_df.head())

    utils.fancy_print("Kicking off data preprocessing")

    # always add decision as a feature to use if not using all features
    features_to_use = ml_config["features"].get("features_to_use", ["*"])
    if features_to_use != ["*"]:
        features_to_use.append(preprocessor.DECISION_FEATURE_NAME)
    features_to_use = list(set(features_to_use))
    dense_features_to_use = ml_config["features"].get("dense_features_to_use", ["*"])

    data = preprocessor.preprocess_data(
        training_df,
        feature_config,
        ml_config["reward_type"],
        features_to_use,
        dense_features_to_use,
    )
    X, y = preprocessor.data_to_pytorch(data)

    model_type = ml_config["model_type"]
    model_params = ml_config["model_params"][model_type]
    reward_type = ml_config["reward_type"]

    feature_importance_params = ml_config.get("feature_importance", {})
    if feature_importance_params.get("calc_feature_importance", False):
        # calculate feature importances - only works on non id list features at this time
        utils.fancy_print("Calculating feature importances")
        feature_scores = feature_importance.calculate_feature_importance(
            reward_type=reward_type,
            feature_names=data["final_float_feature_order"],
            X=X,
            y=y,
        )
        feature_importance.display_feature_importances(feature_scores)

        # TODO: Make keeping the top "n" features work in predictor. Right now
        # using this feature breaks predictor, so don't use it in a final model,
        # just use it to experiment in seeing how model performance is.
        if feature_importance_params.get("keep_only_top_n", False):
            utils.fancy_print("Keeping only top N features")
            X, final_float_feature_order = feature_importance.keep_top_n_features(
                n=feature_importance_params["n"],
                X=X,
                feature_order=data["final_float_feature_order"],
                feature_scores=feature_scores,
            )
            data["final_float_feature_order"] = final_float_feature_order
            logger.info(f"Keeping top {feature_importance_params['n']} features:")
            logger.info(final_float_feature_order)

    utils.fancy_print("Starting training")
    # build the model
    if model_type == "neural_bandit":
        model_spec, model = model_constructors.build_pytorch_net(
            feature_specs=feature_config["features"],
            product_sets=feature_config["product_sets"],
            float_feature_order=data["final_float_feature_order"],
            id_feature_order=data["final_id_feature_order"],
            reward_type=reward_type,
            layers=model_params["layers"],
            activations=model_params["activations"],
            dropout_ratio=model_params["dropout_ratio"],
            input_dim=num_float_dim(data),
        )
        logger.info(f"Initialized model: {model}")
    elif model_type == "linear_bandit":
        assert utils.pset_features_have_dense(feature_config["features"]), (
            "Linear models require that product set features have associated"
            "dense representations."
        )
        model = model_constructors.build_linear_model(
            reward_type=reward_type,
            penalty=model_params.get("penalty"),
            alpha=model_params.get("alpha"),
        )
        model_spec = None
    elif model_type == "gbdt_bandit":
        assert utils.pset_features_have_dense(feature_config["features"]), (
            "GBDT models require that product set features have associated"
            "dense representations."
        )
        model = model_constructors.build_gbdt(
            reward_type=reward_type,
            learning_rate=model_params["learning_rate"],
            n_estimators=model_params["n_estimators"],
            max_depth=model_params["max_depth"],
        )
        model_spec = None
    elif model_type == "random_forest_bandit":
        assert utils.pset_features_have_dense(feature_config["features"]), (
            "Random forest models require that product set features have associated"
            "dense representations."
        )
        model = model_constructors.build_random_forest(
            reward_type=reward_type,
            n_estimators=model_params["n_estimators"],
            max_depth=model_params["max_depth"],
        )
        model_spec = None

    # build the predictor
    predictor = BanditPredictor(
        feature_config=feature_config,
        float_feature_order=data["float_feature_order"],
        id_feature_order=data["id_feature_order"],
        id_feature_str_to_int_map=data["id_feature_str_to_int_map"],
        transforms=data["transforms"],
        imputers=data["imputers"],
        model=model,
        model_type=model_type,
        reward_type=reward_type,
        model_spec=model_spec,
        dense_features_to_use=dense_features_to_use,
    )

    # train the model
    if model_type == "neural_bandit":
        logger.info(f"Training {model_type} for {model_params['max_epochs']} epochs")
        skorch_net = model_trainers.fit_custom_pytorch_module_w_skorch(
            reward_type=reward_type,
            model=predictor.model,
            X=X,
            y=y,
            hyperparams=model_params,
            train_percent=ml_config["train_percent"],
        )
    elif model_type in ("gbdt_bandit", "random_forest_bandit", "linear_bandit"):
        logger.info(f"Training {model_type}")
        sklearn_model, _ = model_trainers.fit_sklearn_model(
            reward_type=reward_type,
            model=model,
            X=X,
            y=y,
            train_percent=ml_config["train_percent"],
        )

    if predictor_save_dir is not None:
        logger.info("Saving predictor artifacts to disk...")
        model_name = ml_config.get("model_name", "model")

        save_dir = f"{predictor_save_dir}/{model_name}/"
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)

        predictor_net_path = f"{save_dir}/{model_name}.pt"
        predictor_config_path = f"{save_dir}/{model_name}.json"
        predictor.config_to_file(predictor_config_path)
        predictor.model_to_file(predictor_net_path)
        shutil.make_archive(save_dir, "zip", save_dir)

    logger.info(f"Traning took {time.time() - start} seconds.")

    return predictor


#!/usr/bin/env python
# -*- coding:utf-8 _*-
"""
:Author     :weijinlong
:Time: 2019/5/24 14:01
:File       : tfos.py
"""
import math
import os

import tensorflow as tf
from tensorflowonspark import TFCluster

from tfos.base import ext_exception, logger
from tfos.base.gfile import ModelDir
from tfos.nets.yolov3.worker import YOLOV3ModelTrainWorker, YOLOV3TinyModelTrainWorker

class YoloTFOS(object):
    def __init__(self, sc, sqlc, cluster_size=2, num_ps=1, input_mode=TFCluster.InputMode.SPARK):
        self.sc = sc
        self.sqlc = sqlc
        self.cluster_size = cluster_size
        self.num_ps = num_ps
        self.input_mode = input_mode
        self.cluster = None
        self.tf_args = {}

    @property
    def num_workers(self):
        num_workers = self.cluster_size - self.num_ps
        assert num_workers > 0, "cluster_size, num_ps must be positive, and cluster_size > num_ps"
        return num_workers

    @ext_exception('yolov3 train model')
    def yolov3_train(self, model_rdd, data_dir, batch_size, epochs, image_size, model_dir, weights_path=None,
                     freeze_body=2, go_on=False):
        train_path = os.path.join(data_dir, 'train.txt')
        assert tf.io.gfile.exists(train_path), "train dataset path not exists!"
        data_rdd = self.sc.textFile(train_path)
        n_samples = data_rdd.count()
        steps_per_epoch = math.ceil(n_samples / batch_size / self.num_workers)
        md = ModelDir(model_dir, 'train*')
        if go_on:
            md.create_model_dir()
        else:
            md = md.rebuild_model_dir()
        worker = YOLOV3ModelTrainWorker(model_rdd,
                                        data_dir,
                                        go_on=go_on,
                                        batch_size=batch_size,
                                        epochs=epochs,
                                        image_size=image_size,
                                        steps_per_epoch=steps_per_epoch,
                                        freeze_body=freeze_body,
                                        **md.to_dict())
        cluster = TFCluster.run(self.sc, worker, self.tf_args, self.cluster_size, self.num_ps,
                                input_mode=self.input_mode)
        cluster.train(data_rdd, num_epochs=epochs, feed_timeout=60000)
        cluster.shutdown()
        results = md.read_result()
        if results:
            return self.sqlc.createDataFrame(results)

    @ext_exception('yolov3 tiny train model')
    def yolov3_tiny_train(self, model_rdd, batch_size, epochs, classes_path, anchors_path, train_path,
                          val_path, image_size, model_dir, weights_path=None, freeze_body=2, go_on=False):
        columns = model_rdd.columns
        assert "model_config" in columns, "not exists model layer config!"
        assert tf.io.gfile.exists(train_path), "train dataset path not exists!"
        data_rdd = self.sc.textFile(train_path)
        n_samples = data_rdd.count()
        steps_per_epoch = math.ceil(n_samples / batch_size / self.num_workers)
        md = ModelDir(model_dir, 'train*')
        if go_on:
            md.create_model_dir()
        else:
            md = md.rebuild_model_dir()
        worker = YOLOV3TinyModelTrainWorker(model_rdd,
                                            go_on=go_on,
                                            batch_size=batch_size,
                                            epochs=epochs,
                                            classes_path=classes_path,
                                            anchors_path=anchors_path,
                                            weights_path=weights_path,
                                            val_path=val_path,
                                            image_size=image_size,
                                            steps_per_epoch=steps_per_epoch,
                                            freeze_body=freeze_body,
                                            **md.to_dict())
        cluster = TFCluster.run(self.sc, worker, self.tf_args, self.cluster_size, self.num_ps,
                                input_mode=self.input_mode)
        cluster.train(data_rdd, num_epochs=epochs, feed_timeout=60000)
        cluster.shutdown()
        results = md.read_result()
        return self.sqlc.createDataFrame(results)


from flask import *
from flask_cors import CORS
from get_database import get_database

app = Flask(
    __name__,
    static_folder="public",
    static_url_path="/"
)
CORS(app, origins="http://localhost:5173")

@app.route("/")
def index():
    return "Hello, world!"

@app.route("/fetch_all_photos")
def fetch_all_photos():
    page_num = int(request.args.get('page'))
    page_size = 50
    skip_count = (page_num - 1) * page_size

    db = get_database('exchange_japan')
    collection = db.photos
    data = list(collection.find({}, {"_id": 0}).sort("iso_date", 1).skip(skip_count).limit(page_size))
    return jsonify(data)
    db.close()

@app.route("/fetch_photo/", methods=['GET'])
def fetch_photo():
    name = request.args.get('name')
    print(f"Received name parameter: {name}")

    db = get_database('exchange_japan')
    collection = db.photos
    data = collection.find_one({'name': name}, {"_id": 0})
    print(f"Result from database: {data}")

    if data is None:
        # 如果找不到對應的照片資料，回傳 404 錯誤
        return jsonify({'error': 'Photo not found'}), 404
    return jsonify(data)
    db.close()

@app.route("/update_photo/", methods=['POST'])
def update_photo():
    try:
        data = request.json
        db = get_database('exchange_japan')
        collection = db.photos
        query = {'name': data['name']}
        collection.update_one(query, {'$set':
            {
                'description': data['description'],
                'colors': data['colors'],
                'places': data['places']
            }
        })
        print(f"已經更新{data['name']}的資料到資料庫")
        return jsonify({
            "message": "資料更新成功",
            "data": data
        })
    except Exception as e:
        # 如果發生錯誤，回傳錯誤訊息
        return jsonify({"error": str(e)}), 500
    db.close()

if __name__ == "__main__":
    app.run(port=3000)


from __future__ import annotations
import pyglet

from typing import TYPE_CHECKING, Optional

from konkyo.utils.gl import *
from konkyo.objects.component import BatchComponent
from pyglet.graphics.shader import Shader, ShaderProgram
from konkyo.structs.vector import Vector

if TYPE_CHECKING:
    from konkyo.asset.image import ImageAsset

vert = Shader("""#version 420 core
    in vec4 position;
    in vec4 color;
    in vec2 uv;

    out vec4 frag_color;
    out vec2 frag_uv;

    layout(binding = 0) uniform WindowBlock
    {
        mat4 projection;
        mat4 view;
    } window;

    void main()
    {
        gl_Position = window.projection * window.view * position;
        //gl_Position = projection * view * position;

        frag_color = color;
        frag_uv = uv;
    }
""", 'vertex')

frag = Shader("""#version 420 core
    in vec4 frag_color;
    in vec2 frag_uv;

    uniform sampler2D tex;

    out vec4 out_color;

    void main()
    {
        out_color = texture(tex, frag_uv) * frag_color;
    }
""", 'fragment')

program = ShaderProgram(vert, frag)

class SpriteGroup(pyglet.graphics.Group):
    def __init__(self, image: ImageAsset):
        super().__init__(program)
        self.image = image

    def set_state(self):
        self.program.use_program()

        # self.program['projection'] = pyglet.matrix.create_orthogonal(0, 160 * 4, 0, 144 * 4, 0, 1)
        # self.program['view'] = pyglet.matrix.Mat4()

        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, self.image.pyglet_image.get_texture().id)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)

        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    def unset_state(self):
        glDisable(GL_BLEND)
        glBindTexture(GL_TEXTURE_2D, 0)
        self.program.stop_program()

class Sprite(BatchComponent):

    def on_spawn(self, image: ImageAsset, scale: float = 1, layer: int = 0):
        """
        A sprite object. These are loaded from an image.

        Args:
            img ([type]): the image to use
            batch ([type], optional): the pyglet batch to render this sprite.
                                      Defaults to None.
        """
        self._image = image
        self._group = SpriteGroup(image)

        self.vertex_list = self.scene.batch.pyglet_batch.add_indexed(
            4, pyglet.gl.GL_TRIANGLES, self._group, [0, 1, 2, 0, 2, 3],
            'position3f',
            # FIXME: 'color3B' (255, 255, 255) higher than (1.0, 1.0, 1.0)?
            ('color3f', (1.0, 1.0, 1.0) * 4),
            'uv2f'
        )

        self._scale = scale

        # offset of position due to inverse scaling
        self._offset = Vector(0, 0)

        self.is_flipped_x = False
        self.is_flipped_y = False

        self._scale_x, self._scale_y = 1, 1

        self._width, self._height = self.orig_width, self.orig_height

        # texture coordinates
        self._s, self._t = (0, 1), (0, 1)

        self.update_vertex_data()

    def update_vertex_data(self):
        """
        Update the vertex data for this sprite.
        Call this when changing any property of the sprite.
        """
        adj_pos = self.position + self.offset
        sc_x, sc_y = self._scale_x, self._scale_y
        x, y = adj_pos.x, adj_pos.y
        w, h = self._width * sc_x * self._scale, self._height * sc_y * self._scale
        s, t = self._s, self._t

        self.vertex_list.position[:] = [
            x,         y, 0,
            x + w,     y, 0,
            x + w, y + h, 0,
            x,     y + h, 0,
        ]

        self.vertex_list.uv[:] = [
            s[0], t[0],
            s[1], t[0],
            s[1], t[1],
            s[0], t[1]
        ]

    @property
    def image(self) -> ImageAsset:
        return self._image

    @image.setter
    def image(self, image: ImageAsset):
        self._image = image
        self.pyglet_group.tex = (image.pyglet_image
                                 .get_image_data()
                                 .create_texture(pyglet.image.Texture))

    @property
    def width(self) -> int:
        return self._width

    @width.setter
    def width(self, width: int):
        self._width = width
        self.update_vertex_data()

    @property
    def height(self) -> int:
        return self._height

    @height.setter
    def height(self, height: int):
        self._height = height
        self.update_vertex_data()

    def set_tex_coords(self, s: tuple, t: tuple):
        assert (isinstance(s, tuple)
                and isinstance(t, tuple))
        self._s = s
        self._t = t
        self.update_vertex_data()

    @property
    def orig_width(self) -> int:
        return self.image.pyglet_image.width

    @property
    def orig_height(self) -> int:
        return self.image.pyglet_image.height

    def flip_x(self, flipped: Optional[bool] = None):

        flipped = not self.is_flipped_x if flipped is None else flipped

        if flipped is not self.is_flipped_x:
            self.set_scale_x(self._scale_x * -1)
            self.is_flipped_x = flipped
            self.on_position_change()

    def flip_y(self, flipped: Optional[bool] = None):

        flipped = not self.is_flipped_y if flipped is None else flipped

        if flipped is not self.is_flipped_y:
            self.set_scale_y(self._scale_y * -1)
            self.is_flipped_y = flipped
            self.on_position_change()

    @property
    def offset(self) -> Vector:
        x, y = tuple(self._offset)
        if self.is_flipped_x: x *= -1
        if self.is_flipped_y: y *= -1
        return Vector(x, y)

    @offset.setter
    def offset(self, offset: tuple):
        self._offset = offset
        self.update_vertex_data()

    def set_scale(self, n: float):
        """
        Sets the scale of the sprite.
        """
        self._scale_x = n
        self._scale_y = n
        self.update_vertex_data()

    def set_scale_x(self, n: float):
        """
        Sets the scale of the sprite.
        """
        self._scale_x = n
        self.update_vertex_data()

    def set_scale_y(self, n: float):
        """
        Sets the scale of the sprite.
        """
        self._scale_y = n
        self.update_vertex_data()

    def on_position_change(self):

        self.update_vertex_data()
        # self.pyglet_sprite.draw()

    def on_set_visible(self):

        self.update_vertex_data()

    def on_set_hidden(self):

        self.update_vertex_data()


import logging
from typing import Dict

import torch
from torch import nn

from rae.data.vision.datamodule import MetaData
from rae.modules.enumerations import Output
from rae.modules.passthrough import PassThrough
from rae.utils.tensor_ops import freeze, get_resnet_model

pylogger = logging.getLogger(__name__)

class ResNet(nn.Module):
    def __init__(
        self,
        metadata: MetaData,
        resnet_size: int,
        hidden_features: int,
        use_pretrained: bool,
        finetune: bool,
        **kwargs,
    ) -> None:
        super().__init__()
        pylogger.info(f"Instantiating <{self.__class__.__qualname__}>")

        self.metadata = metadata

        self.finetune = finetune
        self.resnet, self.resnet_features = get_resnet_model(resnet_size=resnet_size, use_pretrained=use_pretrained)
        self.resnet.fc = PassThrough()
        if not finetune:
            freeze(self.resnet)

        self.resnet_post_fc = nn.Sequential(
            nn.Linear(in_features=self.resnet_features, out_features=self.resnet_features),
            nn.BatchNorm1d(num_features=self.resnet_features),
            nn.Tanh(),
            nn.Linear(in_features=self.resnet_features, out_features=hidden_features),
            nn.Tanh(),
        )

        self.final_layer = nn.Linear(in_features=hidden_features, out_features=len(self.metadata.class_to_idx))

    def set_finetune_mode(self) -> None:
        if not self.finetune:
            self.resnet.eval()

    def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]:
        output = latents = self.resnet(x)
        output = self.resnet_post_fc(output)
        output = self.final_layer(output)
        return {
            Output.LOGITS: output,
            Output.DEFAULT_LATENT: latents,
            Output.BATCH_LATENT: latents,
        }


import vrep # access all the VREP elements
import sys
import numpy as np
import time
import math
import scipy.io
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
from acmR5_fitness import fitness

# mat = scipy.io.loadmat('matlabtrajdata.mat')

class Network:
    def __init__(self, n):
        # TODO: network from csv
        self.w = {}

class Matsuoka:

    def __init__(self, id, tr, ta, beta, w12, w21, A, weij=1, q=1, dt = 0.05, s1=1, s2=1, kp = -0.35, fb1 = 0, fb2 = 0, fk=1):
        # all zero will be equilibrium point, need slightly different initial value to trigger the oscillation
        # inner states of the oscillator
        self.u1=0.00000001
        self.u2=0
        self.v1=0
        self.v2=0

        self.y1=0
        self.y2=0

        self.id=id
        self.fk = fk  # tuning frequency for tau_r and tau_a
        self.tau_r = tr * self.fk
        self.tau_a = ta * self.fk
        self.s1 = s1
        self.s2 = s2
        self.fb1 = fb1
        self.fb2 = fb2

        self.beta = beta
        self.w12 = w12
        self.w21 = w21
        self.weij = weij
        self.q = q
        self.dt = dt
        self.A = A

        self.kp = kp # feedback coefficient for position

        # joint position input command memory, extract current theta command from self.theta[-1]
        self.theta = [0]

        # du1 = 1 / self.tau_r * (-self.u1 - self.beta * self.v1 - self.w12 * self.y2 + self.weij + self.s1)
        # dv1 = 1 / self.tau_a * (-self.v1 + self.y1 ** self.q)
        # self.u1 += du1 * self.dt
        # self.v1 += dv1 * self.dt
        # self.y1 = max(0, self.u1)

    def _step(self, fb = 0):

        # computing feedback terms from the sensor
        self.fb1 = self.kp * fb
        self.fb2 = -self.kp * fb

        du1 = 1/self.tau_r * (-self.u1 - self.beta*self.v1 - self.w12*self.y2 + self.weij + self.s1 + self.fb1)
        dv1 = 1/self.tau_a * (-self.v1 + self.y1**self.q)

        du2 = 1/self.tau_r * (-self.u2 - self.beta*self.v2 - self.w21*self.y1 + self.weij + self.s2 + self.fb2)
        dv2 = 1/self.tau_a * (-self.v2 + self.y2**self.q)

        # RK2
        # k1_u1 = du1 * self.dt
        # k1_v1 = dv1 * self.dt
        # k1_u2 = du2 * self.dt
        # k1_v2 = dv2 * self.dt
        #
        # k2_u1 = 1/self.tau_r * (-(self.u1+k1_u1/2) - self.beta*(self.v1+k1_v1/2) - self.w12*self.y2 + self.weij + self.s1 + self.fb1)
        # k2_v1 = 1/self.tau_a * (-(self.v1+k1_v1/2) + self.y1**self.q)
        # k2_u2 = 1/self.tau_r * (-(self.u2+k1_u2/2) - self.beta*(self.v2+k1_v2/2) - self.w21*self.y1 + self.weij + self.s2 + self.fb2)
        # k2_v2 = 1/self.tau_a * (-(self.v2+k1_v2/2) + self.y2**self.q)
        #
        # self.u1 += k2_u1 * self.dt
        # self.v1 += k2_v1 * self.dt
        # self.u2 += k2_u2 * self.dt
        # self.v2 += k2_v2 * self.dt

        # Euler
        self.u1 += du1 * self.dt
        self.v1 += dv1 * self.dt
        self.u2 += du2 * self.dt
        self.v2 += dv2 * self.dt

        self.y1 = max(0, self.u1)
        self.y2 = max(0, self.u2)

        self.theta.append(self.A*(self.y1 - self.y2))

# def get_values(params, i):
#     q = 1
#
#     Tr = params[0]
#     Ta = params[1]
#     b = params[2]
#     wef = params[3]
#     S = params[4]
#
#     traj = list(mat['theta'+str(i)].T[0])

    # return traj

class robotSim:
    def __init__(self, robotName):
        id = -1
        count = 0
        while id == -1 and count < 10:
            id = vrep.simxStart('127.0.0.1',
                                  19999,
                                  True,
                                  True,
                                  5000,
                                  5)  # start a connection
        self.clientID = id
        if self.clientID == -1:
            print("Not connected to remote API server")
            sys.exit("Could not connect")
        # check if the connection is successfully achieved
        # if self.clientID!=-1:
        #     print ("Connected to remote API server")
        # else:
        #     print("Not connected to remote API server")
        #     sys.exit("Could not connect")

        returnCode, self.robotObj = vrep.simxGetObjectHandle(self.clientID, robotName, vrep.simx_opmode_blocking)
        self.resetFlag = None

        self.robotState = None

    def _reset(self):
        self.resetFlag = vrep.simxRemoveModel(clientID=self.clientID,
                                         objectHandle=self.robotObj,
                                         operationMode=vrep.simx_opmode_streaming) #_wait
        # print('Close Flag:', self.resetFlag)

        time.sleep(2.0)
        self.resetFlag, self.robotObj = vrep.simxLoadModel(clientID=self.clientID,
                                                     modelPathAndName='/Users/xuanliu/Documents/V-REP_PRO_EDU_V3_4_0_Mac/models/robots/mobile/ACM-R5-disabled.ttm',
                                                     operationMode=vrep.simx_opmode_oneshot_wait, # _wait
                                                     options=0)
        # print('Load Flag:', self.resetFlag)

    def update_state(self):
        self.robotState = vrep.simxGetObjectPosition(clientID=self.clientID,
                                                     objectHandle=self.robotObj,
                                                     relativeToObjectHandle=-1,
                                                     operationMode=vrep.simx_opmode_streaming)
        print('current robot position:')
        print(self.robotState)

    def run(self):
        return

def experiment(params):
    vrep.simxFinish(-1)

    robot = robotSim("ACMR")

    kp = params[0]
    w = {}
    for i in range(1, 9):
        w[i] = params[i]
    a = params[9]
    tr = params[10]
    ta = params[11]
    beta = params[12]

    print(params)
    J = {}
    for i in range(1, 9):
        J[i] = Matsuoka(id = i, tr = tr, ta = ta, beta = beta, w12 = w[i], w21 = w[i], A = a, kp = kp)
    #
    # pos = {}
    # for i in range(1, 9):
    #     pos[i] = []
    # Setting CPG oscillator output via PD controller(tuned and set in Vrep env) to the joints

    # t_init = time.time()

    # Read ACMR vJoints
    N = 6  # 8 Joints
    strV = 'ACMR_vJoint#'  # Joint Names
    jointV = strV
    jointsV = {}
    # Read Object Handle for all joints
    returnCode, jointsV[1] = vrep.simxGetObjectHandle(robot.clientID, jointV, vrep.simx_opmode_blocking)

    for i in range(N + 1):
        jointV = strV + str(i)
        returnCode, jointsV[i + 2] = vrep.simxGetObjectHandle(robot.clientID, jointV, vrep.simx_opmode_blocking)

        # vrep.simxStartSimulation(robot.clientID, vrep.simx_opmode_oneshot)
    # robot.update_state()
    # sx = robot.robotState[1][0]
    # sy = robot.robotState[1][1]

    # sx, sy = 0.6536598205566406, -1.9246925115585327
    robot.update_state()
    sx, sy = 0.0, 0.0
    for j in range(300):
        # if j == 2:
        #     robot.update_state()
        #     sx = robot.robotState[1][0]
        #     sy = robot.robotState[1][1]

        t0 = time.time()

            # vrep.simxGetJointPosition()
        # for i in range(1, 9):
        #     res, pos_temp = vrep.simxGetJointPosition(robot.clientID, jointsV[i], vrep.simx_opmode_streaming)
        #         # pos = pos * 180 / math.pi
        #     pos[i].append(pos_temp)

        for i in range(1, 9):
            J[i]._step()

        for i in range(1, 9):
            returnCode = vrep.simxSetJointTargetPosition(robot.clientID, jointsV[i], J[i].theta[-1],
                                                             vrep.simx_opmode_streaming)

        t_ = time.time() - t0
            # pause .01 sec
        time.sleep(.05 - t_)

    robot.update_state()
    ex, ey = robot.robotState[1][0], robot.robotState[1][1]

    robot._reset()

    time.sleep(.05)
    # print("Done")

    # print('cost ', time.time() - t_init, 'seconds.')

    # Shut down the rempote API
    # vrep.simxStopSimulation(robot.clientID, vrep.simx_opmode_oneshot)
    # print('Simulation stopped.')
    value = fitness(start_x=sx, start_y=sy, end_x=ex, end_y=ey, up_time=200*0.05)
    print('current score:', value)

    return value

# Close all opened connections
# vrep.simxFinish(-1)
#
# robot = robotSim("ACMR")
#
# # test_theta1 = []
# J = {}
# J[1] = Matsuoka(id = 1, tr=0.1642, ta=0.6418, beta=8.2401,  w12=5.3571, w21=5.3571, A=0.8539)
# J[2] = Matsuoka(id = 2, tr=0.1276, ta=0.6971, beta=7.5937,  w12=5.4866, w21=5.4866, A=0.7666)
# J[3] = Matsuoka(id = 3, tr=0.1746, ta=0.7378, beta=9.5590,  w12=5.1743, w21=5.1743, A=0.7863)
# J[4] = Matsuoka(id = 4, tr=0.2367, ta=0.5084, beta=8.9907,  w12=6.0466, w21=6.0466, A=0.9515)
# J[5] = Matsuoka(id = 5, tr=0.2674, ta=0.6203, beta=14.9224, w12=9.2390, w21=9.2390, A=1.5598)
# J[6] = Matsuoka(id = 6, tr=0.3250, ta=0.6065, beta=16.000,  w12=9.0270, w21=9.0270, A=1.5434)
# J[7] = Matsuoka(id = 7, tr=0.3527, ta=0.5620, beta=15.2292, w12=8.7594, w21=8.7594, A=1.4544)
# J[8] = Matsuoka(id = 8, tr=0.2862, ta=0.7722, beta=18.2860, w12=9.8201, w21=9.8201, A=1.2749)

# pos = {}
# for i in range(1, 9):
#     pos[i] = []
# Setting CPG oscillator output via PD controller(tuned and set in Vrep env) to the joints
if __name__ == '__main__':

    count = 10

    t_init = time.time()

    while count>0:
        count -= 1

        vrep.simxFinish(-1)

        robot = robotSim("ACMR")

        # test_theta1 = []
        J = {}
        J[1] = Matsuoka(id=1, tr=0.1642, ta=0.6418, beta=8.2401, w12=5.3571, w21=5.3571, A=0.8539)
        J[2] = Matsuoka(id=2, tr=0.1276, ta=0.6971, beta=7.5937, w12=5.4866, w21=5.4866, A=0.7666)
        J[3] = Matsuoka(id=3, tr=0.1746, ta=0.7378, beta=9.5590, w12=5.1743, w21=5.1743, A=0.7863)
        J[4] = Matsuoka(id=4, tr=0.2367, ta=0.5084, beta=8.9907, w12=6.0466, w21=6.0466, A=0.9515)
        J[5] = Matsuoka(id=5, tr=0.2674, ta=0.6203, beta=14.9224, w12=9.2390, w21=9.2390, A=1.5598)
        J[6] = Matsuoka(id=6, tr=0.3250, ta=0.6065, beta=16.000, w12=9.0270, w21=9.0270, A=1.5434)
        J[7] = Matsuoka(id=7, tr=0.3527, ta=0.5620, beta=15.2292, w12=8.7594, w21=8.7594, A=1.4544)
        J[8] = Matsuoka(id=8, tr=0.2862, ta=0.7722, beta=18.2860, w12=9.8201, w21=9.8201, A=1.2749)

        pos = {}
        for i in range(1, 9):
            pos[i] = []

        # Read ACMR vJoints
        N = 6  # 8 Joints
        strV = 'ACMR_vJoint#'  # Joint Names
        jointV = strV
        jointsV = {}
        # Read Object Handle for all joints
        returnCode, jointsV[1] = vrep.simxGetObjectHandle(robot.clientID, jointV, vrep.simx_opmode_blocking)

        for i in range(N + 1):
            jointV = strV + str(i)
            returnCode, jointsV[i + 2] = vrep.simxGetObjectHandle(robot.clientID, jointV, vrep.simx_opmode_blocking)

        # vrep.simxStartSimulation(robot.clientID, vrep.simx_opmode_oneshot)
        robot.update_state()

        for j in range(200):
            t0 = time.time()

            # vrep.simxGetJointPosition()
            for i in range(1, 9):
                res, pos_temp = vrep.simxGetJointPosition(robot.clientID, jointsV[i], vrep.simx_opmode_streaming)
                # pos = pos * 180 / math.pi
                pos[i].append(pos_temp)

            for i in range(1,9):
                J[i]._step(pos[i][-1])

            for i in range(1,9):
                returnCode = vrep.simxSetJointTargetPosition(robot.clientID, jointsV[i], J[i].theta[-1], vrep.simx_opmode_streaming)

            t_ = time.time() - t0
            # pause .01 sec
            time.sleep(.05 - t_)

        robot.update_state()

        robot._reset()

        time.sleep(.05)
        print("Done", count)

    print(count,' runs cost ', time.time()-t_init, 'seconds.')

    # Shut down the rempote API
    vrep.simxStopSimulation(robot.clientID, vrep.simx_opmode_oneshot)
    print('Simulation stopped.')

    # plt.plot(J[1].theta, color='r')
    # plt.plot(pos[1], color='b')
    # # plt.plot(J1.theta, color='g')
    #
    # plt.show()


import time
import webbrowser
import random

total_breaks = 3
break_count = 0

web_list = ["http://www.google.com", "http://twitter.com",
"http://www.youtube.com/watch?v=dQw4w9WgXcQ"]

print("This program started on "+time.ctime())
while(break_count < total_breaks):
    time.sleep(5)
    web = random.choice(web_list)
    webbrowser.open(web)
    break_count = break_count + 1