# coding: utf-8
""" MIT License """
'''
    Project: Personal Backups
    Authors: Axel Masquelin
    Description:
'''
# Libraries
# ---------------------------------------------------------------------------- #

from re import S
from turtle import forward
import torchvision.transforms as transforms
import torchvision.models as models
import torch.nn.functional as F
import torch.optim as optim
import torch.nn as nn
import torch.Tensor as Tensor
import torchvision
import torch

import numpy as np
import utils
# ---------------------------------------------------------------------------- #

class BasicConv2d(nn.Module):
    def __init__(self, chn_in: int, chn_out: int, nxn: int):
        super.__init__()

        self.Conv = nn.Conv2d(chn_in, chn_out, nxn, bias = False)
        self.BatchNorm = nn.BatchNorm2d(chn_out, eps = 0.001)

    def forward(self, x: Tensor) -> Tensor:
        x = self.Conv(x)
        x = self.BatchNorm(x)

        return F.relu(x, inplace=True)

class NaiveInception(nn.Module):
    def __init__(self, chn_in: int, chn_out: int):
        super().__init__()

        self.branch1x1 = BasicConv2d(chn_in= chn_in, chn_out= chn_out, nxn = 1)
        self.branch3x3 = BasicConv2d(chn_in= chn_in, chn_out= chn_out, nxn = 3)
        self.branch5x5 = BasicConv2d(chn_in= chn_in, chn_out= chn_out, nxn = 5)
        self.branchpool = nn.MaxPool2d(kernel_size = 3)

    def _forward(self, x: Tensor) -> Tensor:
        branch1x1 = self.branch1x1(x)
        branch3x3 = self.branch3x3(x)
        branch5x5 = self.branch5x5(x)
        branchpool = self.branchpool(x)

        outputs = [branch1x1, branch3x3, branch5x5, branchpool]

        return outputs

    def forward(self, x: Tensor) -> Tensor:
        outputs = self._forward(x)
        return torch.cat(outputs, 1)

class DRInceptionblock(nn.Module):
    def __init__(self, chn_in: int, chn_out: int) -> None:
        super().__init__()

        self.branch1x1 = BasicConv2d(chn_in= chn_in, chn_out= chn_out, nxn= 1)
        self.branch3x3 = BasicConv2d(chn_in= chn_in, chn_out= chn_out, nxn= 3)
        self.branch5x5 = BasicConv2d(chn_in= chn_in, chn_out= chn_out, nxn= 5)
        self.branchpool = nn.MaxPool2d(kernel_size = 3)

    def _forward(self, x: Tensor) -> Tensor:
        branch1x1 = self.branch1x1(x)
        branch3x3 = self.branch3x3(self.branch1x1(x))
        branch5x5 = self.branch5x5(self.branch1x1(x))
        branchpool = self.branch1x1(self.branchpool(x))

        outputs = [branch1x1, branch3x3, branch5x5, branchpool]

        return outputs

    def forward(self, x: Tensor) -> Tensor:
        outputs = self._forward(x)
        return torch.cat(outputs,1)

class Miniception(nn.Module):
    def __init__(self, n, ch_in, n_classes = 2):
        super(Miniception, self).__init__()

        self.config=[
            # chn_in, chn_out
            [1, 4]
            [16, 4]
        ]

        layers = []
        for c_in, c_out in self.config:
            layers.append(DRInceptionblock(chn_in=c_in, chn_out=c_out))

        self.layers = nn.Sequential(*layers)

        self.avg_pool = nn.AdaptiveAvgPool2d(1)

        self.classifier = nn.Sequential(
            nn.Dropout2d(),
            nn.Linear(256, n_classes)
        )

    def forward(self, x):
        x = self.layers(x)
        x = self.avg_pool(x)
        x = x.view(-1, 256)
        x = self.classifier(x)

        return x


import torch

def is_gpu_available():
    return torch.cuda.is_available()

# from https://github.com/rafaljozefowicz/lm
class HParams(object):
    def __init__(self, **kwargs):
        self._items = {}
        for k, v in kwargs.items():
            self._set(k, v)

    def _set(self, k, v):
        self._items[k] = v
        setattr(self, k, v)

    def parse(self, str_value):
        hps = HParams(**self._items)
        for entry in str_value.strip().split(","):
            entry = entry.strip()
            if not entry:
                continue
            key, sep, value = entry.partition("=")
            if not sep:
                raise ValueError("Unable to parse: %s" % entry)
            default_value = hps._items[key]
            if isinstance(default_value, bool):
                hps._set(key, value.lower() == "true")
            elif isinstance(default_value, int):
                hps._set(key, int(value))
            elif isinstance(default_value, float):
                hps._set(key, float(value))
            else:
                hps._set(key, value)
        return hps

    def update(self, **kwargs):
        for k, v in kwargs.items():
            self._set(k, v)

    def show(self):
        print("\n----------- Current Hyperparameter Settings -----------")
        for k, v in self._items.items():
            print( u'{} : {}'.format(k,v) )
        print("-------------------------------------------------------\n")

    def get_all_param(self):
        all_param = {}
        for k, v in self._items.items():
            all_param[k] = v
        return all_param

import os
def prepare_dir(dir_name):
    if not os.path.exists(dir_name): os.makedirs(dir_name)

def load_model(model_fn, map_location=None):
    if map_location:
        return torch.load(model_fn, map_location=map_location)
    else:
        if torch.cuda.is_available():
            return torch.load(model_fn)
        else:
            return torch.load(model_fn, map_location='cpu')


from io import BytesIO
from PIL import Image, ImageDraw, ImageFilter,ImageEnhance
import time
from time import sleep
from pynput.mouse import Button, Controller, Listener
import glob

import difflib

import pytesseract

import numpy as np
import pyscreenshot as ImageGrab
import cv2
import json
from types import SimpleNamespace

def listFile( path ):
        res = glob.glob(  path + "*")
        for i in range(len(res)):
                res[i] = res[i].replace("\\" , "/")
        return res

def on_click(x, y, button, pressed):
    global clickPos

    if not pressed:
        clickPos = (x,y)
        return False
# Collect events until released
def getNextClickPos():
    with Listener(on_click=on_click) as listener:
        listener.join()
        return clickPos

def moveTo( coord ):
    mouse = Controller()
    mouse.position = (coord[0],coord[1])

def moveToCoord( coord ):
    mouse = Controller()
    mouse.position = (coord['x'],coord['y'])

def moveThenClick( mouseBtn, coord ):
    mouse = Controller()
    mouse.position = (coord[0],coord[1])
    time.sleep(0.05)
    mouse.click( Button[mouseBtn],1)
    time.sleep(0.1)

def moveThenClickCoord( mouseBtn, coord ):
    mouse = Controller()
    mouse.position = (coord["x"],coord["y"])
    time.sleep(0.05)
    mouse.click( Button[mouseBtn],1)
    time.sleep(0.1)

def isPixelColorContainedInRange( begRangeRGB , endRangeRGB, auditedRGB ):
    isContained = True
    for ind in range(3):
        if( auditedRGB[ind] < begRangeRGB[ind] or auditedRGB[ind] > endRangeRGB[ind] ):
            return False

    return isContained

def findFirstPixePosInImgOnColor(im, boxRangeX, boxRangeY,targetColor ):
    for pX in range( boxRangeX ):
        for pY in range( boxRangeY ):
            color = im.getpixel( (pX ,pY) )
            if color == targetColor :
                return [pX,pY]
##replace outter circle by (0,0,0)
def mask_circle_solid(pil_img, background_color, blur_radius, offset=0):
    background = Image.new(pil_img.mode, pil_img.size, background_color)

    offset = blur_radius * 2 + offset
    mask = Image.new("L", pil_img.size, 0)
    draw = ImageDraw.Draw(mask)
    draw.ellipse((offset, offset, pil_img.size[0] - offset, pil_img.size[1] - offset), fill=255)
    mask = mask.filter(ImageFilter.GaussianBlur(blur_radius))

    return Image.composite(pil_img, background, mask)
# maybe try to create ^pixcel map to Optimize like image.load() ?
def getListOfPixelPosByColor(im, boxRangeX, boxRangeY, targetColor, blurArea ):
    targetColorBegRange = [ x - blurArea for x in targetColor]
    targetColorEndRange = [ x + blurArea for x in targetColor]
    imData = []
    for pX in range( boxRangeX ):
        for pY in range( boxRangeY ):
            colorVal = im.getpixel( (pX ,pY) )
            if isPixelColorContainedInRange( targetColorBegRange, targetColorEndRange, colorVal ) == False:
                continue

            imData.append( (pX ,pY) )
            # if colorVal in imData:
            #     oldVal = imData[colorVal]
            #     imData[colorVal] = oldVal+1
            # else :
            #     imData[ colorVal ] = 1

    return imData

################ IMG IN IMG // IMG TO TEXT // TEXT TO PRICE -- TODO LOAD GLOBAL VAR BY ENV VAR ( create .env )

# CONFIG
LTC_IMG_PATH = ['ancor/refs/items/leftTopItemBorder.png','ancor/refs/items/leftTopItemBorder2.png','ancor/refs/items/leftTopItemBorder3.png','ancor/refs/items/leftTopItemBorder4.png']
RTC_IMG_PATH =  ['ancor/refs/items/rightTopItemBorder.png','ancor/refs/items/rightTopItemBorder2.png','ancor/refs/items/rightTopItemBorder3.png','ancor/refs/items/rightTopItemBorder4.png']

GIDP_IMG_PATH = 'img/guessedItemDesription.png'
EIN_IMG_PATH = 'img/extractedItemName.png'

PRICING_JSON_PATH = 'json/items_pricing.json'
# -- tesseract config
pytesseract.pytesseract.tesseract_cmd = r'D:\Web_game_solo\OCR\tesseract'

# FUNCTIONS
def getItemList( jsonFilePath = PRICING_JSON_PATH ):
    input_file = open ( jsonFilePath )
    itemsData = json.load(input_file)

    itemList = []
    for index, item in enumerate(itemsData):
        itemList.append( item )

    return itemList , itemsData

def contrast( val , img ):
    #image brightness enhancer
    enhancer = ImageEnhance.Contrast(img)

    factor = val #gives original image
    im_output = enhancer.enhance(factor)
    return im_output

def getImgPosInImg( large_img_path , small_img_path , method = cv2.TM_SQDIFF_NORMED, debug = False ):
    # Read the images from the file
    large_image = cv2.imread(large_img_path)
    small_image = cv2.imread(small_img_path)
    result = cv2.matchTemplate(small_image, large_image, method)
    # We want the minimum squared difference
    mn,_,mnLoc,_ = cv2.minMaxLoc(result)
    # Draw the rectangle:
    # Extract the coordinates of our best match
    MPx,MPy = mnLoc
    # print( MPx,MPy )
    if debug :
        # - - - DEBUG  Step 2: Get the size of the template. This is the same size as the match.
        trows,tcols = small_image.shape[:2]
        # Step 3: Draw the rectangle on large_image
        cv2.rectangle(large_image, (MPx,MPy),(MPx+tcols,MPy+trows),(0,0,255),2)
        # Display the original image with the rectangle around the match.
        cv2.imshow('output',large_image)
        # The image is only displayed if we call this
        cv2.waitKey(0)

    return [MPx,MPy]

def extractItemNameAsImg( mousePos, screenArea , resultImgPath, debug = False, iter = 0 ):
    im = ImageGrab.grab( bbox=( mousePos['x']-screenArea, mousePos['y']-screenArea, mousePos['x']+screenArea, mousePos['y']+screenArea), backend="mss",childprocess=False )  # X1,Y1,X2,Y2
    im.save(GIDP_IMG_PATH)

    tlBorder = getImgPosInImg( GIDP_IMG_PATH, LTC_IMG_PATH[iter], debug = debug )
    trBorder = getImgPosInImg( GIDP_IMG_PATH, RTC_IMG_PATH[iter], debug = debug )
    # print( tlBorder,  trBorder )
    cropped = Image.open( GIDP_IMG_PATH )
    # Setting the points for cropped image'test shop

    left = tlBorder[0]+20
    right = trBorder[0]-20

    top = tlBorder[1] +15
    bottom = tlBorder[1] + 25
    # Cropped image of above dimension
    # (It will not change original image)

    if debug :
        print('imgSize before ' , cropped.size )
        print('left : ' ,left ,'top : ' ,top ,'right : ' ,right ,'bottom : ' ,bottom)

    cropped = cropped.crop((left, top, right, bottom))

    if debug :
        print('imgSize after ' , cropped.size )
    # # Shows the image in image viewer
    # cropped.show()

    try:
        cropped.save(resultImgPath)
    except:
        print('could not saved cropped img')
        return None

    # im = im.crop((tlBorder[0], tlBorder[1]+ 5, trBorder[0], trBorder[1] +5  ))
    return cropped

