#----------------------------------------------------------------------------#
# Imports
#----------------------------------------------------------------------------#

import json
import dateutil.parser
import babel
from flask import (
Flask,
render_template,
request,
Response,
flash,
redirect,
url_for
)
from models import app, db, Venue, Artist, Show
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
import logging
from logging import Formatter, FileHandler
from flask_wtf import Form
from forms import *
from flask_migrate import Migrate
import sys
from datetime import *
from wtforms.validators import ValidationError
from flask_wtf import CsrfProtect

#----------------------------------------------------------------------------#
# App Config.
#----------------------------------------------------------------------------#

moment = Moment(app)
app.config.from_object('config')

#----------------------------------------------------------------------------#
# csrf Token
#----------------------------------------------------------------------------#
csrf = CsrfProtect()
csrf.init_app(app)

#----------------------------------------------------------------------------#
# Filters.
#----------------------------------------------------------------------------#

def format_datetime(value, format='medium'):
  date = dateutil.parser.parse(value)
  if format == 'full':
      format="EEEE MMMM, d, y 'at' h:mma"
  elif format == 'medium':
      format="EE MM, dd, y h:mma"
  return babel.dates.format_datetime(date, format, locale='en')

app.jinja_env.filters['datetime'] = format_datetime

#----------------------------------------------------------------------------#
# Controllers.
#----------------------------------------------------------------------------#
@app.route('/')
def index():
  return render_template('pages/home.html')

#  Venues
#  ----------------------------------------------------------------
@app.route('/venues')
def venues():
  # TODO: replace with real venues data.
  # num_shows should be aggregated based on number of upcoming shows per venue.
  area_venues = db.session.query(Venue.city,Venue.state).group_by(Venue.city,Venue.state).all()
  data=[]
  for v in area_venues:
      venues = db.session.query(Venue.id,Venue.name,Venue.num_upcoming_shows).filter(Venue.city==v[0],Venue.state==v[1]).all()
      data.append({"city": v[0],
      "state": v[1],
      "venues":venues})
  return render_template('pages/venues.html', areas=data);

#  Search for Venue
#  ----------------------------------------------------------------
@app.route('/venues/search', methods=['POST'])
def search_venues():
    term = '%' + request.form.get('search_term', '')+ '%'
    all_venue = Venue.query.with_entities(Venue.id, Venue.name, Venue.num_upcoming_shows).filter(Venue.name.ilike(term)).all()
    response=[]
    response = { "count": len(all_venue), "data": [{
            "id": venue.id,
            "name": venue.name,
            "num_upcoming_shows": venue.num_upcoming_shows,
          } for venue in all_venue]
        }
    return render_template('pages/search_venues.html', results=response, search_term=request.form.get('search_term', ''))

#  Show Venue
#  ----------------------------------------------------------------
@app.route('/venues/<int:venue_id>')
def show_venue(venue_id):
  venue = Venue.query.get(venue_id)
  past_shows = db.session.query(Artist, Show).join(Show).join(Venue).\
  filter(
        Show.venue_id == venue_id,
        Show.artist_id == Artist.id,
        Show.start_time < datetime.now()
        ).\
        all()
  upcoming_shows = db.session.query(Artist, Show).join(Show).join(Venue).\
  filter(
      Show.venue_id == venue_id,
      Show.artist_id == Artist.id,
      Show.start_time >= datetime.now()
      ).\
      all()

  all_geners=venue.genres.replace('{', '')
  all_geners=all_geners.replace('}', '')
  arr_geners=all_geners.split(",")
  data={
    "id": venue.id,
    "name": venue.name,
    "genres": arr_geners,
    "address": venue.address,
    "city": venue.city,
    "state": venue.state,
    "phone": venue.phone,
    "website": venue.website,
    "facebook_link": venue.facebook_link,
    "seeking_talent": venue.seeking_talent,
    "seeking_description":venue.seeking_description,
    "image_link": venue.image_link,
    "past_shows": [{
      "artist_id": artist.id,
      "artist_name": artist.name,
      "artist_image_link": artist.image_link,
      "start_time": str(show.start_time)
    } for artist, show  in past_shows] ,
    "upcoming_shows": [{
      "artist_id": artist.id,
      "artist_name": artist.name,
      "artist_image_link": artist.image_link,
      "start_time": str(show.start_time)
    } for artist, show  in upcoming_shows],
    "past_shows_count": len(past_shows),
    "upcoming_shows_count": len(upcoming_shows),
  }
  return render_template('pages/show_venue.html', venue=data)

#  Create Venue
#  ----------------------------------------------------------------
@app.route('/venues/create', methods=['GET'])
def create_venue_form():
  form = VenueForm()
  return render_template('forms/new_venue.html', form=form)

@app.route('/venues/create', methods=['POST'])
def create_venue_submission():
  errorFlag=False
  try:
      form=VenueForm(request.form)
      newVenue = Venue()
      if request.method=='POST' and form.validate():
          form.populate_obj(newVenue)
          db.session.add(newVenue)
          db.session.commit()
      else:
          errorFlag=True
          for error in form.errors:
              error_message = str(form.errors[error][0])
              flash(error_message)
  except:
      errorFlag=True
      flash('There is an error \'' + request.form['name'] + '\' could not be added.')
      db.session.rollback()
      print(sys.exc_info())
  finally:
      db.session.close()

  if not errorFlag:
      flash('Venue ' + request.form['name'] + ' was successfully listed!')

  return render_template('pages/home.html')

#  DELETE Venue
#  ----------------------------------------------------------------
@app.route('/venues/<int:venue_id>', methods=['DELETE'])
def delete_venue(venue_id):
    errorondelete=False
    try:
        venue=Venue.query.get(venue_id)
        db.session.delete(venue)
        db.session.commit()
    except:
        errorondelete=True
        db.session.rollback()
        print(sys.exc_info())
    finally:
        db.session.close()

    if not errorondelete:
        flash('Venue was successfully deleted!')
    else:
        flash('There is an error, could not be deleted.')
    return  render_template('pages/home.html')

#  EDIT Venue
#  ----------------------------------------------------------------
@app.route('/venues/<int:venue_id>/edit', methods=['GET'])
def edit_venue(venue_id):
  form = VenueForm()
  venue = Venue.query.get(venue_id)
  form.name.data = venue.name
  form.genres.data = venue.genres
  form.city.data = venue.city
  form.state.data = venue.state
  form.address.data = venue.address
  form.phone.data = venue.phone
  form.website.data = venue.website
  form.facebook_link.data = venue.facebook_link
  form.image_link.data = venue.image_link
  form.seeking_talent.data = venue.seeking_talent
  form.seeking_description.data = venue.seeking_description
  return render_template('forms/edit_venue.html', form=form, venue=venue)

@app.route('/venues/<int:venue_id>/edit', methods=['POST'])
def edit_venue_submission(venue_id):
  # TODO: take values from the form submitted, and update existing
  # venue record with ID <venue_id> using the new attributes
  errorFlag=False
  try:
      form = VenueForm(request.form)
      if request.method=='POST' and form.validate():
          venue = Venue.query.get(venue_id)
          form.populate_obj(venue)
          db.session.commit()
      else:
          errorFlag=True
          for error in form.errors:
              error_message = str(form.errors[error][0])
              flash(error_message)
  except:
      errorFlag=True
      flash('There is an error Venue \'' + request.form['name'] + '\' could not be edited.')
      db.session.rollback()
      print(sys.exc_info())
  finally:
      db.session.close()
  if not errorFlag:
      flash('Venue ' + request.form['name'] + ' was successfully edited!')

  return redirect(url_for('show_venue', venue_id=venue_id))

#  Artists
#  ----------------------------------------------------------------
@app.route('/artists')
def artists():
    artists = db.session.query(Artist.id, Artist.name).all()
    data=[]
    for a in artists:
        data.append({"id": a[0], "name": a[1]})
  # TODO: replace with real data returned from querying the database
    return render_template('pages/artists.html', artists=data)

@app.route('/artists/search', methods=['POST'])
def search_artists():
  # TODO: implement search on artists with partial string search. Ensure it is case-insensitive.
  # seach for "A" should return "Guns N Petals", "Matt Quevado", and "The Wild Sax Band".
  # search for "band" should return "The Wild Sax Band".
  term = '%' + request.form.get('search_term', '')+ '%'
  All_Artist = Artist.query.with_entities(Artist.id, Artist.name, Artist.num_upcoming_shows).filter(Artist.name.ilike(term)).all()
  response=[]
  response = { "count": len(All_Artist), "data": [{
          "id": artist.id,
          "name": artist.name,
          "num_upcoming_shows": artist.num_upcoming_shows,
        } for artist in All_Artist]
      }

  return render_template('pages/search_artists.html', results=response, search_term=request.form.get('search_term', ''))

@app.route('/artists/<int:artist_id>')
def show_artist(artist_id):
    # shows the venue page with the given venue_id
    # TODO: replace with real venue data from the venues table, using venue_id

    artist = Artist.query.filter_by(id=artist_id).all()[0]
    past_shows = db.session.query(Venue, Show).join(Show).join(Artist).\
    filter(
          Show.artist_id == artist_id,
          Show.venue_id == Venue.id,
          Show.start_time < datetime.now()
          ).\
          all()
    upcoming_shows = db.session.query(Venue, Show).join(Show).join(Artist).\
    filter(
        Show.artist_id == artist_id,
        Show.venue_id == Venue.id,
        Show.start_time >= datetime.now()
        ).\
        all()

    all_geners=artist.genres.replace('{', '')
    all_geners=all_geners.replace('}', '')
    arr_geners=all_geners.split(",")
    data={
    "id": artist.id,
    "name": artist.name,
    "genres": arr_geners,
    "city": artist.city,
    "state": artist.state,
    "phone": artist.phone,
    "website": artist.website,
    "facebook_link": artist.facebook_link,
    "seeking_venue": artist.seeking_venue,
    "seeking_description": artist.seeking_description,
    "image_link": artist.image_link,
    "past_shows": [{
      "venue_id": venue.id,
      "venue_name": venue.name,
      "venue_image_link": venue.image_link,
      "start_time": str(show.start_time)
    }  for venue, show in past_shows],
    "upcoming_shows": [{
      "venue_id": venue.id,
      "venue_name": venue.name,
      "venue_image_link": venue.image_link,
      "start_time": str(show.start_time)
    }  for venue, show in upcoming_shows],
    "past_shows_count": len(past_shows),
    "upcoming_shows_count": len(upcoming_shows)
    }
    return render_template('pages/show_artist.html', artist=data)

