#!usr/bin/env python
#raspadmin

import sqlite3
import time
import logging as log
import registrarenbd
import pingserver
import consumidorserviciosweb
import lecturaestados
import cumplimientoaccion

FORMAT_LOG = '%(asctime)s : %(levelname)s : %(message)s'
FILE_NAME = '/opt/raspservices/raspadmin/lograspadmin.log'
LEVEL_F = log.INFO
log.basicConfig(level=LEVEL_F, format=FORMAT_LOG, filename=FILE_NAME)

con = sqlite3.connect("/root/raspproyect/raspweb/db.sqlite3")
ipservidor = "192.168.0.200"
ipequipo = "192.168.0.50"
log.info('*****----Inicio del RaspAdmin----*****')
registrarenbd.historicoraspberry(6, 1, con)
con.close()
def raspprocess():
    con = sqlite3.connect("/root/raspproyect/raspweb/db.sqlite3")
    lecturaestados.equipoconectado(con, ipequipo)
    if pingserver.isAlive(ipservidor):
        log.info('*****Existe conxion con el servidor*****')
        consumidorserviciosweb.enviarlograsp(ipservidor, con)
        consumidorserviciosweb.enviarlogequi(ipservidor, con)
        consumidorserviciosweb.interaccionws(ipservidor, con)
        cumplimientoaccion.realizarinteraccionespendientes(ipservidor, con)
    else:
        log.info('*****No existe conxion con el servidor*****')
    lecturaestados.lecturaestadoequipo(con)
    con.close()
    log.info('*****Esperando 10 Segundos*****')
    log.info('_____________________________________________')
    time.sleep(10)

while True:
    raspprocess()


from pysimpleevent import EventSimpleGUI
import PySimpleGUI as sg

loop = EventSimpleGUI()

@loop.event( '_click' )
def when_btn_was_clicked(event: str, values: dict, window: sg.Window):
    print('Just a normal event')
    return True

layout = [
    [sg.B('Just a button', k='_click')]
]

sg.theme(sg.theme_list()[1])
window = sg.Window('Just a Window.', layout, resizable=True, scaling=5)

if __name__ == '__main__':
    loop.run_window( window )


import argparse
import itertools as it
import json
import math
from functools import reduce
from multiprocessing import Pool

from spread_classification.fetch.tweets.prune_retweet_tree import prune_small_branches
from spread_classification.preprocessing.build_cascades import get_cascades
from spread_classification.preprocessing.build_spreads import get_spreads
from spread_classification.utils import (
    Followers,
    UrlsDataset,
    extract_tweets,
    get_children_ids,
    get_retweet_ids,
)

def get_prune_lengths(settings):
    return range(2, 1 + settings["largest_prune"])

def check_needed_followers(cascade, followers, max_follower_count=5000):
    needed = [
        node[1]["user"]["screen_name"]
        for node in cascade[0][:-1]
        if node[1]["user"]["followers_count"] <= max_follower_count
    ]
    available = [author for author in needed if author in followers]
    return len(needed), len(available)

def process_url(path, followers, settings):
    tweets = extract_tweets(path)
    retweets = get_retweet_ids(tweets)
    children = get_children_ids(tweets)

    cascades = get_cascades(tweets, followers)
    spreads = get_spreads(tweets, followers)

    prune_lengths = get_prune_lengths(settings)
    pruned = {
        length: prune_small_branches(tweets, min_branch_size=length)
        for length in prune_lengths
    }

    needed_followers, available_followers = (
        sum(values)
        for values in zip(
            *[
                check_needed_followers(cascade, followers)
                for cascade in cascades.values()
            ]
        )
    )

    return {
        "full_size": len(tweets),
        **{f"pruned_{length}_size": len(pruned[length]) for length in prune_lengths},
        "needed_followers": needed_followers,
        "available_followers": available_followers,
        "cascades": {k: len(cascade[0]) for (k, cascade) in cascades.items()},
        "spreads": {k: len(spreads[0]) for (k, spreads) in spreads.items()},
    }

def combine_processed(processed, settings):
    prune_lengths = get_prune_lengths(settings)
    fun = lambda acc, new: {
        "full_size": acc["full_size"] + [new["full_size"]],
        **{
            f"pruned_{length}_size": acc[f"pruned_{length}_size"]
            + [new[f"pruned_{length}_size"]]
            for length in prune_lengths
        },
        "needed_followers": acc["needed_followers"] + [new["needed_followers"]],
        "available_followers": acc["available_followers"]
        + [new["available_followers"]],
        "cascades": {**acc["cascades"], **new["cascades"]},
        "spreads": {**acc["spreads"], **new["spreads"]},
    }
    return reduce(
        fun,
        processed,
        {
            "full_size": [],
            **{f"pruned_{length}_size": [] for length in prune_lengths},
            "needed_followers": [],
            "available_followers": [],
            "cascades": {},
            "spreads": {},
        },
    )

def main(args):
    dataset = UrlsDataset(args.urls)
    followers = Followers(args.followers)

    pool = Pool(processes=args.processes)
    ids = (dataset[id_] for id_ in dataset.labels.keys())
    followers_gen = it.repeat(followers)
    settings = it.repeat({"largest_prune": args.largest_prune})
    processed = pool.starmap(process_url, zip(ids, followers_gen, settings))
    combined = combine_processed(processed, next(settings))
    json.dump(combined, args.output)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--urls", "-i", type=str, required=True)
    parser.add_argument("--followers", "-f", type=str, required=True)
    parser.add_argument("--largest-prune", "--len", type=int, default=6)
    parser.add_argument("--processes", "-p", type=int, default=4)
    parser.add_argument("--output", "-o", type=argparse.FileType("w"), required=True)
    main(parser.parse_args())


# 打印菱形
str1='*'
alst1=[x for x in range(1,8,2)]
alst1.extend([y for y in range(5,0,-2)])
print(alst1)
for i in alst1:
    print((str1*i).center(7))


#!/usr/bin/python3

def print_matrix_integer(matrix=[[]]):
    # loop through each row in the matrix
    for row in matrix:
        # initialize an empty string to store the formated row
        row_string = ""
        # loop element in row
        for element in row:
            row_string += "{:d} ".format(element)
        # print the row without tailing space
        print(row_string[:-1])


import os
from time import sleep
import sys
import boto3
import yaml
import botocore
import traceback
from deploy import vpc_deployment_manager
from deploy import load_yaml_file

def get_vpc_ids(configs):
	"""
		Read input configuration file that contains stack creation arguments and parameters
		This function describes created vpc resource id.

		Args:
			config: dictionary containing parameter values to be read
		Returns:
			List of vpc id and residing region key-pair
	"""
	setup_data = load_yaml_file(configs)
	vpc_id_list = []

	for single_setup_data in setup_data:

		# Extract region to query physical resources id
		vpc_region = single_setup_data['Region']
		print('Region to query vpc id = ' + vpc_region)

		# Extract the vpc name and region and create a stack name
		vpc_name = single_setup_data['vpc_name']
		stack_name = vpc_region+'-'+vpc_name
		print ('Stack name of vpc to query = ' + stack_name)

		# Get vpc id for specified stackname
		cfn = boto3.client('cloudformation', region_name=vpc_region)
		response = cfn.describe_stack_resource(StackName=stack_name, LogicalResourceId='VPC')
		vpc_id = response['StackResourceDetail']['PhysicalResourceId']
		print ('VPC ID for deployed vpc = ' + vpc_id)

		# Create vpc-id and region key-value pairs
		keypair = {}
		keypair['VPCID'] = vpc_id
		keypair['REGION'] = vpc_region
		vpc_id_list.append(keypair)

	return vpc_id_list

def request_vpc_peering_connection(accepter_vpc_id, requester_vpc_id, accepter_region, requester_region):
	"""
		Read input data of vpc id and corresponding region to initiate peering
		connection with another vpc using vpc id and associated region

		Args:
			accepter_vpc_id: vpc id of the requesting vpc
			requester_vpc_id: vpc id of the accepting vpc
			accepter_region: The region of the accepting vpc
			requester_region: The region you making the request (default)
		Returns:
			Id of the peering connection
	"""
	ec2 = boto3.client('ec2', region_name=requester_region)
	response = ec2.create_vpc_peering_connection(VpcId=requester_vpc_id, PeerVpcId=accepter_vpc_id, PeerRegion=accepter_region)
	PeeringConnectionId = response['VpcPeeringConnection']['VpcPeeringConnectionId']
	return PeeringConnectionId

def accept_vpc_peering_connection(PeeringConnectionId, accepter_region):
	"""
		Read input data of established vpc peering connection and
		corresponding region of the accepting vpc

		Args:
			PeeringConnectionId: Id of the peering connection
			accepter_region: The region of the accepting vpc
		Returns:
			peering connection status code
	"""
	ec2 = boto3.client('ec2', region_name=accepter_region)
	response = ec2.accept_vpc_peering_connection(VpcPeeringConnectionId=PeeringConnectionId)
	connection_status = response['VpcPeeringConnection']['Status']['Code']
	return connection_status

def get_pairing_config(vpc_region_keypairs):
	"""
		Read input of vpc id and region for creating peering connection

		Args:
		   vpc_region_keypairs: vpc id and region pair
		Returns:
		   First item in the above list and a concatenated list
		   comprising of the second to end items
   """
	popped_vpc = vpc_region_keypairs.pop(0)
	return [popped_vpc, vpc_region_keypairs]

def establish_vpc_connection(main_vpc, pairing_vpcs):
	"""
		Read configuration list with a popped item and a concatenated list
		comprising of the second to end items

		Args:
			main_vpc: first vpc_id_region keypair
			pairing_vpcs: The rest of the vpc_id_region-keypair in the input list
		Returns:
			peering connection id and status code of connection
	"""
	connection_state = []
	requester_region = main_vpc['REGION']
	requester_vpc_id = main_vpc ['VPCID']

	for vpc in pairing_vpcs:
		accepter_region = vpc['REGION']
		accepter_vpc_id = vpc ['VPCID']

		peering_connection_id = request_vpc_peering_connection(accepter_vpc_id, requester_vpc_id, accepter_region, requester_region)

		# wait for peering lifecycle to transition from 'provisioning' to 'active'
		sleep(5)

		peering_connection_status = accept_vpc_peering_connection(peering_connection_id, accepter_region)
		status = {}
		status['Connection ID'] = peering_connection_id
		status['Status'] = peering_connection_status
		connection_state.append(status)
	return connection_state

def main():
	# Define global variables
	CONFIGS=sys.argv[1]

	try:
		# Create a list of vpc_id with region pair
		vpc_region_keypairs = get_vpc_ids(CONFIGS)

		# Create a clone list to work with
		vpc_region_keypairs_clone = list(vpc_region_keypairs)

		# iterate through the cloned list to establish peering connection
		for i in range(1, len(vpc_region_keypairs)):
			main_vpc, pairing_vpcs = get_pairing_config(vpc_region_keypairs_clone)
			vpc_region_keypairs_clone = list(pairing_vpcs)
			if len(pairing_vpcs) < 1:
				break
			print(establish_vpc_connection(main_vpc, pairing_vpcs))

	except Exception as e:
		# If any other exceptions which we didn't expect are raised
		# then fail the query and log the exception message.
		print('Function failed due to exception.')
		print(e)
		traceback.print_exc()
		print('Function exception: ' + str(e))

	print('VPC Peering Connection Complete.')
	return "Complete."

if __name__ =="__main__":
   main()


from email.policy import default
from flask import Flask, request, render_template
from flask_sqlalchemy import SQLAlchemy
from flaskext.markdown import Markdown

app = Flask(__name__)
Markdown(app)

# db_uri = 'mysql+pymysql://root:@localhost/memo?charset=utf8'
# app.config['SQLALCHEMY_DATABASE_URI'] = db_uri
# db = SQLAlchemy(app)

db_uri = 'sqlite:///memo.db'
app.config['SQLALCHEMY_DATABASE_URI'] = db_uri
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Post(db.Model):
    __tablename__ = 'posts'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.Text())
    content = db.Column(db.Text())
    number = db.Column(db.Integer, default=1)

@app.route('/')
def list():

    message = 'Hello paiza memo'
    posts = Post.query.all()

    return render_template('list.html', message = message, posts = posts)