def getItemPriceByParsingMousePosImg( mousePos, nearRange = 220, fontAverageRangeColor = ((180,180,180),(255,255,255)), debug = False, iter = 0 ):

    moveToCoord( mousePos )
    sleep( 0.5 )

    nearRange = 220
    extractedImg = extractItemNameAsImg( mousePos, nearRange, EIN_IMG_PATH, debug = debug, iter = iter  )
    # try :
    #     extractedImg.save("img/tmpState.png")
    # except :
    #     print( 'imgSat' ,  extractedImg )

    if( extractedImg == None ):
        return None

    extractedImg = extractedImg.convert("RGBA")
    pixdata = extractedImg.load()
    imgsize = extractedImg.size

    for pX in range( imgsize[0] ):
        for pY in range( imgsize[1] ):
            colorVal = extractedImg.getpixel( (pX ,pY) )
            if isPixelColorContainedInRange(  fontAverageRangeColor[0], fontAverageRangeColor[1], colorVal ) == False:
                pixdata[pX, pY] = (0, 0, 0, 255)

    extractedImg.save( EIN_IMG_PATH )
    extractedText = pytesseract.image_to_string( EIN_IMG_PATH )
    parsedExtractedText = extractedText.strip()

    itemsList, itemData = getItemList()
    match = difflib.get_close_matches( parsedExtractedText , itemsList)

    if debug :
        print("extracted text => ",  parsedExtractedText  )
        print( "item => " , itemData )
        print( "match => ", match , len(match) )

    if len(match) == 0:
        return None

    pricingData = itemData[match[0]] if itemData.get(match[0]) else None

    return pricingData

# # getImgPosInImg( 'img/guessedItemDesription.png', "ancor/refs/items/leftTopItemBorder.png", method=cv2.TM_SQDIFF_NORMED ,  debug=True )

# getImgPosInImg( 'img/guessedItemDesription.png', "ancor/refs/items/rightTopItemBorder4.png", method=cv2.TM_SQDIFF_NORMED ,  debug=True )
# extractedText = pytesseract.image_to_string( 'img/extractedItemName.png' )
# parsedExtractedText = extractedText.strip()

# print( parsedExtractedText , extractedText )


from django.conf.urls import url
from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework import permissions, routers

from django_scantron.api import views

# Create a router and register our viewsets with it.
# basename requirement: http://www.django-rest-framework.org/api-guide/routers/#usage
router = routers.DefaultRouter(trailing_slash=False)
router.register(r"configuration", views.ConfigurationViewSet, basename="configuration")
router.register(r"engines", views.EngineViewSet, basename="engines")
router.register(r"engine_pools", views.EnginePoolViewSet, basename="engine_pools")
router.register(r"globally_excluded_targets", views.GloballyExcludedTargetViewSet, basename="globally_excluded_targets")
router.register(r"scan_commands", views.ScanCommandViewSet, basename="scan_commands")
router.register(r"scans", views.ScanViewSet, basename="scans")
router.register(r"scheduled_scans", views.ScheduledScanViewSet, basename="scheduled_scans")
router.register(r"sites", views.SiteViewSet, basename="sites")

schema_view = get_schema_view(
    openapi.Info(
        title="Scantron API",
        default_version="v1",
        description="Scantron API documentation",
        terms_of_service="https://github.com/rackerlabs/scantron",
        contact=openapi.Contact(email="https://github.com/rackerlabs/scantron"),
        license=openapi.License(name="Apache License, Version 2.0"),
    ),
    public=False,
    permission_classes=(permissions.IsAuthenticated,),  # comma needed inside parenthesis.
)