#  Edit Artist
#  ----------------------------------------------------------------
@app.route('/artists/<int:artist_id>/edit', methods=['GET'])
def edit_artist(artist_id):
  form = ArtistForm()
  # TODO: populate form with fields from artist with ID <artist_id>
  artist = Artist.query.get(artist_id)
  form.name.data = artist.name
  form.genres.data = artist.genres
  form.city.data = artist.city
  form.state.data = artist.state
  form.phone.data = artist.phone
  form.website.data = artist.website
  form.facebook_link.data = artist.facebook_link
  form.image_link.data = artist.image_link
  form.seeking_venue.data = artist.seeking_venue
  form.seeking_description.data = artist.seeking_description
  return render_template('forms/edit_artist.html', form=form, artist=artist)

@app.route('/artists/<int:artist_id>/edit', methods=['POST'])
def edit_artist_submission(artist_id):
  errorFlag=False
  form = ArtistForm(request.form)
  try:
      if request.method=='POST' and  form.validate():
          artist = Artist.query.get(artist_id)
          form.populate_obj(artist)
          db.session.commit()
      else:
          errorFlag=True
          for error in form.errors:
              error_message = str(form.errors[error][0])
              flash(error_message)
  except:
      errorFlag=True
      flash('There is an error Artist \'' + request.form['name'] + '\' could not be edited.')
      db.session.rollback()
      print(sys.exc_info())
  finally:
      db.session.close()

  if not errorFlag:
      flash('Artist ' + request.form['name'] + ' was successfully edited!')

  return redirect(url_for('show_artist', artist_id=artist_id))

#  Create Artist
#  ----------------------------------------------------------------

@app.route('/artists/create', methods=['GET'])
def create_artist_form():
  form = ArtistForm()
  return render_template('forms/new_artist.html', form=form)

@app.route('/artists/create', methods=['POST'])
def create_artist_submission():
  errorFlag=False
  form = ArtistForm(request.form)
  try:
      newArtist = Artist()
      if request.method=='POST' and form.validate():
          form.populate_obj(newArtist)
          db.session.add(newArtist)
          db.session.commit()
      else:
          errorFlag=True
          for error in form.errors:
              error_message = str(form.errors[error][0])
              flash(error_message)

  except:
      errorFlag=True
      flash('There is an error Artist \'' + request.form['name'] + '\' could not be added.')
      db.session.rollback()
      print(sys.exc_info())
  finally:
      db.session.close()

  if not errorFlag:
      flash('Artist ' + request.form['name'] + ' was successfully listed!')

  return render_template('pages/home.html')

#  DELETE Artist
#  ----------------------------------------------------------------
@app.route('/artists/<int:artist_id>', methods=['DELETE'])
def delete_artist(artist_id):
    errorondelete=False
    try:
        artist=Artist.query.get(artist_id)
        db.session.delete(artist)
        db.session.commit()
    except:
        errorondelete=True
        db.session.rollback()
        print(sys.exc_info())
    finally:
        db.session.close()

    if not errorondelete:
        flash('Artist was successfully deleted!')
    else:
        flash('There is an error, could not be deleted.')
    return render_template('pages/home.html')

#  Shows
#  ----------------------------------------------------------------

@app.route('/shows')
def shows():
  # displays list of shows at /shows
  # TODO: replace with real venues data.
  # num_shows should be aggregated based on number of upcoming shows per venue.
  try:
      today = datetime.now()
      all_shows= Show.query.filter(Show.start_time > today).all()
      data = []
      for show in all_shows:
        venue = Venue.query.get(show.venue_id)
        artist = Artist.query.get(show.artist_id)
        data.append({
          "venue_id": show.venue_id,
          "venue_name": venue.name,
          "artist_id": show.artist_id,
          "artist_name": artist.name,
          "artist_image_link": artist.image_link,
          "start_time": str(show.start_time)
          })
  except :
      print(sys.exc_info())

  return render_template('pages/shows.html', shows=data)

@app.route('/shows/create')
def create_shows():
  # renders form. do not touch.
  form = ShowForm()
  return render_template('forms/new_show.html', form=form)

@app.route('/shows/create', methods=['POST'])
def create_show_submission():
  # called to create new shows in the db, upon submitting new show listing form
  # TODO: insert form data as a new Show record in the db, instead
  errorFlag=False
  try:
      form=ShowForm(request.form)
      newShow = Show()
      if request.method=='POST' and form.validate():
          venue = Venue.query.get(request.form.get('venue_id'))
          venue.num_upcoming_shows = venue.num_upcoming_shows + 1
          artist = Artist.query.get(request.form.get('artist_id'))
          artist.num_upcoming_shows = artist.num_upcoming_shows + 1
          form.populate_obj(newShow)
          db.session.add(newShow)
          db.session.commit()
      else:
          errorFlag=True
          for error in form.errors:
              error_message = str(form.errors[error][0])
              flash(error_message)

  except  AttributeError as ae:
      errorFlag=True
      db.session.rollback()
      flash('The artist or veneu does not exist!')
  except:
      errorFlag=True
      db.session.rollback()
      print(sys.exc_info())
      flash('An error occurred. Show could not be listed.')
  finally:
      db.session.close()

  if not errorFlag:
      flash('Show was successfully listed!')

  return render_template('pages/home.html')

@app.errorhandler(404)
def not_found_error(error):
    return render_template('errors/404.html'), 404

@app.errorhandler(500)
def server_error(error):
    return render_template('errors/500.html'), 500

if not app.debug:
    file_handler = FileHandler('error.log')
    file_handler.setFormatter(
        Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
    )
    app.logger.setLevel(logging.INFO)
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.info('errors')

#----------------------------------------------------------------------------#
# Launch.
#----------------------------------------------------------------------------#

# Default port:
if __name__ == '__main__':
    app.run()

# Or specify port manually:
'''
if __name__ == '__main__':
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)
'''


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: Dango Wang
# time : 2019/6/17

import os
import random

from maya import cmds
from DCC_TOOLS.common.dcc_utils import *
from utils.common_methods import *
import maya.mel as mel
import pymel.core as pm
import mel_context
reload(mel_context)
import logging

try:
    from PySide2 import QtWidgets, QtCore

except ImportError:
    from PySide import QtGui as QtWidgets
    from PySide import QtCore

file_path = str(os.path.split(os.path.realpath(__file__))[0])
form_class, base_class = loadUiType(file_path + '\\ui.ui')

