import time

from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

def is_element_present(how, what):
    if len(driver.find_elements(by=how, value=what)) == 0:
        return False
    else:
        return True

driver = webdriver.Chrome(executable_path=ChromeDriverManager().install())

driver.get('http://www.tizag.com/htmlT/htmlcheckboxes.php')
driver.maximize_window()
driver.implicitly_wait(10)

# driver.find_element(By.XPATH, '//div[4]//input[1]').click()
# driver.find_element(By.XPATH, '//div[4]//input[2]').click()
# driver.find_element(By.XPATH, '//div[4]//input[3]').click()
# driver.find_element(By.XPATH, '//div[4]//input[4]').click()

# i = 1
#
# while is_element_present(By.XPATH, "//div[4]/input["+str(i)+"]"):
#     driver.find_element(By.XPATH, "//div[4]/input["+str(i)+"]").click()
#     i += 1

# print('Total checkboxes are :', i - 1)

checkboxes = driver.find_elements(By.NAME, 'sports')
print(len(checkboxes))

block = driver.find_element(By.XPATH, "//div[@class='display'][1]")

checkbox_in_block = block.find_elements(By.NAME, 'sports')
print(len(checkbox_in_block))

for checkbox in checkboxes:
    print('Before clicking: ', checkbox.is_selected())
    checkbox.click()
    print('After clicking: ', checkbox.is_selected())

time.sleep(3)


from binary_tree import *
import argparse
import csv
import sys

parser = argparse.ArgumentParser(description='annotate with genome loci')
parser.add_argument('input_csv', type=argparse.FileType('r'), help='final checked csv')
parser.add_argument('loci_list_csv', help='csv list of locus,start,end')
parser.add_argument('output_csv', type=argparse.FileType('w'), help='output csv with locus annotation')

def main():
    args = parser.parse_args()
    with open(args.loci_list_csv, 'r') as amr:
        lines = amr.readlines()

    features = []
    for each in lines:
        feat = each.rstrip().split(',')
        # Convert BED coordinates to VCF coordinates
        features.append((feat[0], int(feat[1])+1, int(feat[2])))
    mytree = RangeTree(features)

    variants_reader = csv.DictReader(args.input_csv)
    fieldnames = variants_reader.fieldnames
    fieldnames.append('LOCI')
    writer = csv.DictWriter(args.output_csv, fieldnames = fieldnames)
    writer.writeheader()
    variant = next(variants_reader, None)
    while variant:
        variant['LOCI'] = mytree.assign(int(variant['POS']))
        writer.writerow(variant)
        variant = next(variants_reader, None)
    #print(mytree.assign(5245))

if __name__ == '__main__':
    sys.exit(main())


from flask import Flask, render_template, redirect
import pymongo
import scrape_mars

client = pymongo.MongoClient('mongodb://localhost:27017')
db = client.mars_db
collection = db.mars

app = Flask(__name__)

@app.route("/")
def index():
    mars = collection.find_one()
    return render_template("index.html", mars = mars)

@app.route("/scrape")
def scrape():
    #mars = mongo.db.mars
    mars_data = scrape_mars.scrape(collection)
    collection.update({}, mars_data, upsert=True)
    return redirect("http://localhost:5000/", code=302)

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


import math
from typing import Tuple

import noise

ZONES = {
    "S": (0.0, 0.3),  # Snow
    "F": (0.3, 0.4),  # Forest
    "P": (0.4, 0.7),  # Forest
    "D": (0.7, 1.0)  # Desert
}

def get_for_noise(noise_val):
    noise_val += 1.0
    noise_val /= 2.0
    noise_val = max(0.00, noise_val)
    noise_val = min(0.99, noise_val)

    for zone, temperature in ZONES.items():
        if temperature[0] <= noise_val < temperature[1]:
            return zone

def noise_octave(noise_func=None, octaves: int = 1, persistence: float = 1.0, coordinates: Tuple[float, ...] = ()):
    total = 0.0
    frequency = 1.0
    amplitude = 1.0
    max_value = 0.0
    for _ in range(octaves):
        noise_value = noise_func(*tuple(coord * frequency for coord in coordinates)) * amplitude
        total += noise_value
        max_value += amplitude

        amplitude *= persistence
        frequency *= 2

    return total / max_value

def generate_terrain(dimensions, zone_size=15, spawn_range=50, seed=None):
    # map_middle = dimensions // 2
    # map = [["?" for x in range(dimensions)] for y in range(dimensions)]
    # features = [[None for x in range(dimensions)] for y in range(dimensions)]
    #
    # if not seed:
    #     seed = random.randrange(-1000, 1000)
    #
    # for x in range(dimensions):
    #     for y in range(dimensions):
    #         # within_spawn_range = spawn_range > math.sqrt((x - map_middle) ** 2 + (y - map_middle) ** 2)
    #         pass

    pass

def tile_terrain(x: int, y: int, seed: int, map_size: int, spawn_range=50):
    map_middle = map_size // 2
    terrain_data = get_for_noise(
        noise_octave(
            noise_func=noise.snoise3,
            octaves=2,
            persistence=0.1,
            coordinates=(x / 40, y / 40, seed)
        )
    )
    feature = ""

    # Since we want to avoid having a lot of water near the spawn range, we can use
    # a down-pointing elliptic paraboloid to represent the probability of a river at
    # that position.

    # This is all ad-hoc. Not a lot of thought went into the math.

    # check if the coordinates are within the spawn range (pythagoras theorem)
    max_noise_range = 0.15
    within_spawn_range = spawn_range > math.sqrt((x - map_middle) ** 2 + (y - map_middle) ** 2)
    if within_spawn_range:
        max_noise_range /= 2
        # max_noise_range = ((x ** 2) / 16 + (y ** 2) / 16) / 100000
    river_val = noise_octave(
        noise_func=noise.snoise3,
        octaves=1,
        persistence=0.1,
        coordinates=(x / 50, y / 50, seed)
    )

    if max_noise_range > river_val > 0.0:
        terrain_data = "W"

    # For cities, we will base it off the river noise (cities are typically close to water bodies).
    # But since we don't want cities everywhere, we will do a noise cross between the river noise
    # and a new noise (nRiver X nCities) = nCoastCities.

    city_val = noise_octave(
        noise_func=noise.snoise3,
        octaves=2,
        persistence=0.2,
        coordinates=(x / 30, y / 30, seed)
    )

    if max_noise_range + 0.2 > river_val > max_noise_range > city_val > 0:
        feature = "fC"

    # For shelters, we'll try to keep them pretty far from the cities for the added challenge.
    # The generation is done by making a highly sparse (+octave) noise and using an invert treshold from
    # the cities

    shelter_val = noise_octave(
        noise_func=noise.snoise3,
        octaves=4,
        persistence=0.4,
        coordinates=(x, y, seed)
    )

    if max_noise_range + 0.8 > shelter_val > max_noise_range + 0.75:
        feature = "fS"

    return terrain_data, feature


#!/usr/bin/env python3
# vim: set fileencoding=utf-8 :

from argparse import ArgumentParser
from calendar import timegm
from pathlib import Path
from time import sleep, strptime, time
from urllib.parse import quote

import db
import json
import os
import requests
import shelve
import sys

argparser = ArgumentParser(description='''
  Fetch tweets that match a query, and add them to db/tweets.
''')

defaultargs = {}
configpath = Path('db/config.json')
try:
  with configpath.open() as config:
    defaultargs = json.load(config)
    if False:
      print(defaultargs)
except Exception as e:
  sys.stderr.write('W: no db/config.json {}\n'.format(e))
def argdef(k):
  return defaultargs[k] if k in defaultargs else None

argparser.add_argument('-q',
  help='query')
argparser.add_argument('-geocode', default=argdef('geocode'),
  help='e.g., 44.447924,26.097879,150km')
argparser.add_argument('-authors', default=argdef('authors'), nargs='+',
  help='filter by author')
argparser.add_argument('-count', default=argdef('count'), type=int,
  help='batch size')
argparser.add_argument('-total', default=argdef('total'), type=int,
  help='total number of tweets to fetch')
argparser.add_argument('-delay', default=argdef('delay'), type=float,
  help='delay between batches, in seconds')
argparser.add_argument('-r', '--refetch', action='store_true',
  help='refetch tweets even if we have them')
argparser.add_argument('-verbose', action='store_true')
argparser.add_argument('-d', '--debug', action='store_true',
  help='print to stderr how tweets are parsed')

SEARCH_API_URL = 'https://api.twitter.com/1.1/search/tweets.json'
verbose = None

args = None

# used (rarely) for flow control
class Done(BaseException):
  pass
class NoNewResults(BaseException):
  pass

oauth2_headers = None

last_get = None
def get(url, delay):
  global oauth2_headers
  global last_get
  if last_get:
    sleep(max(0, time() - delay - last_get))
  if False:
    print('GET ', url)
  if oauth2_headers is None:
    with open('secret.credentials') as f:
      for line in f:
        ws = line.split()
        if ws[0] == 'access-token':
          oauth2_headers = {'Authorization' : 'Bearer {}'.format(ws[1])}
          break
  if oauth2_headers is None:
    sys.stderr.write('Please run oauth.py\n')
    raise NoNewResults
  r = requests.get(url, headers=oauth2_headers)
  if verbose and 'x-rate-limit-remaining' in r.headers:
    sys.stderr.write('api-rate-limit-remaining {}\n'.format(r.headers['x-rate-limit-remaining']))
  last_get = time()
  return r.json()

def build_query(q, geocode, count, authors):
  query = ''
  query += '?result_type=recent'
  assert count is not None
  query += '&count={}'.format(count)
  if authors:
    if q is None:
      q = ''
    qs = ['{} from:{}'.format(q, a) for a in authors]
    query += '&q={}'.format(quote(' OR '.join(qs)))
  elif q:
    query += '&q={}'.format(quote(q))
  if geocode:
    query += '&geocode={}'.format(geocode)
  return query

def time_of_raw_tweet(t):
  assert 'created_at' in t
  return timegm(strptime(t['created_at'], '%a %b %d %H:%M:%S +0000 %Y'))

def postprocess_raw_tweets():
  with shelve.open('db/raw') as raw:
    # Update users.
    with shelve.open('db/users') as users:
      for t in raw.values():
        u = t['user']
        users[u['id_str']] = db.User(u['screen_name'])
        for u in t['entities']['user_mentions']:
          users[u['id_str']] = db.User(u['screen_name'])
        if t['in_reply_to_user_id_str']:
          if t['in_reply_to_screen_name']:
            users[t['in_reply_to_user_id_str']] = db.User(t['in_reply_to_screen_name'])

    # Update tweets.
    with shelve.open('db/tweets') as tweets:
      for i, t in raw.items():
        if not args.refetch and i in tweets:
          sys.stderr.write('W: tweet {} already in db\n'.format(i))
        else:
          text = t['text']
          time = time_of_raw_tweet(t)
          author = t['user']['id_str']
          mention = db.Mention()
          for u in t['entities']['user_mentions']:
            mention.users.add(u['id_str'])
          if t['in_reply_to_user_id_str']:
            mention.users.add(t['in_reply_to_user_id_str'])
          for u in t['entities']['urls']:
            mention.urls.add(u['expanded_url'])
          if 'retweeted_status' in t:
            mention.tweets.add(t['retweeted_status']['id_str'])
            mention.users.add(t['retweeted_status']['user']['id_str'])
            for u in t['retweeted_status']['entities']['urls']:
              mention.urls.add(u['expanded_url'])
          if 'quoted_status' in t:
            mention.tweets.add(t['quoted_status']['id_str'])
            mention.users.add(t['quoted_status']['user']['id_str'])
            for u in t['quoted_status']['entities']['urls']:
              mention.urls.add(u['expanded_url'])
          parsed = db.Tweet(text, time, author, mention)
          tweets[i] = parsed
          if args.debug:
            json.dump({'in':t, 'out':parsed.as_dict()}, sys.stderr)
            sys.stderr.write('\n')
  os.remove('db/raw')