urlpatterns = [
    url(r"^swagger(?P<format>\.json|\.yaml)$", schema_view.without_ui(cache_timeout=0), name="schema-json"),
    url(r"^swagger/$", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui"),
    url(r"^redoc/$", schema_view.with_ui("redoc", cache_timeout=0), name="schema-redoc"),
    url(r"^server_time$", views.get_server_time, name="server_time"),
]

urlpatterns += router.urls


import json
import logging

from settings import DEFAULT_LANG

logger = logging.getLogger(__name__)

def translate(message_id: str, lang_code: str, placeholders=None) -> str:
    """
    Loads a specified translation and replaces the placeholders with the provided values.

    :param message_id: A string representing the message ID, in the format 'module.message_name'.
    :param lang_code: The language code (e.g., 'en', 'es') for the desired translation.
    :param placeholders: A dictionary containing the placeholders and their values.
                         Defaults to an empty dictionary if not provided.
    :return: The translated message as a string.
    """
    if placeholders is None:
        placeholders = {}

    trans = load_translation(lang_code)
    module, message_name = message_id.split('.')

    try:
        message_template = trans[module][message_name]
        for placeholder, value in placeholders.items():
            message_template = message_template.replace(f'{{{placeholder}}}', str(value))
        return message_template

    except (KeyError, TypeError) as e:
        if lang_code != DEFAULT_LANG:
            # Try falling back to default language
            logger.warning(f'Could not find translation for {message_id} in {lang_code}', exc_info=e)
            return translate(message_id, DEFAULT_LANG, placeholders)

        logger.error(f'Could not find translation for {message_id} in default {lang_code}', exc_info=e)
        return message_id

def load_translation(lang_code: str) -> dict:
    """
    Loads translations for the given language code from a JSON file.

    :param lang_code: The language code (e.g., 'en', 'es') for the desired translation.
    :return: A dictionary containing the translations.
    :raises ValueError: If the default translation file cannot be loaded.
    """
    try:
        filename = f'locales/translations/{lang_code}.json'.lower()
        with open(filename, 'r', encoding='utf-8') as f:
            return json.load(f)

    except Exception as e:
        if lang_code != DEFAULT_LANG:
            # Try falling back to default language
            logger.warning(f'Could not load translation {lang_code}', exc_info=e)
            return load_translation(DEFAULT_LANG)

        logger.error(f'Default translation {DEFAULT_LANG} could not be loaded', exc_info=e)
        raise ValueError(f'Default translation {DEFAULT_LANG} could not be loaded') from e


from __future__ import absolute_import
from __future__ import unicode_literals

import os
import psutil
import six
import subprocess
import sys

def _wait_and_kill(pid_to_wait, pids_to_kill):
  """ Wait for a process to finish if it exists, and then kill a list of processes.

  Args:
    pid_to_wait: the process to wait for.
    pids_to_kill: a list of processes to kill after the process of pid_to_wait finishes.
  """
  if psutil.pid_exists(pid_to_wait):
    psutil.Process(pid=pid_to_wait).wait()

  for pid_to_kill in pids_to_kill:
    if psutil.pid_exists(pid_to_kill):
      p = psutil.Process(pid=pid_to_kill)
      p.kill()

def run_and_monitor(args, pid_to_wait, std_out_filter_fn=None, cwd=None):
  """ Start a process, and have it depend on another specified process.

  Args:
    args: the args of the process to start and monitor.
    pid_to_wait: the process to wait on. If the process ends, also kill the started process.
    std_out_filter_fn: a filter function which takes a string content from the stdout of the
        started process, and returns True if the string should be redirected to console stdout.
    cwd: the current working directory for the process to start.
  """

  monitor_process = None
  try:
    p = subprocess.Popen(args,
                         cwd=cwd,
                         env=os.environ,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)

    pids_to_kill = [p.pid]
    script = ('import %s;%s._wait_and_kill(%s, %s)' %
              (__name__, __name__, str(pid_to_wait), str(pids_to_kill)))
    monitor_process = subprocess.Popen(['python', '-c', script], env=os.environ)
    while p.poll() is None:
      line = p.stdout.readline()

      if not six.PY2:
        line = line.decode()

      if std_out_filter_fn is None or std_out_filter_fn(line):
        sys.stdout.write(line)
        # Cannot do sys.stdout.flush(). It appears that too many flush() calls will hang browser.
  finally:
    if monitor_process:
      monitor_process.kill()


from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel
from sqlalchemy import select, insert, update
from sqlalchemy.ext.asyncio import AsyncSession
from src.database import get_async_session

from src.reviews.models import Review
from src.reviews.schemas import ReviewRead, ReviewCreate

router = APIRouter(
    prefix="/review",
    tags=["Reviews"]
)

@router.get("/", response_model=List[ReviewRead])
async def get_review_list(page: Optional[int] = Query(1, description="Номер страницы", ge=1),
                          page_size: Optional[int] = Query(10, description="Размер страницы", ge=1, le=100),
                          session: AsyncSession = Depends(get_async_session)):
    offset = (page - 1) * page_size
    query = select(Review).offset(offset).limit(page_size)
    result = await session.execute(query)
    return result.scalars().all()

@router.get("/{review_id}", response_model=ReviewRead)
async def get_review_detail(review_id: int, session: AsyncSession = Depends(get_async_session)):
    query = select(Review).filter_by(id=review_id)
    result = await session.execute(query)
    return result.scalars().first()

@router.post("/")
async def post_review_create(new_review: ReviewCreate, session: AsyncSession = Depends(get_async_session)):
    stmt = insert(Review).values(**new_review.dict())
    await session.execute(stmt)
    await session.commit()
    return {"status": "success"}

@router.put("/{review_id}", response_model=ReviewCreate)
async def put_review_update(review_id: int, product: ReviewCreate,
                            session: AsyncSession = Depends(get_async_session), ):
    stmt = (
        update(Review)
        .where(Review.id == review_id)
        .values(**product.dict())
        .returning(Review)
    )
    result = await session.execute(stmt)
    updated_review = result.scalar()
    if updated_review is None:
        raise HTTPException(status_code=404, detail="Review not found")

    await session.commit()
    return updated_review

@router.delete("/{review_id}", response_model=ReviewRead)
async def review_delete(review_id: int, session: AsyncSession = Depends(get_async_session)):
    stmt = (
        update(Review)
        .where(Review.id == review_id)
        .values({"is_deleted": True})
        .returning(Review)
    )
    result = await session.execute(stmt)
    delete_review = result.scalar()
    if delete_review is None:
        raise HTTPException(status_code=404, detail="Review not found")

    await session.commit()
    return delete_review


import os
import click
import sqlite3

from flask import current_app, g
from flask.cli import with_appcontext

from dotenv import load_dotenv

load_dotenv()

# ---
# Utility functions
# ---
def get_db():
	if 'db' not in g:
		g.db = sqlite3.connect(
			current_app.config['DATABASE'],
			detect_types=sqlite3.PARSE_DECLTYPES
		)
		g.db.row_factory = sqlite3.Row

	return g.db

def close_db(e=None):
	db = g.pop('db', None)
	if db:
		db.close()

def init_app(app):
	app.teardown_appcontext(close_db)
	app.cli.add_command(init_db_command)

# ---
# Command line options
# ---
def init_db_handler():
	db = get_db()
	with current_app.open_resource(os.getenv('DB_FILE')) as dbfile:
		db.executescript(dbfile.read().decode())

@click.command('init-db')
@with_appcontext
def init_db_command():
	init_db_handler()
	click.echo('[!!] Database initialized\n')


import os
from flask_wtf import FlaskForm

from wtforms import PasswordField, StringField, SubmitField, TextAreaField, SelectField
from wtforms.validators import DataRequired, Length, Email
from wtforms import ValidationError

from flask_wtf.file import FileField, FileRequired
import phonenumbers

from flask import current_app, render_template
from werkzeug.utils import secure_filename

from ..email import send_email_attachment, send_email

STATE_CHOICES = [('--Choose--', '--Choose--'), ("AL - Alabama", "AL - Alabama"), ("AK - Alaska", "AK - Alaska"), ("AZ - Arizona", "AZ - Arizona"), ("AR - Arkansas", "AR - Arkansas"), ("CA - California", "CA - California"), ("CO - Colorado", "CO - Colorado"),
                 ("CT - Connecticut", "CT - Connecticut"), ("DC - Washington DC", "DC - Washington DC"), ("DE - Deleware", "DE - Deleware"), ("FL - Florida", "FL - Florida"), ("GA - Georgia", "GA - Georgia"),
                 ("HI - Hawaii", "HI - Hawaii"), ("ID - Idaho", "ID - Idaho"), ("IL - Illinios", "IL - Illinios"), ("IN - Indiana", "IN - Indiana"), ("IA - Iowa", "IA - Iowa"), ("KS - Kansas", "KS - Kansas"), ("KY - Kentucky", "KY - Kentucky"), ("LA - Louisiana", "LA - Louisiana"), ("ME - Maine", "ME - Maine"), ("MD - Maryland", "MD - Maryland"), ("MO - Missouri", "MO - Missouri"), ("MT - Montana", "MT - Montana"), ("NE - Nebraska", "NE - Nebraska"), ("NV - Nevada", "NV - Nevada"), ("NH - New Hampshire", "NH - New Hampshire"),("MA - Massachusetts", "MA - Massachusetts"), ("MI - Michigan", "MI - Michigan"), ("MN - Minnesota", "MN - Minnesota"), ("MS - Mississippi", "MS - Mississippi"),("NJ - New Jersey", "NJ - New Jersey"), ("NM - New Mexico", "NM - New Mexico"), ("NY - New York", "NY - New York"), ("NC - North Carolina", "NC - North Carolina"),
                 ("ND - North Dakota", "ND - North Dakota"), ("OH - Ohio", "OH - Ohio"), ("OK - Oklahoma","OK - Oklahoma"), ("OR - Oregon", "OR - Oregon"), ("PA - Pennsylvania", "PA - Pennsylvania"),("RI - Rhode Island", "RI - Rhode Island"), ("SC - South Carolina","SC - South Carolina"), ("SD - South Dakota", "SD - South Dakota"), ("TN-Tennessee", "TN-Tennessee"),
                 ("TX - Texas", "TX - Texas"), ("UT - Utah", "UT - Utah"), ("VT - Vermont", "VT - Vermont"), ("VA - Virgina", "VA - Virgina"), ("WA - Washington", "WA - Washington"), ("WV - West Virginia", "WV - West Virginia"),
                 ("WI - Wisconsin", "WI - Wisconsin"), ("WY - Wyoming", "WY - Wyoming")]

class PostResumeForm(FlaskForm):
    first_name = StringField('First Name', validators=[DataRequired(message="Please enter first name.")])
    last_name = StringField('Last Name', validators=[DataRequired()])
    contact_number = StringField(
        'Contact Number', validators=[DataRequired(), Length(min=10,max=10)])
    alternate_contact_number = StringField(
        'Alternate Contact Number(if any)', validators=[Length(min=10, max=10)])
    email = StringField('Contact Email', validators=[DataRequired(), Email()])
    alternate_email = StringField('Alternate Contact Email(if any)', validators=[ Email()])
    city = StringField('City', validators=[DataRequired()])
    state = SelectField(
        'State', validators=[DataRequired()], choices=STATE_CHOICES)
    visa_status = SelectField('Visa Status', validators=[DataRequired()],
                              choices=[('--Choose--', '--Choose--'), ('ACTIVE', 'ACTIVE'),
                                 ('EXPIRED', 'EXPIRED'),
                                 ('INVALID', 'INVALID')])
    current_status = SelectField('Current Status (*): (Working or not ) :', validators=[DataRequired()],
                                 choices=[('--Choose--', '--Choose--'),('WORKING', 'WORKING'),
                                          ('NOT WORKING', 'NOT WORKING'),
                                       ('NOTICE PERIOD', 'NOTICE PERIOD')])
    job_title = StringField('Job Title', validators=[DataRequired()])
    available = SelectField('Availability to start the project (*) :', validators=[DataRequired()],
                            choices=[('--Choose--', '--Choose--'), ('YES', 'YES'),
                                          ('NO', 'NO'),
                                          ])
    cover_letter = FileField(validators=[FileRequired()])
    resume = FileField(validators=[FileRequired()])
    summary = TextAreaField('Summary')
    submit = SubmitField('Post Resume')

    def validate_contact_number(form, field):
        # print(f"Debug1 : Outside validate_contact_number")
        # print(f"Debug11 : {field.data}")
        if len(field.data) > 10:
            # print(f"Debug2 : Inside validate_contact_number")
            raise ValidationError('Phone number should be 10 digit long.')

    def validate_alternate_contact_number(form, field):
        # print(f"Debug1 : Outside validate_contact_number")
        # print(f"Debug11 : {field.data}")
        if len(field.data) > 10:
            # print(f"Debug2 : Inside validate_contact_number")
            raise ValidationError('Phone number should be 10 digit long.')

    def validate_state(form, field):
        # print(f"Debug3 : Outside validate_state")
        if field.data == '--Choose--':
            # print(f"Debug4 : Inside validate_state")
            raise ValidationError('Please choose atleast one.')
        # print(f"Debug12 : {field.data}")

    def validate_visa_status(form, field):
        # print(f"Debug5 : Outside validate_state")
        if field.data == '--Choose--':
            # print(f"Debug6 : Inside validate_state")
            raise ValidationError('Please choose atleast one.')
        # print(f"Debug13 : {field.data}")

    def validate_current_status(form, field):
        # print(f"Debug7 : Outside validate_current_status")
        if field.data == '--Choose--':
            # print(f"Debug8 : Inside validate_current_status")
            raise ValidationError('Please choose atleast one.')
        # print(f"Debug14 : {field.data}")

    def validate_available(form, field):
        # print(f"Debug9 : Outside validate_available")
        if field.data == '--Choose--':
            # print(f"Debug9 : Inside validate_available")
            raise ValidationError('Please choose atleast one.')
        # print(f"Debug15 : {field.data}")

    def allowed_image(self, filename):
        if not "." in filename:
            return False
        ext = filename.rsplit(".", 1)[1]
        if ext.upper() in current_app.config["ALLOWED_IMAGE_EXTENSIONS"]:
            return True
        else:
            return False

    def allowed_file(self, filename):
        if not "." in filename:
            return False
        ext = filename.rsplit(".", 1)[1]
        if ext.upper() in current_app.config["ALLOWED_FILE_EXTENSIONS"]:
            return True
        else:
            return False

    def upload_image(self, image):
        if self.allowed_image(image.filename):
            filename = secure_filename(image.filename)
            image.save(os.path.join(
                current_app.config["IMAGE_UPLOADS"], filename))
            print("Image saved")
        else:
            print("Image was not saved.")

    def upload_file(self, ifile):
        # Make instance directory
        if not os.path.exists(current_app.config["FILE_UPLOADS"]):
            os.makedirs(current_app.config["FILE_UPLOADS"])
        else:
            print(f"{current_app.config['FILE_UPLOADS']} already exists.")
        if self.allowed_file(ifile.filename):
            filename = secure_filename(ifile.filename)
            ifile.save(os.path.join(
                current_app.config["FILE_UPLOADS"], filename))
            print("File saved")
        else:
            print("File was not saved.")

    def post_mail(self, cover_letter, resume, form):
        base_dir = current_app.config["FILE_UPLOADS"]
        attachment_list = []
        attachment_list.append({'name': 'cover_letter', 'location': os.path.join(
            base_dir, secure_filename(cover_letter.filename))})
        attachment_list.append({'name': 'resume', 'location': os.path.join(
            base_dir, secure_filename(resume.filename))})
        print(f"In Post Mail..")
        for attachment in attachment_list:
            print(f"post mail >>>> {attachment}")
        # Send email
        send_email_attachment("We recieved Resume.", sender=current_app.config['MAIL_DEFAULT_SENDER'], recipients_list=['nandhu.misc@gmail.com'], text_body=render_template(
            'email/recieved_resume.txt', first_name="Nandha", recruiter_name='Dhamu', form=form), html_body=render_template('email/recieved_resume.html', first_name="Nandha", recruiter_name='Dhamu', form=form), attachment_list=attachment_list)

class ContactUsForm(FlaskForm):
    first_name = StringField('First Name (*)', validators=[
                             DataRequired(message="Please enter first name.")])
    contact_number = StringField(
        'Contact Number (*)', validators=[DataRequired(), Length(min=10, max=10)])
    email = StringField('Contact Email (*)',
                        validators=[DataRequired(), Email()])
    state = SelectField(
        'State (*)', validators=[DataRequired()], choices=STATE_CHOICES)
    city = StringField('City (*)', validators=[DataRequired()])
    comments = TextAreaField('Comments (If any):')
    submit = SubmitField('SEND')

    def validate_contact_number(form, field):
        if len(field.data) > 10:
            raise ValidationError('Phone number should be 10 digit long.')

    def validate_state(form, field):
        if field.data == '--Choose--':
            raise ValidationError('Please choose atleast one.')

    def post_greeting_mail(self, form):
        try:
            # Send Notification to NTech
            send_email("We got a customer Query!!", sender=current_app.config['MAIL_DEFAULT_SENDER'], recipients_list=[
                       'free2dhamu@gmail.com', 'nandhu.misc@gmail.com'], text_body=render_template('email/recieved_contact.txt', form=form), html_body=render_template('email/recieved_contact.html', form=form))

            # Send Greetings to Candidate
            send_email("Greetings from Ntech Global.", sender=current_app.config['MAIL_DEFAULT_SENDER'], recipients_list=[form.email.data], text_body=render_template(
                'email/greet_candidate.txt', form=form), html_body=render_template('email/greet_candidate.html', form=form))

        except:
            print(f"Exception occured, May be check the contact mail={form.email.data}")


'''
Implementation of pathwell attack from TrustedSec hate_crack:
https://github.com/trustedsec/hate_crack
'''

import re
import os
from modules import base

class Attack(base.Attack):
    def init(self):
        '''
        subclass specific initializations - use instead of `__init__`
        for example, use to override self.results_regex
        '''

    def build_commands(self):
        '''
        [hashfile] will be replaced with the actual temp hashfile location
        [potfile] will be replaced with the actual temp potfile location
        for hashcat, make sure to run again with --show parameter to show all cracked hashes, including those that were in potfile
        '''

        commands=[]

        commands.append("{hcat_base_cmd} -a 3 {cwd}/masks/pathwell.hcmask".format(
                            hcat_base_cmd=self.hcat_base_cmd,
                            cwd=os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir),
                            )
                        )

        commands.append(self.hcat_base_cmd + " --show")

        self.commands = commands


import mido
import torch
import NeuralNetUtils as nnu
import MusicTheoryUtils as mtu
import random

ticksPerBeat=480

class WeightedNumberPicker:
	def __init__(self,lowerBounds,upperBounds,probabilities):
		self.lowerBounds=lowerBounds
		self.upperBounds=upperBounds
		self.probabilities=probabilities

	def getValue(self):
		currentPercent=0
		choice=random.randint(1,100)
		for i,prob in enumerate(self.probabilities):
			currentPercent+=prob*100
			if choice <= currentPercent:
				return random.randint(self.lowerBounds[i],self.upperBounds[i])

def percentPicker(numOfNotes):
	if numOfNotes == 1 or numOfNotes == 2:
		return 1
	elif numOfNotes == 3:
		return 2/3
	elif numOfNotes == 4 or numOfNotes == 5:
		return (numOfNotes-2+random.randint(0,1))/numOfNotes
	elif numOfNotes == 6:
		return 4/6
	else:
		return 0.70