class NMWave(base_class, form_class):

    def __init__(self, parent=getMayaWindow()):
        super(NMWave, self).__init__(parent=parent)
        self.setupUi(self)
        self.load_source_pb.clicked.connect(lambda: self.load_selected(self.source_tw))
        self.load_target_pb.clicked.connect(lambda: self.load_selected(self.target_tw))
        self.source_clear_pb.clicked.connect(lambda: self.clear_items(self.source_tw))
        self.target_clear_pb.clicked.connect(lambda: self.clear_items(self.target_tw))

    @staticmethod
    def get_selected():
        return cmds.ls(sl=1) if cmds.ls(sl=1) else []

    @staticmethod
    def add_item(table_widget, label):
        contents = [table_widget.item(i, 0).text() for i in range(table_widget.rowCount())]
        if label in contents:
            return
        row_count = table_widget.rowCount()
        table_widget.setRowCount(row_count + 1)
        new_item = QtWidgets.QTableWidgetItem(label)
        table_widget.setItem(row_count, 0, new_item)
        return True

    @staticmethod
    def clear_items(item):
        item.setRowCount(0)
        item.clearContents()

    def load_selected(self, tw):
        map(self.add_item, [tw] * len(self.get_selected()), self.get_selected())

    @QtCore.Slot()
    def on_input_main_ctrl_pb_clicked(self):
        sel_obj = self.get_selected()
        if sel_obj:
            self.main_ctrl.setText(sel_obj[0])
        return

    @QtCore.Slot(name='on_doit_pb_clicked')
    @undoable
    def on_doit_pb_clicked(self):
        if not cmds.pluginInfo('DsfMyWave', query=1, loaded=1):
            try:
                cmds.loadPlugin('DsfMyWave.mll')
            except RuntimeError:
                raise RuntimeError('DsfMyWave.mll was not found on MAYA_PLUG_IN_PATH')
        sources = [self.source_tw.item(i, 0).text() for i in range(self.source_tw.rowCount())]
        targets = [self.target_tw.item(j, 0).text() for j in range(self.target_tw.rowCount())]
        main_ctrl = self.main_ctrl.text()
        if len(sources) != len(targets):
            logging.error(u'左右两边物体数量不一致！！')
            return False
        main_ctrl_node = cmds.createNode("DsfMyWave", name=main_ctrl + '_my_wave_node')
        add_str = "addAttr -ln \"t_offset\" -at double -min -100 -max 100 -dv -10 {0};" \
                  "setAttr -e -keyable true {0}.t_offset;" \
                  "addAttr -ln \"s_offset\" -at double -min -100 -max 100 -dv -10 {0};" \
                  "setAttr -e -keyable true {0}.s_offset;" \
                  "addAttr -ln \"t_on_off\" -at bool {0};" \
                  "setAttr -e -keyable true {0}.t_on_off;" \
                  "addAttr -ln \"s_on_off\" -at bool {0};" \
                  "setAttr -e -keyable true {0}.s_on_off;".format(main_ctrl)
        mel.eval(add_str)
        cmds.connectAttr(main_ctrl + '.t_on_off', main_ctrl_node + '.t_on_off')
        cmds.connectAttr(main_ctrl + '.s_on_off', main_ctrl_node + '.s_on_off')
        cmds.connectAttr(main_ctrl + '.t_offset', main_ctrl_node + '.t_offset')
        cmds.connectAttr(main_ctrl + '.s_offset', main_ctrl_node + '.s_offset')
        index = 0
        while index < len(sources):
            mel.eval(mel_context.get_mel_text({'ctrl': sources[index]}))
            ctrl_node = cmds.createNode("DsfMyWave", name=sources[index] + '_my_wave_node')
            cmds.connectAttr('time1.outTime', ctrl_node + '.inputTime')
            for each in ['.tx_amplitude', '.ty_amplitude', '.tz_amplitude', '.sx_amplitude', '.sy_amplitude',
                         '.sz_amplitude', '.s_min', '.t_frequency', '.s_frequency']:
                cmds.connectAttr(sources[index] + each, ctrl_node + each)
            for conn_attr in ['.translateX', '.translateY', '.translateZ', '.scaleX', '.scaleY', '.scaleZ']:
                cmds.connectAttr(ctrl_node + conn_attr, targets[index] + conn_attr)
            cmds.connectAttr(main_ctrl + '.t_on_off', ctrl_node + '.t_on_off')
            cmds.connectAttr(main_ctrl + '.s_on_off', ctrl_node + '.s_on_off')
            cmds.connectAttr(main_ctrl_node + '.t_wave_offset[%s]' % index, ctrl_node + '.t_offset')
            cmds.connectAttr(main_ctrl_node + '.s_wave_offset[%s]' % index, ctrl_node + '.s_offset')
            index += 1

    @QtCore.Slot(name='on_add_offset_doit_pb_clicked')
    @undoable
    def on_add_offset_doit_pb_clicked(self):
        sel = cmds.ls(sl=1)
        if sel:
            for each in sel:
                if not cmds.objExists(each + '.t_offset'):
                    continue
                cmds.addAttr(each, ln='wave_offset', at='double', dv=0)
                cmds.setAttr(each+'.wave_offset', e=1, keyable=1)
                out_wave_node = cmds.listConnections(each, s=0, d=1, type='DsfMyWave')[0]
                cmds.connectAttr(each+'.wave_offset', out_wave_node+'.offset')

    @QtCore.Slot(name='on_add_blink_pb_clicked')
    @undoable
    def on_add_blink_pb_clicked(self):
        self.bn = []
        self.random_blink_on_of = []
        random_seed = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 30, 33, 35, 37, 39, 41, 45, 49, 51, 57, 59]
        random_seed_1 = [0]
        random_seed_2 = [-1, 1]
        random_seed_3 = [0, 0, 1, 0.5]
        sources = [self.source_tw.item(i, 0).text() for i in range(self.source_tw.rowCount())]
        main_ctrl = self.main_ctrl.text()
        if not (sources and main_ctrl):
            logging.error(u'请输入正确信息！')
            return
        if sources:
            for s in sources:
                each = pm.PyNode(s)
                if not cmds.objExists(s+'.close_eye'):
                    continue
                if cmds.objExists(each.name() + '_random_blink_node'):
                    continue
                blink_node = pm.createNode('DsfMyBlink', name=(each.name() + '_random_blink_node'))
                self.bn.append(blink_node)
                pm.PyNode('time1').outTime >> blink_node.in_time

                plus_node = pm.PyNode(mel.eval('shadingNode -asUtility plusMinusAverage;'))
                blink_node.blink >> plus_node.input1D[1]
                for anim_crv in pm.listConnections(each.close_eye, s=0, d=1, p=1):
                    plus_node.output1D >> anim_crv
                each.close_eye >> plus_node.input1D[0]
                _str = 'select -r {ctrl};addAttr -ln "random_blink"  -at bool -dv 1  "{ctrl}";'\
                       'setAttr -e -keyable true {ctrl}.random_blink;'.format(**{'ctrl': s})
                mel.eval(_str)
                plus_node_2 = pm.PyNode(mel.eval('shadingNode -asUtility plusMinusAverage;'))
                plus_node_temp = pm.PyNode(mel.eval('shadingNode -asUtility plusMinusAverage;'))
                pm.setAttr(plus_node_temp.input1D[0], -1)
                each.random_blink >> plus_node_2.input1D[0]
                plus_node_2.output1D >> plus_node_temp.input1D[1]
                plus_node_temp.output1D >> blink_node.envelope
                self.random_blink_on_of.append(plus_node_2)
        if main_ctrl:
            if not cmds.objExists(main_ctrl+'.random_blink'):
                mel.eval(mel_context.blink_attr.format(**{'ctrl': main_ctrl}))
            mctl = pm.PyNode(main_ctrl)
            for a in self.random_blink_on_of:
                mctl.random_blink >> a.input1D[1]
            for b in self.bn:
                random_blink_offset = random_seed[random.randint(0, len(random_seed)-1)] * random_seed_2[
                    random.randint(0, len(random_seed_2)-1)]
                random_blink_speed = random_seed_1[random.randint(0, len(random_seed_1)-1)] * random_seed_2[
                    random.randint(0, len(random_seed_2)-1)]
                random_blink_interval = random_seed_3[random.randint(0, len(random_seed_3)-1)] * random_seed_2[
                    random.randint(0, len(random_seed_2)-1)]
                offset_p = pm.PyNode(mel.eval('shadingNode -asUtility plusMinusAverage;'))
                speed_p = pm.PyNode(mel.eval('shadingNode -asUtility plusMinusAverage;'))
                interval_p = pm.PyNode(mel.eval('shadingNode -asUtility plusMinusAverage;'))

                mctl.random_blink_offset >> offset_p.input1D[0]
                pm.setAttr(offset_p.input1D[1], random_blink_offset)
                offset_p.output1D >> b.frame_offset

                mctl.random_blink_speed >> speed_p.input1D[0]
                pm.setAttr(speed_p.input1D[1], random_blink_speed)
                speed_p.output1D >> b.speed

                mctl.random_blink_interval >> interval_p.input1D[0]
                pm.setAttr(interval_p.input1D[1], random_blink_interval)
                interval_p.output1D >> b.interval

    @QtCore.Slot(name='on_delete_old_attr_pb_clicked')
    @undoable
    def on_delete_old_attr_pb_clicked(self):
        for each in pm.ls(typ='DsfMyBlink'):
            blink_ctl = list(set(pm.listConnections(each, s=1, d=0, type='transform')))[0]
            plus_node = pm.listConnections(each.blink, s=0, d=1, p=1)
            for p in plus_node:
                blink_ctl.close_eye >> p
            pm.delete(each)
            pm.delete(pm.listConnections(blink_ctl.random_offset, s=0, d=1))
            mel.eval('catch (`deleteAttr -attribute "%s" "%s"`);' % ('random_blink', blink_ctl.name()))
            mel.eval('catch (`deleteAttr -attribute "%s" "%s"`);' % ('random_speed', blink_ctl.name()))
            mel.eval('catch (`deleteAttr -attribute "%s" "%s"`);' % ('random_offset', blink_ctl.name()))
            mel.eval('catch (`deleteAttr -attribute "%s" "%s"`);' % ('random_interval', blink_ctl.name()))

        # sel = pm.ls(sl=1)
        # if sel:
        #     for each in sel:
        #         if not pm.objExists(each.close_eye):
        #             continue
        #         mel.eval(mel_context.blink_attr.format(**{'ctrl': each.name()}))
        #         each.random_blink_offset >> random_num_plus.input1D[0]
        #         blink_node = pm.createNode('DsfMyBlink', name=each.name()+'_random_blink_node')
        #         pm.PyNode('time1').outTime >> blink_node.in_time
        #         each.random_blink >> blink_node.envelope
        #         each.random_blink_speed >> blink_node.speed
        #         random_num_plus.output1D >> blink_node.frame_offset
        #         each.random_blink_interval >> blink_node.interval
        #         plus_node = pm.PyNode(mel.eval('shadingNode -asUtility plusMinusAverage;'))
        #         blink_node.blink >> plus_node.input1D[1]
        #         for anim_crv in pm.listConnections(each.close_eye, s=0, d=1, p=1):
        #             plus_node.output1D >> anim_crv
        #         each.close_eye >> plus_node.input1D[0]
        #         # random_num = random.randint(0, 15)
        #         random_num_plus = pm.PyNode(mel.eval('shadingNode -asUtility plusMinusAverage;'))
        #
        #         # pm.setAttr(random_num_plus.input1D[1], random_num)
        # pm.select(sel)

if __name__ == '__main__':
    pass


# Oringinal code modified from client.py
# https://github.com/mozilla/DeepSpeech/blob/master/native_client/python/client.py

from spych.utils import error
from deepspeech import Model, version

import numpy as np
import shlex, subprocess, sys, wave, json