@app.route('/show/<int:id>')
def show_post(id):

    message = 'Your memo ' + str(id)
    post = Post.query.get(id)

    return render_template('show.html', message = message, post = post)

@app.route('/new')
def new_post():

    message = 'New memo'
    return render_template('new.html', message = message)

@app.route('/create', methods=['POST'])
def create_post():

    message = 'create your memo'

    new_post = Post()
    new_post.title = request.form['title']
    new_post.content = request.form['content']
    db.session.add(new_post)
    db.session.commit()

    post = Post.query.get(new_post.id)

    return render_template('show.html', message = message, post = post)

@app.route('/edit/<int:id>')
def edit_post(id):

    message = 'Edit your memo ' + str(id)
    post = Post.query.get(id)

    return render_template('edit.html', message = message, post = post)

@app.route('/update/<int:id>', methods=['POST'])
def update_post(id):

    message = 'Update your memo ' + str(id)

    post = Post.query.get(id)
    post.title = request.form['title']
    post.content = request.form['content']
    db.session.commit()

    return render_template('show.html', message = message, post = post)
# @app.route('/garbage', methods=['POST'])
# def garbage_post():

@app.route('/garbage/<int:id>')
def garbage_post(id):

    message = str(id) +  'をゴミ箱に移動しました。'

    garbage_post = Post.query.get(id)
    garbage_post.number = 0
    db.session.add(garbage_post)
    db.session.commit()

    posts = Post.query.all()

    return render_template('list.html', message = message, posts = posts)

@app.route('/recover/<int:id>')
def recover_post(id):

    message = str(id) +  'を復元しました。'

    recover_post = Post.query.get(id)
    recover_post.number = 1
    db.session.add(recover_post)
    db.session.commit()

    posts = Post.query.all()

    return render_template('list.html', message = message, posts = posts)

@app.route('/garbagelist')
def garbage_list():

    message = 'ゴミ箱'
    posts = Post.query.all()

    return render_template('garbage.html', message = message, posts = posts)

@app.route('/destroy/<int:id>')
def destroy_post(id):

    message = 'Destroy your memo ' + str(id)

    destroy_post = Post.query.get(id)
    db.session.delete(destroy_post)
    db.session.commit()

    posts = Post.query.all()

    return render_template('list.html', message = message, posts = posts)


import sys
import labeler_scripts as scripts
import os
import datetime
import ffmpeg
import os
from pathlib import Path
from bson.son import SON
from bson.objectid import ObjectId

def main():
  # arguements = sys.argv
  # video_filename = arguements[1]
  # email = arguements[2]
  # upload_time = arguements[3]

  jpeg_dir = os.path.join(os.path.dirname(__file__),'jpegs')
  fps = 10

  labels = []
  sign_matrix = {'addedLane': {},'curveLeft': {}, 'curveRight': {}, 'dip': {}, 'doNotEnter': {}, 'keepRight': {}, 'laneEnds': {}, 'merge': {}, 'noLeftTurn': {}, 'noRightTurn': {}, 'pedestrianCrossing': {}, 'rightLaneMustTurn': {}, 'school': {}, 'schoolSpeedLimit25': {}, 'signalAhead': {}, 'slow': {}, 'speedLimit15': {}, 'speedLimit25': {}, 'speedLimit30': {}, 'speedLimit35': {}, 'speedLimit40': {}, 'speedLimit45': {}, 'speedLimit50': {}, 'speedLimit55': {}, 'speedLimit65': {}, 'stop': {}, 'stopAhead': {}, 'yield': {}}

  # Temporary
  video_filename = '/home/egm42/sign-spotter/backend/uploads/REC_2020_04_04_08_40_13_F.MP4'
  email = 'test@email.com'
  upload_time = datetime.datetime.now()

  gps_list = scripts.gps_list(video_filename, fps)
  jpeg_list = []

  if(gps_list):
    # The last parameter is fps for processing video in to jpegs
    frame_count = scripts.split_video(video_filename, jpeg_dir, fps)
    frame_count = len(gps_list)

    # Frames start at 1, hence the range(1, frame_count + 1)
    for frame_num in range(1, frame_count + 1):

      left_img = os.path.join(jpeg_dir, Path(video_filename).stem + '_' + str(frame_num) + '_image_l.jpg')
      right_img = os.path.join(jpeg_dir, Path(video_filename).stem + '_' + str(frame_num) + '_image_r.jpg')
      jpeg_list.append(left_img)
      jpeg_list.append(right_img)

      left_labels = scripts.label(left_img)
      right_labels = scripts.label(right_img)

      left_labels = process_labels(left_labels, frame_num, video_filename, email, upload_time, left_img, gps_list, 'left')
      right_labels = process_labels(right_labels, frame_num, video_filename, email, upload_time, right_img, gps_list, 'right')
      labels += left_labels + right_labels

      for label in left_labels + right_labels:
        if 'class' in label.keys():
          if frame_num not in sign_matrix[label['class']].keys():
            sign_matrix[label['class']][frame_num] = {}
          sign_matrix[label['class']][frame_num][label['side']] = True

  else:
    scripts.send_email('no_gps', email)

  for side in ['left', 'right']:
    for sign in sign_matrix.keys():
      sightings = 0
      blanks = 0
      last_sighting = 0
      for frame_num in range(1, frame_count + 1):
        if frame_num in sign_matrix[sign].keys():
          if side in sign_matrix[sign][frame_num].keys():
            sightings += 1
            last_sighting = frame_num
          else:
            blanks += 1
            # TODO: tweak amount of blank frames and sightings needed to trigger saving of sign
            if(blanks >= 2 and sightings >= 3):
              save_label(last_sighting, labels, side)
              sightings = 0
              last_sighting = 0
        else:
          blanks += 1
          # TODO: tweak amount of blank frames and sightings needed to trigger saving of sign
          if(blanks >= 2 and sightings >= 3):
            save_label(last_sighting, labels, side)
            sightings = 0
            last_sighting = 0
      # TODO: tweak amount of blank frames and sightings needed to trigger saving of sign
      if(sightings >= 3 and last_sighting != 0):
        save_label(last_sighting, labels, side)

  # for label in labels:
  #   print('---------------------------------------------------------------')
  #   print(label)
  # print(sign_matrix)
  # db.save_to_mongo(labels)

  # Delete images from jpegs folder after processing and uploading to DB
  for image in jpeg_list:
    os.remove(image)

  # iterate through all gps points and check if signs have been updated
  print('Processing GPS list')

  signs_db = scripts.DB('signs')
  year = int(gps_list[1]['year'])
  month = int(gps_list[1]['month'])
  day = int(gps_list[1]['day'])
  hour = int(gps_list[1]['hour'])
  minute = int(gps_list[1]['minute'])
  second = int(float(gps_list[1]['second']))
  microsecond = int(round((second % 1) * 1000000,0))
  if(microsecond == 1):
    second += 1
    microsecond = 0
  new_sightings = datetime.datetime(year, month, day, hour, minute, second, microsecond) - datetime.timedelta(minutes=1)

  for frame in range(1, frame_count + 1):
    latitude = float(gps_list[frame]['latitude'])
    longitude = float(gps_list[frame]['longitude'])
    azimuth = int(float(gps_list[frame]['azimuth']))

    # Query looks for closest sign within the maxDistance that has a similar azimuth
    query = {'location': SON([('$near', [latitude, longitude]), ('$maxDistance', 0.0003)]), 'azimuth': {'$gte': (azimuth - 15) % 360, '$lte': (azimuth + 15) % 360}}
    existing_signs = signs_db.get_data(query)

    if(existing_signs.count() != 0):
      existing_id = existing_signs[0]['_id']

      # TODO: build logic checking datetime
      if(existing_signs[0]['last_sighting'] < new_sightings):
        update = {
          'missing': True
        }

        signs_db.update_data(existing_id, update)

  # Delete video after processing
  # os.remove(video_filename)

def save_label(last_sighting, labels, side):
  signs_db = scripts.DB('signs')

  if(side == 'left'):
    label = [labels[last_sighting * 2 - 2]]
  else:
    label = [labels[last_sighting * 2 - 1]]

  sign_class = label[0]['class']
  latitude = float(label[0]['location'][0])
  longitude = float(label[0]['location'][1])
  azimuth = int(float(label[0]['azimuth']))
  last_sighting = label[0]['last_sighting']

  query = {'class': sign_class, 'location': SON([('$near', [latitude, longitude]), ('$maxDistance', 0.0003)]), 'azimuth': {'$gte': (azimuth - 15) % 360, '$lte': (azimuth + 15) % 360}}
  existing_signs = signs_db.get_data(query)

  if(existing_signs.count() != 0):
    existing_id = existing_signs[0]['_id']
    prev_lat = existing_signs[0]['location'][0]
    prev_long = existing_signs[0]['location'][1]
    prev_bear = existing_signs[0]['azimuth']
    prev_sight = existing_signs[0]['sightings']

    update = {
      'location': [(prev_lat * prev_sight + latitude)/(prev_sight + 1), (prev_long * prev_sight + longitude)/(prev_sight + 1)],
      'azimuth': (prev_bear * prev_sight + azimuth)/(prev_sight + 1),
      'sightings': prev_sight + 1,
      'last_sighting': last_sighting
    }

    signs_db.update_data(existing_id, update)

  else:
    signs_db.save_to_mongo(label)

def process_labels(labels, frame_num, video_filename, email, upload_time, image_path, gps_list, side):
  if(labels):
    for label in labels:
      label['frame'] = frame_num
      label['original_video_filename'] = video_filename
      label['location'] = [float(gps_list[frame_num]['latitude']), float(gps_list[frame_num]['longitude'])]
      year = int(gps_list[frame_num]['year'])
      month = int(gps_list[frame_num]['month'])
      day = int(gps_list[frame_num]['day'])
      hour = int(gps_list[frame_num]['hour'])
      minute = int(gps_list[frame_num]['minute'])
      second = int(float(gps_list[frame_num]['second']))
      microsecond = int(round((second % 1) * 1000000,0))
      if(microsecond == 1):
        second += 1
        microsecond = 0
      datetimestamp = datetime.datetime(year, month, day, hour, minute, second, microsecond)
      label['last_sighting'] = datetimestamp
      label['azimuth'] = float(gps_list[frame_num]['azimuth']) % 360
      label['user_email'] = email
      label['upload_time'] = upload_time
      label['side'] = side
      label['image_path'] = image_path
      label['missing'] = False
      label['sightings'] = 1

      return labels
  else:
    label = {}
    label['frame'] = frame_num
    label['original_video_filename'] = video_filename
    label['location'] = [gps_list[frame_num]['latitude'], gps_list[frame_num]['longitude']]
    year = int(gps_list[frame_num]['year'])
    month = int(gps_list[frame_num]['month'])
    day = int(gps_list[frame_num]['day'])
    hour = int(gps_list[frame_num]['hour'])
    minute = int(gps_list[frame_num]['minute'])
    second = int(float(gps_list[frame_num]['second']))
    microsecond = int(round((second % 1) * 1000000,0))
    if(microsecond == 1):
      second += 1
      microsecond = 0
    datetimestamp = datetime.datetime(year, month, day, hour, minute, second, microsecond)
    label['last_sighting'] = datetimestamp
    label['azimuth'] = float(gps_list[frame_num]['azimuth']) % 360
    label['user_email'] = email
    label['upload_time'] = upload_time
    label['side'] = side
    label['image_path'] = image_path
    label['missing'] = False
    label['sightings'] = 1

    return [label]

if __name__ == '__main__':
  main()


from tkinter import *
from tkinter import ttk
import tkinter as tk

from tkinter import messagebox
import sqlite3

# import database as db
import log

root = Tk()
root.title("View Users - AMAS")
root.iconbitmap("img/favicon.png")
root.geometry("400x400")

# db.create_user_table()

tree = ttk.Treeview(root, column=("c1"), show='headings')
tree.column("#1", anchor=tk.CENTER)
tree.heading("#1", text="Username")

# tree.column("#2", anchor=tk.CENTER)
# tree.heading("#2", text="Delete")

tree.grid(row=0, column=0, padx=20, ipadx=5, ipady=5)

def View():
    con = sqlite3.connect("db/amas.db")
    c = con.cursor()
    c.execute("SELECT *, oid FROM users")
    rows = c.fetchall()

    for row in rows:
        tree.insert("", tk.END, values=row[0], iid = row[2])

    c.close()