class InstrumentSection:
	def __init__(self,sectionName):
		self.sectionName=sectionName
		self.numOfBars=0
		self.numOfRepetitions=1
		self.creationLog=[]
		self.bars=[]
		self.beatsInBars=[]
		self.subDivisionsPerBeats=[]
		self.sectionEndTimeDelta=0
		self.formattedBars=[]
		self.msgs=[]
		self.chosenRhythm=[]
		self.chosenMelody=[]
		self.chosenVelocities=[]
		self.chosenDurations=[]

	def formatBars(self,noteOverlapFlag,chromaticFrequencyFactor,chromaticSizeRange,slideFrequencyFactor,slideSizeRange,nextNote):
	#making nextNote negative will mean it is ignored, useful for the end of a piece
		flattenBars=[]
		barBeats=0
		for i,bar in enumerate(self.bars):
			for j, nE in enumerate(bar):
				flattenBars.append([barBeats+bar[j][0],bar[j][1],bar[j][2],bar[j][3]])
			barBeats+=self.beatsInBars[i]
		if nextNote >= 0:
			flattenBars.append([barBeats,nextNote,0,0])

		if not noteOverlapFlag:
			for i,nE in enumerate(flattenBars[:-1]):
				if flattenBars[i][0]+flattenBars[i][3] >= flattenBars[i+1][0]:
					flattenBars[i][3]=flattenBars[i+1][0]-flattenBars[i][0]

		sliding=False
		for i,nE in enumerate(flattenBars[:-1]):
			if sliding:
				sliding=False
			else:
				noteDifference=abs(flattenBars[i+1][1]-flattenBars[i][1])
				travelDirection=1
				if flattenBars[i][1] > flattenBars[i+1][1]:
					travelDirection=-1
				if not noteDifference == 0:
					timeInterval=(flattenBars[i+1][0]-flattenBars[i][0])/noteDifference
				if noteDifference in chromaticSizeRange and chromaticFrequencyFactor.getValue() == 1:
					for j in range(0,noteDifference):
						self.formattedBars.append([0,flattenBars[i][0]+j*timeInterval,flattenBars[i][1]+travelDirection*j,flattenBars[i][2],flattenBars[i][3]/noteDifference])
				elif noteDifference in slideSizeRange and slideFrequencyFactor.getValue() == 1:
					self.formattedBars.append([1,flattenBars[i][0],flattenBars[i][1],flattenBars[i+1][2],travelDirection,noteDifference,timeInterval,flattenBars[i+1][3]])
					sliding=True
				else:
					self.formattedBars.append([0]+flattenBars[i])

		#[NoteOrSlideFlag(=0),BeatsSinceSectionStart,Note,Velocity,Duration]
		#[NoteOrSlideFlag(=1),BeatsSinceSectionStart,StartNote,Velocity,TravelDirection,SlideSize,TimePerSemi,FinishDuration]

	def convertToMidi(self,startTime,channelNum,instrumentSound,ticksPerInstrumentBeat):
		toConvert=[]
		time=startTime
		finalBarStart=0
		roundedTime=0
		for i,note in enumerate(self.formattedBars):
			if note[0] == 0:
				toConvert.append([1,int(ticksPerInstrumentBeat*note[1]),note[2],note[3]])
				toConvert.append([0,int(ticksPerInstrumentBeat*(note[1]+note[4])),note[2],0])
			else:
				toConvert.append([2,int(ticksPerInstrumentBeat*note[1])]+note[2:6]+[int(ticksPerInstrumentBeat*note[6]),int(ticksPerInstrumentBeat*note[7])])
		toConvert.sort(key=lambda x: x[1])

		prevTime=-startTime
		self.msgs=[mido.Message('program_change', program=instrumentSound, channel=channelNum, time=0)]
		for i,event in enumerate(toConvert):
			types=["note_off","note_on"]
			deltaTime=max(0,event[1]-prevTime)
			if event[0] == 2:
				self.msgs.append(mido.Message("note_on",time=deltaTime,channel=channelNum,note=event[2],velocity=event[3]))
				self.msgs.append(mido.Message("control_change",time=0,channel=channelNum,control=101,value=0))
				self.msgs.append(mido.Message("control_change",time=0,channel=channelNum,control=100,value=0))
				self.msgs.append(mido.Message("control_change",time=0,channel=channelNum,control=6,value=event[5]))
				for j in range(1,event[5]+1):
					self.msgs.append(mido.Message("pitchwheel",time=int(event[6]/2),channel=channelNum,pitch=round(event[4]*(j-0.5)*(8191.5/event[5])-0.5)))
					self.msgs.append(mido.Message("pitchwheel",time=int(event[6]/2),channel=channelNum,pitch=round(event[4]*j*(8191.5/event[5])-0.5)))
				self.msgs.append(mido.Message("note_off",time=event[7],channel=channelNum,note=event[2],velocity=0))
				self.msgs.append(mido.Message("pitchwheel",time=0,channel=channelNum,pitch=0))
				prevTime=event[1]+event[5]*event[6]+event[7]
			else:
				self.msgs.append(mido.Message(types[event[0]],time=deltaTime,channel=channelNum,note=event[2],velocity=event[3]))
				prevTime=event[1]
		self.sectionEndTimeDelta=sum(self.beatsInBars)*ticksPerInstrumentBeat-prevTime

class MelodyInstrumentSection(InstrumentSection):

	def __init__(self,sectionName,minNote,maxNote,melodyNet):
		InstrumentSection.__init__(self,sectionName)
		self.melodyNet=melodyNet
		self.minNote=minNote
		self.maxNote=maxNote

	def addProgressionBars(self,chords,scales,beatsInBar,subDivsPerBeat,
	div1Of4Factor,div3Of4Factor,div2Or4Of4Factor,
	div1Of3Factor,div2Of3Factor,div3Of3Factor,
	octaveRangeFactor,directionChangeFactor,
	durationRange,velocityRange):
		numOfBars=len(chords)
		self.beatsInBars.extend([beatsInBar]*numOfBars)
		noteCount=0
		notesPerBar=[]
		chosenRhythm=[]
		chosenMelody=[]
		chosenDurations=[]
		chosenVelocities=[]

		def addNoteToRhythmChance(noteCount,currentTime,factor,subDivs):
			if factor.getValue() == 1:
				chosenRhythm.append(currentTime)
				noteCount+=1
			currentTime+=1/subDivs
			return noteCount, currentTime

		for i in range(numOfBars):
			currentTime=0
			prevBarNoteCount=noteCount
			for j in range(beatsInBar):
				subDivisionRemainingCount=subDivsPerBeat
				if subDivisionRemainingCount == 1:
					noteCount, currentTime =addNoteToRhythmChance(noteCount,currentTime,div1Of4Factor,subDivsPerBeat)
				else:
					smallestChunkSize=2
					if subDivsPerBeat == 3 or subDivsPerBeat == 4:
						smallestChunkSize=subDivsPerBeat
					while subDivisionRemainingCount > 0:
						divChunkSize=random.randint(smallestChunkSize,min(4,subDivisionRemainingCount))
						if subDivisionRemainingCount == divChunkSize+1:
							if subDivisionRemainingCount == 5:
								divChunkSize=random.randint(2,3)
							else:
								divChunkSize=subDivisionRemainingCount
						subDivisionRemainingCount-=divChunkSize
						if divChunkSize == 4:
							noteCount, currentTime = addNoteToRhythmChance(noteCount,currentTime,div1Of4Factor,subDivsPerBeat)
							noteCount, currentTime = addNoteToRhythmChance(noteCount,currentTime,div2Or4Of4Factor,subDivsPerBeat)
							noteCount, currentTime = addNoteToRhythmChance(noteCount,currentTime,div3Of4Factor,subDivsPerBeat)
							noteCount, currentTime = addNoteToRhythmChance(noteCount,currentTime,div2Or4Of4Factor,subDivsPerBeat)
						elif divChunkSize == 3:
							noteCount, currentTime = addNoteToRhythmChance(noteCount,currentTime,div1Of3Factor,subDivsPerBeat)
							noteCount, currentTime = addNoteToRhythmChance(noteCount,currentTime,div2Of3Factor,subDivsPerBeat)
							noteCount, currentTime = addNoteToRhythmChance(noteCount,currentTime,div3Of3Factor,subDivsPerBeat)
						else:
							noteCount, currentTime = addNoteToRhythmChance(noteCount,currentTime,div1Of4Factor,subDivsPerBeat)
							noteCount, currentTime = addNoteToRhythmChance(noteCount,currentTime,div3Of4Factor,subDivsPerBeat)
			notesPerBar.append(noteCount-prevBarNoteCount)
		if noteCount > 0:
			scaleNotes=[]
			for i in range(numOfBars):
				scaleNotes.append([(interval+chords[i].rootNote) % 12 for interval in scales[i]])
			blendNoteDepth=0
			potentialIntervals=[]
			for i in range(numOfBars):
				# print("writing bar {}".format(i))
				attemptsPerBlendDepth=25
				suitableNoteChoice=False
				while not suitableNoteChoice:
					# print("notes in current bar {}".format(notesPerBar[i]))
					while len(potentialIntervals) < notesPerBar[i]:
						blendNoteDepth=min(self.melodyNet.numNotesOut,len(potentialIntervals))
						attempts=0
						blendSearching=True
						while blendSearching:
							if blendNoteDepth > 0 and attempts == attemptsPerBlendDepth:
								attempts=0
								blendNoteDepth-=1
							attempts+=1
							genOut=self.melodyNet(torch.randn(1,self.melodyNet.noiseDim))
							generatedNotes=[]
							for oneHotNote in genOut:
								generatedNotes.append(oneHotNote[0].tolist().index(1))
							# print("generatedNotes: {}".format(generatedNotes))
							# print("generatedNotes[:blendNoteDepth] {}".format(generatedNotes[:blendNoteDepth]))
							# print("potentialIntervals {}".format(potentialIntervals))
							# print("potentialIntervals[-blendNoteDepth:] {}".format(potentialIntervals[-blendNoteDepth:]))
							# print("blend note depth {}".format(blendNoteDepth))
							# input()
							blendSearching=not (blendNoteDepth == 0 or generatedNotes[:blendNoteDepth] == potentialIntervals[-blendNoteDepth:])
						potentialIntervals.extend(generatedNotes[blendNoteDepth:])
						# print("potentialIntervals {}".format(potentialIntervals))
					suitableNotes=0
					potentialNotes=[]
					currentNote=chords[0].rootNote
					if chosenMelody:
						currentNote=chosenMelody[-1]
					direction=random.randint(0,1)
					# print(potentialIntervals[:notesPerBar[i]])
					for interval in potentialIntervals[:notesPerBar[i]]:
						if (currentNote+interval) % 12 in scaleNotes[i]:
							suitableNotes+=1
						currentNote+=interval+6*direction*(2*octaveRangeFactor.getValue()+1)-6
						while currentNote < self.minNote:
							currentNote+=12
						while currentNote > self.maxNote:
							currentNote-=12
						# print(currentNote)
						potentialNotes.append(currentNote)
						if directionChangeFactor.getValue() == 1:
							direction=direction-2*direction
					# input()
					# print("suitable notes {}".format(suitableNotes))
					if suitableNotes == 0:
						suitableNoteChoice=(notesPerBar[i] == 0)
					else:
						suitableNoteChoice=(suitableNotes/notesPerBar[i] >= percentPicker(notesPerBar[i]))
					# print("suitableNoteChoice {}".format(suitableNoteChoice))
					if not suitableNoteChoice:
						potentialIntervals=[]
						# print("potentialIntervals {}".format(potentialIntervals))
						# input()
					# if suitableNoteChoice:
						# print("yay")
						# input()
				chosenMelody.extend(potentialNotes[:])
				# print("chosenMelody {}".format(chosenMelody))
				potentialIntervals=potentialIntervals[notesPerBar[i]:]
				# print("remaining potentialIntervals {}".format(potentialIntervals))
				# input()

			for i in range(noteCount):
				chosenVelocities.append(random.randint(*velocityRange))
				chosenDurations.append(random.randint(*durationRange)/subDivsPerBeat)

		prevNoteCount=0
		for nPB in notesPerBar:
			bar=[]
			for i in range(prevNoteCount,prevNoteCount+nPB):
				bar.append([chosenRhythm[i],chosenMelody[i],chosenVelocities[i],chosenDurations[i]])
			prevNoteCount+=nPB
			self.bars.append(bar)