class spych(error):
    def __init__(self, model_file, scorer_file=None):
        """
        Initialize a spych class

        Required:

            - `model_file`:
                - Type: str
                - What: The location of your deepspeech model

        Optional:

            - `scorer_file`:
                - Type: str
                - What: The location of your deepspeech scorer
                - Default: None
        """
        self.model_file=model_file
        self.scorer_file=scorer_file
        self.model = Model(self.model_file)
        if self.scorer_file:
            self.model.enableExternalScorer(self.scorer_file)
        self.desired_sample_rate=self.model.sampleRate()

    def execute_cmd(self, cmd, capture_output=True, check=True):
        """
        Execute a subprocess cmd on the terminal / command line

        Required:

            - `cmd`:
                - Type: str
                - What: The command to execute
        """
        try:
            output = subprocess.run(shlex.split(cmd), check=check, capture_output=capture_output)
        except subprocess.CalledProcessError as e:
            raise RuntimeError(f'Execution of {cmd} returned non-zero status: {e.stderr}')
        except OSError as e:
            raise OSError(e.errno, f'Execution of {cmd} returned OS Error: {e.strerror}')
        return output

    def parse_audio_sox(self, audio_file):
        """
        Attempt auto formatting your audio file using SoX to match that of the DeepSpeech Model

        Required:

            - `audio_file`:
                - Type: str
                - What: The location of your target audio file to transcribe

        Returns:

            - `audio_buffer`:
                - Type: np.array
                - What: A 16-bit, mono raw audio signal at the appropriate sample rate serialized as a numpy array
                - Note: Exactly matches the DeepSpeech Model
        """
        sox_cmd = f'sox {shlex.quote(audio_file)} --type raw --bits 16 --channels 1 --rate {self.desired_sample_rate} --encoding signed-integer --endian little --compression 0.0 --no-dither - '
        output = self.execute_cmd(sox_cmd)
        return np.frombuffer(output.stdout, np.int16)

    def parse_audio(self, audio_file):
        """
        Helper function to parse your raw audio file to match audio structures for the DeepSpeech Model

        Required:

            - `audio_file`:
                - Type: str
                - What: The location of your target audio file to transcribe
                - Note: `.wav` files with the model specified sample rate are handled without external packages. Everything else gets converted using SoX (if possible)

        Returns:

            - `audio_buffer`:
                - Type: np.array
                - What: A 16-bit, mono raw audio signal at the appropriate sample rate serialized as a numpy array
                - Note: Exactly matches the DeepSpeech Model
        """
        if ".wav" not in audio_file:
            self.warn(f"Selected audio file is not in `.wav` format. Attempting SoX conversion.")
            return self.parse_audio_sox(audio_file=audio_file)
        with wave.open(audio_file, 'rb') as audio_raw:
            audio_sample_rate = audio_raw.getframerate()
            if audio_sample_rate != self.desired_sample_rate:
                self.warn(f"Selected audio sample rate ({audio_sample_rate}) is different from the desired rate ({self.desired_sample_rate}). Attempting SoX conversion.")
                return self.parse_audio_sox(audio_file=audio_file)
            else:
                return np.frombuffer(audio_raw.readframes(audio_raw.getnframes()), np.int16)

    def record(self, output_audio_file=None, duration=3):
        """
        Record an audio file for a set duration using SoX

        Optional:

            - `output_audio_file`:
                - Type: str
                - What: The location to output the collected recording
                - Default: None
                - Note: Must be a `.wav` file
                - Note: If specified, the audio file location is returned
                - Note: If not specified or None, an audio buffer is returned

            - `duration`:
                - Type: int
                - What: The duration of time to record in seconds
                - Default: 3

        Returns:

            - `audio_file`:
                - Type: str
                - What: The provided `output_audio_file` given at the invokation of this function
                - Note: Returned only if `output_audio_file` is specified

            - OR

            - `audio_buffer`:
                - Type: np.array
                - What: A 16-bit, mono raw audio signal at the appropriate sample rate serialized as a numpy array
                - Note: Exactly matches the DeepSpeech Model
                - Note: Returned only if `output_audio_file` is not specified

        """
        if output_audio_file:
            sox_cmd = f'sox -d --channels 1 --rate {self.desired_sample_rate} --no-dither {shlex.quote(output_audio_file)} trim 0 {duration}'
            output=self.execute_cmd(sox_cmd)
            return output_audio_file
        else:
            sox_cmd = f'sox -d --type raw --bits 16 --channels 1 --rate {self.desired_sample_rate} --encoding signed-integer --endian little --compression 0.0 --no-dither - trim 0 {duration}'
            output = self.execute_cmd(sox_cmd)
            return np.frombuffer(output.stdout, np.int16)

    def play(self, audio_file):
        """
        Play an audio file using SoX

        Required:

            - `audio_file`:
                - Type: str
                - What: The location of your target audio file to transcribe
        """
        sox_cmd = f'sox {shlex.quote(audio_file)} -d'
        self.execute_cmd(sox_cmd)

    def get_word_timings(self, transcript):
        """
        Helper function to parse word timings and duration from a transcription metadata object

        Required:

            - `transcript`:
                - Type: CandidateTranscript (from deepspeech)
                - What: The candidate transcript to parse

        Returns:

            - `timings`:
                - Type: dict
                - What: A dictionary of the `start_time`, `end_time` and `duration` for each word in this transcript where those values are provided in seconds
        """
        if len(transcript.tokens)==0:
            return []
        word_data=[]
        word_tokens=[]
        for token in transcript.tokens:
            word_tokens.append(token)
            if token.text==" ":
                word_data.append(word_tokens)
                word_tokens=[]
        word_data.append(word_tokens)
        output=[]
        for word_tokens in word_data:
            try:
                start=round(word_tokens[0].start_time,3)
                end=round(word_tokens[-1].start_time,3)
                output.append({
                    'start':start,
                    'end':end,
                    'duration':round(end-start,3)
                })
            except:
                pass
        return output

    def get_transcript_dict(self, transcript, return_text=True, return_confidence=False, return_words=False, return_word_timings=False, return_meta=False):
        """
        Helper function to parse a clean dictionary from a transcription metadata object

        Required:

            - `transcript`:
                - Type: CandidateTranscript (from deepspeech)
                - What: The candidate transcript to parse

        Optional:

            - `return_text`:
                - Type: bool
                - What: Flag to indicate if the predicted text should be returned
                - Default: True
            - `return_confidence`:
                - Type: bool
                - What: Flag to indicate if the confidence level for this text should be returned
                - Default: False
            - `return_words`:
                - Type: bool
                - What: Flag to indicate if a words list (from the predicted text) should be returned
                - Default: False
            - `return_word_timings`:
                - Type: bool
                - What: Flag to indicate if the predicted timings (start, end and duration) for each word should be returned
                - Default: False
            - `return_meta`:
                - Type: bool
                - What: Flag to indicate if the transcript metadata object from DeepSpeech should be returned
                - Default: False

        Returns:

            - `transcript_dictionary`:
                - Type: dict
                - What: Dictionary of serialized transcription items specified by optional inputs
        """
        string=''.join(i.text for i in transcript.tokens)
        output={}
        if return_text:
            output['text']=string
        if return_confidence:
            output['confidence']=transcript.confidence
        if return_words:
            output['words']=string.split(" ")
        if return_word_timings:
            output['words_timings']=self.get_word_timings(transcript)
        if return_meta:
            output['meta']=transcript
        return output

    def stt(self, audio_buffer=None, audio_file=None, ):
        """
        Compute speech-to-text transcription for a provided audio file

        Required:

            - `audio_buffer`:
                - Type: np.array
                - What: A 16-bit, mono raw audio signal at the appropriate sample rate serialized as a numpy array
                - Note: Exactly matches the DeepSpeech Model

            - OR

            - `audio_file`:
                - Type: str
                - What: The location of your target audio file to transcribe

        Returns:

            - `text`:
                - Type: str
                - What: The transcribed text
        """
        if audio_file:
            audio_buffer = self.parse_audio(audio_file)
        if audio_buffer is None:
            self.exception("You must specify a valid audio_file or audio_buffer")
        return self.model.stt(audio_buffer)

    def stt_expanded(self, audio_file=None, audio_buffer=None, num_candidates=1, **kwargs):
        """
        Compute speech-to-text with extra data for N predicted candidates given an audio file

        Required:

            - `audio_buffer`:
                - Type: np.array
                - What: A 16-bit, mono raw audio signal at the appropriate sample rate serialized as a numpy array
                - Note: Exactly matches the DeepSpeech Model

            - OR

            - `audio_file`:
                - Type: str
                - What: The location of your target audio file to transcribe

        Optional:

            - `num_candidates`:
                - Type: int
                - What: The number of potential transcript candidates to return
                - Default: 1
                - Note: The most confident/likely result appears first
            - `return_text`:
                - Type: bool
                - What: Flag to indicate if the predicted text should be returned
                - Default: True
            - `return_confidence`:
                - Type: bool
                - What: Flag to indicate if the confidence level for this text should be returned
                - Default: False
            - `return_words`:
                - Type: bool
                - What: Flag to indicate if a words list (from the predicted text) should be returned
                - Default: False
            - `return_word_timings`:
                - Type: bool
                - What: Flag to indicate if the predicted timings (start, end and duration) for each word should be returned
                - Default: False
            - `return_meta`:
                - Type: bool
                - What: Flag to indicate if the transcript metadata object from DeepSpeech should be returned
                - Default: False

        Returns:

            - `transcriptions`:
                - Type: list of dictionaries
                - What: A list of dictionaries with various transcription output data
        """
        if audio_file:
            audio_buffer = self.parse_audio(audio_file)
        if audio_buffer is None:
            self.exception("You must specify a valid audio_file or audio_buffer")
        output_meta=self.model.sttWithMetadata(audio_buffer, num_candidates)
        return [self.get_transcript_dict(transcript, **kwargs) for transcript in output_meta.transcripts]

    def stt_list(self, audio_file=None, audio_buffer=None, num_candidates=3):
        """
        Compute speech-to-text with extra data for N predicted candidates given an audio file

        Required:

            - `audio_buffer`:
                - Type: np.array
                - What: A 16-bit, mono raw audio signal at the appropriate sample rate serialized as a numpy array
                - Note: Exactly matches the DeepSpeech Model

            - OR

            - `audio_file`:
                - Type: str
                - What: The location of your target audio file to transcribe

        Optional:

            - `num_candidates`:
                - Type: int
                - What: The number of potential transcript candidates to return
                - Default: 1
                - Note: The most confident/likely result appears first

        Returns:

            - `transcriptions`:
                - Type: list of strs
                - What: A list of potential transcriptions in decending order of confidence
        """
        expanded_list=self.stt_expanded(audio_file=audio_file, audio_buffer=audio_buffer, num_candidates=num_candidates, return_text=True)
        return [i['text'] for i in expanded_list]


import torch
from torchvision.datasets import MNIST, CIFAR10
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
import numpy as np

from utils.dataset_utils import DatasetCache, DatasetSubset, TransformDataset

class BanditDataset(Dataset):
    def __init__(self, contexts, actions,
                        rewards, propensities,
                        labels, splits):
        super(BanditDataset, self).__init__
        self.contexts = contexts
        self.actions = actions
        self.rewards = rewards
        self.propensities = propensities
        self.labels = labels
        self.splits = splits

    def __getitem__(self, index):
        return (self.contexts[index],self.actions[index],
                self.rewards[index], self.propensities[index],
                self.labels[index], self.splits[index])

    def __len__(self):
        return self.contexts.shape[0]

    def save(self, path):
        with open(path, 'wb') as f:
            torch.save((self.contexts, self.actions,
                        self.rewards, self.propensities,
                        self.labels, self.splits), f)

    def load(self, path):
        c,a,r,p,l,s = torch.load(path)
        self.contexts = c
        self.actions = a
        self.rewards = r
        self.propensities = p
        self.labels = l
        self.splits = s

def get_bandit_loaders(root_path, subpath,
                        data_type, batch_size,
                        train_on_partition, partition,
                        **kwargs):
    if data_type == 'cifar10':
        path = root_path + '/data'
        class_train = CIFAR10(path, train=True, transform=None, download=True)
        class_test = CIFAR10(path, train=False, transform=None)

        action_path = root_path + '/action_data/cifar10/' + kwargs['action_dir']
        bandit_train = ClassToBandit(class_train, action_path, train=True)
        train_size = 45000
        train_set = DatasetSubset(bandit_train, start=0, stop=train_size)
        val_set = DatasetSubset(bandit_train, start=train_size, stop=None)
        test_set = ClassToBandit(class_test, action_path, train=False)

        transform_train = transforms.Compose([ transforms.Pad(4, padding_mode='reflect'),
                            transforms.RandomHorizontalFlip(),
                            transforms.RandomCrop(32),
                            transforms.ToTensor(),
                            transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),])
        transform_test = transforms.Compose([transforms.ToTensor(),
                        transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),])

        train_set = TransformDataset(DatasetCache(train_set), transform_train)
        val_set = TransformDataset(DatasetCache(val_set), transform_test)
        test_set = TransformDataset(DatasetCache(test_set), transform_test)

    else:
        path = root_path + '/' + subpath
        train_set = BanditDataset(None, None, None, None, None, None)
        val_set = BanditDataset(None, None, None, None, None, None)
        test_set = BanditDataset(None, None, None, None, None, None)

        if train_on_partition:
            train_set.load(path + '/train_' + str(partition) + '.pt')
        else:
            train_set.load(path + '/train.pt')
        test_set.load(path + '/test.pt')
        val_set.load(path + '/val.pt')

    loader_args = {'num_workers': 0, 'pin_memory': True} if torch.cuda.is_available() else {}

    train_loader = torch.utils.data.DataLoader( train_set,
        batch_size=batch_size, shuffle=True, **loader_args)
    val_loader = torch.utils.data.DataLoader(val_set,
        batch_size=batch_size, shuffle=True, **loader_args)
    test_loader = torch.utils.data.DataLoader(test_set,
        batch_size=batch_size, shuffle=True, **loader_args)

    return train_loader, val_loader, test_loader