bad_times = False
def check_times(tweets):
  global bad_times
  if bad_times:
    return
  p = None
  bad = False
  for t in tweets:
    if p is None:
      p = time_of_raw_tweet(t)
    else:
      n = time_of_raw_tweet(t)
      if p < n:
        bad_times = True
        sys.stderr.write('W: tweet times are not ordered\n')

def main():
  global args
  global verbose
  args = argparser.parse_args()
  verbose = args.verbose
  if not args.authors:
    args.authors = [[]]
  else:
    args.authors = [args.authors[i:i+5] for i in range(0,len(args.authors),5)]
  args.total = 1 + args.total // len(args.authors)
  for authors in args.authors:
    processed = 0
    sys.stderr.write('fetching {} from {}\n'.format(args.total, ' '.join(authors)))
    query = build_query(args.q, args.geocode, args.count, authors)
    try:
      with shelve.open('db/tweets') as tweets:
        with shelve.open('db/raw') as raw:
          page = get('{}{}'.format(SEARCH_API_URL, query), args.delay)
          while True:
            check_times(page['statuses'])
            for s in page['statuses']:
              if not args.refetch and s['id_str'] in tweets:
                raise Done # assumes that times are descending
              raw[s['id_str']] = s
              processed += 1
              if args.total and processed >= args.total:
                raise Done
            raw.sync()
            sys.stderr.write('fetched {} tweets\n'.format(processed))
            if 'next_results' not in page['search_metadata']:
              if not args.refetch:
                sys.stderr.write('W: gap in tweet data; run me more often\n')
              raise Done
            query = page['search_metadata']['next_results']
            page = get('{}{}'.format(SEARCH_API_URL, query), args.delay)
    except Done:
      sys.stderr.write('fetched {} tweets (DONE)\n'.format(processed))
    except NoNewResults:
      sys.stderr.write('no tweets to fetch\n')
    postprocess_raw_tweets()

if __name__ == '__main__':
  main()


import math
from argparse import ArgumentParser
from logging import warning

import pathlib
import os
import re
import shutil
import json
from pathlib import Path

def process_script(ds_name, package, file_name, id_, type_, name, known_results, path_to_results):
    from evaluate_ctrl import main
    key = f"{id_}_{type_}"
    if key not in known_results:
        script_results = main(file_name=file_name, package=package, ds_name=ds_name)
        known_results[key] = script_results
        known_results[key]["name"] = name
        with path_to_results.open("w") as f:
            json.dump(dict(sorted(known_results.items())), f, indent=4)
        print("#" * 100)
    return known_results

def load_current_results(results_folder):
    current_results = {}
    for p in results_folder.glob('*json'):
        try:
            for fres in results_folder.glob("results*.json"):
                with fres.open("r") as inp:
                    current_results.update(json.load(inp))
        except Exception as e:
            warning(str(e))
    return current_results

SOLUTION_REGEX = r"(?P<name>^[^_]*)_(?:LATE_)?(?P<id>[0-9]{4,})_.*_(?P<type>[\w-]*$)"

if __name__ == "__main__":

    parser = ArgumentParser()
    parser.add_argument("--hw_folder", help="Path to solutions folder. "
                                            "Should have 'submissions' subfolder with assignment solution files"
                                            "solution file format should match SOLUTION_REGEX",
                        type=Path)
    parser.add_argument("--index", help="Index of the submission to evaluate. Use for parallel evaluation.",
                        default=None,
                        type=int)
    parser.add_argument("--ds_name", help="Dataset name.",
                        default="FILIMDB_hidden",
                        type=str)
    args = parser.parse_args()

    hw_folder = args.hw_folder
    ds_name = args.ds_name

    if not hw_folder.exists():
        raise FileNotFoundError("Solutions directory does not exist")

    eval_folder = hw_folder / "evaluation"
    results_folder = hw_folder / "results"
    submissions_folder = hw_folder / "submissions"

    for folder in [eval_folder, results_folder]:
        if not folder.exists():
            folder.mkdir()

    current_results = load_current_results(results_folder)
    for index, file_path in enumerate(sorted(submissions_folder.glob("*/*.py"))):
        file_name = str(file_path.stem)
        if "__init__" in file_name:
            continue
        print(file_name, SOLUTION_REGEX)
        matched = re.search(SOLUTION_REGEX, file_name)
        if matched is None:
            print(f"Couldn't match filename {file_name} with regex {SOLUTION_REGEX}")
            continue
        matched = matched.groups()

        student_name, student_id, submission_type = matched
        print(index, file_name, student_name, student_id, submission_type, sep=', ', flush=True)
        if args.index is None or args.index == index:
            process_script(ds_name=ds_name, file_name=file_name, id_=student_id, type_=submission_type, name=student_name,
                           known_results=current_results,
                           package=".".join(str(file_path).split("/")[:-1]),
                           path_to_results=results_folder / f"results{index}.json")


# coding: utf-8

from unipath import Path

PROJECT_DIR = Path(__file__).ancestor(3)

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
	('Felipe Coelho', 'fcoelho.9@gmail.com'),
	('Guilherme Gibertoni', 'kuramayoko10@gmail.com'),
	('Cesar Milano', 'cesar.milano@gmail.com')
)

MANAGERS = ADMINS

TIME_ZONE = 'America/Sao_Paulo'
LANGUAGE_CODE = 'pt-BR'

USE_I18N = True
USE_L10N = True
USE_TZ = True

MEDIA_ROOT = PROJECT_DIR.child('media')
MEDIA_URL = '/media/'

STATIC_ROOT = PROJECT_DIR.child('static')
STATIC_URL = '/static/'

SECRET_KEY = 'gwxr4yc-*@85$#9s@uh268y7c2xxad1+#g+n*$hk9j%gihpo2r'

ROOT_URLCONF = 'wict.urls'

INSTALLED_APPS = (
	# Wict apps come first -> select wict templates first!
	'website',
	'submission',
	'review',
	# Django contrib apps
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
	# Thirdy party apps
	'signup',
	'sendfile',
)