class PercussionInstrumentSection(InstrumentSection):

	def __init__(self,sectionName,melodyNet):
		InstrumentSection.__init__(self,sectionName)
		self.melodyNet=melodyNet
		self.sectionSkeleton=[]

	def getModifiedSkeleton(self,skeleton,removeChance,addChance,addPercussionGroups,melodyChoiceFactor,velocity):
		newSkeleton=skeleton
		numDivs=skeleton[0]*skeleton[1]
		for i in range(numDivs):
			newSkeleton[2][i]=[elem for elem in skeleton[2][i] if random.randint(1,100) > removeChance]
		netInp=[]
		emptyCount=0
		while len(netInp) < self.melodyNet.layerSizes[0] and emptyCount < numDivs:
			emptyCount=0
			for subDiv in newSkeleton[2]:
				if subDiv:
					drumHits=[0]*self.melodyNet.layerSizes[-1]
					for beat in subDiv:
						drumHits[mtu.lookUpDrumType(beat[0])[0]]=1
					netInp.extend(drumHits)
				else:
					emptyCount+=1
		if emptyCount < numDivs:
			netInp=netInp[-self.melodyNet.layerSizes[0]:]
			for i in range(numDivs):
				if random.randint(1,100) <= addChance:
					self.melodyNet.forwardPropagation(netInp,[0]*self.melodyNet.layerSizes[-1])
					possibleGroups=[group for group in nnu.getIndexesOfSortedList(self.melodyNet.outputs[-1])[:melodyChoiceFactor.getValue()] if group in addPercussionGroups]
					addGroup=random.choice(addPercussionGroups)
					if possibleGroups:
						addGroup=random.choice(possibleGroups)
					hitNote=random.choice(mtu.lookUpDrumCategory(addGroup))[1]
					newSkeleton[2][i].append([hitNote,velocity])
				drumHits=[0]*self.melodyNet.layerSizes[-1]
				for beat in newSkeleton[2][i]:
					drumHits[mtu.lookUpDrumType(beat[0])[0]]=1
				netInp=netInp[self.melodyNet.layerSizes[-1]:]
				netInp.extend(drumHits)
		return newSkeleton

	def setSectionSkeleton(self,skeleton,removeChance,addChance,addPercussionGroups,melodyChoiceFactor,velocity):
		self.sectionSkeleton=self.getModifiedSkeleton(skeleton,removeChance,addChance,addPercussionGroups,melodyChoiceFactor,velocity)

	def addBar(self,removeChance,addChance,addPercussionGroups,melodyChoiceFactor,velocity,fillSkeleton=[]):
		self.numOfBars+=1
		newBeats=self.getModifiedSkeleton(self.sectionSkeleton,removeChance,addChance,addPercussionGroups,melodyChoiceFactor,velocity)
		if fillSkeleton:
			newBeats=self.getModifiedSkeleton(fillSkeleton,removeChance,addChance,addPercussionGroups,melodyChoiceFactor,velocity)
		beatsInBar=newBeats[0]
		subDivsPerBeat=newBeats[1]
		self.beatsInBars.append(beatsInBar)
		self.subDivisionsPerBeats.append(subDivsPerBeat)
		subDivTimeDelta=1/subDivsPerBeat
		bar=[]
		for i in range(beatsInBar):
			for j in range(subDivsPerBeat):
				hitStartTime=i+j*subDivTimeDelta
				for beat in newBeats[2][i*subDivsPerBeat+j]:
					bar.append([hitStartTime,*beat,1])
		self.bars.append(bar)

class AccompanyInstrumentSection(InstrumentSection):
	def __init__(self,sectionName):
		InstrumentSection.__init__(self,sectionName)

	def addBar(self,chord,beatsInBar,subDivisionsPerBeat,velocity):
		self.numOfBars+=1
		self.beatsInBars.append(beatsInBar)
		self.subDivisionsPerBeats.append(subDivisionsPerBeat)
		bar=[]
		for note in chord.chordIntervals:
			bar.append([0,note+chord.rootNote,velocity,beatsInBar])
		self.bars.append(bar)

def combineMidi(midiTracks,saveName):
	mid = mido.MidiFile()
	for midiTrack in midiTracks:
		track = mido.MidiTrack()
		mid.tracks.append(track)
		for msg in midiTrack:
			track.append(msg)
	mid.save(saveName)

cuda=torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

melodyModel_5304 = nnu.NoteGenerator(5,144,4,8,0.1,cuda)
melodyModel_5304.load_state_dict(torch.load("trained networks/5304.pt",map_location='cpu'))
melodyModel_5304.eval()

melodyModel_5305 = nnu.NoteGenerator(5,144,4,7,0.1,cuda)
melodyModel_5305.load_state_dict(torch.load("trained networks/5305.pt",map_location='cpu'))
melodyModel_5305.eval()

melodyModel_5306 = nnu.NoteGenerator(5,144,4,9,0.1,cuda)
melodyModel_5306.load_state_dict(torch.load("trained networks/5306.pt",map_location='cpu'))
melodyModel_5306.eval()

melodyModel_6276=nnu.NoteGenerator(5,144,1,8,0.1,cuda)
checkpoint = torch.load("trained networks/6276.pt",map_location='cpu')
melodyModel_6276.load_state_dict(checkpoint['model_state_dict'])
melodyModel_6276.eval()

drumsNet=nnu.VanillaNeuralNet([44,44,44,22,11,11])
drumsNet.readFromcsv('trained networks/d3.csv')


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('admin', '0007_account_name'),
    ]

    operations = [
        migrations.AlterUniqueTogether(
            name='account',
            unique_together=set([('base_id', 'type')]),
        ),
    ]


import unittest

from marshmallow import fields

from forex_miner_thor.model.trade import TradeSignalSchema

class TestTradeSignalSchema(unittest.TestCase):
    def test_init(self):
        # Arrange
        # Act
        trade_signal_schema = TradeSignalSchema()

        # Assert
        self.assertEqual(type(trade_signal_schema.fields["instrument"]), fields.String)
        self.assertEqual(type(trade_signal_schema.fields["direction"]), fields.String)
        self.assertEqual(type(trade_signal_schema.fields["confidence"]), fields.Float)

    def test_make(self):
        # Arrange
        instrument = 'EUR_USD'
        direction = 'long'
        confidence = 1.0

        # Act
        trade_signal_schema = TradeSignalSchema()
        trade_signal_make = trade_signal_schema.make_trade_signal(
            {
                'instrument': instrument,
                'direction': direction,
                'confidence': confidence,
            }
        )

        # Assert
        self.assertEqual(trade_signal_make.instrument, instrument)
        self.assertEqual(trade_signal_make.direction, direction)
        self.assertEqual(trade_signal_make.confidence, confidence)

if __name__ == '__main__':
    unittest.main()


import sqlite3
import time
import os
import json
import requests

from apscheduler.schedulers.background import BackgroundScheduler

def add_table(db_name, table_name):
    db = sqlite3.connect(db_name)
    curs = db.cursor()
    curs.execute("DROP TABLE IF EXISTS [" + table_name + "];")
    curs.execute("CREATE TABLE [" + table_name +
                 """] (tdatetime DATETIME, rank INT, price_usd REAL, price_btc REAL,
                 \"24h_volume_usd\" REAL, market_cap_usd REAL, available_supply REAL,
                 total_supply REAL, percent_change_1h REAL, percent_change_24h REAL, percent_change_7d REAL);""")
    db.commit()
    db.close()
    print("Added " + table_name + " to " + db_name)

def get_tables_from(db):
    db = sqlite3.connect(db)
    curs = db.cursor()
    res = curs.execute("""SELECT name FROM sqlite_master WHERE TYPE=\'table\'""")
    res = curs.fetchall()
    db.close()

    tables = []
    for i in range(len(res)):
        temp = str(res[i])
        temp=temp[2:len(temp)-3]
        tables.append(temp)
    return tables

def add_data_to(database, table, rank, price_usd,
                  price_btc, volume_usd_24h, market_cap_usd, available_supply,
                  total_supply, percent_change_1h, percent_change_24h, percent_change_7d
                  ):

    db = sqlite3.connect(database)
    curs = db.cursor()
    tdatetime = time.strftime("%Y-%m-%d %H:%M:%S")
    curs.execute("INSERT INTO [" + table + "] VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                 (tdatetime, rank, price_usd, price_btc, volume_usd_24h, market_cap_usd,
                  available_supply, total_supply, percent_change_1h, percent_change_24h, percent_change_7d))
    db.commit()
    db.close()
    print ("Data added to " + database + ', ' + table)

def query_coinmarketcap(db):

    coins = get_tables_from(db)
    ticker = requests.get('https://api.coinmarketcap.com/v1/ticker/?limit=20')
    json_ticker = ticker.json()
    print(time.strftime("%Y-%m-%d %H:%M:%S"))
    for i in json_ticker:
        if i['id'] not in coins:
            add_table(db, i['id'])
        add_data_to(db, i['id'], i['rank'], i['price_usd'], i['price_btc'], i['24h_volume_usd'], i['market_cap_usd'], i['available_supply'],
                    i['total_supply'], i['percent_change_1h'], i['percent_change_24h'], i['percent_change_7d'])
    print('\n')