class ClassToBandit(Dataset):
    def __init__(self, class_dataset, action_dir, train=True):

        self.class_dataset = class_dataset
        self.train = train

        if self.train:
            self.actions, self.rewards, self.propensities = torch.load(action_dir + '/train.pt')
        else:
            self.actions, self.rewards, self.propensities = torch.load(action_dir + '/test.pt')

    def __getitem__(self, index):
        context, label = self.class_dataset.__getitem__(index)
        action = int(self.actions[index])
        propensity = self.propensities[index]
        reward = self.rewards[index]
        return context, action, reward, propensity, label, 0

    def __len__(self):
        return self.class_dataset.__len__()

def get_data_dim(data_type):
    if data_type == 'mnist':
        context_dim = 784
        num_actions = 10
    elif data_type == 'cifar10':
        context_dim = 3072
        num_actions = 10
    elif data_type == 'toy':
        context_dim = 5
        num_actions = 2
    elif data_type == 'world3':
        context_dim = 12
        num_actions = 2

    return context_dim, num_actions

def split_dataset(data):
    new_data = data
    split_size = int(new_data.__len__() / 2)
    split_0 = BanditDataset(np.zeros_like(data.contexts[:split_size]),
                            np.zeros_like(data.actions[:split_size]),
                            np.zeros_like(data.rewards[:split_size]),
                            np.zeros_like(data.propensities[:split_size]),
                            np.zeros_like(data.labels[:split_size]),
                            np.zeros_like(data.splits[:split_size]))
    split_1 = BanditDataset(np.zeros_like(data.contexts[:split_size]),
                            np.zeros_like(data.actions[:split_size]),
                            np.zeros_like(data.rewards[:split_size]),
                            np.zeros_like(data.propensities[:split_size]),
                            np.zeros_like(data.labels[:split_size]),
                            np.zeros_like(data.splits[:split_size]))
    idx_0 = 0
    idx_1 = 0

    idxs = np.random.choice(new_data.__len__(), size=split_size, replace=False)
    for i in range(new_data.__len__()):
        if i in idxs:
            new_data.splits[i] = 0
            split_0.contexts[idx_0] = new_data.contexts[i]
            split_0.actions[idx_0] = new_data.actions[i]
            split_0.rewards[idx_0] = new_data.rewards[i]
            split_0.propensities[idx_0] = new_data.propensities[i]
            split_0.labels[idx_0] = new_data.labels[i]
            split_0.splits[idx_0] = new_data.splits[i]
            idx_0 += 1
        else:
            new_data.splits[i] = 1
            split_1.contexts[idx_1] = new_data.contexts[i]
            split_1.actions[idx_1] = new_data.actions[i]
            split_1.rewards[idx_1] = new_data.rewards[i]
            split_1.propensities[idx_1] = new_data.propensities[i]
            split_1.labels[idx_1] = new_data.labels[i]
            split_1.splits[idx_1] = new_data.splits[i]
            idx_1 += 1

    assert idx_0 == split_size
    assert idx_1 == split_size
    assert np.sum(split_0.contexts - split_1.contexts) != 0

    return new_data, split_0, split_1


class NotFound(Exception):
    """Resource could not be located"""

    def __init__(self, status_code=-1, text=""):
        self.status_code = status_code
        self.text = text

class ConnectionError(Exception):
    """Problem while connecting to remote host"""


from .. import models,schema
from fastapi import FastAPI, HTTPException,Depends,status,APIRouter
from sqlalchemy.orm import Session
from ..database import get_db

router=APIRouter(
    tags=['post']
)
#read all posts
@router.get("/posts")
def view_posts(db: Session=Depends(get_db)):
    posts = db.query(models.Post).all()
    return posts

#create a new post
@router.post("/posts",status_code=status.HTTP_201_CREATED)
def create_post(post:schema.Post, db: Session=Depends(get_db)):
    new_post = models.Post(title=post.title,content=post.content,image_url=post.image_url)
    db.add(new_post)
    db.commit()
    db.refresh(new_post)
    return new_post

#delete a new post
@router.delete("/posts/{id}")
def delete_post(id:int,db: Session = Depends(get_db)):
    post = db.query(models.Post).filter(models.Post.post_id == id).first()
    if post is None:
        raise HTTPException(status_code=404, detail="Post not found")
    db.delete(post)
    db.commit()
    return {"status_code": 200, "detail":"Post deleted successfully"}

#update a certain post
@router.put("/posts/{id}")
def update_post(id:int, post:schema.Post, db: Session = Depends(get_db)):
    db_post = db.query(models.Post).filter(models.Post.post_id == id).first()
    if db_post is None:
        raise HTTPException(status_code=404, detail="Post not found")
    db_post.title = post.title
    db_post.content = post.content
    db.commit()
    return {"status_code": 200, "detail":"Post updated successfully"}


from logic import *

AKnight = Symbol("A is a Knight")
AKnave = Symbol("A is a Knave")

BKnight = Symbol("B is a Knight")
BKnave = Symbol("B is a Knave")

CKnight = Symbol("C is a Knight")
CKnave = Symbol("C is a Knave")

character_possibles = [(AKnight, AKnave), (BKnight, BKnave), (CKnight, CKnave)]
general_knowledge = {} # To store that any character is a either a Knight or a Knave

for index, character in enumerate(['A', 'B', 'C']):
    general_knowledge[character] = [
        Or(*character_possibles[index]), # Character is either be A knave or A knight,
        Not(And(*character_possibles[index])) # but not both
        ]

# Puzzle 0
# A says "I am both a knight and a knave."
satement_A0 = And(AKnight, AKnave) # A is both a Knight and a Knave.

knowledge0 = And(
    Implication(AKnight, satement_A0), # if AKnight, then statement_A0 is true.
    Implication(AKnave, Not(satement_A0)), # if AKnave, then statement_A0 is false.
    *general_knowledge['A']
)

# Puzzle 1
# A says "We are both knaves."
# B says nothing.
satement_A1 = And(AKnave, BKnave) # A and B are both Knaves
knowledge1 = And(
    Implication(AKnight, satement_A1), # If A is a knight, then statement_A1 is true.
    Implication(AKnave, Not(satement_A1)), # if A is a knave, then satement_A1 is false.
    *general_knowledge['A'], *general_knowledge['B']
)

# Puzzle 2
# A says "We are the same kind."
# B says "We are of different kinds."
statement_A2 = Or(And(AKnight, BKnight), And(AKnave, BKnave)) # A and B are of the same kind
statement_B2 = Or(And(AKnight, BKnave), And(AKnave, BKnight)) # A and B are of different kinds
knowledge2 = And(
    Implication(AKnight, statement_A2), # Look up puzzle 1 above to understand
    Implication(AKnave, Not(statement_A2)),
    Implication(BKnight, statement_B2),
    Implication(BKnave, Not(statement_B2)),
    *general_knowledge['A'], *general_knowledge['B']
)

# Puzzle 3
# A says either "I am a knight." or "I am a knave.", but you don't know which.
# B says "A said 'I am a knave'."
# B says "C is a knave."
# C says "A is a knight."

#

C_is_saying = And(Implication(CKnight, AKnight), Implication(CKnave, Not(AKnight)))
A_is_saying = Or(And( Implication(AKnight, AKnight), Implication(AKnave, Not(AKnight)) ),\
                 And( Implication(AKnight, AKnave), Implication(AKnave, Not(AKnave)) ))
A_says_according_to_B = And(Implication(AKnight, AKnave), Implication(AKnave, Not(AKnave)))
B_is_saying1 = And(Implication(BKnight, A_says_according_to_B), Implication(BKnave, Not(A_says_according_to_B)))
B_is_saying2 = And(Implication(BKnight, CKnave), Implication(BKnave, Not(CKnave)))

knowledge3 = And(
    A_is_saying,
    B_is_saying1,
    B_is_saying2,
    C_is_saying,
    *general_knowledge['A'],
    *general_knowledge['B'],
    *general_knowledge['C']
    )

def main():
    symbols = [AKnight, AKnave, BKnight, BKnave, CKnight, CKnave]
    puzzles = [
        ("Puzzle 0", knowledge0),
        ("Puzzle 1", knowledge1),
        ("Puzzle 2", knowledge2),
        ("Puzzle 3", knowledge3)
    ]
    for puzzle, knowledge in puzzles:
        print(puzzle)
        if len(knowledge.conjuncts) == 0:
            print("    Not yet implemented.")
        else:
            for symbol in symbols:
                if model_check(knowledge, symbol):
                    print(f"    {symbol}")

if __name__ == "__main__":
    main()


from dataclasses import dataclass
from time import time

# each social channel has a type
# and the current number of followers
# SocialChannel = tuple[str, int]
@dataclass
class SocialChannel:
    channel_type: str
    followers: int

# each post has a message and the timestamp when it should be posted
# Post = tuple[str, int]
@dataclass
class Post:
    message: str
    timestamp: int

def post_to_channel(channel: SocialChannel, message: str) -> None:
    type, followers = channel.channel_type, channel.followers
    print(f"{type} channel: {message}")

def post_to_facebook(channel: SocialChannel, message: str) -> None:
    type, followers = channel
    print(f"{type} channel: {message}")

def post_to_twitter(channel: SocialChannel, message: str) -> None:
    type, followers = channel
    print(f"{type} channel: {message}")

def post_a_message(channel: SocialChannel, message: str) -> None:
    type, followers = channel.channel_type, channel.followers
    if type in ["youtube", "facebook", "twitter"]:
        print(f"{type} channel: {message}")
    # elif type == "facebook":
    #     post_to_facebook(channel, message)
    # elif type == "twitter":
    #     post_to_twitter(channel, message)

def process_schedule(posts: list[Post], channels: list[SocialChannel]) -> None:
    for post in posts:
        message, timestamp = post.message, post.timestamp
        for channel in channels:
            if timestamp <= time():
                post_a_message(channel, message)

def main() -> None:
    posts = [
        Post(
            "Grandma's carrot cake is available again (limited quantities!)!",
            1568123400,
        ),
        Post("Get your carrot cake now, the promotion ends today!", 1568133400),
    ]
    channels = [
        SocialChannel("youtube", 100),
        SocialChannel("facebook", 100),
        SocialChannel("twitter", 100),
    ]

    process_schedule(posts, channels)

if __name__ == "__main__":
    main()


import cv2

from camera import CameraThread

def get_cameras():
    max_tested = 100
    for i in range(max_tested):
        temp_camera = cv2.VideoCapture(i)
        if temp_camera.isOpened():
            temp_camera.release()
            continue
        return i