View()

def onlick_delete_selected():

    try:
        row_id = tree.focus()

        conn = sqlite3.connect("db/amas.db")
        c = conn.cursor()
        c.execute("DELETE from users WHERE oid=" + row_id)

        # Commit Changes And Close Connection
        conn.commit()
        conn.close()

        messagebox.showinfo("Success", "User Deleted!")
    except ValueError:
        messagebox.showwarning("Warning", "Kindly select a User to delete!")
    except sqlite3.OperationalError:
        messagebox.showwarning("Warning", "Kindly select a User to delete!")

    tree.delete(*tree.get_children())
    View()

btn_delete = Button(root, text="Delete Selected", command=onlick_delete_selected)
btn_delete.grid(row=1, column=0, columnspan=2, padx=5, pady=5, ipady=5, ipadx=60)

# Close Window
btn_close = Button(root, text="Close", command=root.destroy)
btn_close.grid(row=2, column=0, columnspan=2, pady=5, padx=5, ipadx=85, ipady=5)

# btn_display.pack(pady=10)

root.mainloop()


#Create a function named double_index that has two parameters: a list named my_list and a single number named index.
#The function should return a new list where all elements are the same as in my_list except for the element at index. The element at index should be double the value of the element at index of the original my_list.
#If index is not a valid index, the function should return the original list.
#For example, the following code should return [1,2,6,4] because the element at index 2 has been doubled:
#double_index([1, 2, 3, 4], 2)

#Write your function here
def double_index(my_list, index):
    if index >= len(my_list):
        return my_list
    else:

        new_list = my_list[0:index] # Gets the original list up to index
        new_list.append(my_list[index] * 2) # Adds double the value of index to the new list
        new_list = new_list + my_list[index+1:] # Adds the rest of the original list
    return new_list

#Uncomment the line below when your function is done
print(double_index([3, 8, -10, 12], 2))


#!/usr/bin/env python

def isSorted(lst):
    length = len(lst)
    current = lst[0]
    for number in lst:
        if current <= number:
            current = number
            continue
        else:
            return False
    return True

# Let's do this...
numbers = input("Please enter a list of numbers: ")
numbers = [eval(i) for i in numbers.split()]
if isSorted(numbers):
    print("The list is already sorted")
else:
    print("The list is not sorted")


# Advent of code 2022
# Day 13

def get_data():
    with open("day_13_data.txt") as f:
        pairs = []
        while True:
            # Eval converts string representation of list to list
            list1 = eval(f.readline().strip())
            list2 = eval(f.readline().strip())
            pairs.append([list1, list2])

            linebreak = f.readline()
            if (linebreak != '\n'):
                break # Skip newline

    return pairs

def compare(left, right):
    # True
    if left < right:
        return 1
    # False
    elif left > right:
        return -1
    # Neutral
    else:
        return 0

def compare_lists(left, right):
    """Compare 2 lists to establish correct order"""

    if type(left) == int and type(right) == int:
        return compare(left, right)

    elif type(left) == int and type(right) == list:
        return compare_lists([left], right)

    elif type(left) == list and type(right) == int:
        return compare_lists(left, [right])

    elif type(left) == list and type(right) == list:
        for l, r in zip(left, right):
            outcome = compare_lists(l, r)
            # If not neutral (0), then return, otherwise, move to next pair
            if outcome != 0:
                return outcome

        return compare_lists(len(left), len(right))

def part1(data):
    sum = 0
    for i, pairs in enumerate(data, 1):
        in_order = compare_lists(*pairs)  # Extract the pairs into separate lists
        if in_order == 1:
            sum += i  # Increment the sum by the index of those pairs that are in the correct order

    print("Part1:", sum)

data = get_data()
part1(data)


import userAgent as ua
METHOD = "POST"
VERSION = "1.1"
TOKENFILEPATH = "/getSecure"
FLAGTWOFILEPATH = "/getFlag2"
URI = "csec380-core.csec.rit.edu"
PORT = 82

def main():
    #make call to get token
    resp = ua.makeReq(METHOD, TOKENFILEPATH, VERSION, URI, PORT)

    prettyResp = ua.parseResp(resp)
    print(prettyResp)

    #pull token
    body = resp.split("'")[1].split("\\r\\n\\r\\n")[1].split('"')[1]
    token = body.split(": ")[1]

    #make a call to get flag
    resp = ua.makeReq(METHOD, FLAGTWOFILEPATH, VERSION, URI, PORT,[f"token={token}"])

    #print formatted response
    prettyResp = ua.parseResp(resp)
    print(prettyResp)
    return resp

if __name__ == "__main__":
    main()


#
# netlab config command
#
# Deploy custom configuration template to network devices
#
import typing
import argparse
import os
import glob
import subprocess
import shutil

from box import Box
from pathlib import Path

from .. import common
from . import create
from . import external_commands
from .. import providers

#
# Extra arguments for 'netlab up' command
#
def up_parse_args() -> argparse.ArgumentParser:
  parser = argparse.ArgumentParser(description='netlab up extra arguments',add_help=False)
  parser.add_argument(
    '--no-config',
    dest='no_config',
    action='store_true',
    help='Do not configure lab devices')
  parser.add_argument(
    '--fast-config',
    dest='fast_config',
    action='store_true',
    help='Use fast device configuration (Ansible strategy = free)')
  return parser

def run(cli_args: typing.List[str]) -> None:
  up_args_parser = up_parse_args()
  topology = create.run(cli_args,'up','Create configuration files, start a virtual lab, and configure it',up_args_parser)
  settings = topology.defaults

  (args,rest) = up_args_parser.parse_known_args(cli_args)
  external_commands.run_probes(settings,topology.provider,2)

  provider = providers._Provider.load(topology.provider,topology.defaults.providers[topology.provider])

  if hasattr(provider,'pre_start_lab') and callable(provider.pre_start_lab):
    provider.pre_start_lab(topology)

  external_commands.start_lab(settings,topology.provider,3,"netlab up")

  if hasattr(provider,'post_start_lab') and callable(provider.post_start_lab):
    provider.post_start_lab(topology)

  if not args.no_config:
    external_commands.deploy_configs(4,"netlab up",args.fast_config)
  else:
    print("\nInitial configuration skipped, run 'netlab initial' to configure the devices")


#!/usr/bin/python3
# -*- coding: utf-8 -*-

import hashlib
import sys
sys.path.append("..")
from cryptolib import *

def random_string(stringLength):
	letters = string.ascii_lowercase
	return ''.join(random.choice(letters) for i in range(stringLength))

class Client():

	def __init__(self, I, P, N, g, k):
		self.I = I
		self.P = P
		self.N = N
		self.g = g
		self.k = k

	def genA(self):
		self.a = random.randint(1, self.N - 1)
		self.A = pow(self.g, self.a, self.N)
		return self.A

	def genK(self, salt, B):
		self.salt = salt
		self.B = B

		h = hashlib.sha256()
		h.update(str(self.A).encode('utf-8') + str(self.B).encode('utf-8'))
		uH = h.hexdigest()
		u = int(uH, 16)
		h = hashlib.sha256()
		h.update(self.salt + self.P)
		xH = h.hexdigest()
		x = int(xH, 16)
		aux = self.B - self.k * pow(self.g, x, self.N) # add modulo N
		S = pow(aux, self.a + u * x, self.N)
		h = hashlib.sha256()
		h.update(str(S).encode('utf-8'))
		self.K = h.hexdigest()
		return self.K

class Server():

	def __init__(self, N, g, k):
		self.users = {}
		self.N = N
		self.g = g
		self.k = k

	def addUser(self, I, P):
		self.users[I] = P

	def genB(self, I, A):
		self.A = A

		assert I in self.users
		P = self.users[I]
		self.salt = rand_bytes(16)
		h = hashlib.sha256()
		h.update(self.salt + P)
		xH = h.hexdigest()
		x = int(xH, 16)
		self.v = pow(self.g, x, self.N)

		self.b = random.randint(1, self.N - 1)
		self.B = (self.k * self.v) + pow(self.g, self.b, self.N)
		return [self.salt, self.B]

	def genK(self):
		h = hashlib.sha256()
		h.update(str(self.A).encode('utf-8') + str(self.B).encode('utf-8'))
		uH = h.hexdigest()
		u = int(uH, 16)
		aux = self.A * pow(self.v, u, self.N) # add modulo N
		S = pow(aux, self.b, self.N)
		h = hashlib.sha256()
		h.update(str(S).encode('utf-8'))
		self.K = h.hexdigest()
		return self.K

def SRP(C, S):
	A = C.genA()

	salt, B = S.genB(C.I, A)

	Kc = C.genK(salt, B)

	Ks = S.genK()

	if Kc == Ks:
		print('shared key:{}'.format(Kc))
	else:
		print('Failed!')

def main():
	I = b'user@mail.com'
	P = random_string(20).encode('utf-8')
	N = 0xffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff
	g = 2
	k = 3

	c = Client(I, P, N, g, k)
	s = Server(N, g, k)
	s.addUser(I, P)

	SRP(c, s)

if __name__ == '__main__':
	main()


'''
Created on Mar 10, 2016

@author: laurent
'''
from runtest.fixture import FixtureJoystick

class Joystick(FixtureJoystick):
    '''
    Class implementing fixture's expected results for the specified controller.

    The base class implements fixture required parameters to enable the
    controller. It also groups parameters and results before giving them to the
    TestCase method.

    '''
    def results(self, controller, index, player, verbose=True):
        '''
        Provide results expected for the specified requested parameters.

        The format of the result is free, here a dictionary is used, you can
        use your own, as you will be responsible to check the result in your
        TestCase method.

        Args:
            controller (controllerConfig.Controller):
                Controller that will be used by the player (player)
            index (int):
                System index of the controller
            player (int):
                Player number

        Returns (dict, None):
            Return the dictionary that will be apply to linapple settings to make
            same changes as the tested function.
            Return an empty dictionary for ignored players (2-5)
            Return None if an error occured, so the TestCase method is able to
            skip the test.

        '''
        # Find the input corresponding to the requested type (itype)
        def find(itype, *choices):
            for a in choices:
                value = controller.inputs.get(a, None)
                if value is None: continue
                if value.type != itype: continue
                else: break
            else:
                raise UserWarning('Unsupported hardware (no {})'.format(itype))

            if verbose:
                exp = choices[0]
                if (a != exp) :
                    msg = '[INFO] Uses ({}) instead of ({})'.format(a, exp)
                    print(self.message(controller, message=msg))

            return str(value.id)

        # Player number is zero based in linapple
        player = player - 1
        try:
            results = {} if player > 0 else {
        # Strange button behaviour with 2 joysticks enabled :-( TBD
        #    results = {} if player > 1 else {
                'Joystick {}'.format(player) : '1',
                'Joy{}Index'.format(player) : str(index),
                'Joy{}Axis0'.format(player) :
                    find('axis', 'joystick1left', 'joystick2left', 'left'),
                'Joy{}Axis1'.format(player) :
                    find('axis','joystick1up', 'joystick2up', 'up'),
                'Joy{}Button1'.format(player) :
                    find('button', 'pagedown','x'),
            }
            if player  < 1 :
                results.update({
                    'Joy{}Button2'.format(player) :
                        find('button', 'pageup', 'y'),
                    'JoyExitEnable' : '1',
                    'JoyExitButton0' :
                        str(controller.inputs['select'].id),
                    'JoyExitButton1' :
                        str(controller.inputs['start'].id),
                })

        except Exception as e:
            print(self.message(controller, message='[WARNING] {}'.format(e)))
            results = None

        return results

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:


# [SublimeLinter @python:3]

from .base import Command
from .arghelpers import process_files, format_file_path

class SampleCommand(Command):

    cli_command = "sample"
    cli_command_aliases = ()
    cli_command_help = "get first 1M of file"

    ############################################################################

    @classmethod
    def run(cls, args):
        for file in process_files(args):
            file_out = format_file_path("!\\!_SAMPLE.!", file)

            with open(file, "rb") as fpi, open(file_out, "wb") as fpo:
                fpo.write(fpi.read(1024 ** 2))

    ############################################################################

    @classmethod
    def _add_arguments(cls, parser):
        cls._add_files_arguments(parser)


count = int(input())