if __name__ == '__main__':

    scheduler = BackgroundScheduler()
    scheduler.add_job(query_coinmarketcap, 'cron',args=['coins.db'], minute ='*/5')
    scheduler.start()
    print ('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))


import os
import unittest
from unittest import mock
import tempfile

import repo_manager
import utils

OSS_FUZZ_REPO = 'https://github.com/google/oss-fuzz'

class TestRepoManager(unittest.TestCase):
  """Class to test the functionality of the RepoManager class."""

class RepoManagerCloneUnitTest(unittest.TestCase):
  """Class to test the functionality of clone of the RepoManager class."""

  def test_clone_valid_repo(self):
    """Tests the correct location of the git repo."""
    with tempfile.TemporaryDirectory() as tmp_dir:
      test_repo_manager = repo_manager.RepoManager(OSS_FUZZ_REPO, tmp_dir)
      git_path = os.path.join(test_repo_manager.base_dir,
                              test_repo_manager.repo_name, '.git')
      self.assertTrue(os.path.isdir(git_path))
      test_repo_manager.remove_repo()

  def test_clone_invalid_repo(self):
    """Test that constructing RepoManager with an invalid repo will fail."""
    with tempfile.TemporaryDirectory() as tmp_dir:
      with self.assertRaises(ValueError):
        repo_manager.RepoManager(' ', tmp_dir)
      with self.assertRaises(ValueError):
        repo_manager.RepoManager('not_a_valid_repo', tmp_dir)
      with self.assertRaises(ValueError):
        repo_manager.RepoManager('https://github.com/oss-fuzz-not-real.git',
                                 tmp_dir)

class RepoManagerCheckoutUnitTest(unittest.TestCase):
  """Class to test the functionality of checkout of the RepoManager class."""

  def test_checkout_valid_commit(self):
    """Tests that the git checkout command works."""
    with tempfile.TemporaryDirectory() as tmp_dir:
      test_repo_manager = repo_manager.RepoManager(OSS_FUZZ_REPO, tmp_dir)
      commit_to_test = '04ea24ee15bbe46a19e5da6c5f022a2ffdfbdb3b'
      test_repo_manager.checkout_commit(commit_to_test)
      self.assertEqual(commit_to_test, test_repo_manager.get_current_commit())

  def test_checkout_invalid_commit(self):
    """Tests that the git checkout invalid commit fails."""
    with tempfile.TemporaryDirectory() as tmp_dir:
      test_repo_manager = repo_manager.RepoManager(OSS_FUZZ_REPO, tmp_dir)
      with self.assertRaises(ValueError):
        test_repo_manager.checkout_commit(' ')
      with self.assertRaises(ValueError):
        test_repo_manager.checkout_commit(
            'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
      with self.assertRaises(ValueError):
        test_repo_manager.checkout_commit('not-a-valid-commit')

class RepoManagerGetCommitListUnitTest(unittest.TestCase):
  """Class to test the functionality of get commit list in the
   RepoManager class."""

  def test_get_valid_commit_list(self):
    """Tests an accurate commit list can be retrieved from the repo manager."""
    with tempfile.TemporaryDirectory() as tmp_dir:
      test_repo_manager = repo_manager.RepoManager(OSS_FUZZ_REPO, tmp_dir)
      old_commit = '04ea24ee15bbe46a19e5da6c5f022a2ffdfbdb3b'
      new_commit = 'fa662173bfeb3ba08d2e84cefc363be11e6c8463'
      commit_list = [
          'fa662173bfeb3ba08d2e84cefc363be11e6c8463',
          '17035317a44fa89d22fe6846d868d4bf57def78b',
          '97dee00a3c4ce95071c3e061592f5fd577dea886',
          '04ea24ee15bbe46a19e5da6c5f022a2ffdfbdb3b'
      ]
      result_list = test_repo_manager.get_commit_list(new_commit, old_commit)
      self.assertListEqual(commit_list, result_list)

  def test_invalid_commit_list(self):
    """Tests that the propper Errors are thrown when invalid commits are
    passed."""
    with tempfile.TemporaryDirectory() as tmp_dir:
      old_commit = '04ea24ee15bbe46a19e5da6c5f022a2ffdfbdb3b'
      new_commit = 'fa662173bfeb3ba08d2e84cefc363be11e6c8463'
      test_repo_manager = repo_manager.RepoManager(OSS_FUZZ_REPO, tmp_dir)
      with self.assertRaises(ValueError):
        test_repo_manager.get_commit_list('fakecommit', new_commit)
      with self.assertRaises(ValueError):
        test_repo_manager.get_commit_list(new_commit, 'fakecommit')
      with self.assertRaises(RuntimeError):
        # pylint: disable=arguments-out-of-order
        test_repo_manager.get_commit_list(old_commit, new_commit)

class GitDiffUnitTest(unittest.TestCase):
  """Class testing functionality of get_git_diff in the repo_manager module."""

  def test_diff_exists(self):
    """Tests that a real diff is returned when a valid repo manager exists."""
    with tempfile.TemporaryDirectory() as tmp_dir:
      repo_man = repo_manager.RepoManager(OSS_FUZZ_REPO, tmp_dir)
      with mock.patch.object(utils,
                             'execute',
                             return_value=('test.py\ndiff.py', None, 0)):
        diff = repo_man.get_git_diff()
        self.assertCountEqual(diff, ['test.py', 'diff.py'])

  def test_diff_empty(self):
    """Tests that None is returned when there is no difference between repos."""
    with tempfile.TemporaryDirectory() as tmp_dir:
      repo_man = repo_manager.RepoManager(OSS_FUZZ_REPO, tmp_dir)
      with mock.patch.object(utils, 'execute', return_value=('', None, 0)):
        diff = repo_man.get_git_diff()
        self.assertIsNone(diff)

  def test_error_on_command(self):
    """Tests that None is returned when the command errors out."""
    with tempfile.TemporaryDirectory() as tmp_dir:
      repo_man = repo_manager.RepoManager(OSS_FUZZ_REPO, tmp_dir)
      with mock.patch.object(utils,
                             'execute',
                             return_value=('', 'Test error.', 1)):
        diff = repo_man.get_git_diff()
        self.assertIsNone(diff)

  def test_diff_no_change(self):
    """Tests that None is returned when there is no difference between repos."""
    with tempfile.TemporaryDirectory() as tmp_dir:
      repo_man = repo_manager.RepoManager(OSS_FUZZ_REPO, tmp_dir)
      diff = repo_man.get_git_diff()
      self.assertIsNone(diff)

class CheckoutPRIntegrationTest(unittest.TestCase):
  """Class testing functionality of checkout_pr in the repo_manager module."""

  def test_pull_request_exists(self):
    """Tests that a diff is returned when a valid PR is checked out."""
    with tempfile.TemporaryDirectory() as tmp_dir:
      repo_man = repo_manager.RepoManager(OSS_FUZZ_REPO, tmp_dir)
      repo_man.checkout_pr('refs/pull/3415/merge')
      diff = repo_man.get_git_diff()
      print(diff)
      self.assertCountEqual(diff, ['README.md'])

  def test_checkout_invalid_pull_request(self):
    """Tests that the git checkout invalid pull request fails."""
    with tempfile.TemporaryDirectory() as tmp_dir:
      test_repo_manager = repo_manager.RepoManager(OSS_FUZZ_REPO, tmp_dir)
      with self.assertRaises(RuntimeError):
        test_repo_manager.checkout_pr(' ')
      with self.assertRaises(RuntimeError):
        test_repo_manager.checkout_pr(
            'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')
      with self.assertRaises(RuntimeError):
        test_repo_manager.checkout_pr('not/a/valid/pr')

if __name__ == '__main__':
  unittest.main()


#!/usr/bin/python

from PIL import ImageColor
import sys, getopt

red_f   = .2126
green_f = .7152
blue_f  = .0722

def _luminance(v):
    v /= 255
    return v / 12.92 if v <= .03928 else ((v+.055) / 1.055)**2.4

def luminance(color):
    (r,g,b) = map(_luminance, ImageColor.getcolor(color, "RGB"))
    return red_f * r + green_f * g + blue_f * b

def main() -> int:
    if len(sys.argv) < 3: return 1

    [_,color1,color2] = sys.argv

    lum1 = luminance(color1)
    lum2 = luminance(color2)
    l1 = lum1 if lum1 > lum2 else lum2
    l2 = lum2 if lum1 > lum2 else lum1
    cr = (l1+.05) / (l2+.05)

    print(color1, lum1)
    print(color2, lum2)
    print("Contrast Ratio", cr)

    return 0

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


from tkinter import ttk
from tkinter import *
import sqlite3

class product:

    db_name = 'My_database.db'

    def __init__(self, window):         #Constructor que hace que cada vez que se inicia la clase, ejecute una instancia que le de nombre a la ventana de la aplicacion
        self.wind = window
        self.wind.title('Products Aplication')

#Creación del frame para adaptar los elementos
        frame = LabelFrame(self.wind, text = 'Register a new Product')
        frame.grid(row = 0, column = 0, columnspan= 3, pady=20)

#Creación de input: Employee_Name, Employee_LastName, Basic Wage, Worked_Days and ID Document
        Label(frame, text = 'Employee Name: ').grid(row =1, column = 0)
        self.name = Entry(frame)
        self.name.focus()
        self.name.grid(row=1, column = 1)

        Label(frame, text = 'Employee Last Name: ').grid(row =2, column = 0)
        self.lname = Entry(frame)
        self.lname.grid(row=2, column = 1)

        Label(frame, text = 'Id Document: ').grid(row =3, column = 0)
        self.document = Entry(frame)
        self.document.grid(row=3, column = 1)

        Label(frame, text = 'Basic Wage: ').grid(row =4, column = 0)
        self.wage = Entry(frame)
        self.wage.grid(row=4, column = 1)

        Label(frame, text = 'Worked Days: ').grid(row =5, column = 0)
        self.workdays = Entry(frame)
        self.workdays.grid(row=5, column = 1)

        #Boton Entrada de Productos
        ttk.Button(frame, text= ' SaveProduct ', command=self.add_product).grid(row = 6, columnspan= 2, sticky =W + E)

        #Mensajes de alerta
        self.message = Label(text='', fg = 'red')
        self.message.grid(row = 3, column=0, columnspan= 2, sticky= W+E)

        #Creación de la tabla con detalles del empleado:
        self.tree = ttk.Treeview(height = 10, columns= ('#1', '#2', '#3','#4','#5'))
        self.tree['show'] = 'headings'
        self.tree.grid(row = 7, column = 0, columnspan = 6)
        self.tree.heading('#1', text = 'Name', anchor= CENTER)
        self.tree.heading('#2', text = 'LastName', anchor= CENTER)
        self.tree.heading('#3', text = 'Id Document', anchor= CENTER)
        self.tree.heading('#4', text = 'Wage', anchor= CENTER)
        self.tree.heading('#5', text = 'Worked Days', anchor= CENTER)

        # Botones de la tabla para borrar registro
        ttk.Button(text = 'DELETE', command=self.delete_employee).grid(row = 8, column=2, sticky= W + E)
        ttk.Button(text = 'EDIT').grid(row = 8, column=3, sticky= W + E)
        self.get_employees()

    def run_query(self, query, parameters = ()):
        with sqlite3.connect(self.db_name) as conn:
            cursor = conn.cursor()
            result =  cursor.execute(query, parameters)
            conn.commit()
        return result

    def get_employees (self):
        #lIMPIAR TABLE
        records = self.tree.get_children()
        for element in records:
            self.tree.delete(element)

        #query
        query = 'SELECT * FROM employees ORDER BY name DESC'
        db_rows = self.run_query(query)
        for row in db_rows:
            self.tree.insert('', 0, text = row[1], values = row[0])

    def validation(self):
        return len(self.name.get()) != 0 and len(self.lname.get()) != 0

    def add_product(self):
        if self.validation():
            query = 'INSERT INTO employees VALUES (?, ?)'
            parameters = (self.name.get(), self.lname.get())
            self.run_query(query, parameters)
            self.message['text'] = 'Empleado {} añadido satisfactoriamente'.format(self.name.get())
            self.name.delete(0, END)
            self.lname.delete(0, END)

        else:
            self.message['text'] = 'Nombre y Precio son requeridos'
        self.get_employees()

    def delete_employee(self):
        self.message['text'] = ''
        try:
            self.tree.item(self.tree.selection())['text']
        except IndexError as e:
            self.message['text'] = 'Porfavor elija un empleado para eliminar su registro'
            return
        self.message['text'] = ''
        name = self.tree.item(self.tree.selection())['text']
        quey = 'DELETE FROM employees WHERE name = ?'
        self.run_query(query, (name, ))
        self.message['text'] = 'Registro {} eliminado satisfactoriamente'.format(name)
        self.get_employees()

if __name__ == '__main__':
    window = Tk()
    application = product (window)
    window.mainloop()


import subprocess
from time import time, sleep
import psutil
import shlex

from .InputData import InputData
from .OutputData import OutputData
from .Compiler import Compiler
from .VirtualEnvironment import VirtualEnvironment
from ..Models.ReportTesting import ReportTesting
from .Grading import Rating

class StartFileProgram:
    def __init__(self, virtual: VirtualEnvironment, input_stream: InputData,
                 output_stream: OutputData, type_compilation: Compiler):
        self.__venv = virtual
        self.__input_stream = input_stream
        self.__output_stream = output_stream
        self.__process = None
        self.__compiler = type_compilation
        self.__garbage_memory = 17  # цифра взятая с неба необходимы тесты на разных платформах

    def __create_sub_proces(self):
        self.__process = psutil.Popen(shlex.split(self.__compiler.command), shell=False, stdin=subprocess.PIPE,
                                      stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.__venv.path_virtual_environment)

    def start_process(self, input_in_process: str, time_out: int) -> ReportTesting:
        input_data = self.__input_stream.start_stream(input_in_process)
        try:
            self.__create_sub_proces()
            memory = []
            start_time = time()
            outs = self.__process.communicate(input=input_data, timeout=time_out * 1000)
            end_time = time() - start_time
            answer = self.__output_stream.read_output(str(outs[0].decode()))
            outSecond = str(outs[1].decode()).replace("\n", "")
            if outSecond.isdigit():
                memory.append(round((int(outSecond) / 2**10), 3))
                errs = ""
            else:
                memory.append(0)
                errs = outSecond
            if len(errs) == 0:
                errs = 0
            elif len(errs) > 0:
                errs = 1
            report = {
                "out": answer,
                "errors": Rating.OK,
                "time": end_time * 1000,
                "memory": [max(memory)]
            }
            report = ReportTesting(**report)
            return report
        except TimeoutError:
            self.__process.kill()
            return ReportTesting(**{
                "out": [],
                "errors": Rating.TIME_LIMIT_EXCEEDED,
                "time": 0 * 1000,
                "memory": [0.0]
            })
        except Exception:
            return ReportTesting(**{
                "out": [],
                "errors": Rating.COMPILATION_ERROR,
                "time": 0 * 1000,
                "memory": [0.0]
            })


###
# Group Members
# Matthew: 1669326
# Mikayla: 1886648
# Michael-John: 1851234
###

#######################################################################
# Following are some utilities for tile coding from Rich.
# To make each file self-contained, I copied them from
# http://incompleteideas.net/tiles/tiles3.py-remove
# with some naming convention changes
#
# Tile coding starts
from math import floor
import numpy as np
from gym.spaces import Discrete
import gym
from gym import spaces
from gym.utils import seeding
from matplotlib import pyplot as plt
from gym import wrappers
class IHT:
    "Structure to handle collisions"

    def __init__(self, size_val):
        self.size = size_val
        self.overfull_count = 0
        self.dictionary = {}

    def count(self):
        return len(self.dictionary)

    def full(self):
        return len(self.dictionary) >= self.size

    def get_index(self, obj, read_only=False):
        d = self.dictionary
        if obj in d:
            return d[obj]
        elif read_only:
            return None
        size = self.size
        count = self.count()
        if count >= size:
            if self.overfull_count == 0: print('IHT full, starting to allow collisions')
            self.overfull_count += 1
            return hash(obj) % self.size
        else:
            d[obj] = count
            return count

def hash_coords(coordinates, m, read_only=False):
    if isinstance(m, IHT): return m.get_index(tuple(coordinates), read_only)
    if isinstance(m, int): return hash(tuple(coordinates)) % m
    if m is None: return coordinates

def tiles(iht_or_size, num_tilings, floats, ints=None, read_only=False):
    """returns num-tilings tile indices corresponding to the floats and ints"""
    if ints is None:
        ints = []
    qfloats = [floor(f * num_tilings) for f in floats]
    tiles = []
    for tiling in range(num_tilings):
        tilingX2 = tiling * 2
        coords = [tiling]
        b = tiling
        for q in qfloats:
            coords.append((q + b) // num_tilings)
            b += tilingX2
        coords.extend(ints)
        tiles.append(hash_coords(coords, iht_or_size, read_only))
    return tiles

# Tile coding ends
#######################################################################

# bound for position and velocity
POSITION_MIN = -1.2
POSITION_MAX = 0.5
VELOCITY_MIN = -0.07
VELOCITY_MAX = 0.07

# wrapper class for state action value function
class ValueFunction:
    # In this example I use the tiling software instead of implementing standard tiling by myself
    # One important thing is that tiling is only a map from (state, action) to a series of indices
    # It doesn't matter whether the indices have meaning, only if this map satisfy some property
    # View the following webpage for more information
    # http://incompleteideas.net/sutton/tiles/tiles3.html
    # @max_size: the maximum # of indices
    def __init__(self, alpha, n_actions, num_of_tilings=8, max_size=2048):
        self.action_space = Discrete(n_actions)
        self.max_size = max_size
        self.num_of_tilings = num_of_tilings

        # divide step size equally to each tiling
        self.step_size = alpha / num_of_tilings

        self.hash_table = IHT(max_size)

        # weight for each tile
        self.weights = np.zeros(max_size)

        # position and velocity needs scaling to satisfy the tile software
        self.position_scale = self.num_of_tilings / (POSITION_MAX - POSITION_MIN)
        self.velocity_scale = self.num_of_tilings / (VELOCITY_MAX - VELOCITY_MIN)

    # get indices of active tiles for given state and action
    def _get_active_tiles(self, position, velocity, action):
        # I think positionScale * (position - position_min) would be a good normalization.
        # However positionScale * position_min is a constant, so it's ok to ignore it.
        active_tiles = tiles(self.hash_table, self.num_of_tilings,
                             [self.position_scale * position, self.velocity_scale * velocity],
                             [action])
        return active_tiles

    # estimate the value of given state and action
    def __call__(self, state, action):
        position, velocity = tuple(state)
        if position == POSITION_MAX:
            return 0.0
        active_tiles = self._get_active_tiles(position, velocity, action)
        return np.sum(self.weights[active_tiles])

    # learn with given state, action and target
    def update(self, target, state, action):
        active_tiles = self._get_active_tiles(state[0], state[1], action)
        estimation = np.sum(self.weights[active_tiles])
        delta = self.step_size * (target - estimation)
        for active_tile in active_tiles:
            self.weights[active_tile] += delta

    def act(self, state, epsilon=0):
        if np.random.random() < epsilon:
            return self.action_space.sample()
        return np.argmax([self(state, action) for action in range(self.action_space.n)])

env= gym.make("MountainCar-v0")
alpha = 0.1
gamma = 1
goal = POSITION_MAX
iht = IHT(8)
numRuns = 1
maxEpisodes = 500
maxSteps = 200

# for a set of episodes
averageEpisode = np.zeros((maxEpisodes))
for run in range(numRuns):
    valFun = ValueFunction(alpha=alpha, n_actions=3, num_of_tilings=8)
    numSteps = []
    for episode in range(maxEpisodes):
        # get initial state and action of the episode
        state = env.reset()
        action = valFun.act(state, epsilon=0.1)
        print("Run {0}, Episode: {1}".format(run,episode))
        episodeFinished = False

        for step in range(maxSteps):
            if episode > 485:
                env.render()
            # if it is in the set of days that we would like to see - just for an example
            # of what the agent learnt, show it
            # if episode > 498:
            #     env.render()
            # take an action and observe
            obs = env.step(action)
            newState = obs[0]
            reward = obs[1]
            # if the position is now at/past the goal
            if newState[0] >= goal:
                # Update the Q-Values based on this new w - It seems to overwrite the wights based on what it learnt itself, so I am really uncertain here ***
                valFun.update(reward, state, action)
                # go to the next episode
                print("SUCCESS")
                break

            # get new action
            newAction = valFun.act(newState)

            # update w - not too certain how to deal with the grad in this case ****
            # valFun.update(goal, newState, newAction)
            # valFun.weights = valFun.weights + alpha * (reward + gamma*valFun.__call__(newState,newAction) - valFun.__call__(state,action)) * valFun.weights

            # Update the Q-Values based on this new w - It seems to overwrite the wights based on what it learnt itself, so I am really uncertain here
            # print(valFun.__call__(newState,newAction))
            valFun.update(reward + valFun.__call__(newState,newAction), state, action)
            state = newState
            action = newAction
        numSteps.append(step)
    if run == 0:
        averageEpisode = numSteps
    else:
        for val in range(len(averageEpisode)):
            averageEpisode[val] = averageEpisode[val] + numSteps[val]

for val in range(len(averageEpisode)):
    averageEpisode[val] = np.log(averageEpisode[val] / numRuns)
plt.plot(averageEpisode)
plt.title("Average Number of Steps Per Episode (max steps was 200)")
plt.ylabel("Num Steps (Logged)")
plt.xlabel("Episode")
plt.show()


import random
import string
import tensorflow as tf
import numpy as np
import seq2seq as seq2seq
import data
from corpus_utils import LanguageIndex, tokenize_sentence

# def get_ELMo_embeddings():
#     url = "https://tfhub.dev/google/elmo/2"
#     elmo = hub.Module(url)
#     return elmo

def max_length(tensor):
    return max(len(t) for t in tensor)

def load_trained_model(batch_size, embedding_dim, units, optimizer, empty_token, unknown_token):
    questions, answers = data.load_conv_text()

    inp_lang = LanguageIndex(
        questions, empty_token=empty_token, unknown_token=unknown_token)
    targ_lang = LanguageIndex(
        answers, empty_token=empty_token, unknown_token=unknown_token)

    checkpoint_dir = './training_checkpoints'
    vocab_inp_size = len(inp_lang.word2idx)
    vocab_tar_size = len(targ_lang.word2idx)
    model = seq2seq.Seq2Seq(
        vocab_inp_size, vocab_tar_size, embedding_dim, units, batch_size, inp_lang, targ_lang,
        use_GloVe=True,
        mode=seq2seq.BASIC,
        use_bilstm=True)
    checkpoint = tf.train.Checkpoint(optimizer=optimizer, seq2seq=model)
    # restoring the latest checkpoint in checkpoint_dir
    checkpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))

    return model


'''
修改数据库的数据
'''
import sqlite3
conn = sqlite3.connect("lin01.db")
# 游标对象，创建一个Cursor 对象并调用其execute()方法来执行SQL命令
c = conn.cursor()

# 把id为'004'的数据的name改为'xxx'
c.execute("update user set name='lin2' where id = '004'")

conn.commit()
conn.close()


#!/usr/bin/env python

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

#Importing Dataset and Segregating Independent & Dependent Variables
dataset = pd.read_csv("../Data/3_50Startups.csv")
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values

#Taking Care of Columns with Missing Data
#Not Applicable

#Encoding Categorical Data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
labelencoder_State = LabelEncoder()
labelencoder_State = labelencoder_State.fit(X[:, 3])
X[:, 3] = labelencoder_State.transform(X[:, 3])
column_transformer = ColumnTransformer([("ohe", OneHotEncoder(), [3])], remainder = "passthrough")
X = np.array(column_transformer.fit_transform(X), dtype = np.int)

#Avoiding Dummy Variable Trap
X = X[:, 1:]                #Need not specifically code as MLR algorithm automatically takes care of it

#Splitting Dataset into Training & Testing Set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)

#Fitting the Training Set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)

#Modelling Prediction Using Training Set
train_pred = regressor.predict(X_train)

#Validating Prediction Using Testing Set
test_pred = regressor.predict(X_test)

'''
#Comparing the Actual Values with the Predicted Values
print("Actual Result for X_test : \n")
print(y_test)
print("\n")
print("Predicted Values for X_test : \n")
print(test_pred)
'''

#Building Optimal Model Using Backward Elimination
import statsmodels.api as sm
##MLR ==> y = b0    + b1.X1 + b2.X2 + .... + bn.Xn
###    ==> y = b0.X0 + b1.X1 + b2.X2 + .... + bn.Xn where X0 = 1
##Insert X0 (a column of 1s in the beginning of X
##This manipulation is automatically taken care of by LinearRegression(). However, statsmodel.formula.api needs this to be done manually.
X = np.append(arr = np.ones((50, 1)).astype(int), values = X, axis = 1)  #Adding intercept i.e column of ones

##Manually finding the most significant Independent Variables with P < 0.05
'''
##Fitting the model with all possible predictors i.e., columns 0, 1, 2, 3 ...
##X : Original Matrix of Features
##X_optimal : Matrix of Optimal Features after eliminating insignifcant columns using Backward Elimination
X_optimal = X[:, [0, 1, 2, 3, 4, 5]]
regressor_OLS = sm.OLS(endog = y, exog = X_optimal).fit()
regressor_OLS.summary()     #Repeat the last three steps to remove the columns with P > 0.05 till identifying only the most significant I.Vs
'''

#Automatically finding the most significant Independent Variables with P < 0.05
def backwardElimination(sl, x_opt):
    numColumns = len(x_opt[0])          #Number of Columns
    for i in range(0, numColumns):
        regressor_OLS = sm.OLS(endog = y, exog = x_opt).fit()
        maxPvalue = max(regressor_OLS.pvalues).astype(float)

        if maxPvalue > sl:
            for j in range(0, numColumns - i):
                if(regressor_OLS.pvalues[j].astype(float) == maxPvalue):
                        x_opt = np.delete(x_opt, j, 1)
            print(regressor_OLS.summary())
    return x_opt

sig_level = 0.05
X_optimal = X[:, [0, 1, 2, 3, 4, 5]]
X_modelled = backwardElimination(sig_level, X_optimal)

#Build automatic Backward Elimination Model using P-values and Adjusted R squares values
print("\n\n")
print("***Build Automatic Backward Elimination Model Using P-values and Adjusted-R-Squares values***")


import numpy as np
import time
import os
import scipy.stats as st
from pathlib import Path, PureWindowsPath
from Mutual_Information_Main.functions.toy_model_functions import Toy_Model_Functions as tmf
import pandas as pd

# Simulates population of cells with networks defined by toy receptor model for different levels of parameter variation
# Records:
# Single cell mutual information for population of cells for various distributions of parameters
# Mutual information of cell state agnostic response for various distributions of parameters

# _____ Setting the CWD to be Mutual_Information_Main BEGIN _____
# Cell_signaling_information path here
path_to_CSI = ""
if path_to_CSI == "":
	try:
		# Obtains the location of the Cell_signaling_information folder if it is in the cwd parents
		path_to_CSI = Path.cwd().parents[[Path.cwd().parents[i].parts[-1] for i in range(len(Path.cwd().parts) - 1)].index(
			"Cell_signalling_information")]
	except ValueError:
		print("Cell_signalling_information not found in cwd parents, trying sys.path")
		try:
			# Obtains the location of the Cell_signaling_information folder if it is in sys.path
			path_to_CSI = Path(sys.path[[Path(i).parts[-1] for i in sys.path].index("Cell_signalling_information")])
		except ValueError:
			print("Cell_signalling_information not found in sys.path "
			      "consult 'Errors with setting working directory' in README")
else:
	path_to_CSI = Path(path_to_CSI)
path_to_MIM = path_to_CSI/"Mutual_Information_Main"
os.chdir(path_to_MIM)
# _____ Setting the CWD to be Mutual_Information_Main END _____

# _____ File path declarations BEGIN _____
# location of the output data
output_file_path = Path("Data/Toy_Model/Information_Values/framework_comparison")
# output data filename prefix
output_file_name_prefix = "toy_model_system"
ceemi_deg_array_filename = output_file_path/(output_file_name_prefix+"_cmi_deg.csv")
ceemi_r0_array_filename = output_file_path/(output_file_name_prefix+"_cmi_r0.csv")
mi_deg_array_filename = output_file_path/(output_file_name_prefix+"_mi_deg.csv")
mi_r0_array_filename = output_file_path/(output_file_name_prefix+"_mi_r0.csv")
# _____ File path declarations END _____

# _____ Main Code BEGIN _____
# cv of input distribution
input_cv = 1

# mean of input distribution
input_mean = 10

# Number of bins to use for input discretization
input_partitions = 25

# Values of parameter cv's to plot, linspace arguement, base 10
parameter_cv = 10**np.linspace(-1.5,-0.5,50)

# average degredation rate, k_deg
deg_mean = 5

# average initial receptor count value, r0
r0_mean = 500

# rate of binding, k_bind
k_bind = 1

# rate of unbinding, k_unbind
k_unbind = 10

# for case where degradation varies
r0_val = 50

# for case where receptor average varies
deg_val = 5

# Performs this many monte carlo draws for each integral (50000)
mc_draws = 50000

# MI array for different values of r0 variance
mir0 = np.zeros((1,np.size(parameter_cv)))

# Cee-MI array for different values of r0 variance
cmi_r0_array = np.zeros((mc_draws,np.size(parameter_cv)))

# MI array for different values of kdeg variance
mideg = np.zeros((1,np.size(parameter_cv)))

# Cee-MI array for different values of kdeg variance
cmi_deg_array = np.zeros((mc_draws,np.size(parameter_cv)))

# obtains the input variance
input_variance = (input_cv*input_mean)**2

# Generates input distribution by percentile binning of a gamma
u_scale1 = input_variance/ input_mean
uvar_shape1 = input_mean / u_scale1
edge = np.linspace(0, 1, input_partitions+1)
center = (edge[1:]+edge[:-1])/2
ulist = st.gamma.ppf(center, uvar_shape1, scale=u_scale1)

# defines the kdeg variance from the mean and CV
deg_variance = (deg_mean * parameter_cv) ** 2

# defines the r0 variance from the mean and CV
r0_variance = (r0_mean * parameter_cv) ** 2

# used to track estimated time remaining
time_start = time.time()

for pvarind in range(np.size(parameter_cv)):
    # Calculates the Cee-MI for the given kdeg variance
    cmi_deg_array[:,pvarind] = -1*tmf.cmi_deg_var(ulist,deg_variance[pvarind],deg_mean,mc_draws,r0_val,k_bind,k_unbind)

    # Calculates the Cee-MI for the given r0 variance
    cmi_r0_array[:,pvarind] = -1*tmf.cmi_r0_var(ulist,r0_variance[pvarind],r0_mean,mc_draws,deg_val,k_bind,k_unbind)

    # Calculates the MI of the CSAR for the given deg variance
    mideg[0,pvarind] = -1*tmf.mi_deg_var(ulist,deg_variance[pvarind],deg_mean,mc_draws,r0_val,k_bind,k_unbind)

    # Calculates the MI of the CSAR for the given r0 variance
    mir0[0,pvarind] = -1*tmf.mi_r0_var(ulist,r0_variance[pvarind],r0_mean,mc_draws,deg_val,k_bind,k_unbind)

    # Tracks time remaining
    time_elapsed = time.time() - time_start
    print(f"Approximately {round(time_elapsed/(pvarind+1)*((np.size(input_variance)-1)*np.size(parameter_cv)+np.size(parameter_cv)-pvarind-1)/60)} minutes remain")

# Saves resulting arrays
pd.DataFrame(cmi_deg_array,columns=parameter_cv).to_csv(ceemi_deg_array_filename)
pd.DataFrame(cmi_r0_array,columns=parameter_cv).to_csv(ceemi_r0_array_filename)
pd.DataFrame(mideg,columns=parameter_cv).to_csv(mi_deg_array_filename)
pd.DataFrame(mir0,columns=parameter_cv).to_csv(mi_r0_array_filename)
# _____ Main Code END _____


# encoding: utf-8
# pylint: disable=too-few-public-methods
"""
measurement schemas
------------
"""
from marshmallow import fields, Schema, post_load
from .models import Measurement

class MeasurementSchema(Schema):
    msg_id = fields.Int()
    start_time = fields.DateTime()
    device_id = fields.Int()
    mea_id = fields.Int()
    c1 = fields.Float()
    c2 = fields.Float()
    c3 = fields.Float()

    class Meta:
        #load_only = ("msg_id",)
        #fields = ("start_time", "c1", "c2", "c3")
        load_only = ("msg_id", "device_id", "mea_id")
        ordered = True

    @post_load
    def make_Measurement(self, data):
        return Measurement(**data)

class MeaQuerySChema(Schema):
    "This calss used to validate the input parameters for query measurement"
    #dev_id = fields.Int(required=True, allow_none=False)
    dev_id = fields.List(fields.Int, required=True, allow_none=False)
    stime = fields.DateTime(required=False)
    etime = fields.DateTime(required=False)


import os
from re import S
import cv2
import glob
import numpy as np
from moviepy.editor import *
import time
import pickle

def video_olustur(folders):
    #Amacım .mp4 formatından biten videoların tespiti ve bunların  jpg formatına çevirerek
    # (1920,1080) ve 5 fps formatlarında output videosu oluşturmak.
  videonames_list = []
  for folder in folders:
    for f in glob.glob(folder+'/*.mp4'):
      videonames_list.append(f)
      print(f)

  print('There are {} videos in Folder'.format(len(videonames_list)))

  count = 0
  for i in range(0,len(videonames_list)):
   video_data = videonames_list[i]
   video = cv2.VideoCapture(video_data)
   success = True
   while success:
    success,image = video.read()
    name = 'C:/Users/DELL/Desktop/Ornek/Resim/'+str(count)+'.jpg'
    if success == True:
      cv2.imwrite(name,image)
      print('Frame {} Extracted Successfully'.format(count))
      count+=1
    else:
      i = i+1
    i = i+1
  print('\n\n\nVideo {} Extracted Successfully\n\n\n'.format(video_data))

  image_folder = 'Resim'
  video_name = 'video.avi'

  images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
  frame = cv2.imread(os.path.join(image_folder, images[0]))
#   height, width, layers = frame.shape

#Video oluşturuyoruz
  fourcc = cv2.VideoWriter_fourcc(*'XVID')
  video=cv2.VideoWriter('output6.avi',fourcc, 5, (1920,1080))

  for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))
  return video