class CameraEnv:
	def __init__(self, env):
		self.env = env
		self.camera_list = [CameraThread() for i in range(10)] #example

	def get_observation(self):
		camera_obs = [c.get_image() for c in self.camera_list]

		obs = self.env.get_observation() #{ee_pos, ee_vel, etc}


import sys

maxl = 998244353
max_n = 12

def check(num):
    datas = open("../data/{}.in".format(num), "r")

    n, k = datas.readline().split(" ")
    n, k = int(n), int(k)

    if k >= n:
        return False
    if n > max_n or n < 2:
        return False

    g = set()
    count = 0

    while True:
        data = datas.readline()
        if not data:
            break

        x, y, p, q = data.split(" ")
        x, y, p, q = int(x), int(y), int(p), int(q)

        if x == y:
            return False

        if x < 1 or x > n:
            return False
        if y < 1 or y > n:
            return False
        if not (0 <= p <= q < maxl and q > 0):
            return False
        if (x,y) not in g:
            g.add((x,y))
            count += 1
        else:
            return False

    return count == (n * (n-1))

if __name__ == "__main__":
    for i in range(1,21):
        if not check(i):
            print("Error {}".format(i))
        else:
            print("Pass check {}".format(i))


import math

# Asks for input "invesmenet" or "Bond"

# "investment" - prompts them for 3 integers
# asks 1 more question: 'simple or compound'
# then prints formula result

# "bond" - prompts them for 3 integers and print a formula result

user_input = input("""Choose either 'investment' or 'bond' from the menu below to proceed:

investment        - to calculate the amount of interest you'll earn on interest
bond              - to calculate the amount you'll have to pay for a home loan

Input choice here: """).lower()

# Gets input, and returns error message and repeats question is not in desired range

# Removes " ", from large number input to avoid errors using .replace
# Changes case of inputs containing words using .lower()
# Rounds our answer to rwo decimal places using round()

retry = """
Error. Invalid Input.                              Retry: """
while not (user_input == "investment" or user_input == "bond"):
    user_input = input(retry).lower()

# Investment Branch:
if user_input == "investment":

    deposit = input("""
How much would you like to deposit?       Deposit Amount: R """).replace(" ","")
    while not deposit.isdigit():
        deposit = input(retry).replace(" ","")

    interest_rate = input("""
Please enter the interest rate                   (1-100): """)
    while not (interest_rate.isdigit() and int(interest_rate)>0 and int(interest_rate)<100):
        interest_rate = input(retry)
    interest_rate = float(interest_rate)/100

    years = input("""
Length of investment (in years)                     (0+): """)
    while not (years.isdigit() and int(years)>0):
        years = input(retry)

    interest = input("""
Which Interest type would you like?     simple/compound): """).lower()
    while not (interest == "compound" or interest == "simple"):
        interest = input(retry).lower()

    print(f"""\n
Amount                   - R {deposit}.00
Investment Period        - {years} years
interest rate            - {interest_rate*100}%
interest type            - {interest} interest

The total amount recevied after investment period  """, end="")
# prints total amounts for the interest type chosen using formulas from variables below
    comp = float(deposit)*math.pow((1+interest_rate), float(years))
    simp = float(deposit)*(1+interest_rate*float(years))
    if interest == "compound":
        print(f"R {round(comp,2)}")
        print(f"Interest Earned = R {round(comp-float(deposit),2)}")
    elif interest == "simple":
        print(f"R {round(simp,2)}")
        print(f"Interest Earned = R {round(simp-float(deposit),2)}")

elif user_input.lower() == "bond":
# Bond Branch:

    house_value = input("""
What is the value of the house?                         : R """).replace(" ","")
    while not house_value.isdigit():
            house_value = input(retry).replace(" ","")

    interest_rate = input("""
What is the intereste rate?                      (0-100): """)
    while not interest_rate.isdigit():
            interest_rate = input(retry)
    interest_rate = ((float(interest_rate)/100)/12)

    num_months = input("""
How many months do you want to pay loan back over?      : """)
    while not num_months.isdigit():
        num_months = inpout(retry)

    instlmnt = (interest_rate*float(house_value))/(1-math.pow((1+interest_rate),(-float(num_months))))
    print(f"""
Value of the house       - R {house_value}.00
months of repayment      - {num_months} months
Interest Rate            - {interest_rate*100*12}%

The monthly repayment on your bond will be:
= R{round(instlmnt,2)}""")


""" RTMA API MODULE

    - This module contains any API based methods that users interact with.

    When the library is installed, this is the module users should interact with.

    For detailed information on the methods and configuring the library,
    please see our Readme on our Github.
    https://github.com/RTMAAI/CO600-Musical-Analysis
"""
import wave
import logging
from rtmaii.hierarchy import Hierarchy
from rtmaii.configuration import Config
from numpy import int16, frombuffer
from pydispatch import dispatcher
import pyaudio

FORMATTER = logging.Formatter('%(asctime)s [%(levelname)s]: %(message)s')
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.DEBUG)
SH = logging.StreamHandler()
FH = logging.FileHandler('rtma-log.log', mode='w')
FH.setLevel(logging.DEBUG)
FH.setFormatter(FORMATTER)
SH.setFormatter(FORMATTER)
LOGGER.addHandler(FH)
LOGGER.addHandler(SH)

class Rtmaii(object):
    """ Interface for real-time musical analysis library.

        Args:
            - Callbacks: List of dicts with a callback and the signal to will trigger it.
            - Source: The path of a track to be played, defaults to microphone input.
            - Config: Dict of settings to change. (See our Readme for a list of options.)
            - Custom_Nodes: List of custom nodes to add to Hierarchy. (See Readme for details.)

        Kwargs:
            - Mode: Logging mode, options = {'DEBUG','WARNING','CRITICAL','INFO','ERROR'}

        Example:
            ```python
                source = r'.\\Tracks\\LetItGo.wav'
                callbacks = [{'function': callback_function, 'signal':'frequency'}]
                config = {
                    "bands": {
                        "bass": {min: 200, max: 2000}
                    },
                    "tasks": {
                        "genre": False,
                    }
                }
                custom_nodes = {
                    'Node1': {'class_name': 'NewWorker', 'parent': 'SpectrumCoordinator',
                              'args': (), 'kwargs':{}}
                }
                analyser = rtmaii.Rtmaii(callbacks, source, config, custom_nodes)
                analyser.start()

                while analyser.is_active():
                    pass #Keep main thread running.
            ```
    """
    def __init__(self, callbacks: list = (), source: str = None,
                 config: dict = None, custom_nodes: dict = None, **kwargs):

        self.config = Config()
        self.audio = pyaudio.PyAudio()
        self.stream = None
        self.set_source(source)
        self.set_callbacks(callbacks)
        if config:
            self.config.set_config(**config)

        self.hierarchy = Hierarchy(self.config, custom_nodes)
        mode = 'ERROR' if 'mode' not in kwargs else kwargs['mode']
        SH.setLevel(mode)
        LOGGER.debug('RTMAAI Initiliazed')

    def __stream_callback__(self, in_data, frame_count, _, __):
        """ Convert raw stream data into signal bin and put data on the coordinator's queue. """
        data = self.waveform.readframes(frame_count) if hasattr(self, 'waveform') else in_data
        self.hierarchy.put(frombuffer(data, int16))
        return (data, pyaudio.paContinue)

    def is_active(self) -> bool:
        """ Check that coordinator thread is still running.

            Returns
                - bool: True is alive, False otherwise.
        """
        return bool(self.stream and self.stream.is_active())

    def start(self):
        """ Start audio stream and analysis. """
        pyaudio_settings = self.config.get_config('pyaudio_settings')
        pyaudio_settings['stream_callback'] = self.__stream_callback__

        if hasattr(self, 'waveform'):
            min_start = self.waveform.getnframes() - self.config.get_config('frames_per_sample')
            # Reset wav file to start, if next sample would retrieve less than the frame count.
            if self.waveform.tell() >= min_start:
                self.waveform.rewind() # Reset wave file to initial position.

        self.stream = self.audio.open(**pyaudio_settings)
        self.stream.start_stream()

        LOGGER.info('Stream started')

    def pause(self):
        """ Pause the stream. Analogous to stop if analysing live music. """
        if self.stream:
            self.stream.stop_stream()
        else:
            LOGGER.warning('Stream is not active, pausing has no effect.')

    def stop(self):
        """ Stop the stream & reset track's position (if set). """
        if hasattr(self, 'waveform'):
            self.waveform.setpos(0) # Reset wave file to initial position.
        if self.stream:
            self.stream.stop_stream()
        else:
            LOGGER.warning('Stream is not active, stopping has no effect.')

    def set_config(self, **kwargs: dict):
        """ Change configuration options, i.e. what bands should be look at.

            Note:
                - Please see our Readme for a detailed list of configuration options.
        """
        self.config.set_config(**kwargs)
        if hasattr(self, 'hierarchy'):
            # As these changes require a change in the Hierarchy.
            # We simply recreate the Hierarchy, which is currently quite expensive.
            if 'merge_channels' in kwargs or 'tasks' in kwargs:
                self.hierarchy.reset_hierarchy()
            else:
                self.hierarchy.update_nodes()

    def set_source(self, source: object = None, **kwargs: dict):
        """ Change the analyzed source. By default this sets the stream to use
            your default input device with it's default configuration.

            When specifying an input device in which you have changed the configuration
            such as a higher sampling rate/channels, please supply these in the kwargs.

            ```python
                set_source(**{'rate' : 96000, 'channels' : 3})
            ```
            If this is not set to match your system's configuration
            artefacts may arise in the analysis.

            Args:
                - source: Int (Index of input device) || String (Path of audio file)
                - kwargs: Additional configuration to be used in Pyaudio.

            Please see our readme for more information.
        """
        if not isinstance(source, (type(None), int, str)):
            raise TypeError('Provided source {}, should be a str, int or None type. '
                            .format(source))

        if isinstance(source, int) or source is None:
            if hasattr(self, 'waveform'):
                delattr(self, 'waveform')
            # Extract relevant configuration to use in waveform.
            try:
                device = (self.audio.get_device_info_by_index(source) if source
                          else self.audio.get_default_input_device_info())
            except Exception:
                print('Exception: Input device could not be found.')
                raise

            pyaudio_kwargs = {
                'format': pyaudio.paInt16,
                'input': True
            }
            # Grab relevant default settings to use as pyaudio args.
            pyaudio_kwargs.update({'input_device_index': device['index'],
                                   'channels': device['maxInputChannels'],
                                   'rate': int(device['defaultSampleRate'])
                                  })
        else:
            try:
                self.waveform = wave.open(source)
            except Exception:
                print('Exception: Specified wav file {} could not be opened.'.format(source))
                raise

            pyaudio_kwargs = { # Extract relevant configuration from .wav file to use in Pyaudio.
                'format': self.audio.get_format_from_width(self.waveform.getsampwidth()),
                'output': True,
                'rate': self.waveform.getframerate(),
                'channels': self.waveform.getnchannels()
            }

        self.config.set_source(pyaudio_kwargs, **kwargs)
        LOGGER.debug('Audio source has been successfully configured.')

        if hasattr(self, 'hierarchy'):
            if self.config.get_config('merge_channels'):
                # Only update nodes instead of reconstructing.
                self.hierarchy.update_nodes()
            else:
                self.hierarchy.reset_hierarchy()

    def get_input_devices(self):
        """ Lists the names and IDs of the input devices on your system. """
        info = self.audio.get_host_api_info_by_index(0)
        numdevices = info.get('deviceCount')
        for i in range(0, numdevices):
            audio_device = self.audio.get_device_info_by_host_api_device_index(0, i)
            if (audio_device.get('maxInputChannels')) > 0:
                print("Input Device index {} - {}".format(i, audio_device.get('name')))

    @staticmethod
    def set_callbacks(callbacks: list):
        """ Attach supplied callbacks to signals on the dispatcher.
            Dispatcher is a loose form of the observer pattern.
            When the dispatcher is sent a signal, each observee will have their callback run.

            Example:
            ```python
                set_callbacks([{'function': callback_method, 'signal':'frequency'}])
            ```
        """
        if isinstance(callbacks, (tuple, list)):
            for callback in callbacks:
                __validate_callback__(callback)
                dispatcher.connect(callback['function'], callback['signal'], sender=dispatcher.Any)
        else:
            raise TypeError('Provided callbacks {}, should be in the form of a list. '
                            .format(callbacks))

    @staticmethod
    def remove_callbacks(callbacks: list):
        """ Remove supplied callbacks from the dispatcher.

            Example:
            ```python
                remove_callbacks([{'function': callback_method, 'signal':'frequency'}])
            ```
        """
        if isinstance(callbacks, (tuple, list)):
            for callback in callbacks:
                __validate_callback__(callback)
                dispatcher.disconnect(callback['function'], callback['signal'],
                                      sender=dispatcher.Any)
        else:
            raise TypeError('Provided callbacks {}, should be in the form of a list/tuple. '
                            .format(callbacks))

    def add_node(self, class_name: str, node_id: str = None, parent: str = 'root',
                 init_args: list = (), **kwargs: dict):
        """ Add a new node to the hierarchy on each channel tree.

            When adding a custom node, you will need to make sure they inherit from,
            either the base Worker or Coordinator in rtmaii.worker||rtmaii.coordinator.

            Args:
                - class_name: class_name of object to add to hierarchy.
                - node_id: unique id to give node in hierarchy, if not set, class_name is used.
                - parent: Parent node's class_name to attach to.
                - init_args: Tuple of arguments needed to initialise the node.
                - **kwargs: Any extra arguments to pass to the node initialisation.
        """
        self.hierarchy.add_custom_node(class_name, node_id, parent, *init_args, **kwargs)

    def remove_node(self, node_id: str):
        """ Remove a node from the hierarchy.

            If you are analysing multiple channels independently,
            the node will be removed from every channels hierarchy.

            Args:
                - node_id: id of object to add to hierarchy.

            To remove inbuilt nodes, use the class name of the node.
            I.e. 'SpectrumCoordinator'
        """
        self.hierarchy.remove_node(node_id)