p1_count = 0  # < 200
p2_count = 0  # < 400
p3_count = 0  # < 600
p4_count = 0  # < 800
p5_count = 0  # >= 800

for i in range(count):
    number = int(input())
    if number < 200:
        p1_count += 1
    elif number < 400:
        p2_count += 1
    elif number < 600:
        p3_count += 1
    elif number < 800:
        p4_count += 1
    else:
        p5_count += 1

p1_perc = p1_count / count * 100
p2_perc = p2_count / count * 100
p3_perc = p3_count / count * 100
p4_perc = p4_count / count * 100
p5_perc = p5_count / count * 100

print(f'{p1_perc:.2f}%')
print(f'{p2_perc:.2f}%')
print(f'{p3_perc:.2f}%')
print(f'{p4_perc:.2f}%')
print(f'{p5_perc:.2f}%')


from typing import Any, Callable, Optional

import fsspec
from pystac.stac_io import DefaultStacIO, StacIO

from stactools.core import utils

ReadHrefModifier = Callable[[str], str]
"""Type alias for a function parameter
that allows users to manipulate HREFs for reading,
e.g. appending an Azure SAS Token or translating
to a signed URL
"""

def read_text(href: str, read_href_modifier: Optional[ReadHrefModifier] = None) -> str:
    if read_href_modifier is None:
        return StacIO.default().read_text(href)
    else:
        return StacIO.default().read_text(read_href_modifier(href))

class FsspecStacIO(DefaultStacIO):
    def read_text_from_href(self, href: str, *args: Any, **kwargs: Any) -> str:
        with fsspec.open(href, "r") as f:
            s = f.read()
            if isinstance(s, str):
                return s
            elif isinstance(s, bytes):
                return str(s, encoding="utf-8")
            else:
                raise ValueError(f"Unable to decode data loaded from HREF: {href}")

    def write_text_from_href(
        self, href: str, txt: str, *args: Any, **kwargs: Any
    ) -> None:
        utils.deprecate(
            "FsspecStacIO.write_text_from_href",
            "FsspecStacIO.write_text_to_href",
            "v0.5.0",
        )
        return self.write_text_to_href(href, txt)

    def write_text_to_href(self, href: str, txt: str) -> None:
        """Writes text to an href using fsspec."""
        with fsspec.open(href, "w") as destination:
            destination.write(txt)

def use_fsspec() -> None:
    StacIO.set_default(FsspecStacIO)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: a2htray
# create date: 2023/4/22

"""
PAT 乙级 1025
"""
import sys