if __name__ == "__main__":

    yol=glob.glob('C:/Users/DELL/Desktop/Ornek')
    folder=video_olustur(yol)
    time.sleep(10)
    cap = cv2.VideoCapture('C:/Users/DELL/Desktop/Ornek/output6.avi')  # 0 olarak değiştirildi
    frame=[]
    color2=[]
    my_dict=dict()

    #number of frames 670
    for frame_indx in range(670) :
      while (cap.isOpened()):
       ret, frame = cap.read()
       if ret==True:
        hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        height, width, _ = frame.shape

        cx = int(width / 2)
        cy = int(height / 2)

     # Pick pixel value
        pixel_center = hsv_frame[cy, cx]
        hue_value = pixel_center[0]

        i=0
        color = "Undefined"
        if hue_value < 5:
          color = "KIRMIZI"
          color2.append(color)

        elif hue_value < 78:
          color = "YEŞİL"
          #print('Yeşil')
          color2.append(color)

        elif hue_value < 131:
           color = "MAVi"
           color2.append(color)

        else:
           color = "KIRMIZI"
          # print('Kırnızı')

    # print(color2)

        # pixel_center_bgr = frame[cy, cx]
        # b, g, r = int(pixel_center_bgr[0]), int(pixel_center_bgr[1]), int(pixel_center_bgr[2])

        # cv2.rectangle(frame, (cx - 220, 10), (cx + 200, 120), (255, 255, 255), -1)
        # cv2.putText(frame, color, (cx - 200, 100), 0, 3, (b, g, r), 5)
        # cv2.circle(frame, (cx, cy), 5, (25, 25, 25), 3)

        cv2.imshow("Frame", frame)
        key = cv2.waitKey(1)
        if key == 27:
          break
        else:

          break