def __validate_callback__(callback: dict):
    """ Validate that a given callbacks parameters.

        Expected signature:
            {'function': callback_method, 'signal':'frequency'}

        Args:
            - callback: callback signature to validate.
    """
    if 'function' in callback and 'signal' in callback:
        if not callable(callback['function']):
            raise TypeError('Provided function {} is not callable.'
                            .format(callback['function']))
        if not isinstance(callback['signal'], str):
            raise TypeError('Provided signal {} is not of type str'
                            .format(callback['signal']))
    else:
        raise ValueError('Callback {}, missing required attribute signal or function.'
                         .format(callback))


import pandas as pd

from dml.Fetch_Query import query_with_fetchmany
from dml.coffee_delete import delete_product
from dml.coffee_insert import insert_product, insert_products
from dml.coffee_procedure import call_sale_stat_sp, call_order_price_by_issale
from dml.coffee_select import query_with_fetchone, query_with_fetchall, query_with_fetchall2, \
    query_with_fetchall_by_code
from dml.coffee_update import update_product
from dml.connection_pool import ConnectionPool
from dml.create_procedure import create_procedure
from dml.transaction_query import transaction_fail1, transaction_fail2, transaction_success

# ctrl + alt + m = 메소드 만들기
def connection_pool_test():
    connection_pool = ConnectionPool.get_instance()
    connection = connection_pool.get_connection()
    print("connection : ", connection)

def fetch_all2_test(sql):
    query_with_fetchall(sql)
    res = query_with_fetchall2(sql)
    print(type(res), 'size = ', len(res))
    # for pno, pname in res:
    #     print(pno, pname)
    query_with_fetchmany(sql)

    # query_with_fetchall(sale_select_sql)
    # res = query_with_fetchall2(sale_select_sql)
    # print(type(res), 'size = ', len(res))
    # for pno, pname in res:
    #     print(pno, pname)
    # query_with_fetchmany(sale_select_sql)

def fetch_one_test():
    query_with_fetchone(product_select_sql)
    query_with_fetchone(sale_select_sql)

def fetch_all_where_test():
    product_select_whiere01 = "select * from product where code = %s"
    res = query_with_fetchall_by_code(product_select_whiere01, 'A001')
    print(res)
    # product_select_whiere02 = "select * from product where code = {}".format('A001')
    # query_with_fetchall(product_select_whiere02)

def insert_test():
    insert_sql = "insert into product values(%s, %s)"
    insert_product(insert_sql, 'C001', '라떼')
    products = [('C002', '라떼2'), ('C003', '라떼3'), ('C004', '라떼4')]
    insert_products(insert_sql, products)
    query_with_fetchall(product_select_sql)

def update_test():
    select_sql_by_code = "select code, name from product where code = '{code}'".format(code='C001')
    query_with_fetchone(select_sql_by_code)
    update_sql = "update product set name = %s where code = %s"
    update_product(update_sql, '라떼수정', 'C001')
    query_with_fetchone(select_sql_by_code)

def delete_test():
    delete_select_sql = "select code, name from product where code like 'C___'"
    res = query_with_fetchall2(delete_select_sql)
    columns_list = ['code', 'name']
    df = pd.DataFrame(res, columns=columns_list)
    print(df)
    delete_sql = "delete from product where code = %s"
    delete_product(delete_sql, 'C004')
    for code, name in (query_with_fetchall2(delete_select_sql)):
        print(code, " ", name)

if __name__ == "__main__":
    connection_pool_test()

    product_select_sql = "select * from product"
    sale_select_sql = "select * from sale"

    # fetch_one_test()
    # fetch_all2_test(product_select_sql)
    # fetch_all2_test(sale_select_sql)

    # where
    # fetch_all_where_test()

    # insert문
    # insert_test()

    # update문
    # update_test()

    # Delete문
    # delete_test()

    # transaction
    # transaction_fail1()
    # transaction_fail2()
    # transaction_success()

    # create_procedure()
    call_sale_stat_sp('proc_sale_stat')
    print()
    call_order_price_by_issale('proc_saledetail_orderby', False)
    print()
    call_order_price_by_issale('proc_saledetail_orderby', True)


class PostResource(ModelResource):

    author = fields.ForeignKey(UserResource, 'author')

    class Meta:
        queryset = Post.objects.all()
        resource_name = 'post'
        authorization = Authorization()
        always_return_data = True

    def build_schema(self):
        base_schema = super(ModelResource, self).build_schema()
        base_schema['fields']['author'][
            'resource'] = this.author.get_resource_uri()
        return base_schema


from __future__ import print_function
import numpy as np
import pickle as pk
import copy
try:
    import Queue as Q  # ver. < 3.0
except ImportError:
    import queue as Q
import math
import random
import sys
import matplotlib.pyplot as plt
outLis = []
tim = []
Domain = "01"
populationSize = 100
# assumption, a's have integer value and is a list
def f1 (a):
    sm = 0
    na = copy.deepcopy (a)
    for i in range (len (na)):
        na[i] = na[i] / 100
    for i in range (len (na)):
        sm = sm + na[i] * na[i]
    return sm
def f2 (a):
    sm = 0
    na = copy.deepcopy (a)
    for i in range (len (na)):
        na[i] = na[i] / 100
    for i in range (len (na)):
        sm = sm + math.floor (na[i])
    return sm
def gaussNoise ():
    return np.random.normal (0, 1)
def f3 (a):
    sm = 0
    na = copy.deepcopy (a)
    for i in range (len (na)):
        na[i] = na[i] / 100
    for i in range (len (na)):
        sm = sm + (i + 1) * (na[i] * na[i] * na[i] * na[i])
    sm = sm + gaussNoise ()
    return sm
def sum_ (a):
    return f1(a) + f2(a) + f3 (a)
def isNDS (index, Data):
    oz = f1 (Data[index].n)
    oo = f2 (Data[index].n)
    ot = f3 (Data[index].n)
    for i in range (len (Data)):
        if (i == index):
            continue
        z = f1 (Data[i].n)
        o = f2 (Data[i].n)
        t = f3 (Data[i].n)
        if (z < oz and o < oo and t < ot):
            return False
    return True

class Gene:
    def __init__ (self):
        self.n = [0 for i in range (5)]
        self.bin_ = [0 for i in range (5)]
        for i in range (5):
            self.n[i] = random.randint (-204, 205)
            self.bin_[i] = list ("{0:010b}".format (self.n[i]))
        self.nds = False
        self.fitness = sum_ (self.n)

    def __lt__ (self, other):
        if (self.nds and not (other.nds)):
            return True
        elif (other.nds and not (self.nds)):
            return False
        else:  # either both are nds or both are not nds, in either case we want to minimize the total loss
            return self.fitness < other.fitness
def Solve ():
    Data = []
    for i in range (0, populationSize):
        Data.append (Gene ())
    newLimit = int (0.5 * populationSize);  # Elitism
    offLimit = populationSize - newLimit
    global outLis
    outLis = []
    global tim
    tim = []
    tim.append (1)
    for i in range (len (Data)):
        if (isNDS (i, Data)):
            Data[i].nds = True
    Data.sort ()
    outLis.append (Data[0].fitness)
    toRet = Data[0].n
    return toRet