if __name__ == '__main__':
    tokens = sys.stdin.readline().strip().split()

    start = tokens[0]
    n = int(tokens[1])
    k = int(tokens[2])
    if k > n:
        k = n

    order_dict = {}  # addr: [value, next]
    for _ in range(n):
        tokens = sys.stdin.readline().strip().split()
        order_dict[tokens[0]] = [tokens[1], tokens[2]]

    nodes = []
    while start != '-1':
        nodes.append([start, order_dict[start][0]])
        start = order_dict[start][1]

    new_nodes = []

    for i in range(0, n // k):
        tmp = nodes[i*k:(i+1)*k]
        tmp.reverse()
        new_nodes = new_nodes + tmp

    nodes = new_nodes + nodes[-(n % k):]

    for i in range(n):
        if i == n - 1:
            print(nodes[i][0], nodes[i][1], '-1')
        else:
            print(
                nodes[i][0], nodes[i][1], nodes[i + 1][0])


#!/usr/bin/python3
""" Square """
from models.rectangle import Rectangle

class Square(Rectangle):
    """ Square class """
    def __init__(self, size, x=0, y=0, id=None):
        """ Init """
        super().__init__(size, size, x, y, id)

    def __str__(self):
        """ String representation """
        s = "[Square] (" + str(self.id) + ") " + str(self.x) + "/"\
            + str(self.y) + " - " + str(self.width)
        return s

    @property
    def size(self):
        """ Size Getter """
        return self.width

    @size.setter
    def size(self, value):
        """ Size Setter """
        if type(value) is not int:
            raise TypeError("width must be an integer")
        if value <= 0:
            raise ValueError("width must be > 0")
        self.width = value
        self.height = value

    def update(self, *args, **kwargs):
        """ Updates attributes of the instance in order:
        (id, size, x, y)
        If args is None or empty, kwargs will be used instead.
        """
        if args is not None and len(args) != 0:
            atts = ['id', 'size', 'x', 'y']
            for index in range(0, len(args)):
                setattr(self, atts[index], args[index])
        else:
            for key in kwargs:
                setattr(self, key, kwargs[key])

    def to_dictionary(self):
        """ Returns the dictionary representation of the instance """
        return {'id': self.id,
                'size': self.size,
                'x': self.x,
                'y': self.y}


# -*- coding: utf-8 -*-
from setuptools import setup
from setuptools import find_packages

long_description = '''
This package is a snipped of the internal anysma project to train LVQ-based
networks on GPU with Tensorflow. The package is sparsely documented and I
highly recommend to study the examples first. There is no guarantee that the
package works with other package version. Thus, I made the package versions
strict and recommend the installation inside a docker or a pipenv. The
required Tensorflow version requires Python 3.6.
'''

setup(name='anysma',
      version='0.0.0',
      description='Experiments of my PhD thesis.',
      long_description=long_description,
      author='Sascha Saralajew',
      author_email='sascha.saralajew@gmail.com',
      url='https://github.com/saralajew/thesis_GTLVQ_experiments',
      download_url='https://github.com/saralajew/thesis_GTLVQ_experiments.git',
      license='BSD 3-Clause License',
      install_requires=['tensorflow-gpu==2.5.1',
                        'keras==2.2.4',
                        'numpy==1.16.4',
                        'six==1.12.0',
                        'scikit-image==0.15.0',
                        'scikit-learn==0.21.2',
                        'matplotlib==3.1.0',
                        'scipy==1.3.0',
                        'sklearn==0.0',
                        'spectral==0.19',
                        'opencv-python==4.2.0.32'
                        ],
      classifiers=[
          'Development Status :: 3 - Alpha',
          'Intended Audience :: Developers',
          'Intended Audience :: Education',
          'Intended Audience :: Science/Research',
          'License :: OSI Approved :: BSD License',
          'Programming Language :: Python :: 3.6',
          'Topic :: Software Development :: Libraries',
          'Topic :: Software Development :: Libraries :: Python Modules'
      ],
      packages=find_packages())


import pandas as pd
import numpy as np
import torch

device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
torch.set_default_dtype(torch.float64)

class NCF:

	def __init__(self, train):
		self.movieIds = NCF._get_list_of_all_movies(train)
		self.train = train

	# Private functions

	# Function: returns a dataframe of unique movieIds
	@staticmethod
	def _get_list_of_all_movies(df_train):
	  return pd.DataFrame(data=df_train['movieId'].unique(), columns=['movieId']) #movieIds

	# Function: recommends movies
	@staticmethod
	def _recommend_movies(userID, df_movieIds, df_train, technique, n=5, df_preds_MF=None, model=None):

	  """ Function: returns top-5 recommended movies for userID
	  	args:
		----
		  userID: userId in training set

		  df_movieIds: all unique movies in the training set (DataFrame of all unique movieId's)

		  df_train: training set (DataFrame with at least three columns: userId, movieId, rating)

		  technique: 'NN' for Neural Network and 'MF' for Matrix Factorization

		  df_preds_MF: reconstructed matrix from matrix factorization if technique == 'MF'

		  model: NN model if technique == 'NN'

		return:
		-------
		  movies_watched: previously liked movie
		  recommendations:  new recommendations
	  """

	  if technique != 'NN' and technique != 'MF':
	    print("You must enter the 'technique' type correctly: 'MF' for Matrix Factorization or 'NN' for Neural Network")
	    return;

	  #1. >get       watched movieIds by the user  +  sort them by rating (descending)
	  movies_watched = df_train[df_train.userId == (userID)].sort_values(['rating'], ascending=False) # get all userId:	movieId, rating

	  #2. >get >NOT< watched movieIds by the user
	  movies_not_watched = df_movieIds[~df_movieIds['movieId'].isin(movies_watched['movieId'])]

	  # MATRIX FACTORIZATION
	  # ====================

	  if technique == 'MF':
	    #3.` get all movieIds that exist in the dataset + sort them by rating (descending)
	    sorted_user_predictions = df_preds_MF[df_preds_MF.index==userID].sort_values(by=userID, axis=1, ascending=False)
	    sorted_user_predictions = pd.DataFrame(np.transpose(sorted_user_predictions.values), columns=sorted_user_predictions.index, index=sorted_user_predictions.columns)

	    #4.` get predictions for NON-watched movies
	    recommendations = (movies_not_watched).merge(
		pd.DataFrame(sorted_user_predictions).reset_index(),
		how = 'left', left_on = 'movieId', right_on = 'movieId').rename(
		    columns = {userID: 'Predictions'}).sort_values(
		        'Predictions', ascending = False).iloc[:n]

	  # NEURAL COLLABORATIVE FILTERING
	  # ===============================
	  elif technique == 'NN':
	    user = [userID] * len(movies_not_watched) #userID (repeated)
	    new_movies = movies_not_watched['movieId'].tolist() #non-watched movies

	    user = torch.tensor(user).to(device=device, dtype=torch.long)
	    new_movies = torch.tensor(new_movies).to(device=device, dtype=torch.long)

	    rating_preds = model(user, new_movies).squeeze() # get a list of predicted ratings from the model

	    # 3.`` prepare the data for the model
	    new_movies = new_movies.cpu().detach().tolist()
	    rating_preds = rating_preds.cpu().detach().tolist()
	    data = {"movieId":new_movies, userID:rating_preds}

	    #4.`` get predictions for NON-watched movies
	    recommendations = pd.DataFrame(data).sort_values(by=userID, ascending=False).iloc[:n] # this list only has non-watched movies

	  if 'index' in recommendations.columns:
	    recommendations.drop(columns='index')

	  return movies_watched.iloc[:n], recommendations

	# Public functions

	def predictMF(self, userID, P, Q, df_user_item):
	  # Get the predictions from Matrix Factorization technique.
	  y_predicted = P @ Q.T
	  preds_df = pd.DataFrame(y_predicted, columns = df_user_item.columns)

	  # Get top 5 recommneded movies for user with id "330"
	  y_test_df, y_predicted_df = NCF._recommend_movies(userID, self.movieIds, self.train, technique='MF', df_preds_MF=preds_df)

	  return y_test_df, y_predicted_df

	def predictNN(self, userID, model):
	  # Get top 5 recommneded movies for user with id "330" with NN technique
	  y_test_df, y_predicted_df = NCF._recommend_movies(userID, self.movieIds, self.train, technique='NN', model=model)

	  return y_test_df, y_predicted_df


import pandas as pd
import os
import sys
import re
import json
import warnings
from sklearn.feature_extraction.text import CountVectorizer
from fuzzywuzzy import fuzz

#ignore warnings
warnings.filterwarnings("ignore")

# Dinamically add the library to sys.path
PATH = os.path.dirname(os.__file__)
sys.path.append(os.path.join(PATH, 'Libraries-GP'))

#eutop Libraries
from SQLServer import DATABASE_CONFIG_NEW, sql_cnnt
from AzureStorage import blob_download

basepath = './PipelinePredictions/models/'

tagtoidmap = pd.read_sql_query("""SELECT [id],[tag],[edited_date] FROM [dbo].[tb_tags]""", sql_cnnt("cnnt", DATABASE_CONFIG_NEW))
idtotag = dict(zip(tagtoidmap.id, tagtoidmap.tag.apply(lambda x : x.lower())))
tagtoid = dict((x,i) for i,x in idtotag.items())

with open('PipelinePredictions/tag_data/tags_mapping_dict.json') as fp:
    nested_tags = json.load(fp)

#function that uses a tokenizer and a dictionary of seedowrds to predict labels
def generate_pseudo_labelsTag(strings, labelsdict):

    #labels and dictionary of seedwords, not needed the sorting anymore
    labels = sorted(labelsdict.keys())

    #this an implementation for multilabel, returns a one-hot-encoded array
    def argmax_perfectmatch(count_dict, thresh=1):
        total = 0
        labcounts = []
        for l in labels:
            count = 0
            try:
                for t in count_dict[l]:
                    count += count_dict[l][t]
            except:
                pass
            labcounts.append((l, count))
            total += count

        predlabels = []
        for lbl,count in labcounts:
            if count >= thresh:
                predlabels.append(tagtoid[lbl])

        return  predlabels

    y = []
    X = []

    for line in strings:
        count_dict= {}
        flag = 0
        try:
            countvec = CountVectorizer(ngram_range=(1, 4))
            countvec.fit_transform([line])
            words = countvec.get_feature_names()
        except:
            # if there are some errors in fit transform just skip the line
            continue

        for l in labels:
            seed_words = set()
            for w in labelsdict[l]:
                seed_words.add(w)
            int_labels = list(set(words).intersection(seed_words))
            if len(int_labels) == 0:
                continue
            for word in words:
                if word in int_labels:
                    flag = 1
                    try:
                        temp = count_dict[l]
                    except:
                        count_dict[l] = {}
                    try:
                        count_dict[l][word] += 1
                    except:
                        count_dict[l][word] = 1
        if flag:
            lbl = argmax_perfectmatch(count_dict)
            for lb in lbl:
                linked_tags = nested_tags[str(lb)]
                lbl = lbl + linked_tags
            #remove duplicates
            lbl = list(set(lbl))

            y.append(lbl)
            X.append(line)
        else:
            #fix to not allow empty result from pseudo label
            X.append(line)
            y.append([-1])

    y = [item for sublist in y for item in sublist]
    y = [tg for tg in y if tg in idtotag.keys()]
    return X, y


import plotly.express as px
import plotly.graph_objects as go
import matplotlib.pyplot as plt

import pandas as pd
import numpy as np
import networkx as nx

import processing
import network

import warnings
warnings.filterwarnings("ignore")

overlapped_data = processing.fake_data(n = 500, course_dev = 20, n_classes = 10, major_range=range(0,200,10))
overlapped_data.head()

majors = sorted(list(overlapped_data.major.unique()))

major2colleges = {}
for major in majors:
    if major <= 190: major2colleges[major] = 1
    if major >= 200 and major <= 400: major2colleges[major] = 2
    if major >= 400 and major <= 600: major2colleges[major] = 3
    if major >= 600 and major <= 800: major2colleges[major] = 4
    if major >= 800 and major <= 1000: major2colleges[major] = 5

# Assign colleges and sort by college
assigned_colleges = []
for index, row in overlapped_data.iterrows():
    assigned_college = major2colleges[row['major']]
    assigned_colleges.append(assigned_college)
overlapped_data['college'] = assigned_colleges

#overlapped_data = overlapped_data.sort_values(['major','college'])
overlapped_data = overlapped_data.sort_values(['major'])

student_list = list(overlapped_data.student.unique())

# Get student-student weighted edgelist
partition, g = network.bipartite_to_projection(overlapped_data, name = 'heatmap_test', col1 = 'student', col2 = 'course')
A = nx.to_numpy_matrix(g, nodelist = student_list)

fig = go.Figure(data=go.Heatmap(z = A))
fig.show()


# 탐색적 데이터 분석
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import font_manager, rc

# 그래프처리 및 파일 로드
fontname = font_manager.FontProperties(fname='C://myData//Fonts///malgun.ttf').get_name()
rc('font',family=fontname)

# 1)
data = pd.read_csv('data/rtest.csv')
# print(data.dtypes)
# print(data.shape)

# 2)
def getResident2(x):
    if x == 1:
        return '서울'
    elif x == 2:
        return '인천'
    elif x == 3:
        return '대전'
    elif x == 4:
        return '대구'
    else:
        return '시군구'
data['resident2'] = data['resident'].apply(getResident2)
# print(data.head())

# 3)
# print(data.shape)
data = data[data['age'].notnull()]
# print(data.shape)

# 4)
# print(data['age'].min())
# print(data['age'].max())
# print(data['age'].mean())

# 5)
# plt.boxplot(data['age'])
# plt.title('연령대')
# plt.show()

# 6)
def getAge2(x):
    if x<=30:
        return '청년층'
    elif 31<=x<=55:
        return '중년층'
    elif x>=56:
        return '장년층'

data['age2'] = data['age'].apply(getAge2)
print(data.head())

# 7)
def getGender2(x):
    if x == 1:
        return '남자'
    elif x == 2:
        return '여자'

data['gender2'] = data['gender'].apply(getGender2)
print(data.head())

# 8)
s1 = data.groupby('gender2').size()
print(s1)

# 9)
plt.pie(s1, labels=s1.index)
plt.title('남녀의 빈도수')
plt.show()

# 10)
plt.scatter(data['age'], data['price'])
plt.show()


import time
from dockets.stat_gatherer import StatGatherer
from mock import Mock
from util import *
from dockets.queue import Queue

def assert_within_a_second_of(topic, expected):
    assert topic > expected - 1 and topic < expected + 1

def test_queue_provides_stats():
    queue = Queue(redis, 'test')
    assert queue.stats
    assert queue.stats.successes_per_s is not None

def test_queue_with_stats_disabled_does_not_provide_stats():
    queue = Queue(redis, 'test', stat_gatherer_cls=None)
    assert not hasattr(queue, 'stats')

class FakeGatherer(object):
    pass

def test_queue_with_custom_stat_gatherer():
    queue = Queue(redis, 'test', stat_gatherer_cls=FakeGatherer)
    assert isinstance(queue.stats, FakeGatherer)

queue = Mock()
queue.redis = redis
gatherer = StatGatherer()
gatherer.on_register(queue)

@clear
def test_push():
    pipeline = redis.pipeline()
    gatherer.on_push(pipeline=pipeline)
    pipeline.execute()
    assert_within_a_second_of(float(gatherer.last_push()), time.time())

@clear
def test_pop():
    pipeline = redis.pipeline()
    gatherer.on_pop(123, pipeline=pipeline)
    pipeline.execute()
    assert_within_a_second_of(float(gatherer.last_pop()), time.time())

@clear
def test_complete():
    pipeline = redis.pipeline()
    gatherer.on_complete(123, 456, pipeline=pipeline)
    pipeline.execute()
    assert_within_a_second_of(float(gatherer.last_complete()), time.time())

@clear
def test_success():
    pipeline = redis.pipeline()
    gatherer.on_success(pipeline=pipeline)
    pipeline.execute()
    assert_within_a_second_of(float(gatherer.last_success()), time.time())

@clear
def test_error():
    pipeline = redis.pipeline()
    gatherer.on_error(pipeline=pipeline)
    pipeline.execute()
    assert_within_a_second_of(float(gatherer.last_error()), time.time())

@clear
def test_retry():
    pipeline = redis.pipeline()
    gatherer.on_retry(pipeline=pipeline)
    pipeline.execute()
    assert_within_a_second_of(float(gatherer.last_retry()), time.time())

@clear
def test_remove():
    pipeline = redis.pipeline()
    gatherer.on_remove(pipeline=pipeline)
    pipeline.execute()
    assert_within_a_second_of(float(gatherer.last_remove()), time.time())

@clear
def test_expire():
    pipeline = redis.pipeline()
    gatherer.on_expire(pipeline=pipeline)
    pipeline.execute()
    assert_within_a_second_of(float(gatherer.last_expire()), time.time())

@clear
def test_operation_error():
    pipeline = redis.pipeline()
    gatherer.on_operation_error(pipeline=pipeline)
    pipeline.execute()
    assert_within_a_second_of(float(gatherer.last_operation_error()), time.time())

@clear
def test_reclaim():
    pipeline = redis.pipeline()
    gatherer.on_reclaim(pipeline=pipeline)
    pipeline.execute()
    assert_within_a_second_of(float(gatherer.last_reclaim()), time.time())

@clear
def test_pop():
    pipeline = redis.pipeline()
    gatherer.on_pop(123, pipeline=pipeline)
    pipeline.execute()
    assert_within_a_second_of(float(gatherer.last_pop()), time.time())


# PROGRAMMING ASSIGNMENT 1 - VHAIJAIYANTHISHREE VENKATARAMANAN
# THIS PROGRAM USES PYTHON VERSION 3 (3.6.4)
# THE LIBRARIES USED ARE:
# 		1)REGULAR EXPRESSIONS
#		2)NUMPY
# TO EXECUTE THIS PROGRAM PLEASE USE THE FOLLOWING COMMAND:
#			python3 Vhaijaiyanthi_pa1.py
# ONCE THE PROGRAM IS EXECUTED USING THE ABOVE COMMAND, PLEASE ENTER THE NAMES OF THE
# REQUIRED SOURCE AND THE TARGET FILES IN THE RESPECTIVE FIELDS THAT APPEAR ON THE SCREEN
# *THANK YOU FOR YOUR TIME*

import re
import numpy as np
import copy

# FETCHING THE INPUT SOURCE AND TARGET FILES FROM THE USER
print("\n\nUniversity of Central Florida \nCAP6640 Spring 2018 - Dr. Glinos \n\nText Similarity Analysis by <Vhaijaiyanthishree Venkataramanan>\n\n")
origin = input("Source File: ")
destination = input("Target File: ")

# OPENING AND READING THE SOURCE AND THE TARGET FILES
source = open(origin).read()
target = open(destination).read()
print("\n")

#DISPLAYING THE RAW TOKENS
print("Raw Tokens:")
print("  Source > " + source)
print("  Target > " + target)

# TOKENIZATION OF THE RAW TOKENS
#CONVERSION OF THE TOKENS TO LOWER CASE
source = source.lower()
target = target.lower()

# ADDING SPACES BETWEEN ALPHANUMERIC AND NON-ALPHANUMERIC CHARACTERS
def my_replace(match):
    if match.group(1) is not None:
        return '{} '.format(match.group(1))  #SPACE BEFORE WORD
    else:
        return ' {}'.format(match.group(2))  #SPACE BEFORE SPACE

# CONVERTING THE RAW TOKENS TO NORMALIZED TOKENS
print("\nNormalized Tokens:")

def normalize(string):
	q = re.compile(r'^(\W+)|(\W+)$') # checks if the there is non alpha numeric characters at the beginning or at the end of a word
	strings_list = []
	for term in string.split():
		e = list(filter(bool,q.sub(my_replace, term).split(' ')))
		if e:
			if len(e) == 1:
				strings_list.append(''.join(e))
			else:
				if any(f.isalnum() for f in e):
					for token in e:
						if not token.isalnum():
							index = e.index(token)
							e[index] = ' '.join(token)
						strings_list.append(' '.join(e))
	return strings_list
source = " ".join(normalize(source))
target = " ".join(normalize(target))

# SEPARATING APOSTROPE FROM WORDS
def replaces(item):
    if item.endswith("'s"):
        return re.match(r"(.*)('s$)", item).groups()
    elif item.endswith("n't"):
        return re.match(r"(.*)n't$", item).groups() + ("not",)
    elif item.endswith("'m"):
        return re.match(r"(.*)'m$", item).groups() + ("am",)
    else:
        return item

# JOINING THE STRINGS TOGETHER AFTER NORMALIZATION
sections = []
for first_half in source.split():
    a = replaces(first_half)
    if isinstance(a, tuple):
        for x in a:
            sections.append(x)
    else:
        sections.append(a)

source = " ".join(sections)
print("  Source > " + source)
sections = []
for first_half in target.split():
    a = replaces(first_half)
    if isinstance(a, tuple):
        for x in a:
            sections.append(x)
    else:
        sections.append(a)

target = " ".join(sections)
print("  Target > " + target)

# CONSTRUCTING THE EDIT DISTANCE TABLE AND THE BACKTRACE TABLE
print("\nEdit Distance Table: \n")

source_input = source.split()
target_input = target.split()
r = len(source_input)
c = len(target_input)

#USING THE ALIGNMENT PARAMETERS
gap = -1
mismatch = -1
match = 2

# INITIALIZING THE EDIT DISTANCE MATRIX AND THE BACKTRACE MATRIX

scoreM = [[0 for col in range(c + 1)] for row in range(r + 1)]
tracebackM = [['' for col in range(c + 1)] for row in range(r + 1)]
END, DIAG, UP, LT = ('', 'DI', 'UP', 'LT')

# FILLING THE BACKTRACE TABLE
def moves(up, left, diag, tot_val):
    if tot_val == 0:
        return ''
    elif tot_val == up:
        return UP
    elif tot_val == left:
        return LT
    elif tot_val == diag:
        return DIAG
    else:
        raise ValueError('invalid')

# FILLING THE EDIT DISTANCE TABLE
for i in range(1,r+1):
    for j in range(1,c+1):
        top_score = scoreM[i-1][j] + gap;
        left_score= scoreM[i][j-1] + gap;
        if source_input[i-1] == target_input[j-1]:
            diagonal_score = scoreM[i-1][j-1] + match;
        else:
            diagonal_score = scoreM[i-1][j-1] + mismatch;
        X = max(0,top_score,left_score,diagonal_score);
        scoreM[i][j] = X
        tracebackM[i][j] = moves(top_score,left_score,diagonal_score, X)

# MODIFIYING THE STRING IN ORDER TO PRINT ONLY THE FIRST THREE LETTERS OF THE STRING
def stringModifier(input_seq_list):
    list_modify = []
    for str in input_seq_list:
        if len(str) >= 3:
            list_modify.append(str[:3])
        else:
            list_modify.append(str)
    return list_modify

# PRINTING THE SOURCE AND THE TARGET STRINGS IN EDIT DISTANCE AND BACKTRACE TABLES
def score_output(source, target, table):

    src = stringModifier(list(source))
    src.insert(0,'#')
    tgt = stringModifier(list(target))
    tgt.insert(0,'#')
    matrix = copy.deepcopy(table)
    for i in range(len(src)):
        row = matrix[i]
        row.insert(0, i)
        row.insert(1, src[i])
    row_one = ['','']
    row_two = ['',''] + tgt
    for i in range(len(tgt)):
        row_one.append(i)
    matrix.insert(0, row_one)
    matrix.insert(1, row_two)

    rows = len(matrix)
    cols = len(matrix[0])
    for row in range(rows):
        for col in range(cols):
        	print('{0}'.format(str(matrix[row][col])).center(4), end='   ')
        print()

#PRINTING THE FINAL EDIT DISTANCE TABLE
score_output(source_input, target_input, scoreM)

#PRINTING THE FINAL BACKTRACE TABLE
print("\nBacktrace Table: \n")
score_output(source_input, target_input, tracebackM)

#TO FIND THE MAXIMUM VALUE IN THE EDIT DISTANCE TABLE
array_max = np.max(np.array(scoreM))
print("\nMaximum value in distance table:", array_max)

# FINDING THE MAXIMA AMONGST THE MAXIMAL VALUES IN THE EDIT DISTANCE TABLE
scoreM_array = np.array(scoreM)
indices = np.where(scoreM_array == scoreM_array.max())
print("\nMaxima:")
for z in zip(indices[0], indices[1]):
    print("    ",list(z),"\n")

# CONSTRUCTING THE MAXIMAL-SIMILARITY ALIGNMENTS AND PRINTING THEM
def string_edit(source_aligned, target_aligned):
    alignment_s = []
    for base1, base2 in zip(source_aligned, target_aligned):
        if base1 == base2:
            alignment_s.append(' ')
        elif '-' in base1:
            alignment_s.append('i')
        elif '-' in base2:
            alignment_s.append('d')
        else:
            alignment_s.append('s')

    return alignment_s

def alignment_sequence(max_positions, tracebackM, count):
    source_input_aligned = []
    target_input_aligned = []
    l, m = max_positions
    move = tracebackM[l][m]
    while move != END:
        if move == DIAG:
            source_input_aligned.append(source_input[l - 1])
            target_input_aligned.append(target_input[m - 1])
            l -= 1
            m -= 1
        elif move == UP:
            source_input_aligned.append(source_input[l - 1])
            target_input_aligned.append('-')
            l -= 1
        else:
            source_input_aligned.append('-')
            target_input_aligned.append(target_input[m - 1])
            m -= 1
        move = tracebackM[l][m]

    l1 = len(max(source_input_aligned, key=len))
    l2 = len(max(target_input_aligned, key=len))
    l3 = max(l1, l2)

    print("\n   Alignment {0} (length {1}):".format(count, len(source_input_aligned)))

    print("       Source at    {0}:".format(l), end='')
    for str1 in source_input_aligned[::-1]:
        print("{0}".format(str1).center(l3 + 3), end='')
    print()

    print("       Target at    {0}:".format(m), end='')
    for str2 in target_input_aligned[::-1]:
        print("{0}".format(str2).center(l3 + 3), end='')
    print()

    string_edited = string_edit(source_input_aligned[::-1], target_input_aligned[::-1])
    print("       Edit Action   :", end='')
    for str3 in string_edited:
        print("{0}".format(str3).center(l3 + 3), end='')
    print()

    return source_input_aligned[::-1], target_input_aligned[::-1], count

print("\nMaximal-similarity alignments:")
count = 0
for z in zip(indices[0], indices[1]):
    alignment_sequence(z, tracebackM, count)
    count += 1

print("\n")


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# y = np.arange(4)
# plt.plot(y)
# plt.ylabel('liczby')
# plt.show()

# x = np.array([1,2,3,4])
# y = x**2
# plt.plot(x, y, 'ro-')
# plt.axis([0,6, 0,20])
# plt.show()
#
# plt.plot(x, y, 'r')
# plt.plot(x, y, 'o')
# plt.axis([0,6, 0,20])
# plt.show()

# a = np.arange(0, 5, 0.2)
# plt.plot(a, a, 'r--', a, a**2, 'bs', a, a**3, 'g^')
# plt.legend(labels=['liniowa', 'kwadratowa', 'sześcienna'], loc='center left')
# plt.show()

# z = np.arange(0, 5, 0.2)
# plt.plot(z, z, 'r--', label='liniowa')
# plt.plot(z, z**2, 'bs', label='kwadratowa')
# plt.plot(z, z**3, 'g^', label='sześcienna')
# plt.xlabel('etykieta x')
# plt.ylabel('etykieta y')
# plt.title('Wykres liniowy')
# plt.legend()
# plt.savefig('wykres1.png')
# plt.show()

# x = np.arange(0, 10.1, 0.1)
# y = np.sin(x)
# plt.plot(x, y, 'b-')
# plt.xlabel('x')
# plt.ylabel('sin(x)')
# plt.title('Sinus')
# plt.show()

# data = {'a': np.arange(50),
#         'c': np.random.randint(0, 50, 50),
#         'd': np.random.rand(50)}
# data['b'] = data['a'] + 10 * np.random.rand(50)
# data['d'] = np.abs(data['d']) * 100
# plt.scatter('a', 'b', c='c', s='d', data=data, cmap='plasma')
# plt.xlabel('wartości a')
# plt.ylabel('wartości b')
# plt.show()

# x1 = np.arange(0, 2, 0.02)
# x2 = np.arange(0, 2, 0.02)
# y1 = np.sin(2* np.pi *x1)
# y2 = np.cos(2* np.pi *x2)
#
# plt.subplot(4, 1, 1)
# plt.plot(x1, y1)
# plt.title('Wykres sin(x)')
# plt.xlabel('x')
# plt.ylabel('sin(x)')
#
# plt.subplot(4, 1, 4)
# plt.plot(x2, y2, 'r')
# plt.xlabel('x')
# plt.ylabel('cos(x)')
# plt.title('Wykres cos(x)')
#
# plt.subplots_adjust(hspace=0.5)
# plt.show()

# fig, axs = plt.subplots(3, 2)
# axs[0, 0].plot(x1, y1, 'g-')
# axs[0, 0].set_xlabel('x')
# axs[0, 0].set_ylabel('sin(x)')
# axs[0, 0].set_title('Wykres sin(x)')
#
# axs[1, 1].plot(x2, y2, 'r-')
# axs[1, 1].set_xlabel('x')
# axs[1, 1].set_ylabel('cos(x)')
# axs[1, 1].set_title('Wykres cos(x)')
#
# axs[2, 0].plot(x1, y1, 'y-')
# axs[2, 0].set_xlabel('x')
# axs[2, 0].set_ylabel('sin(x)')
# axs[2, 0].set_title('Wykres sin(x)')
#
# fig.delaxes(axs[0, 1])
# fig.delaxes(axs[1, 0])
# fig.delaxes(axs[2, 1])
#
# plt.show()
#
# data = {'Kraj': ['Belgia', 'Indie', 'Brazylia', 'Polska'],
#         'Stolica': ['Bruksela', 'New Delhi', 'Brasilia', 'Warszawa'],
#         'Kontynent': ['Europa', 'Azia', 'Ameryka Południowa', 'Europa'],
#         'Populacja': [12111111, 212321323, 32132423, 321323]}
# df = pd.DataFrame(data)
# print(df)
# grupa = df.groupby('Kontynent')
# etykiety = list(grupa.groups.keys())
# wartosc = list(grupa.agg('Populacja').sum())
#
# plt.bar(etykiety, wartosc, color=['yellow', 'red', 'green'])
# plt.xlabel('Kontynent')
# plt.ylabel('Populacja w mld')
# plt.show()
#
# ts = pd.Series(np.random.randn(1000))
# ts = ts.cumsum()
#
# ts.plot()
# plt.show()

# #korzystając z funkcji random oraz data_rangemożemy wygenerować szereg czasowy danych
# ts = pd.Series(np.random.randn(1000))
# # #funkcja biblioteki pandas generująca skumulowaną sumę kolejnych elementów
# ts = ts.cumsum()#rzutowanie Series na DataFrame
# df = pd.DataFrame(ts, columns=['wartości'])
# print(df)
# # dodanie nowej kolumny i wykorzystanie funkcji rolling do stworzenia kolejnych wartości średniej kroczącej
# df['Średnia krocząca'] = df.rolling(window=50).mean()
# df.plot()
# plt.legend()
# plt.show()

# x = np.random.randn(10000)
# plt.hist(x, bins=59, facecolor='g', alpha=0.75, density=True)
# plt.xlabel('Wartość')
# plt.ylabel('Prawdopodobieństwo')
# plt.title('Histogram')
# plt.grid()
# plt.show()

df = pd.read_csv('dane.csv', header=0, sep=";", decimal=".")
print(df)
seria = df.groupby('Imię i nazwisko')['Wartość zamówienia'].sum()
wedges, texts, autotext = plt.pie(x = seria, labels=seria.index,
                                  autopct=lambda pct: "{:.1f}%".format(pct),
                                  textprops=dict(color="black"),
                                  colors=['red', 'green'])
plt.title('Suma zamówień dla sprzedawców')
plt.legend(loc = 'lower right')
plt.ylabel('Procentowy wynik wartości zamówień')
plt.show()


import random
import keyboard
import time

size = random.randint(20, 25) # gives the length of the scramble

def length(size:int): #this creates the scramble

    count = 0

    moves = ["R", "L", "U", "D", "B"] # 1
    moves_prime = ["R'", "L'", "U'", "D'", "B'"] # 2
    moves_double = ["R2", "L2", "U2", "D2", "B2"] # 3

    scramble = [" "] #this is where the computer will store the scramble
    scramble_index = [" "] #lets the computer store the randomly generated indices
    scramble_dam = [" "] #lets the computer keep track of the generated type of move

    for i in range(size):
        dam = random.randint(1,3) #this lets the computer pick what type of move will be used
        scramble_dam.append(dam)

        if dam == 1:
            lmao = random.choice(moves)
            index = moves.index(lmao)
            count += 1

            wow = scramble_index[count - 1] # accesses the previous randomly generated index

            while wow == index: #checks to see if the index is equal to the previous index;
                lmao = random.choice(moves) # if it is, it will loop through until it is not the same;
                index = moves.index(lmao) # this allows it to not have consutive R and R'

            scramble_index.append(index)
            scramble.append(lmao)

        elif dam == 2:
            lmao = random.choice(moves_prime)
            index = moves_prime.index(lmao)
            count += 1

            wow = scramble_index[count - 1] # accesses the previous randomly generated index

            while wow == index: #same as line 29
                lmao = random.choice(moves_prime)
                index = moves_prime.index(lmao)

            scramble_index.append(index)
            scramble.append(lmao)

        elif dam == 3:
            lmao = random.choice(moves_double)
            index = moves_double.index(lmao)
            count += 1

            wow = scramble_index[count - 1] # accesses the previous randomly generated index

            while wow == index: #same as line 29
                lmao = random.choice(moves_double)
                index = moves_double.index(lmao)

            scramble_index.append(index)
            scramble.append(lmao)

    return " ".join(scramble)

# the following code (with some revisions) come from: https://www.codespeedy.com/how-to-create-a-stopwatch-in-python/
def time_convert(s): #code for the timer

  m = s // 60
  s = s % 60
  m = m % 60

  print("Time Solved = {0}:{1}".format(int(m),s))

  python_file = open("deez.txt", "a") #opens a separate txt file
  python_file.write(("Time = {0}:{1}\n".format(int(m),s))) #puts the time in a txt file
  python_file.close()

#code to activate the scrambler + timer
def main():

        print("Press shift if you want to show the scramble or press q if you want to quit!")
        if keyboard.read_key() == "shift":
            print(length(size)) #activates the scramble

        elif keyboard.read_key() == "q":
            print("Thank you for accessing!")
            quit()

        input("Press enter to start the timer. ")
        start_time = time.time()

        input("Press enter to stop the timer. ")
        end_time = time.time()
        print("You stopped the timer!")

        time_lapsed = end_time - start_time
        time_convert(time_lapsed) #prints the time

        print("Nice try!")

main()


from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.db.models import Q
from django.shortcuts import render, redirect, get_object_or_404

from django.urls import reverse, reverse_lazy
from django.utils.decorators import method_decorator
from django.views.generic import CreateView, DetailView, UpdateView, DeleteView, ListView
from noticeapp.forms import NoticeCreationForm
from noticeapp.models import Notice
from noticeapp.decorators import notice_ownership_required

@login_required(login_url='accountapp:login')
def Notice_create(request):
    """
    공지사항 등록
    """
    if not request.user.is_superuser == 1:
        return render(request, 'error.html')

    if request.method == 'POST':
        form = NoticeCreationForm(request.POST, request.FILES)
        if form.is_valid():
            notice = form.save(commit=False)
            notice.writer = request.user
            notice.title = request.POST['title']
            notice.save()
            return redirect('noticeapp:list')
    else:
        form = NoticeCreationForm()

    context = {'form': form }
    return render(request, 'noticeapp/create.html', context)

def Notice_detail(request, pk):
    notice = get_object_or_404(Notice, pk=pk)
    context = {'target_notice': notice}

    response = render(request, 'noticeapp/detail.html', context)

    expire_time = 600
    cookie_value = request.COOKIES.get('hitboard', '_')

    if f'_{pk}_' not in cookie_value:
        cookie_value += f'{pk}_'
        response.set_cookie('hitboard', value=cookie_value, max_age=expire_time, httponly=True)

        notice.watches += 1
        notice.save()

    return response

# class NoticeDetailView(DetailView):
#     model = Notice
#     context_object_name = 'target_notice'
#     template_name = 'noticeapp/detail.html'

@method_decorator(notice_ownership_required, 'get')
@method_decorator(notice_ownership_required, 'post')
class NoticeUpdateView(UpdateView):
    model = Notice
    context_object_name = 'target_notice'
    form_class = NoticeCreationForm
    template_name = 'noticeapp/update.html'

    def get_success_url(self):
        return reverse('noticeapp:detail', kwargs={'pk': self.object.pk})

@method_decorator(notice_ownership_required, 'get')
@method_decorator(notice_ownership_required, 'post')
class NoticeDeleteView(DeleteView):
    model = Notice
    context_object_name = 'target_notice'
    success_url = reverse_lazy('noticeapp:list')
    template_name = 'noticeapp/delete.html'

class NoticeListView(ListView):
    model = Notice
    context_object_name = 'notice_list'
    template_name = 'noticeapp/list.html'

    ordering = ['-pk']

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        request = self.request

        page = request.GET.get('page', '1')  # 페이지
        kw = request.GET.get('kw', '')  # 검색어

        notice_list = Notice.objects.order_by('-pk')
        if kw:
            notice_list = notice_list.filter(
                Q(title__icontains=kw) |  # 제목검색
                Q(content__icontains=kw) |  # 내용검색
                Q(writer__username__icontains=kw) # 질문 글쓴이검색
            ).distinct()

        paginator = Paginator(notice_list, 8)
        page_obj = paginator.get_page(page)

        context['notice_list'] = page_obj
        context['kw'] = kw
        context['page'] = page

        return context


# © 2017 Akretion, Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

import odoo.tests.common as test_common

class TestSaleOrderLotGenerator(test_common.SingleTransactionCase):
    def setUp(self):
        super().setUp()
        self.prd_flipover = self.env.ref("product.product_product_20")
        self.prd_desk = self.env.ref("product.product_product_22")
        self.prd_acoustic = self.env.ref("product.product_product_25")
        self.prd_flipover.write(
            {"tracking": "lot", "type": "product", "auto_generate_prodlot": True}
        )
        self.prd_desk.write(
            {"tracking": "lot", "type": "product", "auto_generate_prodlot": True}
        )
        self.prd_acoustic.write(
            {"tracking": "lot", "type": "product", "auto_generate_prodlot": True}
        )

    def test_sale_order_lot_generator(self):
        # create order
        self.order1 = self.env["sale.order"].create(
            # Lumber partner
            {"partner_id": self.env.ref("base.res_partner_18").id}
        )
        self.sol1 = self.env["sale.order.line"].create(
            {
                "name": "sol1",
                "order_id": self.order1.id,
                "product_id": self.prd_flipover.id,
                "product_uom_qty": 1,
            }
        )
        # confirm orders
        self.order1.action_confirm()
        lot_number = "%s-%03d" % (self.order1.name, 1)
        self.assertEqual(self.sol1.lot_id.name, lot_number)
        # add second line after order redraft
        self.order1._action_cancel()
        self.order1.action_draft()
        self.sol2 = self.env["sale.order.line"].create(
            {
                "name": "sol2",
                "order_id": self.order1.id,
                "product_id": self.prd_desk.id,
                "product_uom_qty": 1,
            }
        )
        self.order1.action_confirm()
        lot_number = "%s-%03d" % (self.order1.name, 2)
        self.assertEqual(self.sol2.lot_id.name, lot_number)
        # add third line after order confirm
        self.sol3 = self.env["sale.order.line"].create(
            {
                "name": "sol3",
                "order_id": self.order1.id,
                "product_id": self.prd_acoustic.id,
                "product_uom_qty": 1,
            }
        )
        lot_number = "%s-%03d" % (self.order1.name, 3)
        self.assertEqual(self.sol3.lot_id.name, lot_number)
        for line in self.order1.picking_ids.move_line_ids:
            if line.product_id.id == self.prd_flipover.id:
                self.assertEqual(line.lot_id, self.sol1.lot_id)
            if line.product_id.id == self.prd_desk.id:
                self.assertEqual(line.lot_id, self.sol2.lot_id)
            if line.product_id.id == self.prd_acoustic.id:
                self.assertEqual(line.lot_id, self.sol3.lot_id)


# print largest number by rearranging elements of list

def largest_number(nums):

    if len(nums) == 1:
        return str(nums[0])

    for i in range(len(nums)):
        for j in range(i+1, len(nums)):
            if int(str(nums[i])+str(nums[j])) < int(str(nums[j])+str(nums[i])):
                nums[i], nums[j] = nums[j], nums[i]
    return ''.join(map(str, nums))

nums = [3, 30, 34, 5, 9]
print(largest_number(nums))


# -*- coding: utf-8 -*-
import unittest
import tagging

from pdb import set_trace
from StringIO import StringIO

from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import smart_unicode

from tagging.fields import TagField
from tagging.models import Tag, TaggedItem, Synonym
from tagging.utils import replace_synonyms
from multilingual.languages import set_default_language

class TestItem( models.Model ):
    title = models.CharField( _('Title'), max_length = 30)
    tags = TagField()

    def __unicode__(self):
        return self.title

def create_synonyms(tag_name):
    from django.template.defaultfilters import slugify
    return [slugify(tag_name)]

class TestItemWithCallback( models.Model ):
    title = models.CharField( _('Title'), max_length = 30)
    tags = TagField(create_synonyms = create_synonyms)

    def __unicode__(self):
        return self.title

class TaggingTestCase(unittest.TestCase):
    def setUp(self):
        TestItem.objects.all().delete()
        Tag.objects.all().delete()
        TaggedItem.objects.all().delete()
        Synonym.objects.all().delete()

        self.first = TestItem(title = 'first')
        self.second = TestItem(title = 'second')
        self.third = TestItem(title = 'third')
        self.four = TestItem(title = 'four')

    def saveAll(self):
        self.first.save()
        self.second.save()
        self.third.save()
        self.four.save()

    def testJoining(self):
        self.first.tags = 'hello, world'
        self.second.tags = 'aloha'
        self.third.tags = 'bla'
        self.saveAll()

        # renaming
        aloha = Tag.objects.get(name = 'aloha')
        hello = Tag.objects.get(name = 'hello')
        Tag.objects.join([aloha, hello])

        all_tags = Tag.objects.all()
        self.assertEquals(3, len(all_tags))

        self.assertEquals(0, len(Tag.objects.filter(name = 'hello')))
        self.assertEquals(1, len(Tag.objects.filter(name = 'world')))
        self.assertEquals(1, len(Tag.objects.filter(name = 'bla')))

        tags = Tag.objects.filter(name = 'aloha')
        self.assertEquals(1, len(tags))
        objs = TaggedItem.objects.get_by_model(TestItem, tags)

        self.assertEquals(2, len(objs))
        self.assertTrue(self.first in objs)
        self.assertTrue(self.second in objs)

    def testJoiningMultiple(self):
        self.first.tags = 'hello, world'
        self.second.tags = 'aloha'
        self.third.tags = 'bla'
        self.saveAll()

        # renaming
        aloha = Tag.objects.get(name = 'aloha')
        hello = Tag.objects.get(name = 'hello')
        bla   = Tag.objects.get(name = 'bla')
        Tag.objects.join([aloha, hello, bla])

        all_tags = Tag.objects.all()
        self.assertEquals(2, len(all_tags))

        self.assertEquals(0, len(Tag.objects.filter(name = 'hello')))
        self.assertEquals(0, len(Tag.objects.filter(name = 'bla')))
        self.assertEquals(1, len(Tag.objects.filter(name = 'world')))
        self.assertEquals(1, len(Tag.objects.filter(name = 'aloha')))

        tags = Tag.objects.filter(name = 'aloha')
        self.assertEquals(1, len(tags))
        objs = TaggedItem.objects.get_by_model(TestItem, tags)

        self.assertEquals(3, len(objs))
        self.assertTrue(self.first in objs)
        self.assertTrue(self.second in objs)
        self.assertTrue(self.third in objs)

    def testJoiningTagsFromOneObject(self):
        self.first.tags = 'fruit, apple'
        self.saveAll()

        # renaming
        Tag.objects.join(\
                Tag.objects.filter(name__in = ('fruit', 'apple')))

        all_tags = Tag.objects.all()
        self.assertEquals(1, len(all_tags))

        self.assertEquals(1, len(Tag.objects.filter(name = 'apple')))
        self.assertEquals(0, len(Tag.objects.filter(name = 'fruit')))

    def testJoinUsingTextFormat(self):
        self.first.tags = 'hello, world'
        self.second.tags = 'aloha'
        self.third.tags = 'bla'
        self.saveAll()

        # renaming
        Tag.objects.process_rules(' first-non-existent = hello = aloha = second-non-existent = bla = non-existed')

        all_tags = Tag.objects.all()
        self.assertEquals(2, len(all_tags))

        self.assertEquals(1, len(Tag.objects.filter(name = 'hello')))
        self.assertEquals(1, len(Tag.objects.filter(name = 'world')))

        tags = Tag.objects.filter(name = 'hello')
        self.assertEquals(1, len(tags))
        objs = TaggedItem.objects.get_by_model(TestItem, tags)

        self.assertEquals(3, len(objs))
        self.assertTrue(self.first in objs)
        self.assertTrue(self.second in objs)
        self.assertTrue(self.third in objs)

    def testRenameUsingTextFormat(self):
        self.first.tags = 'hello-world'
        self.saveAll()

        Tag.objects.process_rules( \
                u'''hello-world: hello; ru: Привет;
                    hello; en: Hello;
                    non-existent: normal''')

        tag = Tag.objects.get(name='Hello')
        self.assertEquals(u'Привет', tag.name_ru)
        self.assertEquals(u'Hello', tag.name_en)

    def testDumpTagsAsText(self):
        set_default_language('en')

        hello = Tag.objects.create(name='hello')
        syn = Synonym.objects.create(name='aloha', tag=hello)

        self.first.tags = 'hello, world'
        self.second.tags = 'aloha'
        self.saveAll()

        self.assertEquals( \
u'''hello == aloha
hello; en: hello
world; en: world''', Tag.objects.dumpAsText())

        hello.name_ru = u'Привет'
        hello.name_en = u'Hello'
        hello.save()

        self.assertEquals( \
u'''Hello == aloha
Hello; en: Hello; ru: Привет
world; en: world''', Tag.objects.dumpAsText())

    def testTagRenameChangesObjectsProperties(self):
        self.first.tags = 'hello, world'
        self.saveAll()

        hello = Tag.objects.get(name='hello')
        hello.name = u'Привет'
        hello.save()

        self.first = TestItem.objects.get(id=self.first.id)
        self.assertEquals(u'world Привет', self.first.tags)

    def testTagJoinChangesObjectsProperties(self):
        self.first.tags = 'hello, world'
        self.saveAll()

        Tag.objects.join( \
                Tag.objects.filter(name__in = ('hello', 'world')))

        self.first = TestItem.objects.get(id=self.first.id)
        self.assertEquals('hello', self.first.tags)

    def testTagRemoveChangesObjectsProperties(self):
        self.first.tags = 'hello, world'
        self.saveAll()

        Tag.objects.get(name = 'world').delete()

        self.first = TestItem.objects.get(id=self.first.id)
        self.assertEquals('hello', self.first.tags)

    def testTagSynonym(self):
        tag = Tag.objects.create(name='hello')
        syn = Synonym.objects.create(name='aloha', tag=tag)

        self.first.tags = 'aloha, world'
        self.saveAll()

        self.first = TestItem.objects.get(id=self.first.id)
        self.assertEquals('hello world', self.first.tags)

    def testCreatingSynonymUsingTextFormat(self):
        self.first.tags = 'hello, world'
        self.second.tags = 'aloha'
        self.saveAll()

        # renaming
        self.assertEquals(3, Tag.objects.count())
        Tag.objects.process_rules('hello == aloha == privet')
        self.assertEquals(2, Tag.objects.count())

        self.assertEquals(1, len(Tag.objects.filter(name = 'hello')))
        self.assertEquals(1, len(Tag.objects.filter(name = 'world')))

        hello = Tag.objects.get(name = 'hello')
        self.assertEquals(2, len(hello.synonyms.all()))
        self.assertTrue('aloha', hello.synonyms.all()[0].name)
        self.assertTrue('privet', hello.synonyms.all()[1].name)

        objs = TaggedItem.objects.get_by_model(TestItem, [hello,])

        self.assertEquals(2, len(objs))
        self.assertTrue(self.first in objs)
        self.assertTrue(self.second in objs)

    def testExistingSynonymsAreIgnored(self):
        self.first.tags = 'hello, world'
        self.saveAll()
        Tag.objects.process_rules('hello == aloha == privet')
        self.assert_(Tag.objects.process_rules('hello == aloha == privet'))

    def testReplaceSynonyms(self):
        tag = Tag.objects.create(name='hello')
        Synonym.objects.create(name='aloha', tag=tag)
        self.assertEquals(['hello', 'world'], replace_synonyms(['aloha', 'world']))

    def testCreateSynonymUsingFieldCallback(self):
        tag = Tag.objects.create(name='hello')
        Synonym.objects.create(name='aloha', tag=tag)
        self.assertEquals(['hello', 'world'], replace_synonyms(['aloha', 'world']))

        Synonym.objects.all().delete()
        self.assertEqual(0, len(Synonym.objects.all()))
        test_item = TestItemWithCallback(title='Test callbacks', tags='Test, Create Callbacks')
        test_item.save()
        second_item = TestItemWithCallback(title='Another test', tags='Test')
        second_item.save()

        synonyms = Synonym.objects.all()
        self.assertEqual(2, len(synonyms))
        self.assertEqual('create-callbacks', synonyms[0].name)
        self.assertEqual('test', synonyms[1].name)

        objs = TaggedItem.objects.get_by_model(TestItemWithCallback, ['create-callbacks'])
        self.assertEqual(1, len(objs))
        self.assertEqual('Test callbacks', objs[0].title)


# -*- coding: utf-8 -*-
#library pandas to read files
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats

#load my data inside a data frame
startups_df = pd.read_csv(r"ds.csv")

#select X variables (independant)
X_RD_Spend = startups_df.iloc[0:len(startups_df),0]
X_Administration_Spend = startups_df.iloc[0:len(startups_df),1]
X_MarketingSpend = startups_df.iloc[0:len(startups_df),2]
#select Y variables (dependent)
Y_Profit = startups_df.iloc[0:len(startups_df),4]

slope, intercept, r_value, p_value,std_err = stats.linregress(X_RD_Spend,Y_Profit)
def predict(x) :
    return (slope * x + intercept)
#draw a graph using payplot including FitLine(ligne des prédictions)
fitLine = predict(X_RD_Spend)
plt.plot(X_RD_Spend,fitLine,c='red')
axes = plt.axes()
axes.grid()
plt.scatter(X_RD_Spend,Y_Profit)

#plt.scatter(X_Administration_Spend, Y_Profit)
#plt.scatter(X_MarketingSpend, Y_Profit)
plt.show()

print("R² :--------->  ", r_value)
print("p-value :---->  ", p_value)
print("std_err :---->  ", std_err)


import re
from flask import render_template, url_for, redirect, request, flash, jsonify, session
from werkzeug.urls import url_parse
from flask_login import login_user, logout_user, current_user, login_required
from app import db
from app.controllers.api import bp
from app.models import User, Book, User_Book

# check if username is existed. Needs username as data
@bp.route("/userexist", methods=["POST"])
def user_exist():
    username = request.get_json()
    if username["username"]:
        if User.query.filter_by(username=username["username"]).first() is None:
            return jsonify({"usable": "true"})
    return jsonify({"usable": "false"})

# flashed message API. Take in a message then it would put a flash in the stack
@bp.route("/flash_message", methods=["POST"])
@login_required
def flash_message():
    try:
        message = request.get_json()
        if message["message"]:
            flash(message["message"])
    except KeyError:
        return redirect(url_for("errors.bad_request"))
    return jsonify()

# take in the isbn of the book
@bp.route("/addbook", methods=["POST"])
@login_required
def add_book_by_isbn():
    try:
        data = request.get_json()
        isbn = str(data["isbn"])
        authors = str(data["authors"])
        pages = str(data["pages"])
        title = str(data["title"])
        if len(isbn) != 10 and len(isbn) != 13:
            return redirect(url_for("errors.bad_request"))
        book = Book.query.filter_by(id=isbn).first()
        if not book:
            book = Book(id=str(isbn))
            db.session.add(book)
            db.session.commit()
            book = Book.query.filter_by(id=isbn).first()
        book_exist = User_Book.query.filter_by(user_id=current_user.id, book_id=isbn).first()
        if book_exist:
            User_Book.query.filter_by(user_id=current_user.id, book_id=isbn).delete()
            db.session.commit()
            return jsonify({"success": True, "delete": True})
        else:
            current_user.add_book(book, authors=authors, pages=pages, title=title)
    except KeyError:
        return redirect(url_for("errors.bad_request"))
    return jsonify({"success": True, "delete": False})

# get a list of all books user have
@bp.route("/getbooks", methods=["POST"])
@login_required
def get_books():
    try:
        data = request.get_json()
        username = data["username"]
        user = User.query.filter_by(username=username).first()
        if not user:
            return redirect(url_for("errors.bad_request"))
        list_of_books = user.get_books()
        return jsonify({"value": list_of_books})
    except KeyError:
        return redirect(url_for("errors.bad_request"))
    return jsonify()

# check if a book is owned by a specific user
@bp.route("/hasbook", methods=["POST"])
@login_required
def has_book():
    try:
        data = request.get_json()
        isbn = data["isbn"]
        book = Book.query.filter_by(id=isbn).first()
        if not book:
            return jsonify({"has": False})
        return jsonify({"has": (isbn in current_user.get_books())})
    except KeyError:
        return redirect(url_for("errors.bad_request"))

# change the status of finishign the book of a user
@bp.route("/changefinish", methods=["POST"])
@login_required
def change_finish():
    try:
        data = request.get_json()
        isbn = data["isbn"]
        book = Book.query.filter_by(id=isbn).first()
        if not book:
            return redirect(url_for("errors.bad_request"))
        user_book = User_Book.query.filter_by(user_id=current_user.id, book_id=book.id).first()
        if not user_book:
            return redirect(url_for("errors.bad_request"))
        current_user.change_finish(user_book)
        return jsonify({"success": True, "finished": user_book.finished})
    except KeyError:
        return redirect(url_for("errors.bad_request"))


import csv
import os

total_months = 0
total = 0.0
first_profit_loss = 0.0
last_profit_loss = 0.0
current_profit_loss = 0.0
average_profit = 0.0
change_profit = 0.0
greatest_increase = 0.0
greatest_increase_month = ""
greatest_decrease_month = ""
greatest_decrease = 0.0

file_path = os.path.join("Resources", "budget_data.csv")
with open(file_path, "r") as bank_file:
    csvreader = csv.reader(bank_file)
    # store the header and move the reader to data in csv
    header = next(csvreader,None)
    if header[0] == 'Date' and header[1] == 'Profit/Losses':
        # loop though rows of the csv file
        for line in csvreader:
            current_profit_loss = float(line[1])
            total += current_profit_loss
            total_months +=1
            change_profit = current_profit_loss - last_profit_loss
            if(greatest_increase < change_profit):
                greatest_increase = change_profit
                greatest_increase_month = line[0]

            if(greatest_decrease > change_profit):
                greatest_decrease = change_profit
                greatest_decrease_month = line[0]

            if(total_months ==1):
                first_profit_loss = current_profit_loss

            # Just before leaving the loop update last_profit_loss
            last_profit_loss = current_profit_loss

average_profit  = round((last_profit_loss - first_profit_loss)/(total_months - 1),2)

results = ("Financial Analysis",
            "----------------------------",
            f"Total Months : {total_months}",
            "Total : $" + "{:.0f}".format(total),
            f"Average Change : {average_profit }",
            f"Greatest Increase in Profits: {greatest_increase_month} " + "($"+"{:.0f}".format(greatest_increase)+")",
            f"Greatest Decrease in Profits: {greatest_decrease_month} " + "($"+"{:.0f}".format(greatest_decrease)+")")

#  print results
for row in results:
    print(row)

# publish the analysis to output.csv
output_file = os.path.join("analysis", "output.csv")
with open(output_file, "w", newline='\n') as datafile:
    writer = csv.writer(datafile, delimiter =" ", escapechar=' ', quoting=csv.QUOTE_NONE)
    writer.writerows(results)


def minAndMax(i, j, Max, Min, operator):
    minValue = float('inf')
    maxValue = float('-inf')
    for k in range(i, j):
        a = int(eval(str(Max[i][k]) + operator[k] + str(Max[k + 1][j])))
        b = int(eval(str(Max[i][k]) + operator[k] + str(Min[k + 1][j])))
        c = int(eval(str(Min[i][k]) + operator[k] + str(Max[k + 1][j])))
        d = int(eval(str(Min[i][k]) + operator[k] + str(Min[k + 1][j])))
        minValue = min(minValue, a, b, c, d)
        maxValue = max(maxValue, a, b, c, d)
    return minValue, maxValue

def parentheses(d, op):
    n = len(digits)
    M = [[0] * n for _ in range(n)]
    m = [[0] * n for _ in range(n)]
    for i in range(n):
        m[i][i] = d[i]
        M[i][i] = d[i]
    for s in range(1, n - 1):
        for i in range(1, n - s):
            j = i + s
            m[i][j], M[i][j] = minAndMax(i, j, M, m, op)
    return M[1][n - 1]

expression = input()
digits = [0]
operators = ['0']
for i in expression:
    if i.isdigit():
        digits.append(int(i))
    else:
        operators.append(i)
print(parentheses(digits, operators))