MIDDLEWARE_CLASSES = (
	'django.middleware.common.CommonMiddleware',
	'django.contrib.sessions.middleware.SessionMiddleware',
	'django.middleware.csrf.CsrfViewMiddleware',
	'django.contrib.auth.middleware.AuthenticationMiddleware',
	'django.contrib.messages.middleware.MessageMiddleware',
	'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

AUTH_USER_MODEL = 'website.WictUser'
SIGNUP_FORM_CLASS = 'website.forms.UserSignUpForm'

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

ACCOUNT_ACTIVATION_DAYS = 2

LOGIN_REDIRECT_URL = '/'

MAX_ARTICLE_FILE_SIZE = 2 * 1024 * 1024
MAX_ARTICLE_PAGES = 3


from .common import *

# Heroku
import dj_database_url

# ##############  DATABASES
# Heroku settings
DATABASES = {
    'default':  dj_database_url.config(),
}

# # ########################## AWS S3 Private Media Upload
if USE_S3:
    # # ########################## AWS S3 - Settings Variable
    AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME')
    AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'

   # # ########################## AWS S3 Static files (CSS, JavaScript, Images)
    # # Amazon S3/myBucketName/static/myimage/files
    STATICFILES_LOCATION = 'static'
    STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{STATICFILES_LOCATION}/'
    # STATIC_ROOT = [os.path.join(BASE_DIR, 'mypage/static'), ]  # Não usar com S3
    STATICFILES_STORAGE = config('AWS_STATICFILES_STORAGE')

    # # ########################## AWS S3 Private Media Upload
    # # Amazon S3/myBucketName/media/myimage/files
    MEDIAFILES_LOCATION = 'media'

    # https://testheroku-assets.s3.amazonaws.com/media/myimage/images/Course_6.png
    AWS_S3_PATH = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com'  # 20190822/0724
    MEDIA_URL = f'https://{AWS_S3_PATH}/{MEDIAFILES_LOCATION}/'

    # MEDIA_ROOT = os.path.join(BASE_DIR, 'mypage/media') # Não usar com S3
    DEFAULT_FILE_STORAGE = config('AWS_DEFAULT_FILE_STORAGE')


import numpy as np

from gym.spaces import Box
from gym import ObservationWrapper

class ResizeObservation(ObservationWrapper):
    r"""Downsample the image observation to a square image. """
    def __init__(self, env, shape):
        super(ResizeObservation, self).__init__(env)
        if isinstance(shape, int):
            shape = (shape, shape)
        assert all(x > 0 for x in shape), shape
        self.shape = tuple(shape)

        obs_shape = self.shape + self.observation_space.shape[2:]
        self.observation_space = Box(low=0, high=255, shape=obs_shape, dtype=np.uint8)

    def observation(self, observation):
        import cv2
        observation = cv2.resize(observation, self.shape[::-1], interpolation=cv2.INTER_AREA)
        if observation.ndim == 2:
            observation = np.expand_dims(observation, -1)
        return observation


from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.views.generic import ListView, DetailView
from .models import Item, OrderItem, Order
from django.contrib import messages
from django.utils import timezone
from django.views import View

class HomeView(View):

    def get(self, request, *args, **kwargs):
        # Get all items from the Item model
        products = Item.objects.all()

        # Get the current user's cart items, assuming the user is logged in via admin panel
        # You can update this logic as per your authentication implementation
        if request.user.is_authenticated:
        # Assuming Order model has a one-to-one relationship with User model
        # You can adjust the relationship based on your actual model structure
            order = Order.objects.filter(user=request.user, ordered=False).first()
            if order:
                # Count only the OrderItems that are still associated with the Order
                cart_count = order.items.filter(ordered=False).count()
            else:
                cart_count = 0
        else:
            cart_count = 0

        context = {
            'products': products,
            'cart_count': cart_count
        }
        return render(request, 'home.html', context)

        # Add cart_items_count to the context

class ProductDetailView(DetailView):
    model = Item
    template_name = 'product.html'
    context_object_name = 'product'

class AddToCartView(View):
    def get(self, request, slug):
        item = get_object_or_404(Item, slug=slug)
        order_item, created = OrderItem.objects.get_or_create(item=item, user=request.user, ordered=False)
        order_qs = Order.objects.filter(user=request.user, ordered=False)
        if order_qs.exists():
            order = order_qs[0]
            if order.items.filter(item__slug=item.slug):
                order_item.quantity += 1
                order_item.save()
                messages.success(request, f"{item.title}'s quantity was successfully updated in cart")
                return redirect('product', slug=slug)
            else:
                order.items.add(order_item)
                order.save()
                messages.success(request, f"{item.title} was successfully added to cart")
                return redirect('product', slug=slug)

        else:
            ordered_date = timezone.now()
            order = Order.objects.create(user=request.user, ordered=False, ordered_date=ordered_date)
            order.items.add(order_item)
            order.save()
            messages.success(request, f"{item.title} was successfully added to cart")
            return redirect('product', slug=slug)

    def post(self, request, slug):
        return self.get(request, slug)

class RemoveItemFromCartView(View):
    def get(self, request, slug):
        item = get_object_or_404(Item, slug=slug)
        order_item = OrderItem.objects.filter(item=item, user=request.user, ordered=False)
        order_qs = Order.objects.filter(user=request.user, ordered=False)
        if order_qs.exists():
            order = order_qs[0]
            if order.items.filter(item__slug=item.slug).exists():
                order_item.delete()  # Remove the item from OrderItem table
                order.save()
                messages.success(request, f"{item.title} was successfully removed from your cart")
                return redirect('product', slug=slug)
            else:
                messages.info(request, f"{item.title} was not in your cart")
                return redirect('product', slug=slug)
        else:
            messages.info(request, "You do not have an active order!")
            return redirect('product', slug=slug)

    def post(self, request, slug):
        return self.get(request, slug)

class CartView(View):
    def get(self, request, *args, **kwargs):
        cart = None
        cart_total = 0
        if request.user.is_authenticated:
            # Assuming Order model has a one-to-one relationship with User model
            # You can adjust the relationship based on your actual model structure
            order = Order.objects.filter(user=request.user, ordered=False).first()
            if order:
                # Count only the OrderItems that are still associated with the Order
                cart = order.items.filter(ordered=False)
                # Calculate the total amount for checked items in the cart
                checked_items = request.GET.getlist('items')  # Get the list of checked items from query parameters
                cart_total = sum(item.item.price * item.quantity for item in cart if str(item.item.slug) in checked_items)
            else:
                messages.info(request, 'You have no item in your cart!')
        else:
            messages.info(request, 'Please sign in to view your cart')

        context = {'cart': cart, 'cart_total': cart_total}
        return render(request, 'cart.html', context)


from datetime import datetime
from typing import List
import logging
import requests
from requests.exceptions import RequestException
from bs4 import BeautifulSoup

import discord
from discord import app_commands
from discord.ext import commands

from uqcsbot.bot import UQCSBot
from uqcsbot.yelling import yelling_exemptor

MAX_COUPONS = 10  # Prevents abuse
COUPONESE_DOMINOS_URL = "https://www.couponese.com/store/dominos.com.au/"

class HTTPResponseException(Exception):
    """
    An exception for when a HTTP response is not requests.codes.ok
    """

    def __init__(self, http_code: int, *args: object) -> None:
        super().__init__(*args)
        self.http_code = http_code

class DominosCoupons(commands.Cog):
    def __init__(self, bot: UQCSBot):
        self.bot = bot

    @app_commands.command()
    @app_commands.describe(
        number_of_coupons="The number of coupons to return. Defaults to 5 with max 10.",
        ignore_expiry="Indicates to include coupons that have expired. Defaults to True.",
        keywords="Words to search for within the coupon. All coupons descriptions will mention at least one keyword.",
    )
    @yelling_exemptor(input_args=["keywords"])
    async def dominoscoupons(
        self,
        interaction: discord.Interaction,
        number_of_coupons: int = 5,
        ignore_expiry: bool = True,
        keywords: str = "",
    ):
        """
        Returns a list of dominos coupons
        """
        if number_of_coupons < 1 or number_of_coupons > MAX_COUPONS:
            await interaction.response.send_message(
                content=f"You can't have that many coupons. Try a number between 1 and {MAX_COUPONS}.",
                ephemeral=True,
            )
            return
        await interaction.response.defer(thinking=True)

        try:
            coupons = _get_coupons(number_of_coupons, ignore_expiry, keywords.split())
        except RequestException as error:
            logging.warning(
                f"Could not connect to dominos coupon site ({COUPONESE_DOMINOS_URL}): {error.response.content}"
            )
            await interaction.edit_original_response(
                content=f"Sadly could not reach the coupon website (<{COUPONESE_DOMINOS_URL}>)..."
            )
            return
        except HTTPResponseException as error:
            logging.warning(
                f"Received a HTTP response code {error.http_code}. Error information: {error}"
            )
            await interaction.edit_original_response(
                content=f"Could not find the coupons on the coupon website (<{COUPONESE_DOMINOS_URL}>)..."
            )
            return

        if not coupons:
            await interaction.edit_original_response(
                content=f"Could not find any coupons matching the given arguments from the coupon website (<{COUPONESE_DOMINOS_URL}>)."
            )
            return

        embed = discord.Embed(
            title="Domino's Coupons",
            url=COUPONESE_DOMINOS_URL,
            description=f"Keywords: *{keywords}*" if keywords else None,
            timestamp=datetime.now(),
        )
        for coupon in coupons:
            embed.add_field(
                name=coupon.code,
                value=f"{coupon.description} *[Expires: {coupon.expiry_date}]*",
                inline=False,
            )
        await interaction.edit_original_response(embed=embed)

class Coupon:
    def __init__(self, code: str, expiry_date: str, description: str) -> None:
        self.code = code
        self.expiry_date = expiry_date
        self.description = description

    def is_valid(self) -> bool:
        try:
            expiry_date = datetime.strptime(self.expiry_date, "%Y-%m-%d")
            now = datetime.now()
            return all(
                [
                    expiry_date.year >= now.year,
                    expiry_date.month >= now.month,
                    expiry_date.day >= now.day,
                ]
            )
        except ValueError:
            return True

    def keyword_matches(self, keyword: str) -> bool:
        return keyword.lower() in self.description.lower()

def _get_coupons(n: int, ignore_expiry: bool, keywords: List[str]) -> List[Coupon]:
    """
    Returns a list of n Coupons
    """

    coupons = _get_coupons_from_page()

    if not ignore_expiry:
        coupons = [coupon for coupon in coupons if coupon.is_valid()]

    if keywords:
        coupons = [
            coupon
            for coupon in coupons
            if any(coupon.keyword_matches(keyword) for keyword in keywords)
        ]
    return coupons[:n]

def _get_coupons_from_page() -> List[Coupon]:
    """
    Strips results from html page and returns a list of Coupon(s)
    """
    http_response = requests.get(COUPONESE_DOMINOS_URL)
    if http_response.status_code != requests.codes.ok:
        raise HTTPResponseException(http_response.status_code)
    soup = BeautifulSoup(http_response.content, "html.parser")
    soup_coupons = soup.find_all(class_="ov-coupon")

    coupons: List[Coupon] = []

    for soup_coupon in soup_coupons:
        expiry_date_str = soup_coupon.find(class_="ov-expiry").get_text(strip=True)
        description = soup_coupon.find(class_="ov-desc").get_text(strip=True)
        code = soup_coupon.find(class_="ov-code").get_text(strip=True)
        coupon = Coupon(code, expiry_date_str, description)
        coupons.append(coupon)

    return coupons

async def setup(bot: UQCSBot):
    await bot.add_cog(DominosCoupons(bot))


from PyQt5.QtWidgets import (QWidget, QLCDNumber, QSlider, QMainWindow,
                             QGridLayout, QApplication, QPushButton, QLabel, QLineEdit)

from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
from PyQt5.QtCore import Qt
# from predictsingle import predict
from PIL import Image
import predictclass

class Ui_example(QWidget):
    def __init__(self):
        super().__init__()  # 主函数了

        self.layout = QGridLayout(self)  # 创建一个整体界面
        self.setStyleSheet('background:green')
        self.label_image = QLabel(self)  # 选择图片后显示图片的标签
        self.label_predict_result = QLabel('识别结果', self)  # 识别结果文本提示标签
        self.label_predict_result_display = QLabel(self)  # 识别结果标签
        self.label_predict_acc = QLabel('识别准确率', self)  # 识别准确率文本提示标签
        self.label_predict_acc_display = QLabel(self)  # 识别准确率结果标签

        self.button_search_image = QPushButton('选择图片', self)  # 选择图片的文本提示标签
        self.button_run = QPushButton('运行', self)  # 运行标签
        self.setLayout(self.layout)  # 设置程序界面,并将创建的界面添加到这里
        self.initUi()  # 调用下面的方法,将初始化函数中的这个self传进去

    def initUi(self):
        self.layout.addWidget(self.label_image, 1, 1, 3, 2)  # 将上面创建的一系列标签按追加到界面中,并设置显示位置
        self.layout.addWidget(self.button_search_image, 1, 3, 1, 2)
        self.layout.addWidget(self.button_run, 3, 3, 1, 2)
        self.layout.addWidget(self.label_predict_result, 4, 3, 1, 1)
        self.layout.addWidget(self.label_predict_result_display, 4, 4, 1, 1)
        self.layout.addWidget(self.label_predict_acc, 5, 3, 1, 1)
        self.layout.addWidget(self.label_predict_acc_display, 5, 4, 1, 1)

        self.button_search_image.clicked.connect(self.openimage)  # 对选择图片按钮设置点击操作,点击后执行openimage操作
        self.button_run.clicked.connect(self.run)  # 对运行按钮执行运行函数 self.openimage self.run指的应该是本类函数

        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle('flowers-10十分类')
        self.show()

    def openimage(self):
        global fname
        imgName, imgType = QFileDialog.getOpenFileName(self, "选择图片", "", "*.jpg;;*.png")  # imgName返回文件绝对路径
        # imgType返回文件类型即拓展名
        print('imgName:{}'.format(imgName))
        print('imgType:{}'.format(imgType))
        jpg = QPixmap(imgName).scaled(self.label_image.width(), self.label_image.height())
        self.label_image.setPixmap(jpg)
        fname = imgName

    def run(self):
        global fname
        print('type(fname):{}'.format(type(fname)))
        # file_name = str(fname) #下面去掉了对fname的强转str的操作，因为上面打印fname类型发现已经是str了
        file_name = fname
        img = Image.open(file_name)

        a, b = predictclass.predict(img)
        self.label_predict_result_display.setText(a)
        self.label_predict_acc_display.setText(str(b))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Ui_example()
    sys.exit(app.exec_())


import pygame
from pygame.locals      import *
from utils              import my_quit

class KeyboardEvent:

    def __init__(self):
        self.x = 0
        self.y = 0
        self.game_speed = 0.5
        self.disco = 0

    def key_callback(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                my_quit()
            elif event.type == pygame.KEYDOWN:
                self.key_down(event)
            elif event.type == pygame.KEYUP:
                self.key_up(event)
        self.key_pressed()

    def key_pressed(self):
        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[K_a]:
            self.x += 0.10
        if keys_pressed[K_d]:
            self.x -= 0.10
        if keys_pressed[K_w]:
            self.y -= 0.10
        if keys_pressed[K_s]:
            self.y += 0.10
        if keys_pressed[K_LSHIFT]:
            self.game_speed = 1.5

    def key_up(self, event):
        if event.key == pygame.K_a or event.key == pygame.K_d:
            self.x = 0
        if event.key == pygame.K_w or event.key == pygame.K_s:
            self.y = 0
        if event.key == pygame.K_LSHIFT:
            self.game_speed = 0.5

    def key_down(self, event):
        if event.key == pygame.K_ESCAPE:
            my_quit()
        if event.key == pygame.K_SPACE:
            if self.disco == 1:
                self.disco = 0
            else:
                self.disco = 1


import scrapy
import os
### THIS FILE IS COMPLETE
counter = 0
class imdbSpider(scrapy.Spider):

    def stringGen():
        toReturn = []
        minUserrtg = 1.0
        maxUserrtg = 1.0
        BASE_STRING = 'https://www.imdb.com/search/title?title_type=feature&user_rating='
        REST_OF_STRING = '&count=10000&sort=alpha,asc'

        while minUserrtg <4:

            maxUserrtg = min(maxUserrtg, 10)
            minUserrtg = min(minUserrtg, 10)
            toReturn.append(BASE_STRING +(str)(minUserrtg) + ',' + (str)(maxUserrtg) + REST_OF_STRING)
            minUserrtg += 0.1
            maxUserrtg += 0.1

        return toReturn

    name = 'imdb'
    start_urls = stringGen()
    print(start_urls)
    handle_httpstatus_list = [404]

    def parse(self, response):

        SET_SELECTOR = '.lister-item-content'
        global counter
        for object in response.css(SET_SELECTOR):

            NAME_SELECTOR = 'a ::text'
            YEAR_SELECTOR = '.lister-item-year ::text'
            GENRE_SELECTOR = '.genre ::text'
            yield{

                 'name': object.css(NAME_SELECTOR).extract_first().encode('utf-8'),

                 'imdbRating': object.xpath(".//strong/text()").extract_first().encode('utf-8'),
                 'year': object.css(YEAR_SELECTOR).extract_first().strip("()").encode('utf-8'),
                 'genre': [x.strip() for x in object.css(GENRE_SELECTOR).extract()],
                 'BoxOffice': object.xpath('//span[5]/@data-value').extract_first().strip(",")
            }

        NEXT_PAGE_SELECTOR = 'a ::attr(href)'
        if(counter == 0):
            next_page = response.xpath("//*[@id='main']/div/div/div[4]/div/a/@href").extract_first()
        else:
            next_page = response.xpath("//*[@id='main']/div/div/div[4]/div/a[2]/@href").extract_first()
        counter = counter + 1
        if next_page:
            yield scrapy.Request(
                response.urljoin(next_page),
                callback=self.parse
            )


from gpiozero import LED, Button
import time
from random import uniform
from os import _exit

leftName = input("Left player, Type Name: ")
rightName = input("Right player, Type Name: ")
led = LED(4)
rightBTN = Button(15)
leftBTN = Button(14)

led.on()
time.sleep(uniform(5,10))
led.off()

def pressed(button):
    if button.pin.number == 14:
        print(leftName + " won the game!")
    else:
        print(rightName + " won the game!")
    _exit(0)

rightBTN.when_pressed = pressed
leftBTN.when_pressed = pressed


from django.shortcuts import render
from realtys.models import Realty, RealtyType, Bill, RealtyManager, Usd
from django.db.models import Q
from django import template

# Create your views here.

def index(request):
    title = 'Агенство недвижимости'
    managers = RealtyManager.objects.all()[:3]
    realtys = Realty.objects.all()[:5]
    return render(request, 'index.html', {'realtys': realtys, 'managers': managers, 'title': title})

def contacts(request):
    title = 'Контакты'
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        subject = request.POST.get('subject')
        message = request.POST.get('message')
        from_email = 'plotnikov-d@bk.ru'
        email_manager = 'menedger@mail.ru'
        bill_obj = Bill(name=name, email=email, subject=subject, message=message, from_email=from_email,
                        email_manager=email_manager)
        bill_obj.save()
    return render(request, 'contacts.html', {'title': title})

def search(request):
    usd = Usd.objects.last()
    rate_usd = round(1/usd.usd_now, 2)
    title = 'Поиск'
    text_q = request.GET.get('text')
    price1_q = request.GET.get('price1')
    price2_q = request.GET.get('price2')
    s1_q = request.GET.get('s1')
    s2_q = request.GET.get('s2')
    type_q = request.GET.get('type')

    if text_q:
        text = text_q.split()
        q_object = Q()
        for i in text:
            q_object &= (Q(info__iregex=i) | Q(header__iregex=i))
        realtys = Realty.objects.filter(q_object)
    else:
        realtys = Realty.objects.all()

    if price1_q:
        realtys = realtys.filter(cost__gte=price1_q)

    if price2_q:
        realtys = realtys.filter(cost__lte=price2_q)

    if s1_q:
        realtys = realtys.filter(s__gte=s1_q)

    if s2_q:
        realtys = realtys.filter(s__lte=s2_q)

    if type_q:
        realtys = realtys.filter(type=type_q)

    types = RealtyType.objects.all()

    return render(request, 'search.html', {'realtys': realtys, 'types': types, 'title': title, 'rate_usd': rate_usd})

def detail(request, id):
    realty = Realty.objects.get(id=id)
    title = realty.header
    if realty.sale:
        new_cost = int(realty.cost  - (realty.cost * realty.sale))
    else:
        new_cost = 0

    return render(request, 'detail.html', {'realty': realty, 'title': title, 'new_cost': new_cost})


import requests
import data.get_Spotify_token as get_Spotify_token

# Get top 10 most listened songs on Spotify

access_token = get_Spotify_token.get_token()
base_url = 'https://api.spotify.com/v1/'

headers = {
    'Authorization': 'Bearer {}'.format(access_token)
}

featured_playlists_endpoint = \
    'playlists/2YRe7HRKNRvXdJBp9nXFza/tracks?offset=0&limit=10'
featured_playlists_url = ''.join([base_url, featured_playlists_endpoint])

def get_most_popular_songs():
    response = requests.get(featured_playlists_url, headers=headers)
    songs = response.json().get('items')
    return songs


from collections import defaultdict

def change(s):
    # '{'와 '}'를 제거한 뒤 ','단위로 잘라 리스트 반환
    s = s.lstrip('{')
    s = s.rstrip('}')
    return s.split(',')

def solution(s):
    answer = []
    # 중복 방지를 위한 used dict
    used = defaultdict(lambda: 0)
    # s를 '},'단위로 잘라 리스트로 변환 후 각 항목 마다 change 실행
    ns = list(map(change, s.split('},')))
    # 길이 순서로 오름차순 정렬
    # ns.sort(key=len)
    ns.sort(key=lambda x: len(x))

    # 순서에 맞춰 answer 배열에 값 추가
    for t in ns:
        for i in range(len(t)):
            if used[t[i]]:
                continue
            used[t[i]] = 1
            answer.append(int(t[i]))

    return answer

print(solution('{{2},{2,1},{2,1,3},{2,1,3,4}}'))


import random

import numpy as np
import os
from dotenv import load_dotenv

load_dotenv()

L = int(os.getenv("L"))
# Space between next car
S0 = int(os.getenv("S0"))
# Reaction time
T = int(os.getenv("T"))
# Max speed between V_MAX1 et V_MAX2 (m/s)
V_MAX1, V_MAX2 = float(os.getenv("V_MAX1")), float(os.getenv("V_MAX2"))
# Acceleration max between A_MAX1 and A_MAX2 (m/s^^2)
A_MAX1, A_MAX2 = float(os.getenv("A_MAX1")), float(os.getenv("A_MAX2"))
# Max brake between B_MAX1 and B_MAX2 (m/s^^2)
B_MAX1, B_MAX2 = float(os.getenv("B_MAX1")), float(os.getenv("B_MAX2"))
# 1/TRUCK_RATE will be a truck
TRUCK_RATE = int(os.getenv("TRUCK_RATE"))
# Same goes for motorcycles
MOTOR_RATE = int(os.getenv("MOTOR_RATE"))

checkpoint1 = int(os.getenv("CHECKPOINT1"))
checkpoint2 = int(os.getenv("CHECKPOINT2"))
checkpoint3 = int(os.getenv("CHECKPOINT3"))
checkpoint4 = int(os.getenv("CHECKPOINT4"))

class Vehicle:
    def __init__(self, config={}):
        self.type = "car"  # Or "Truck" or "Motorcycle"
        self.checkpoints = {checkpoint1: False, checkpoint2: False, checkpoint3: False, checkpoint4: False}
        self.last_time_lane_change = 0
        self.started_insertion = 0
        self.position = 0
        self.stopped = False
        self.a = 0
        self.x = 0
        self.adj = []
        self.path = []
        self.b_max = random.uniform(B_MAX1, B_MAX2)
        self.a_max = random.uniform(A_MAX1, A_MAX2)
        self.v_max = random.uniform(V_MAX1, V_MAX2)
        self.v = self.v_max
        self.T = T
        self.s0 = S0
        self.timeline = 0
        self.l = L
        self.h = 2
        self.color = (0, 0, 255)
        # Calculate properties
        self.sqrt_ab = 2 * np.sqrt(self.a_max * self.b_max)
        self._v_max = self.v_max

        # Update configuration
        for attr, val in config.items():
            setattr(self, attr, val)

        self.current_road_index = self.path[0]

        self.init_type()

    # Generates buses and motorcycles
    def init_type(self):
        # Generate randomly bus
        random_number = random.randint(1, TRUCK_RATE)
        if random_number == TRUCK_RATE:
            self.type = "truck"
            self.l = 8
            self.a_max = 1.2
            self.v_max = 18
            self.color = (255, 0, 0)
            return
        random_number = random.randint(1, MOTOR_RATE)
        if random_number == MOTOR_RATE:
            self.l = 3
            self.h = 1
            self.a_max = 4
            self.v_max = 48
            self.color = (255,255,0)

    def set_started_insertion(self, time):
        self.started_insertion = time

    def update(self, lead, dt):

        # Update position and velocity
        if self.v + self.a * dt < 0:
            self.x -= 1 / 2 * self.v * self.v / self.a
            self.v = 0
        else:
            self.v += self.a * dt
            self.x += self.v * dt + self.a * dt * dt / 2

        # Update acceleration
        alpha = 0
        if lead:
            delta_x = lead.x - self.x - lead.l
            delta_v = self.v - lead.v

            alpha = (self.s0 + max(0, self.T * self.v + delta_v * self.v / self.sqrt_ab)) / delta_x

        self.a = self.a_max * (1 - (self.v / self.v_max) ** 4 - alpha ** 2)

        if self.stopped:
            self.a = -self.b_max * self.v / self.v_max

    def stop(self):
        self.stopped = True

    def unstop(self):
        self.stopped = False

    def slow(self, v):
        self.v_max = v

    def unslow(self):
        self.v_max = self._v_max

    def set_pos(self, position):
        self.position = position


import logging
from typing import Dict, List, Optional, Any

from langchain.callbacks.manager import (
    AsyncCallbackManagerForChainRun,
    CallbackManagerForChainRun,
)

from ix.chains.callbacks import IxHandler
from langchain.chains.base import Chain
from pydantic import BaseModel

from ix.chat.models import Chat
from ix.task_log.models import Task
from ix.task_log.tasks.agent_runner import start_agent_loop

logger = logging.getLogger(__name__)

MODERATOR_PROMPT = """
You are Ix, an AI assistant. You assist you user with requests by delegating work
to your team of agents.

Respond to all questions for help about Ix and how you work with links to discord and github.
The github includes documentation and source code.

discord: https://discord.gg/jtrMKxzZZQ
github: https://github.com/kreneskyp/ix

AGENTS:
{agents}

CHAT_HISTORY:
{chat_history}

INSTRUCTION:
- Choose the agent from AGENTS who can best process the user request.
- If no AGENT can process then respond as best you can.
- You must choose an agent or respond to the user request.
- Consider the CHAT_HISTORY in your decisions.
"""

CHOOSE_AGENT_PARAMS = {
    "type": "object",
    "properties": {
        "agents": {
            "type": "string",
        }
    },
    "required": ["agents"],
}

class ChooseAgent(BaseModel):
    agent_id: int

CHOOSE_AGENT_FUNC = {
    "class_path": "ix.chains.functions.FunctionSchema",
    "config": {
        "name": "delegate_to_agent",
        "description": "delegate the user request to this agent.",
        "parameters": ChooseAgent.schema_json(indent=4),
    },
}

LLM_CHOOSE_AGENT_CONFIG = {
    "class_path": "ix.chains.llm_chain.LLMChain",
    "config": {
        "verbose": True,
        "output_key": "delegation_or_text",
        "llm": {
            "class_path": "langchain.chat_models.openai.ChatOpenAI",
            "config": {
                "model": "gpt-4-0613",
                "request_timeout": 240,
                "temperature": 0,
                "verbose": True,
                "max_tokens": 1000,
                "streaming": True,
            },
        },
        "prompt": {
            "class_path": "langchain.prompts.chat.ChatPromptTemplate",
            "config": {
                "messages": [
                    {
                        "role": "assistant",
                        "template": MODERATOR_PROMPT,
                        "input_variables": ["agents", "chat_history"],
                    },
                    {
                        "role": "user",
                        "template": "{user_input}",
                        "input_variables": ["user_input"],
                    },
                ]
            },
        },
        "functions": [CHOOSE_AGENT_FUNC],
        "output_parser": {
            "class_path": "ix.chains.functions.OpenAIFunctionParser",
            "config": {
                "parse_json": True,
            },
        },
    },
}

class ChatModerator(Chain):
    """
    Chain that compares user input to a list of agents and chooses the best agent to handle the task
    """

    selection_chain: Chain

    @property
    def _chain_type(self) -> str:
        return "ix_chat_moderator"

    @property
    def output_keys(self) -> List[str]:
        """Outputs task_id of spawned subtask"""
        return ["task_id"]

    @property
    def input_keys(self) -> List[str]:
        """Input keys this chain expects."""
        return ["user_input", "chat_id"]

    def agent_prompt(self, chat: Chat) -> str:
        """build prompt for configured tools"""
        lines = []
        agents = chat.agents.all().order_by("alias")
        for i, agent in enumerate(agents):
            lines.append(f"{i}. {agent.alias}: {agent.purpose}")
        return "\n".join(lines)

    def _call(
        self,
        inputs: Dict[str, Any],
        run_manager: Optional[CallbackManagerForChainRun] = None,
    ) -> Dict[str, Any]:
        # 0. get chat and agents
        chat_id = inputs["chat_id"]
        chat = Chat.objects.get(id=chat_id)
        agents = list(chat.agents.order_by("alias"))

        # 1. select agent
        agent_prompt = "\n".join(
            [f"{i}. {agent.alias}: {agent.purpose}" for i, agent in enumerate(agents)]
        )
        user_input = inputs["user_input"]
        logger.debug(f"Routing user_input={user_input}")
        inputs_mutable = inputs.copy()
        inputs_mutable["agents"] = agent_prompt
        response = self.selection_chain(
            inputs=inputs_mutable, callbacks=run_manager.get_child()
        )
        delegation_or_text = response["delegation_or_text"]
        logger.debug(f"Moderator returned response={delegation_or_text}")

        # response is either a delegation or a direct text response
        if isinstance(delegation_or_text, dict):
            agent_index = delegation_or_text["arguments"]["agent_id"]
            delegate_to = agents[agent_index].alias
            text = f"Delegating to @{delegate_to}"
        else:
            text = delegation_or_text
            delegate_to = None

        # 2. send message to chat
        ix_handler = IxHandler.from_manager(run_manager)
        ix_handler.send_agent_msg(text)

        # 3. delegate to the agent
        task_id = None
        if delegate_to is not None:
            agent = chat.agents.get(alias=delegate_to)
            subtask = chat.task.delegate_to_agent(agent)
            logger.debug(
                f"Delegated to agent={agent.alias} task={subtask.id} input={inputs}"
            )
            start_agent_loop.delay(
                task_id=str(subtask.id), chain_id=str(agent.chain_id), inputs=inputs
            )
            task_id = str(subtask.id)

        return {"text": text, "task_id": task_id}

    async def _acall(
        self,
        inputs: Dict[str, str],
        run_manager: Optional[AsyncCallbackManagerForChainRun] = None,
    ) -> Dict[str, str]:
        # 0. get chat and agents
        chat_id = inputs["chat_id"]
        chat = await Chat.objects.aget(id=chat_id)
        agents = [value async for value in chat.agents.order_by("alias").aiterator()]

        # 1. select agent
        agent_prompt = "\n".join(
            [f"{i}. {agent.alias}: {agent.purpose}" for i, agent in enumerate(agents)]
        )
        user_input = inputs["user_input"]
        logger.debug(f"Routing user_input={user_input}")
        inputs_mutable = inputs.copy()
        inputs_mutable["agents"] = agent_prompt
        response = await self.selection_chain.acall(
            inputs=inputs_mutable, callbacks=run_manager.get_child()
        )
        delegation_or_text = response["delegation_or_text"]
        logger.debug(f"Moderator returned response={delegation_or_text}")

        # response is either a delegation or a direct text response
        if isinstance(delegation_or_text, dict):
            agent_index = delegation_or_text["arguments"]["agent_id"]
            delegate_to = agents[agent_index].alias
            text = f"Delegating to @{delegate_to}"
        else:
            text = delegation_or_text
            delegate_to = None

        # 2. send message to chat
        ix_handler = IxHandler.from_manager(run_manager)
        await ix_handler.send_agent_msg(text)

        # 3. delegate to the agent
        task_id = None
        if delegate_to is not None:
            task = await Task.objects.aget(id=chat.task_id)
            agent = await chat.agents.aget(alias=delegate_to)
            subtask = await task.adelegate_to_agent(agent)
            logger.debug(
                f"Delegated to agent={agent.alias} task={subtask.id} input={inputs}"
            )
            start_agent_loop.delay(
                task_id=str(subtask.id), chain_id=str(agent.chain_id), inputs=inputs
            )
            task_id = str(subtask.id)

        return {"text": text, "task_id": task_id}


import urllib.request
import json
import pprint

# write a program that:
# 1. Prompts the user for a search term
# 2. Queries Twitter for status updates based on the search term
# 3. Iterates through the resulting data dictionary and
# 4. Prints the text of the status with the most retweets,
#    along with the number of times the status has been retweeted.

search_term = input('Please enter a search term: ')
url = 'https://eecs110-twitter-proxy.herokuapp.com/1.1/search/tweets.json?q='
url += search_term
request = urllib.request.urlopen(url)
data = json.loads(request.read().decode())

pprint.pprint(data, depth=1) # dictionary with 2 entries
pprint.pprint(data, depth=2) # The first value is another dictionary, the second is a list of dictionaries
#pprint.pprint(data, depth=3)


from django.shortcuts import render,redirect
import app25
from .models import Product,LoginDetails
from django.contrib import messages

def showIndex(request):
    qs = Product.objects.all()
    return render(request,"index.html",{"data":qs,"c_len":len(request.COOKIES)})

def storeInCokkie(request):
    pid = request.GET.get("pid")
    pname = request.GET.get("pname")
    response = redirect('/index/')
    #response = render(request,"index.html",{"data":qs,"c_len":len(request.COOKIES)})
    response.set_cookie(pid,pname)
    return response

def showcookies(request):
    keys = []
    for x in request.COOKIES.keys():
        keys.append(int(x))

    qs = Product.objects.all()

    return render(request,"cartitems.html",{"data":qs,"keys":keys})

def removecookie(request):
    id = request.GET.get("idno")

    response = redirect('/showcookies/')

    response.delete_cookie(id)
    return response

def showloginpage(request):
    return render(request,"login.html")

def logincheck(request):
    un = request.POST.get("t1")
    up = request.POST.get("t2")
    try:
        result = LoginDetails.objects.get(username=un,password=up)

        #request.session["1"] = un

        return redirect('main')

    except app25.models.LoginDetails.DoesNotExist:
        messages.error(request,"Invalid User")
        return redirect('loginuser')


###### Voice Comparison Engine ######

# imports
from sklearn.manifold import TSNE, MDS
from keras.models import load_model
from IPython.display import SVG, Audio, display
from keras.utils.vis_utils import model_to_dot
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Model
from keras.layers import Input
import soundfile as sf
import os
import sys

# session controll parameters to keep keras from hogging all the GPU memory
from keras.backend.tensorflow_backend import set_session
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.allow_growth = True  # dynamically grow the memory used on the GPU
config.log_device_placement = True  # to log device placement (on which device the operation ran)

sess = tf.Session(config=config)

set_session(sess)  # set this TensorFlow session as the default session for Keras

# load model
model_path = 'models/siamese_voice.hdf5'
siamese = load_model(model_path)
siamese = load_model(model_path)
siamese._make_predict_function()

def whiten(batch, rms=0.038021):
    """This function whitens a batch so each sample has 0 mean and the same root mean square amplitude """

    if len(batch.shape) != 3:
        raise(ValueError, 'Input must be a 3D array of shape (n_segments, n_timesteps, 1).')

    # Subtract mean
    sample_wise_mean = batch.mean(axis=1)
    whitened_batch = batch - np.tile(sample_wise_mean, (1, 1, batch.shape[1])).transpose((1, 2, 0))

    # Divide through
    sample_wise_rescaling = rms / np.sqrt(np.power(batch, 2).mean())
    whitened_batch = whitened_batch * np.tile(sample_wise_rescaling, (1, 1, batch.shape[1])).transpose((1, 2, 0))

    return whitened_batch

def preprocessor(downsampling, whitening=True):
    """ Downsample and fix RMS for inference """
    def preprocessor_(batch):
        ([i_1, i_2], labels) = batch
        i_1 = i_1[:, ::downsampling, :]
        i_2 = i_2[:, ::downsampling, :]
        if whitening:
            i_1, i_2 = whiten(i_1), whiten(i_2)

        return [i_1, i_2], labels

    return preprocessor_

downsampling = 4
whiten_downsample = preprocessor(downsampling, whitening=True)

def embedings(file_path_list):
    """ Make embedings from a list of audio files"""

    X=[]
    Z=[]
    for file_path in file_path_list:
        instance,samperate=sf.read(file_path)
        instance=instance[:48000]
        Z.append([instance,samperate])
    X_ = np.stack(list(zip(*Z))[0])[:, :, np.newaxis]
    [X_, _], _ = whiten_downsample(([X_, X_], []))

    X.append(X_)
    X = np.concatenate(X)
    return X

def average_distance(audio_list1,audio_list2):
    """ Calculate distance between list of two audio sample/s """

    voice_saved=embedings(audio_list1)
    voice_captured=embedings(audio_list2)
    all_distances=siamese.predict([voice_saved,voice_captured])
    avg_dist=np.average(all_distances)
    return avg_dist


from store_api import app, db
from flask import jsonify
from store_api.models import Order, PostStatus, Product

@app.route("/api/admin/update_post_status_order/<order_uuid>/<int:post_status_id>")
def update_post_status_order(order_uuid, post_status_id):

    order = Order.query.filter_by(order_uuid=order_uuid).first()
    ps = PostStatus.query.filter_by(id=post_status_id).first()
    order.post_status = ps
    db.session.add(order)
    db.session.commit()

    return jsonify({"message": "Post status has been updated!"})

@app.route("/api/admin/cancel_order/<order_uuid>")
def cancel_order(order_uuid):
    order = Order.query.filter_by(order_uuid=order_uuid).first()
    if order and order.orderitems:
        for oi in order.orderitems:
            p = Product.query.filter_by(id=oi.product_id).first()
            p.quantity = p.quantity + oi.quantity
            db.session.delete(oi)
        db.session.delete(order)
        db.session.commit()

        return jsonify({"message": "Prodcts has been updated!"}), 200

    else:
        return jsonify({"message": "Order isn't exist!"}), 200


# Create a deg degree polynomial and add the bias column
def make_poly(X, deg):
    n = len(X)
    data = [np.ones(n)]
    for d in range(deg):
        data.append(X**(d+1))
    return np.vstack(data).T

# Find the vector of weights
def fit(X,Y):
    return np.linalg.solve(X.T.dot(X), X.T.dot(Y))

def fit_and_display(X, Y, sample, deg):
    # Split to train and test sets
    N = len(X)
    train_idx = np.random.choice(N, sample)
    X_train = X[train_idx]
    Y_train = Y[train_idx]

    plt.scatter(X_train, Y_train)
    plt.show()

    # Fit the polynomial
    X_train_poly = make_poly(X_train, deg)
    w = fit(X_train_poly, Y_train)

    # Display the polynomial
    X_poly = make_poly(X, deg)
    Yhat = X_poly.dot(w)
    plt.plot(X, Y)
    plt.plot(X, Yhat)
    plt.scatter(X_train, Y_train)
    plt.title("deg = %d" % deg)
    plt.show()

def get_mse(Y, Yhat):
    d = Y-Yhat
    return d.dot(d)/len(d)

def plot_train_test_curves(X, Y, sample=20, max_deg=20):
    N = len(X)
    train_idx = np.random.choice(N, sample)
    X_train = X[train_idx]
    Y_train = Y[train_idx]

    test_idx = [idx for idx in range(N) if idx not in train_idx]
    X_test = X[test_idx]
    Y_test = Y[test_idx]

    mse_trains = []
    mse_tests = []
    for deg in range(max_deg+1):
        X_train_poly = make_poly(X_train, deg)
        w = fit(X_train_poly, Y_train)
        Yhat_train = X_train_poly.dot(w)
        mse_train = get_mse(Y_train, Yhat_train)

        X_test_poly = make_poly(X_test, deg)
        Yhat_test = X_test_poly.dot(w)
        mse_test = get_mse(Y_test, Yhat_test)

        mse_trains.append(mse_train)
        mse_tests.append(mse_test)

    plt.plot(mse_trains, label = "train mse")
    plt.plot(mse_tests, label = "test mse")
    plt.legend()
    plt.show()

    plt.plot(mse_trains, label = "train mse")
    plt.legend()
    plt.show()

if __name__ == "__main__":
    import numpy as np
    import matplotlib.pyplot as plt

    # Generate a sine wave and plot
    N = 100
    X = np.linspace(0, 6*np.pi, N)
    Y = np.sin(X)

    plt.plot(X,Y)
    plt.show()

    for deg in (5, 6, 7, 8, 9):
        fit_and_display(X, Y, 10, deg)
    plot_train_test_curves(X,Y)


import os
import sys
import argparse
import numpy as np
import time

# Still TODO: optimize, write outputfile function, account for unknown words

def init_training(training_list):
    '''Given a list of training files, parse through each file to create a list
    of lists, where each list is a sentence. Each element in each sentence is a
    mini-list where the 1st element is the word, and the 2nd element is the tag.

    The format of the each training file in the list is:
    word1 : tag1
    word2 : tag2 and so on.'''

    big_list = [] # list of lists, where each list is a sentence

    for train_file in training_list:

        f = open(train_file, 'r')
        words = f.readlines() # words is a list, every element being: "word : tag"
        # remove any empty lines:
        # words = [w for w in words if w != '\n']
        tmp_sentence = [] # list of word, tag pairs (temporary; overwritten after every sentence found)

        for w in words: # w has format: "word : tag"

            #if it's a blank line, ignore it:
            if w == '\n':
                continue

            w = w.split(" : ") # split w into a list with format: w = ["word", "tag"]

            # if the tag has a newline character in it (e.g. "NP0\n"), remove it
            if w[1][-1:] == '\n':
                w[1] = w[1][:-1]
            tmp_sentence.append(w)

            # if the word is "." or "!" or "?" or ";" then it's the end of a sentence, so restart the sentence list
            if w[0] == "." or w[0] == "!" or w[0] == "?" or w[0] == ";":
                big_list.append(tmp_sentence)
                tmp_sentence = []

        # if finished the file and still contents in tmp_sentence, append the last "sentence" anyway
        if len(tmp_sentence) != 0:
            big_list.append(tmp_sentence)
            tmp_sentence = []

        f.close()

    return big_list

def init_I(training_data, all_tags):
    '''Given a big list of lists (each list is a sentence, each elem in the list
    is a ["word", "tag"] pair), initialize the I matrix, which is row containing
    the probability of each tag for the first word (s0) in the sentence.'''

    first_tags = [] # list of the first tags for the first word of each sentence (evidence for s0)

    for sentence in training_data:
        first_tags.append(sentence[0][1])

    # print("first tags: ", first_tags)
    first_tags = np.array(first_tags)

    # initialize the I matrix as a numpy list of 0's, the same length as all_tags:
    I = np.zeros(len(all_tags))

    # for each tag in all_tags, count how many times it appears in first_tags and give its probability using numpy
    for i in range(len(all_tags)):
        I[i] = np.count_nonzero(first_tags == all_tags[i]) # len(first_tags) is the total number of sentences

    # add a small number to each elem in I to prevent 0 rows, and renormalize
    I = I + 0.01
    I = I / np.sum(I)
    # print(I)
    return I # each index in I corresponds to the index of the tag in all_tags

def init_T(training_data, all_tags):
    '''Given the big list of lists, initialize the T (state transition) matrix,
    which is an n x n numpy array where n is the number of all tags. Each elem
    in the matrix is the probability of transition from tag [row] to tag [col].
    In other words, the elem at index ["NPO"]["ADJ"] is the probability of transitioning
    from an NPO tag to an ADJ tag.'''

    # initialize T as a numpy 2D array of 0.000001's, the same size as all_tags:
    T = np.full((len(all_tags), len(all_tags)), 0.01) # to prevent 0 rows
    # print(len(all_tags))

    for sentence in training_data:
        # count every transition from one tag to another in the sentence.
        # Add 1 to the corresponding elem in T for each transition
        for i in range(len(sentence) - 1):
            T[all_tags.index(sentence[i][1])][all_tags.index(sentence[i+1][1])] += 1

    # divide each elem in T by the total number of transitions FROM that tag
    for i in range(len(all_tags)):
        if np.sum(T[i]) != 0: # to prevent dividing
            T[i] = T[i] / np.sum(T[i])

    return T

def init_M(training_data, all_tags):
    '''Initialize the M (observation probabilities) dictionary, where each key
    is a word that has been encountered in training, and each value is a list
    (length = 91) of probabilities of each tag for that word. These numbers
    are normalized by the total number of times that TAG has appeared. P(ek | sk)'''

    M = {}
    tag_count = np.zeros(len(all_tags)) # list of the number of times each tag has appeared

    for sentence in training_data:
        for word in sentence:
            if word[0] not in M:
                M[word[0]] = np.zeros(len(all_tags))
            M[word[0]][all_tags.index(word[1])] += 1 # add 1 to the corresponding tag (word[1]) in the list at the correct index
            tag_count[all_tags.index(word[1])] += 1 # add 1 to the corresponding tag counter list at the correct index

    # Normalize numbers in M by the total number of times that TAG has appeared (not the word)
    for word in M:
        for i in range(len(all_tags)):
            if tag_count[i] != 0:
                M[word][i] = M[word][i] / tag_count[i]

    return M

def init_E(test_file):
    '''Given the test file, create a list of lists of all the sentences and words
    in the test file.'''
    E = [] # list of lists
    f = open(test_file, 'r')
    W = list(map(str.rstrip, f.readlines())) # remove the newline characters too. list of all words
    f.close()

    tmp_sentence = [] # list of words in the current sentence
    for w in W:
        if w != "." and w != "!" and w != "?" and w != ";":
            tmp_sentence.append(w)
        else:
            tmp_sentence.append(w)
            E.append(tmp_sentence)
            tmp_sentence = []

    # account for last sentence anyway if doesn't end in proper punctuation
    if len(tmp_sentence) != 0:
        E.append(tmp_sentence)

    # for sentence in E:
    #     print(sentence)
    #     print()

    return E

def viterbi(E, S, I, T, M): #TODO - make faster (vectorize?) and account for never seen before words
    '''Execute the Viterbi algorithm to predict the most likely sequence of tags.
    The inputs to the function are:
    - E: list of observations (all words in ONE sentence; test sentence); e.g.  ["she", "walked", "downstairs", "."]
    - S: set of hidden state values (set of all tags)
    - I: initial probabilities row vector; P(s0)
    - T: transition matrix; P(S_k+1 | S_k)
    - M: observation dictionary; P(E_k | S_k)'''

    prob = np.zeros((len(E), len(S)))
    prev = np.zeros((len(E), len(S)))

    # determine values for time step 0 (base case):
    if E[0] not in M.keys():
        # at first, just assume a uniform distribution for all tags (since I should be good enough)
        prob[0] = I*1/len(S)
        pass
    else:
        # print("base case M[E[0]]: ", M[E[0]])
        prob[0] = I*M[E[0]]

    prev[0] = None
    x = np.argmax(prob[0])

    # create distribution (array with 91 elems) for unseen words;
    unknown_tagp = np.zeros(len(S))
    unknown_tagp[S.index("NP0")] = 0.1 # proper nouns
    unknown_tagp[S.index("AJ0")] = 0.1 # adjectives
    unknown_tagp[S.index("NN2")] = 0.1 # plural common nouns
    unknown_tagp[S.index("NN1")] = 0.1 # singular common nouns
    # make the remaining values equal so it adds to 1:
    unknown_tagp[unknown_tagp == 0] = 0.6 / (len(S) - 2)

    # time steps 1 to length(E) (recursive case):
    for t in range(1, len(E)): # t is the index of the current word
        for i in range(0, len(S)): # i is the index of the current tag

            # if it's a word that hasn't been seen before: TODO. Also TODO - deal with tags never appearing (don't make 0)
            if E[t] not in M.keys():
                # print("word not in M: ", E[t])
                #TODO - set prob[t][i] and prev[t][i] to something
                x = np.argmax(prob[t-1]*T.T[i]*unknown_tagp[i]) # or * 1/len(S))
                prob[t][i] = prob[t-1][x] * T[x][i] * unknown_tagp[i] # the probability of the current tag given the previous tag
                prev[t][i] = x # the previous tag that maximizes the probability

            else:
                x = np.argmax(prob[t-1]*T.T[i]*M[E[t]][i])
                prob[t][i] = prob[t-1][x] * T[x][i] * M[E[t]][i] # the probability of the current tag given the previous tag
                prev[t][i] = x # the previous tag that maximizes the probability

        # normalize to prevent probabilities from getting too small:
        if np.sum(prob[t]) != 0:
            prob[t] = prob[t] / np.sum(prob[t])
        else:
            print("PROBLEM: all of prob[t] is 0 for E[t] = ", E[t]) # TODO - fix this
            pass

    # for l in prev:
    #     print(l)
    #     print()

    tag_sequence = []

    # Backtrack to find the most likely sequence of tags:
    x = np.argmax(prob[len(E)-1]) # in the last row of prob, get the index of the max probability:
    # in the last row of prev, get the tag corresponding to that maxp index:
    tag_sequence = np.concatenate((int(x), tag_sequence), axis=None)

    # now backtrack through prev to get the rest of the tags:
    for t in range(len(E)-1, 0, -1): # go backwards from the last to the first row of prev
        tag_sequence = np.concatenate((prev[t][int(x)], tag_sequence), axis=None)
        x = prev[t][int(x)]

    # print("tag_sequence: ", tag_sequence)
    # show tags corresponding to each tag in tag sequence:
    # for i in range(len(tag_sequence)):
        # print(S[int(tag_sequence[i])])

    return tag_sequence

def get_accuracy(tag_guesses, answerfile, all_tags):
    '''After running Viterbi, compare the predicted tag sequence to the actual
    tag sequence in the test file. Return the accuracy. The inputs are:
    - tag_guesses: list of lists of the predicted tags for each sentence in the test file
    - answerfile: the test file with the answers
    - all_tags: list of all possible tags'''

    f = open(answerfile, 'r')
    W = list(map(str.rstrip, f.readlines())) # remove the newline characters too. list of all words
    f.close()

    # get the true tag sequence:
    true_tag_sequence = []
    f = open(answerfile, 'r')
    words = f.readlines() # words is a list, every element being: "word : tag"
    tmp_sentence = [] # list of word, tag pairs (temporary; overwritten after every sentence found)

    for w in words: # w has format: "word : tag"
        w = w.split(" : ") # split w into a list with format: w = ["word", "tag"]

        # if there's no index error and has a newline character in it (e.g. "NP0\n"), remove it
        if w[1] != '' and w[1][-1:] == '\n':
            w[1] = w[1][:-1]
        tmp_sentence.append(w)

        # if the word is "." or "!" or "?" or ";" then it's the end of a sentence, so restart the sentence list
        if w[0] == "." or w[0] == "!" or w[0] == "?" or w[0] == ";":
            true_tag_sequence.append(tmp_sentence)
            tmp_sentence = []

    # if finished the file and still contents in tmp_sentence, append the last "sentence" anyway
    if len(tmp_sentence) != 0:
        true_tag_sequence.append(tmp_sentence)
        tmp_sentence = []
    f.close()

    # format of true_tag_sequence: list of lists of word, tag pairs

    # for sentence in true_tag_sequence:
    #     print(sentence)
    #     print()

    # for every sentence and every tag, compare and get accuracy:
    correct = 0
    total = 0
    for i in range(len(true_tag_sequence)):
        for j in range(len(true_tag_sequence[i])):
            total += 1
            # compare the actual tag to the predicted tag:
            # print(tag_guesses)
            if true_tag_sequence[i][j][1] == all_tags[int(tag_guesses[i][j])]:
                correct += 1
            else:
                # print("wrong guess for this word: ", true_tag_sequence[i][j][0], "expected tag: ", true_tag_sequence[i][j][1])
                pass

    return correct/total

def write_output(tag_guesses, E, outputfile, all_tags):
    '''Write the predicted tag sequence to a file. The inputs are:
    - tag_guesses: list of lists of the predicted tags for each sentence in the test file
    - E: the test list of lists (just the words to add the tags to with format word : tag)
    - outputfile: the file to write the output to with formaat word : tag on each line
    - all_tags: list of all possible tags'''

    # Read through every word (line) in the test file and add the : tag from the tag_guesses list:
    # f = open(testfile, 'r')
    # testwords = f.readlines() # words is a list, every element being: "word : tag"
    # # remove the newline characters too:
    # testwords = list(map(str.rstrip, testwords))
    # f.close()

    # Write in the output file the word corresponding to the tag:
    f = open(outputfile, 'w')
    for sentence_i in range(len(tag_guesses)):
        for word_i in range(len(tag_guesses[sentence_i])):
            # hardcode to ensure all punctuation correct:
            if E[sentence_i][word_i] == "." or E[sentence_i][word_i] == "!" or E[sentence_i][word_i] == "?" \
                or E[sentence_i][word_i] == ";" or E[sentence_i][word_i] == "," or E[sentence_i][word_i] == ":":
                # print("replaced punctuation")
                f.write(E[sentence_i][word_i] + " : " + "PUN" + "\n")
            elif E[sentence_i][word_i] == '"':
                # print("replaced quotation")
                f.write(E[sentence_i][word_i] + " : " + "PUQ" + "\n")
            else:
                f.write(E[sentence_i][word_i] + " : " + all_tags[int(tag_guesses[sentence_i][word_i])] + "\n")

    f.close()

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--trainingfiles",
        action="append",
        nargs="+",
        required=True,
        help="The training files."
    )
    parser.add_argument(
        "--testfile",
        type=str,
        required=True,
        help="One test file."
    )
    parser.add_argument(
        "--outputfile",
        type=str,
        required=True,
        help="The output file."
    )
    args = parser.parse_args()

    training_list = args.trainingfiles[0]
    print("training files are {}".format(training_list))
    print("test file is {}".format(args.testfile))
    print("output file is {}".format(args.outputfile))

    time1 = time.time()

    print("************************* INITIALIZING DATA ************************")

    all_tags = ["AJ0", "AJC", "AJS", "AT0", "AV0", "AVP", "AVQ", "CJC", "CJS", "CJT", "CRD",
        "DPS", "DT0", "DTQ", "EX0", "ITJ", "NN0", "NN1", "NN2", "NP0", "ORD", "PNI",
        "PNP", "PNQ", "PNX", "POS", "PRF", "PRP", "PUL", "PUN", "PUQ", "PUR", "TO0",
        "UNC", 'VBB', 'VBD', 'VBG', 'VBI', 'VBN', 'VBZ', 'VDB', 'VDD', 'VDG', 'VDI',
        'VDN', 'VDZ', 'VHB', 'VHD', 'VHG', 'VHI', 'VHN', 'VHZ', 'VM0', 'VVB', 'VVD',
        'VVG', 'VVI', 'VVN', 'VVZ', 'XX0', 'ZZ0', 'AJ0-AV0', 'AJ0-VVN', 'AJ0-VVD',
        'AJ0-NN1', 'AJ0-VVG', 'AVP-PRP', 'AVQ-CJS', 'CJS-PRP', 'CJT-DT0', 'CRD-PNI', 'NN1-NP0', 'NN1-VVB',
        'NN1-VVG', 'NN2-VVZ', 'VVD-VVN', 'AV0-AJ0', 'VVN-AJ0', 'VVD-AJ0', 'NN1-AJ0', 'VVG-AJ0', 'PRP-AVP',
        'CJS-AVQ', 'PRP-CJS', 'DT0-CJT', 'PNI-CRD', 'NP0-NN1', 'VVB-NN1', 'VVG-NN1', 'VVZ-NN2', 'VVN-VVD']

    # initialize the training data
    training_data = init_training(training_list)

    # training_data = training_data[0:2] # shorten training to 2 sentences for testing
    # for sentence in training_data:
    #     print(sentence)
    #     print("")
    # initialize the 3 probability matrices
    I = init_I(training_data, all_tags)
    # print(I)
    T = init_T(training_data, all_tags)
    # for line in T:
    #     print(line)
    M = init_M(training_data, all_tags)
    # print(M)

    # initialize the other inputs to viterbi:
    E = init_E(args.testfile)

    print("*************************** TAGGING ********************************")

    tag_guesses = []
    for i in range(len(E)): # for every sentence
        tag_guesses.append(viterbi(E[i], all_tags, I, T, M))

    # answerfile = training_list[0] #  for now, test on the same file that was used to train
    answerfile = "training2.txt" # for testing on a specific dataset - MODIFY depending on what answers are

    # write to output file:
    write_output(tag_guesses, E, args.outputfile, all_tags)

    time2 = time.time()
    print("time taken is {}\n".format(time2-time1))
    # print("accuracy is {}".format(get_accuracy(tag_guesses, answerfile, all_tags))) #TODO  - comment out later


import pytest
from Funciones import add_digits, fill_word

def test_sum_digits():
    assert add_digits(123)==6

@pytest.mark.parametrize(
        "input_number, expected",
        [
            (458, 17),
            (920, 11),
            (add_digits(5261), 5),
            (8375, 23),
            (add_digits(62934), 6)
        ]
)
def test_sum_digits_parameters(input_number,expected):
    assert add_digits(input_number)==expected

def test_fill_word():
    assert fill_word("UAI", "USUARIO")=="U_UA_I_"

@pytest.mark.parametrize(
        "input_characters, input_hidden_word, expected",
        [
            ("AODRH", "ARCHIVO", "AR_H__O"),
            ("NTE", "INTERNET", "_NTE_NET"),
            ("MPSR", "IMPRESORA", "_MPR_S_R_"),
        ]
)
def test_fill_word_parameters(input_characters, input_hidden_word, expected):
    assert fill_word(input_characters, input_hidden_word)==expected


from typing import Dict, Union
import pdb
import logging

from overrides import overrides
import numpy
import torch
from torch.autograd import Variable

from allennlp.data.fields.field import Field
from allennlp.data.vocabulary import Vocabulary
from allennlp.common.checks import ConfigurationError

logger = logging.getLogger(__name__)  # pylint: disable=invalid-name

class NumericField(Field[numpy.ndarray]):
    """
    A ``LabelField`` is a categorical label of some kind, where the labels are either strings of
    text or 0-indexed integers (if you wish to skip indexing by passing skip_indexing=True).
    If the labels need indexing, we will use a :class:`Vocabulary` to convert the string labels
    into integers.

    This field will get converted into an integer index representing the class label.

    Parameters
    ----------
    label : ``Union[str, int]``
    label_namespace : ``str``, optional (default="labels")
        The namespace to use for converting label strings into integers.  We map label strings to
        integers for you (e.g., "entailment" and "contradiction" get converted to 0, 1, ...),
        and this namespace tells the ``Vocabulary`` object which mapping from strings to integers
        to use (so "entailment" as a label doesn't get the same integer id as "entailment" as a
        word).  If you have multiple different label fields in your data, you should make sure you
        use different namespaces for each one, always using the suffix "labels" (e.g.,
        "passage_labels" and "question_labels").
    skip_indexing : ``bool``, optional (default=False)
        If your labels are 0-indexed integers, you can pass in this flag, and we'll skip the indexing
        step.  If this is ``False`` and your labels are not strings, this throws a ``ConfigurationError``.
    """
    def __init__(self,
                 label: Union[float, int],
                 label_namespace: str = 'labels') -> None:
        self.label = label
        self._label_namespace = label_namespace
        self._label_id = numpy.array(label, dtype=numpy.float32)
        if not (self._label_namespace.endswith("labels") or self._label_namespace.endswith("tags")):
            logger.warning("Your label namespace was '%s'. We recommend you use a namespace "
                           "ending with 'labels' or 'tags', so we don't add UNK and PAD tokens by "
                           "default to your vocabulary.  See documentation for "
                           "`non_padded_namespaces` parameter in Vocabulary.", self._label_namespace)

    # idk what this is for
    @overrides
    def count_vocab_items(self, counter: Dict[str, Dict[str, int]]):
        if self._label_id is None:
            counter[self._label_namespace][self.label] += 1  # type: ignore

    @overrides
    def get_padding_lengths(self) -> Dict[str, int]:  # pylint: disable=no-self-use
        return {}

    def as_array(self, padding_lengths: Dict[str, int]) -> numpy.ndarray:  # pylint: disable=unused-argument
        return numpy.asarray([self._label_id])

    @overrides
    def as_tensor(self, padding_lengths: Dict[str, int],
                  cuda_device: int = -1,
                  for_training: bool = True) -> torch.Tensor:  # pylint: disable=unused-argument
        label_id = self._label_id.tolist()
        tensor = Variable(torch.FloatTensor([label_id]), volatile=not for_training)
        return tensor if cuda_device == -1 else tensor.cuda(cuda_device)

    @overrides
    def empty_field(self):
        return NumericField(0, self._label_namespace)


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

from django.contrib import admin
from django.contrib.auth.decorators import login_required
from website.views import (index_page, robots_txt, error_403,
                            error_404, error_500, favicon_ico)
from accounts.views import login, logout
from asterisk.views import (
    IndexPage, WebsitesPage, save_website_js, ExternalPhonesPage,
    ExternalPhoneAddView, ExternalPhoneEditView, InternalPhonesPage,
    InternalPhoneAddView, InternalPhoneEditView, EmployeesPage,
    EmployeeAddView, EmployeeEditView, StatPageView, DepartmentPage,
    DepartmentAddView, DepartmentEditView, update_call_status,
    check_wav_file_exists, get_wav_file, get_num_comments, add_call_comment,
    get_call_comments
)
admin.autodiscover()

urlpatterns = [
    url(r'^$', IndexPage.as_view(), name='home'),
    url(r'^get-num-comments/$', get_num_comments, name='get_num_comments'),
    url(r'^add-call-comment/$', add_call_comment, name='add_call_comment'),
    url(r'^get-call-comments/$', get_call_comments, name='get_call_comments'),
    url(r'^update-call-status/$', update_call_status,
        name='update_call_status'),
    url(r'^check-wav-file-exists/$', check_wav_file_exists,
        name='check_wav_file_exists'),
    url(r'^get-wav-file/$', get_wav_file, name='get_wav_file'),
    # url(r'^favicon.ico$', favicon_ico, name='favicon_ico'),
    url(r'^robots.txt$', robots_txt, name='robots_txt'),
    url(r'^login/$', login, name='main_login'),
    url(r'^logout/$', logout, name='logout'),
    url(r'^websites/$', WebsitesPage.as_view(), name='websites'),
    url(r'^external-phones/$', ExternalPhonesPage.as_view(),
        name='external_phones'),
    url(r'^external-phone-add/$', ExternalPhoneAddView.as_view(),
        name='external_phone_add'),
    url(r'^external-phone-edit/(?P<pk>[\w-]+)/$',
        ExternalPhoneEditView.as_view(), name='external_phone_edit'),
    url(r'^internal-phones/$', InternalPhonesPage.as_view(),
        name='internal_phones'),
    url(r'^internal-phone-add/$', InternalPhoneAddView.as_view(),
        name='internal_phone_add'),
    url(r'^internal-phone-edit/(?P<pk>[\w-]+)/$',
        InternalPhoneEditView.as_view(), name='internal_phone_edit'),
    url(r'^add-website/$', login_required(save_website_js),
        name='save_website_js'),
    url(r'^employees-list/$', EmployeesPage.as_view(), name='employees_page'),
    url(r'^employee-add/$', EmployeeAddView.as_view(), name='employee_add'),
    url(r'^employee-edit/(?P<pk>[\w-]+)/$', EmployeeEditView.as_view(),
        name='employee_edit'),
    url(r'^departments/$', DepartmentPage.as_view(), name='departments'),
    url(r'^department-add/$', DepartmentAddView.as_view(),
        name='department_add'),
    url(r'^department-edit/(?P<pk>[\w-]+)/$', DepartmentEditView.as_view(),
        name='department_edit'),
    url(r'^statistics/$', StatPageView.as_view(), name='stats'),
    url(r'^admin/', include(admin.site.urls)),
]

if 'rosetta' in settings.INSTALLED_APPS:
    urlpatterns += [
        url(r'^rosetta/', include('rosetta.urls')),
    ]


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings
import datetime

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('varer', '0017_salgsvare_kassenavn'),
    ]

    operations = [
        migrations.AddField(
            model_name='varetellingvare',
            name='added_by',
            field=models.ForeignKey(help_text='Brukeren som registrerte oppføringen', null=True, to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE),
        ),
        migrations.AddField(
            model_name='varetellingvare',
            name='time_added',
            field=models.DateTimeField(auto_now_add=True, default=datetime.datetime(2016, 1, 28, 22, 3, 18, 828239, tzinfo=datetime.timezone.utc)),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='varetellingvare',
            name='time_price',
            field=models.DateTimeField(blank=True, help_text='Overstyring av tidspunkt varen skal prises', null=True),
        ),
        migrations.AlterField(
            model_name='varetellingvare',
            name='sted',
            field=models.CharField(blank=True, max_length=50, null=True),
        ),
    ]