def plotit (n,k):
    plt.scatter (tim, outLis)
    plt.xlabel("epoch")
    plt.ylabel("fitness")
    plt.title("GA with Randomness N = %d"%n)
    plt.savefig ("Random" + str(k + 1) + ".png")
    plt.clf ()
    # plt.show ()
sys.stdin = open("in.txt", "r")
sys.stdout = open("out.txt", "w")
i = 0
for n in [50, 100, 200]:
    populationSize = n
    ans_ = Solve ()
    plotit (n,i)
    i += 1


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

# In[1]:

import pandas as pd
import numpy as np
from surprise import Reader, Dataset, KNNBasic, SVD, NMF
from surprise.model_selection import GridSearchCV, cross_validate
from surprise import accuracy
from math import sqrt
from sklearn.metrics import mean_squared_error
from surprise.model_selection import train_test_split
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')

# In[2]:

movies_df = pd.read_csv(r'C:\Users\P Sai Deekshith\Recommender Systems\ml-100k\movies.csv')

ratings_df = pd.read_csv(r'C:\Users\P Sai Deekshith\Recommender Systems\ml-100k\ratings.csv')

# In[3]:

reader = Reader(rating_scale=(0.5, 5.0))

data = Dataset.load_from_df( ratings_df[['userId', 'movieId', 'rating']], reader = reader )

def rmseKNN():
    sim_options = {'name': 'msd'}

    algo = KNNBasic(k=20, sim_options=sim_options)
    cross_validate(algo=algo, data=data, measures=['RMSE'], cv=5, verbose=True)
    n_neighbours = [10, 20, 30]
    param_grid = {'n_neighbours': n_neighbours}

    gs = GridSearchCV(KNNBasic, measures=['RMSE'], param_grid=param_grid)
    gs.fit(data)
    print('\n\n###############')

    print('Best Score :', gs.best_score['rmse'])

    print('Best Parameters :', gs.best_params['rmse'])
    print('###############')

    return gs.best_score['rmse']

def rmseSVD():
    algo = SVD()
    cross_validate(algo=algo, data=data, measures=['RMSE'], cv=5, verbose=True)
    param_grid = {'n_factors': [50, 75], 'lr_all': [0.5, 0.05], 'reg_all': [0.06, 0.04]}

    gs = GridSearchCV(algo_class=SVD, measures=['RMSE'], param_grid=param_grid)
    gs.fit(data)
    print('\n###############')
    print('Best Score :', gs.best_score['rmse'])

    print('Best Parameters :', gs.best_params['rmse'])
    print('###############')

    return gs.best_score['rmse']


import requests

word = input("PLease input the word that you want search for in a Dictionary: ")
url = "https://api.dictionaryapi.dev/api/v2/entries/en/{0}".format(word)

api_response = requests.get(url)
my_dictionary = api_response.json()

for dictionary in my_dictionary:
    print(dictionary)
    print(f"Word: {dictionary['word']} Definition: {dictionary['meanings[0].definitions[0].definition']}")


import torch
import torchvision
import torchvision.models.detection as models
from torchvision.models.detection.roi_heads import RoIHeads
from torchvision.models.detection import FasterRCNN
from torchvision.models.detection.backbone_utils import resnet_fpn_backbone
from collections import OrderedDict

def build_model(args):
    model = models.fasterrcnn_resnet50_fpn(pretrained=True)

    num_classes = args.num_classes + 1
    in_features = model.roi_heads.box_predictor.cls_score.in_features
    model.roi_heads.box_predictor = models.faster_rcnn.FastRCNNPredictor(in_features, num_classes)

    return model

class CustomRoIHeads(RoIHeads):

    def forward(self, features, proposals, image_shapes, targets=None):
        box_features = self.box_roi_pool(features, proposals, image_shapes)
        box_features = self.box_head(box_features)
        class_logits, box_regression = self.box_predictor(box_features)

        return class_logits, box_regression

class CustomFasterRCNN(FasterRCNN):

    def __init__(self, args):
        backbone = resnet_fpn_backbone('resnet50', pretrained=True)

        # box roi pool
        box_roi_pool = torchvision.ops.MultiScaleRoIAlign(
            featmap_names=[0], output_size=7, sampling_ratio=2)

        # box head
        resolution = box_roi_pool.output_size[0]
        representation_size = 1024
        box_head = torchvision.models.detection.faster_rcnn.TwoMLPHead(
            backbone.out_channels * resolution ** 2,
            representation_size)

        # box predictor
        box_predictor = torchvision.models.detection.faster_rcnn.FastRCNNPredictor(
            representation_size,
            args.num_classes + 1)

        roi_heads = CustomRoIHeads(
            box_roi_pool,
            box_head,
            box_predictor,
            fg_iou_thresh=0.5,  # default value
            bg_iou_thresh=0.5,  # default value
            batch_size_per_image=512,  # default value
            positive_fraction=0.25,  # default value
            bbox_reg_weights=None,
            score_thresh=0.05,
            nms_thresh=0.5,
            detections_per_img=100)  # default value

        super(CustomFasterRCNN, self).__init__(backbone, num_classes=args.num_classes + 1, roi_heads=roi_heads)

    def forward(self, images, targets=None):
        # Expect images to be an ImageList

        features = self.backbone(images.tensors)
        if isinstance(features, torch.Tensor):
            features = OrderedDict([('0', features)])

        proposals, proposal_losses = self.rpn(images.tensors, features, targets)
        class_logits, box_regression = self.roi_heads(features, proposals, images.image_sizes)

        return proposals, proposal_losses, class_logits, box_regression


def isSet(c1,c2,c3):
 # write your code here
 # 1จะเช็คcardเป็นัวๆ เช่น [purple,2 ,squiggle ,striped]

 #ทัละตัวทำเป็นsetละมาunionกับอีกสองไพ่ ภ้าเหมือนหมดlen = 1 ต่างหมด len = 3
 #ดังนั้นFalseเมื่อlen union = 2
    state = True
    for i in range(4):
        union = {c1[i]}.union({c2[i]}).union({c3[i]})
        if len(union) == 2:
            state = False
            break
    return state

cards = []
for i in range(12):
    cards.append(input().strip().split())
for i in range(12):
    for j in range(i+1,12):
        for k in range(j+1,12):
            if isSet(cards[i],cards[j],cards[k]):
                print(i,j,k)


import tensorflow as tf
import numpy as np
from bench.core.executer import Executer

def masks_to_boxes(masks):
    """Compute the bounding boxes around the provided masks

    The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions.

    Returns a [N, 4] tensors, with the boxes in xyxy format
    """
    # if tf.size(masks) == 0:
    #     return tf.zeros((0, 4))

    h, w = masks.shape[-2:]
    y = tf.range(0, h, dtype=tf.float32)
    x = tf.range(0, w, dtype=tf.float32)
    y, x = tf.meshgrid(y, x)
    x_mask = (masks * tf.expand_dims(x, axis=0))
    x_max = tf.math.reduce_max(tf.reshape(x_mask, (x_mask.shape[0], -1)), axis=-1)
    x_min = tf.math.reduce_min(tf.reshape(tf.where(~tf.cast(masks, tf.bool), 1e8, x_mask), (x_mask.shape[0], -1)), axis=-1)

    y_mask = (masks * tf.expand_dims(y, 0))
    y_max = tf.math.reduce_max(tf.reshape(y_mask, (y_mask.shape[0], -1)), axis=-1)
    y_min = tf.math.reduce_min(tf.reshape(tf.where(~tf.cast(masks, tf.bool), 1e8, y_mask), (y_mask.shape[0], -1)), axis=-1)

    return tf.stack([x_min, y_min, x_max, y_max], 1)

def args_adaptor(np_args):
    masks = tf.convert_to_tensor(np_args[0], tf.float32)

    return [masks]

def executer_creator():
    return Executer(masks_to_boxes, args_adaptor)


# -*- coding: utf-8 -*-
"""
Created on Mon Apr 25 18:36:21 2022

@author: Tanushree Gupta
"""

# To open the file
ref = open("romeo.txt", "rt")
content = ref.readlines()

    # List to hold the list of the words
req_content = []
for var in content:

    req_content.append(var.split())

    # To count the words using dictionary
r_and_j = {}
for var2 in req_content:
    for var3 in var2:
        if var3 not in r_and_j:
            r_and_j[var3] = 1
        else:
            r_and_j[var3]+=1

    print(str(r_and_j))

    len(r_and_j)
    type(r_and_j)

DS DAY 5 LEARNINGS/day5task_romeo and juliet.py


import streamlit as st
import pandas as pd

from sklearn import tree
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix

siteHeader = st.container()
with siteHeader:
    st.title('Modelo de evaluación de ingresos')
    st.markdown(""" En este proyecto se busca encontrar cuáles son las características
    principales que pueden predecir que una persona gane más o menos de $50 K anuales.""")

dataExploration = st.container()
with dataExploration:
    st.header('Dataset: Ingresos')
    st.text("""Este dataset corresponde a una transformación del set de datos oficial proveniente del
    siguiente set de datos:""")

df = pd.read_csv('https://raw.githubusercontent.com/fridaruh/dashboard_streamlit/master/income.csv')

st.write(df.head())

st.subheader('Distrbuciones:')

distribution_sex = pd.DataFrame(df.sex.value_counts())

st.bar_chart(distribution_sex)

st.text('Con esta gráfica buscamos mostrar la distribución de los datos con respecto al sexo.')

newFeatures = st.container()
with newFeatures:
    st.header('Nuevas variables: ')
    st.text('Demos un vistazo a las principales variables de este dataset: ')

st.markdown('* **first feature:** this is the explanation')
st.markdown('* **second feature:** another explanation')

modelTraining = st.container()
with modelTraining:
    st.header('Entrenamiento del modelo')
    st.text('En esta sección puedes hacer una selección de los hiperparámetros del modelo.')

df = df.drop(['Unnamed: 0','income','fnlwgt','capital-gain','capital-loss','native-country'], axis=1)
Y = df['income_bi']
df = df.drop(['income_bi'], axis=1)
X = pd.get_dummies(df, columns = ['race','sex','workclass','education','education-num','marital-status','occupation','relationship'])
x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state= 15)

max_depth = st.slider ('¿Cuál debería ser el valor de max_depth para el modelo?', min_value=1, max_value=10, value=2, step=1)

t = tree.DecisionTreeClassifier(criterion = 'entropy', max_depth=max_depth)
model = t.fit(x_train, y_train)

prediction = model.predict(x_test)
score = model.score(x_train, y_train)

st.header('Performance del Modelo')
st.text('Score:')
st.text(score)

st.markdown( """ <style>
 .main {
 background-color: #AF9EC;
}
</style>""", unsafe_allow_html=True )