#Bu kısımda color2 listesini dictionary çeviriyorum
    for index,value in enumerate(color2):
       my_dict[index] = value
    print(my_dict)

    with open('renk.pickle', 'wb') as handle:
       pickle.dump(my_dict, handle, protocol=pickle.HIGHEST_PROTOCOL)

    with open('renk.pickle', 'rb') as handle:
       b = pickle.load(handle)

    print(my_dict == b)
    cap.release()
# video.release()
    cv2.destroyAllWindows()


import builtins as _builtins

_readline_available = False

try:
    import readline
    _readline_available = True
except ImportError:
    pass

class Completer:
    def __init__(self, namespace: dict):
        self.namespace = namespace
        self.matches = []

    def complete(self, text: str, state: int) -> str:
        if not _readline_available:
            return '\t'

        namespace = self.namespace

        if not text.strip():
            if state == 0:
                readline.insert_text('\t')
                readline.redisplay()
                return ''
            else:
                return None

        if state == 0:
            if '.' in text:
                self.matches = self.match_attr(text)
            else:
                self.matches = self.match_name(text)

        try:
            return self.matches[state]
        except IndexError:
            return None

    def __check_callable_prefix(self, word, obj) -> str:
        return ('%s(' % word) if callable(obj) else word

    def match_name(self, text: str):
        from ..core.aparser import _keywords

        ns = self.namespace
        matches = []
        n = len(text)

        for word in _keywords:
            if word not in matches:
                if word[:n] == text:
                    matches.append(word)

        for word in ns.keys():
            if '::' in word:
                continue

            if word[:n] == text:
                try:
                    word = self.__check_callable_prefix(word, ns[word])
                except Exception:
                    pass
                matches.append(word)

        for word in dir(_builtins):
            if '::' in word:
                continue

            if word not in matches:
                if word[:n] == text:
                    try:
                        word = self.__check_callable_prefix(
                                word, getattr(_builtins, word))
                    except Exception:
                        pass
                    matches.append(word)

        return matches

    def match_attr(self, text: str):
        import re
        m = re.match(r"(\w+(\.\w+)*)\.(\w*)", text)
        if not m:
            return []

        expr, attr = m.group(1, 3)

        try:
            this = eval(expr, self.namespace)
        except Exception:
            return []

        words = set(dir(this))

        n = len(attr)

        matches = []

        show_prefix = attr[:1] == '_'

        for word in words:
            if '::' in word:
                continue

            if word[:1] == '_' and not show_prefix:
                continue
            if word[:n] == attr:
                try:
                    word = self.__check_callable_prefix(word, getattr(this, word))
                except Exception:
                    pass

                matches.append('%s.%s' % (expr, word))

        matches.sort()
        return matches

_AIL_PYC_MODULE_ = True
_AIL_NAMESPACE_ = {'Completer': Completer}