import sqlite3
import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Replace with your own token
bot = telegram.Bot(token='6280857926:AAF9I7zUDbaEE-gv0PuuT31JrALqffQ0MqE')

# Connect to the database
conn = sqlite3.connect('items.db')
c = conn.cursor()

# Create the items table if it does not exist
c.execute('''CREATE TABLE IF NOT EXISTS items
             (name text, price real)''')

# Insert some sample items
c.execute("INSERT INTO items VALUES ('spotify 1m', 10.0)")
c.execute("INSERT INTO items VALUES ('spotify 2m', 20.0)")
c.execute("INSERT INTO items VALUES ('spotify 3m', 30.0)")

# Handler for /start command
def start(update, context):
    context.bot.send_message(chat_id=update.effective_chat.id, text="Welcome to my store! Here are the items we sell:")

    # Retrieve the items from the database
    c.execute("SELECT * FROM items")
    items = c.fetchall()

    # Send the items as a list
    item_list = '\n'.join([f'{item[0]} - PHP {item[1]}' for item in items])
    context.bot.send_message(chat_id=update.effective_chat.id, text=item_list)

# Handler for text messages
def order(update, context):
    item_name = update.message.text

    # Check if the item is in the database
    c.execute("SELECT * FROM items WHERE name=?", (item_name,))
    item = c.fetchone()

    if item is None:
        context.bot.send_message(chat_id=update.effective_chat.id, text="Sorry, that item is not available.")
    else:
        # Save the order to user data
        context.user_data['order'] = item_name
        context.user_data['price'] = item[1]

        # Send the GCash details
        context.bot.send_message(chat_id=update.effective_chat.id, text=f"To order {item_name} (PHP {item[1]}), please pay through GCash to 09550388450 and send a screenshot of the payment confirmation to me.")

# Handler for payment confirmation
def payment(update, context):
    if update.message.photo:
        # Check if the payment is correct
        amount_paid = 0.0
        for photo in update.message.photo:
            file_id = photo.file_id
            file = context.bot.get_file(file_id)
            file.download()
            amount_paid += 1.0 # Assume that each photo represents 1 PHP

        if amount_paid >= context.user_data['price']:
            # Send the confirmation message and the ordered items
            context.bot.send_message(chat_id=update.effective_chat.id, text="Thank you for your payment! Your order will be shipped soon.")
            context.bot.send_message(chat_id=update.effective_chat.id, text="Here are your ordered items: {} - PHP {}".format(context.user_data['order'], context.user_data['price']))

# Create the handlers and attach them to the dispatcher
updater = Updater(token='6280857926:AAF9I7zUDbaEE-gv0PuuT31JrALqffQ0MqE', use_context=True)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_handler(MessageHandler(Filters.regex(r'^\d+$'), order))
dispatcher.add_handler(MessageHandler(Filters.photo, payment))

# Start the bot
updater.start_polling()
updater.idle()

# Close the database connection
conn.close()


import time
from box import Box

def init_timings():
    return Box({
        'current_time': time.time(),
        'last_time_idle': time.time(),
        'last_time_swapped': time.time(),
    })

def time_to_swap_games(timings):
    been_8_hours_since_change = timings.current_time - timings.last_time_swapped > 60 * 60 * 8
    been_20_mins_since_idle = timings.current_time - timings.last_time_idle > 60 * 20
    between_3_and_5am = 3 < time.localtime().tm_hour < 5
    return been_8_hours_since_change and between_3_and_5am and been_20_mins_since_idle