#!/usr/bin/env python
"""Example of using Cockroach DB with SQLAlchemy."""

import uuid
from sqlalchemy import create_engine, Column, String, Integer, DateTime, Boolean
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import func
from cockroachdb.sqlalchemy import run_transaction

Base = declarative_base()

class ShoppingListItem(Base):
    """Mapping class for shopping list item table rows."""
    # set the table name
    __tablename__ = 'shopping_lists'
    # use a composite primary key
    username = Column(String, primary_key=True)
    item_id = Column(UUID(as_uuid=True), primary_key=True)
    # automatically set the time to when the item is added
    added = Column(DateTime(timezone=True), server_default=func.now())
    item = Column(String)
    quantity = Column(Integer)
    # defaults to False as the item has just been added
    bought = Column(Boolean, default=False)

# we are not using security in this example
connect_args = {'sslmode': 'disable'}

# connect to the chores database running locally
engine = create_engine(
    'cockroachdb://root@localhost:26257/chores',
    connect_args=connect_args,
    echo=True                   # Log SQL queries to stdout
)

# automatically create the database table based on the ShoppingListItem class
Base.metadata.create_all(engine)

def create_shopping_list(session):
    """Create a shopping list row."""
    apples = ShoppingListItem(
        username="alice",
        item_id=uuid.uuid4(),
        item="Gala apples",
        quantity=3
    )
    session.add(apples)
    print("\n*** Added shopping list item. ***")
    print(apples.username, apples.item_id, apples.item, apples.quantity)
    print("\n")

# call the create function
run_transaction(sessionmaker(bind=engine), create_shopping_list)

def read_shopping_list(session):
    """Read the rows in the shopping list table."""

    # there is only one row, so we can retrieve the first result
    apples = session.query(ShoppingListItem).filter_by(
        username='alice').first()
    print("\n*** Retrieved a row from shopping_lists. ***")
    print(apples.username, apples.item_id, apples.item, apples.added,
          apples.quantity, apples.bought)
    print("\n")

# call the read function
run_transaction(sessionmaker(bind=engine), read_shopping_list)

def update_shopping_list(session):
    """Update, or modify, the contents of a row in the shopping list table."""

    apples = session.query(ShoppingListItem).filter_by(
        username='alice').first()
    # modify the shopping list item, which triggers an update
    apples.bought = True

    # show the modified shopping list item
    print("\n*** Modified a shopping list item. ***")
    print(apples.username, apples.item_id, apples.item, apples.added,
          apples.quantity, apples.bought)
    print("\n")

# call the update function
run_transaction(sessionmaker(bind=engine), update_shopping_list)

def delete_shopping_list(session):
    """Delete a shopping list row."""

    apples = session.query(ShoppingListItem).filter_by(
        username='alice').first()
    # delete the shopping list item
    session.delete(apples)

    # show that there's no more rows in the table
    print("\n*** Deleted a row in shopping_lists. Rows in shopping_lists: ***",
          session.query(ShoppingListItem).filter_by(username='alice').count(),
          "\n")

# call the delete function
run_transaction(sessionmaker(bind=engine), delete_shopping_list)


import numpy
from chainer import functions
# import chainer_chemistry
from chainer_chemistry.links import EmbedAtomID
from chainer_chemistry.links import GraphLinear

atom_size = 5
out_dim = 4
batch_size = 3
heads = 2
hidden_dim = 16

atom_data = numpy.random.randint(
    0, high=110, size=(batch_size, atom_size)
).astype(numpy.int32)
adj_data = numpy.random.randint(
    0, high=2, size=(batch_size, atom_size, atom_size)
).astype(numpy.float32)

embed = EmbedAtomID(out_size=hidden_dim, in_size=110)
weight = GraphLinear(hidden_dim, heads * hidden_dim)
att_weight = GraphLinear(hidden_dim * 2, 1)

def test(atom_array, adj_data):
    x = embed(atom_array)
    mb, atom, ch = x.shape
    print(x.shape)
    test = weight(x)
    print(test.shape)
    x = functions.expand_dims(test, axis=1)
    print(x.shape)
    x = functions.broadcast_to(x, (mb, atom, atom, heads * ch))
    print(x.shape)
    y = functions.copy(x, -1)
    print(y.shape)
    y = functions.transpose(y, (0, 2, 1, 3))
    print(y.shape)
    z = functions.concat([x, y], axis=3)
    print(z.shape)
    z = functions.reshape(z, (mb * heads, atom * atom, ch * 2))
    print(z.shape)
    z = att_weight(z)
    print(z.shape)
    z = functions.reshape(z, (mb * heads, atom, atom))
    print(z.shape)
    z = functions.leaky_relu(z)
    # print(adj_data.array.astype(numpy.bool))
    # cond = adj_data.array.astype(numpy.bool)
    cond = adj_data.astype(numpy.bool)
    print(cond.shape)
    z = functions.reshape(z, (heads, mb, atom, atom))
    cond = numpy.broadcast_to(cond, z.array.shape)
    print(cond.shape)
    z = functions.where(cond, z,
                        numpy.broadcast_to(numpy.array(-100), z.array.shape)
                        .astype(numpy.float32))
    print(z.shape)
    z = functions.softmax(z)
    print(z.shape)
    z = functions.mean(z, axis=0)
    print(z.shape)
    print(test.shape)
    z = functions.matmul(z, test)
    return z

a = test(atom_data, adj_data)
print(a)


import pymysql

class Modelo_inicio:
    def __init__(self):
        self.conexion  = pymysql.connect(
            host="localhost",
            user="root",
            password="",
            db="bd_prueba"

        )
        self.cursor = self.conexion.cursor()

    def iniciar_sesion(self, usuario, contraseña):
        try:
            query = "SELECT contraseña FROM usuario WHERE usuario = %s and contraseña=%s"
            data =(usuario, contraseña)
            self.cursor.execute(query, data)
            return self.cursor.fetchall()
        except Exception as e:
            print("El error esta en: ", e)
    def cerrar_conexion(self):
        self.conexion.close()


from datetime import datetime, timedelta
import random

from fastapi import APIRouter, status, Depends, HTTPException, Form, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates

from models import PomodoroResponse, ResponseUser, Satisfaction
from data import DB
import query as q
from utils import get_current_user, get_satisfaction_int

templates = Jinja2Templates(directory="templates")

router = APIRouter(
    prefix='/pomodoros',
    tags=["Pomodoros"]
)

# Pomodoro paths
@router.get(
    path="/",
    response_class=HTMLResponse,
    status_code=status.HTTP_200_OK,
    include_in_schema=False
)
def get_pomodoros_home(request:Request, current_user:ResponseUser = Depends(get_current_user)):
    user_id = current_user['user_id']

    previous_30_days = datetime.today() - timedelta(days=30)
    values = (user_id, previous_30_days)
    df = q.get_pomodoros(values, all=True)

    pomodoros = df.to_dict('records')
    context = {
        'request': request,
        'pomodoros': pomodoros
    }

    return templates.TemplateResponse("general_pages/pomodoros.html", context=context)

@router.post(
    path="/",
    status_code=status.HTTP_201_CREATED,
    summary="Create pomodoro",
    response_class=HTMLResponse
)
def create_pomodoro(
        category_id:int = Form(...),
        project_id:int = Form(...),
        duration:int = Form(...),
        current_user:ResponseUser = Depends(get_current_user)
    ):
    user_id = current_user['user_id']
    pomodoro_date = datetime.today()
    values = (
        category_id, project_id, duration,
        pomodoro_date, user_id
    )
    query = q.create_pomodoro()

    # Execute query
    DB.execute_query(query, values)

    color = "#{:06x}".format(random.randint(0, 0xFFFFFF))

    return f'
Pomodoro created, Start the timer
'

@router.put(
    path="/",
    status_code=status.HTTP_200_OK,
    summary="Measure pomodoro satisfaction",
    response_class=HTMLResponse,
)
def update_pomodoro_satisfaction(request: Request, satisfaction:Satisfaction = Form(...), current_user:ResponseUser = Depends(get_current_user)):
    user_id = current_user['user_id']
    values = (user_id,)
    df = q.get_latest_pomodoro(values)
    pomodoro = df.to_dict('records')[0]

    satisfaction = get_satisfaction_int(satisfaction.value)
    values = (satisfaction, pomodoro['pomodoro_id'], user_id)
    query = q.update_pomodoro_satisfaction()

    # Execute query
    DB.execute_query(query, values)

    return '
Sent
'

@router.get(
    path="/satisfaction",
    status_code=status.HTTP_200_OK,
    response_class=HTMLResponse,
    include_in_schema=False,
)
def get_satisfaction_modal(request:Request, current_user:ResponseUser = Depends(get_current_user)):
    return '

'

@router.get(
    path="/{category_id}/{project_id}",
    response_model=list[PomodoroResponse],
    status_code=status.HTTP_200_OK,
    summary="Get pomodoros in a project"
)
def get_pomodoro(category_id:int, project_id:int, current_user:ResponseUser = Depends(get_current_user)):
    user_id = current_user['user_id']
    values = (user_id, category_id, project_id)

    df = q.get_pomodoros(values)
    if df.empty:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="There are not pomodoros for this project"
        )

    # Satisfaction
    df.pomodoro_satisfaction.fillna("", inplace=True)
    satisfaction = {0: "missing", 1: "good", 2: "bad"}
    df.pomodoro_satisfaction.replace(satisfaction, inplace=True)

    return df.to_dict('records')


# BOJ 2527 직사각형

for _ in range(4):
    x1,y1,p1,q1,x2,y2,p2,q2 = map(int,input().split())
    if p1<x2 or p2<x1 or y1>q2 or q1<y2: #공통부분 없음
        print('d')
    elif x1==p2 or x2==p1:
        if q1==y2 or q2==y1: #점
            print('c')
        else: #선분
            print('b')
    elif q1==y2 or q2==y1: #선분
        print('b')
    else:
        print('a')


import torch
import numpy as np
from torch.utils.data import Dataset
import os
import random
import cv2
import string

from data import consts, vocabulary

class VSADisentangle(Dataset):
    def __init__(self, mode, shuffle=True):
        if mode not in ("train", "test"):
            raise Exception("invalid dataset mode")
        self.mode = mode
        self.data_root = consts.DATA_ROOT + "/vsa"
        self.flow_root = consts.DATA_ROOT + "/vsa_flow"
        if mode == "train":
            users = consts.VSA_TRAIN_USERS
            group = [50, 35, 1]
        else:
            users = consts.VSA_TEST_USERS
            group = [20, 2, 20]
        user_list = ["user" + str(i) for i in users]

        self.user_list = user_list

        file_list = []
        random_appear_dict = {}
        fixed_appear_dict = {}
        for user in self.user_list:
            fixed_utterances = os.listdir(os.path.join(self.data_root, user, "fixed"))
            samples_0 = group[0] if len(fixed_utterances) >= group[0] else len(fixed_utterances)
            fixed_utterances = random.sample(fixed_utterances, samples_0)
            for fixed_utt in fixed_utterances:
                other_users = list(filter(lambda x: x != user, self.user_list))
                samples_1 = group[1] if len(other_users) >= group[1] else len(other_users)
                other_users = random.sample(other_users, samples_1)
                for other_user in other_users:
                    if fixed_utt not in os.listdir(os.path.join(self.data_root, other_user, "fixed")):
                        continue
                    random_utterances = os.listdir(os.path.join(self.data_root, user, "random"))
                    samples_2 = group[2] if len(random_utterances) >= group[2] else len(random_utterances)
                    random_utterances = random.sample(random_utterances, samples_2)
                    for random_utt in random_utterances:
                        random_path = "/".join([user, "random", random_utt])
                        fixed_path = "/".join([user, "fixed", fixed_utt])
                        item = [fixed_path, random_path, "/".join([other_user, "fixed", fixed_utt])]
                        if random_path not in random_appear_dict:
                            random_appear_dict[random_path] = [item]
                        else:
                            random_appear_dict[random_path].append(item)
                        if fixed_path not in fixed_appear_dict:
                            fixed_appear_dict[fixed_path] = [item]
                        else:
                            fixed_appear_dict[fixed_path].append(item)
        for k, v in random_appear_dict.items():
            sample_num = 1 if len(v) >= 1 else len(v)
            file_list.extend(random.sample(v, sample_num))
        for k, v in fixed_appear_dict.items():
            sample_num = 1 if len(v) >= 1 else len(v)
            file_list.extend(random.sample(v, sample_num))

        if shuffle:
            random.shuffle(file_list)
        self.file_list = file_list

    def get_images_and_token(self, img_path):
        s = img_path.split("/")
        horizon_flip = self.mode == "train" and random.random() > 0.5
        img_sequence_list = []
        for index, img_name in enumerate(sorted(os.listdir(img_path))):
            img = cv2.imread(os.path.join(img_path, img_name))  # (H, W, c)
            img = img / 255.0
            img_tensor = torch.from_numpy(np.transpose(img, (2, 0, 1))).float()
            img_sequence_list.append(img_tensor)
        img_sequence = torch.stack(img_sequence_list[:50], 1)
        flow_data = np.load(os.path.join(self.flow_root, s[-3], s[-2], s[-1] + ".npy"))
        flow_data = flow_data[:49, :, :, :]
        flow_data = np.transpose(flow_data, (1, 0, 2, 3))
        flow_sequence = torch.from_numpy(flow_data)

        if horizon_flip:
            img_sequence = torch.flip(img_sequence, dims=[3])
            flow_sequence = torch.flip(flow_sequence, dims=[3])

        label = s[-1]
        user_id = self.user_list.index(s[-3])
        full = " ".join([consts.NUMBER[n] for n in label])
        token = vocabulary.txt2token(full, consts.VOCAB)
        token.insert(0, consts.BOS)
        token.append(consts.EOS)
        for i in range(consts.TOKEN_MAX_LEN - len(token)):
            token.append(consts.PAD)

        token = torch.tensor(token, dtype=torch.int64)
        return img_sequence, token, user_id, flow_sequence

    def __getitem__(self, index):
        img_files = self.file_list[index]
        return [self.get_images_and_token(os.path.join(self.data_root, f)) for f in img_files]

    def __len__(self):
        return len(self.file_list)


# -*- coding: utf-8 -*-
import random
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import warnings
warnings.filterwarnings('ignore')

import os
import pymorphy2
import re
import chardet

import nltk

nltk.download('popular', quiet=True) # for downloading packages

# uncomment the following only the first time
#nltk.download('punkt') # first-time use only
#nltk.download('wordnet') # first-time use only
morph = pymorphy2.MorphAnalyzer()

def Lemmatizer(text):
    # Detecting codepage, recoding, cleaning, lemmatizing
    codepage = chardet.detect(text.encode())['encoding']
    text = (text.encode()).decode(codepage)
    text = " ".join(word.lower() for word in text.split())  # lowercasing and removing short words
    text = re.sub('\-\s\r\n\s{1,}|\-\s\r\n|\r\n', '', text)  # deleting newlines and line-breaks
    text = re.sub('[.,:;%©?*,!@#$%^&()\d]|[+=]|[[]|[]]|[/]|"|\s{2,}|-', ' ', text)  # deleting symbols
    text = " ".join(morph.parse(str(word))[0].normal_form for word in text.split())
    text = text.encode("utf-8")
    return nltk.word_tokenize(text.decode())

with open('chatbot.txt', 'r', encoding='utf-8', errors='ignore') as fin:
    raw = fin.read()
with open('stopwords.txt', 'r', encoding='utf-8', errors='ignore') as fin:
    stopwords = fin.read()
#TOkenisation
sent_tokens = nltk.sent_tokenize(raw)# converts to list of sentences
word_tokens = nltk.word_tokenize(raw)# converts to list of words
stop_words = nltk.word_tokenize(stopwords)

# Keyword Matching
GREETING_INPUTS = ("здравствуй", "добрый день", "доброе утро", "добрый вечер", "доброго времени суток", "приветствую", "привет", "мое почтение", "приветик", "хей", "здарова", "салют", "Сколько лет, сколько зим!", "рад видеть", "ку")
GREETING_RESPONSES = ["Здравствуй", "Доброго времени суток", "Приветствую", "Мое почтение", "Сколько лет, сколько зим!", "Рад видеть"]

def greeting(sentence):
    for word in sentence.split():
        if word.lower() in GREETING_INPUTS:
            return random.choice(GREETING_RESPONSES)

# Generating response
def response(user_response):
    robo_response = ''
    sent_tokens.append(user_response)
    TfidfVec = TfidfVectorizer(tokenizer=Lemmatizer, stop_words=stop_words)
    tfidf = TfidfVec.fit_transform(sent_tokens)
    vals = cosine_similarity(tfidf[-1], tfidf)
    idx = vals.argsort()[0][-2]
    flat = vals.flatten()
    flat.sort()
    req_tfidf = flat[-2]
    if(req_tfidf == 0):
        robo_response = robo_response + "Хмм...Я пока не готов ответить на этот вопрос, нужно еще поразмыслить. Может сменим тему?"
        return robo_response
    else:
        robo_response = robo_response + sent_tokens[idx]
        return robo_response

flag = True
print("Приветствую. Я философ-бот и постараюсь поддержать ваш разговор.")
while(flag == True):
    user_response = input()
    user_response = user_response.lower()
    if(user_response != 'пока'):
        if(user_response == 'спасибо'):
            flag = False
            print("Приходи еще!")
        else:
            if(greeting(user_response) != None):
                print(greeting(user_response))
            else:
                print(end="")
                print(response(user_response))
                sent_tokens.remove(user_response)
    else:
        flag = False
        print("Бывай! Береги себя..")


from odoo import models, fields, api

class SaleOrder(models.Model):

    _inherit = 'sale.order'

    invoice_type_id = fields.Many2one('res.partner.invoice.type', "Invoice type")

    @api.multi
    @api.onchange('partner_id')
    def onchange_partner_id(self):
        super().onchange_partner_id()
        if self.partner_id:
            part = self.partner_id
            self.invoice_type_id = part.invoice_type_id and part.invoice_type_id.id \
                or part.commercial_partner_id.invoice_type_id and part.commercial_partner_id.invoice_type_id.id \
                or False

    @api.model
    def cron_create_invoices(self, limit):
        sale_obj = self.env['sale.order']
        ctx = dict(self._context or {})
        ctx['bypass_risk'] = True
        templates = []
        validate = True
        ok_validation = True

        # Sales to Invoice
        sales = sale_obj.\
            search([('invoice_status_2', '=', 'to_invoice'),
                    ('invoice_type_id.name', '=', 'Diaria'),
                    ('tests', '=', False)],
                   order='confirmation_date desc', limit=limit)
        # Create invoice
        res = []
        for sale in sales:
            try:
                invoices = sale.action_invoice_create()
                res.extend(invoices)
            except:
                print("No invoiceable lines on sale {}".format(sale.name))
                invoices = self.env['account.invoice'].\
                    search([('state', '=', 'draft'),
                            ('origin', '=', sale.name)])
                if invoices:
                    invoices.unlink()
                pass
        # if len(sales) != len(res):
            # templates.append(self.env.ref('picking_invoice_pending.alert_cron_create_invoices', False))
        invoices_created = self.env['account.invoice'].with_context(ctx).\
            browse(res)
        if len(res) != len(invoices_created.mapped('invoice_line_ids.invoice_id.id')):
            # There are invoices created without lines
            templates.append(self.env.ref('picking_invoice_pending.alert_cron_create_invoices_empty_lines', False))
            # Do not validate them because it will generate an error
            validate = False
        if validate:
            # Validate invoice
            for inv in invoices_created:
                inv.action_invoice_open()
                if inv.state in ('draft', 'cancel', 'proforma', 'proforma2'):
                    ok_validation = False
            if not ok_validation:
                templates.append(self.env.ref('picking_invoice_pending.alert_cron_validate_invoices', False))
        if invoices_created:
            for tmpl in templates:
                ctx.update({
                    'default_model': 'account.invoice',
                    'default_res_id': invoices_created[0].id,
                    'default_use_template': bool(tmpl.id),
                    'default_template_id': tmpl.id,
                    'default_composition_mode': 'comment',
                    'mark_so_as_sent': True
                })
                composer_id = self.env['mail.compose.message'].\
                    with_context(ctx).create({})
                composer_id.with_context(ctx).send_mail()

        return True

    @api.multi
    def action_invoice_create(self, grouped=False, final=False):
        res = super(SaleOrder, self).action_invoice_create(grouped=grouped, final=final)
        orders_to_done = self.env['sale.order']
        for order in self:
            if not order.order_line.mapped('product_id').filtered(lambda x: x.type != 'service'):
                orders_to_done += order
        orders_to_done.write({'state': 'done'})
        return res

    @api.multi
    def _prepare_invoice(self):
        res = super(SaleOrder, self)._prepare_invoice()
        invoice_type = (self.invoice_type_id
                        or self.partner_id.commercial_partner_id.invoice_type_id)
        if invoice_type and invoice_type.journal_id:
            res['journal_id'] = invoice_type.journal_id.id
        return res


#!/usr/bin/env python3
""" Module tests basic/introductory MondoDB features with pymongo """
from typing import Collection, Iterable

def top_students(mongo_collection: Collection) -> Iterable:
    """ Returns all students sorted by average score """
    # Create aggregate() query object from MongoDB collection
    # This is to make the next line shorter and human-readable
    aggr = mongo_collection.aggregate

    # Query database and return results with sorted average score
    return aggr([{'$project': {'_id': '$_id', 'name': '$name',
                               'averageScore': {'$avg': '$topics.score'}}},
                 {'$sort': {'averageScore': -1}}])

if __name__ == '__main__':
    """ Tests the code in this module """
    from pymongo import MongoClient
    list_all = __import__('8-all').list_all
    insert_school = __import__('9-insert_school').insert_school
    with MongoClient() as client:
        students_collection = client.my_db.students
        j_students = [
            {'name': 'John', 'topics': [{'title': 'Algo', 'score': 10.3},
                                        {'title': 'C', 'score': 6.2},
                                        {'title': 'Python', 'score': 12.1}]},
            {'name': 'Bob', 'topics': [{'title': 'Algo', 'score': 5.4},
                                       {'title': 'C', 'score': 4.9},
                                       {'title': 'Python', 'score': 7.9}]},
            {'name': 'Sonia', 'topics': [{'title': 'Algo', 'score': 14.8},
                                         {'title': 'C', 'score': 8.8},
                                         {'title': 'Python', 'score': 15.7}]},
            {'name': 'Amy', 'topics': [{'title': 'Algo', 'score': 9.1},
                                       {'title': 'C', 'score': 14.2},
                                       {'title': 'Python', 'score': 4.8}]},
            {'name': 'Julia', 'topics': [{'title': 'Algo', 'score': 10.5},
                                         {'title': 'C', 'score': 10.2},
                                         {'title': 'Python', 'score': 10.1}]}]
        for j_student in j_students:
            insert_school(students_collection, **j_student)

        students = list_all(students_collection)
        for student in students:
            print(
                '[{}] {} - {}'.format(student.get('_id'), student.get('name'),
                                      student.get('topics')))

        top_students = top_students(students_collection)
        for student in top_students:
            print(
                '[{}] {} => {}'.format(student.get('_id'), student.get('name'),
                                       student.get('averageScore')))


from numpy import *
def file2matrix(filename):
	datalist=[]
	datalabel=[]
	datalistex=[]
	f=open(filename,'r',encoding='utf-8')
	fi1=f.readlines()
	for fi in fi1:
		fi=fi.strip()
		filist=fi.split(',')
		datalistex=[]
		for x in range(len(filist)-1):
			datalistex.append(float(filist[x]))
		datalist.append(datalistex)
		datalabel.append(float(filist[-1]))
	return datalist,datalabel

def toPCA(datalist,numberofk):
	dataarray = array(datalist)

	meandataofdata = mean(dataarray,axis=0)
	dataminusmean = dataarray - meandataofdata
	stded=dataminusmean/std(dataminusmean,axis=0)
	covdata = cov(stded,rowvar=0) #对每列求协方差
	evals,evects=linalg.eig(covdata)
	evalsex=argsort(evals)
	evalsex=evalsex[-1:-(numberofk+1):-1]
	evectsex=evects[:,evalsex]
	#returndatafinal=dot(stded,evectsex)
	#returndata=dot(returndatafinal,evectsex.T) + meandataofdata
	return evectsex

def judgement(datatrainlist,datatrainlabel,datatestlist):
	testlabel=[]
	for x in range(len(datatestlist)):
		closest=[]
		distancefinal=[]
		for n in range(len(datatrainlist)):
			diffmat=datatestlist[x]-datatrainlist[n]
			sqdiffmatex=diffmat**2
			sqdiffmat=array(list(sqdiffmatex))
			sqdistance=sqdiffmat.sum()
			distance=sqdistance**0.5
			closest.append(distance)
		distancefinal=sorted(closest)
		number=closest.index(distancefinal[0])
		testlabel.append(datatrainlabel[closest.index(distancefinal[0])])
	return testlabel

def finalpercentage(testlabel,turelabel):
	truenumber=0
	for x in range(len(turelabel)):
		if testlabel[x]==turelabel[x]:
			truenumber += 1
	print(truenumber)
	trueper=truenumber/len(turelabel)
	return trueper

if __name__ == '__main__':
	datatrain,labeltrain=file2matrix('datatrain1.txt')
	datatest,labeltest=file2matrix('datatest1.txt')
	returndatatrain=dot(datatrain,toPCA(datatrain,10))
	returndatatest=dot(datatest,toPCA(datatrain,10))
	testlabel=judgement(returndatatrain,labeltrain,returndatatest)
	trueper=finalpercentage(testlabel,labeltest)
	print('the percentage of data 1 is(k=10):')
	print(trueper)
	returndatatrain=dot(datatrain,toPCA(datatrain,20))
	returndatatest=dot(datatest,toPCA(datatrain,20))
	testlabel=judgement(returndatatrain,labeltrain,returndatatest)
	trueper=finalpercentage(testlabel,labeltest)
	print('the percentage of data 1 is(k=20):')
	print(trueper)
	returndatatrain=dot(datatrain,toPCA(datatrain,30))
	returndatatest=dot(datatest,toPCA(datatrain,30))
	testlabel=judgement(returndatatrain,labeltrain,returndatatest)
	trueper=finalpercentage(testlabel,labeltest)
	print('the percentage of data 1 is(k=30):')
	print(trueper)
	datatrain,labeltrain=file2matrix('datatrain2.txt')
	datatest,labeltest=file2matrix('datatest2.txt')
	returndatatrain=dot(datatrain,toPCA(datatrain,10))
	returndatatest=dot(datatest,toPCA(datatrain,10))
	testlabel=judgement(returndatatrain,labeltrain,returndatatest)
	trueper=finalpercentage(testlabel,labeltest)
	print('the percentage of data 2 is(k=10):')
	print(trueper)
	returndatatrain=dot(datatrain,toPCA(datatrain,20))
	returndatatest=dot(datatest,toPCA(datatrain,20))
	testlabel=judgement(returndatatrain,labeltrain,returndatatest)
	trueper=finalpercentage(testlabel,labeltest)
	print('the percentage of data 2 is(k=20):')
	print(trueper)
	returndatatrain=dot(datatrain,toPCA(datatrain,30))
	returndatatest=dot(datatest,toPCA(datatrain,30))
	testlabel=judgement(returndatatrain,labeltrain,returndatatest)
	trueper=finalpercentage(testlabel,labeltest)
	print('the percentage of data 2 is(k=30):')
	print(trueper)


#!/usr/bin/env python
"""
This is a straightforward Python implementation of a generative adversarial network.
The code is derived from the O'Reilly interactive tutorial on GANs
(https://www.oreilly.com/learning/generative-adversarial-networks-for-beginners).

The tutorial's code trades efficiency for clarity in explaining how GANs function;
this script refactors a few things to improve performance, especially on GPU machines.
In particular, it uses a TensorFlow operation to generate random z values and pass them
to the generator; this way, more computations are contained entirely within the
TensorFlow graph.

A version of this model with explanatory notes is also available on GitHub
at https://github.com/jonbruner/generative-adversarial-networks.

This script requires TensorFlow and its dependencies in order to run. Please see
the readme for guidance on installing TensorFlow.

This script won't print summary statistics in the terminal during training;
track progress and see sample images in TensorBoard.
"""

import tensorflow as tf
import datetime
import matplotlib.pyplot as plt
import numpy as np

# Load MNIST data
from tensorflow.examples.tutorials.mnist import input_data
#读取数据集
mnist = input_data.read_data_sets("MNIST_data/")

# Define the discriminator network
#具有两个卷积层和两个全连接层，特征为5x5
def discriminator(images, reuse_variables=None):
    #遍历各层数据
    with tf.variable_scope(tf.get_variable_scope(), reuse=reuse_variables) as scope:
        # First convolutional and pool layers
        # This finds 32 different 5 x 5 pixel features
        #截断正态分布初始化权值
        d_w1 = tf.get_variable('d_w1', [5, 5, 1, 32], initializer=tf.truncated_normal_initializer(stddev=0.02))
        #初始化偏置
        d_b1 = tf.get_variable('d_b1', [32], initializer=tf.constant_initializer(0))
        #标准库中的卷积神经网络
        d1 = tf.nn.conv2d(input=images, filter=d_w1, strides=[1, 1, 1, 1], padding='SAME')
        #增加偏置
        d1 = d1 + d_b1
        #激活函数
        d1 = tf.nn.relu(d1)
        #池化来处理特征
        d1 = tf.nn.avg_pool(d1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

        # Second convolutional and pool layers
        # This finds 64 different 5 x 5 pixel features
        # 截断正态分布初始化权值
        d_w2 = tf.get_variable('d_w2', [5, 5, 32, 64], initializer=tf.truncated_normal_initializer(stddev=0.02))
        # 初始化偏置
        d_b2 = tf.get_variable('d_b2', [64], initializer=tf.constant_initializer(0))
        # 标准库中的卷积神经网络
        d2 = tf.nn.conv2d(input=d1, filter=d_w2, strides=[1, 1, 1, 1], padding='SAME')
        # 增加偏置
        d2 = d2 + d_b2
        # 激活函数
        d2 = tf.nn.relu(d2)
        # 池化来处理特征
        d2 = tf.nn.avg_pool(d2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

        # First fully connected layer
        # 截断正态分布初始化权值
        d_w3 = tf.get_variable('d_w3', [7 * 7 * 64, 1024], initializer=tf.truncated_normal_initializer(stddev=0.02))
        # 初始化偏置
        d_b3 = tf.get_variable('d_b3', [1024], initializer=tf.constant_initializer(0))
        #整合数据
        d3 = tf.reshape(d2, [-1, 7 * 7 * 64])
        #矩阵相乘获得函数值
        d3 = tf.matmul(d3, d_w3)
        #增加偏置
        d3 = d3 + d_b3
        #激活函数
        d3 = tf.nn.relu(d3)

        # Second fully connected layer
        #截断正态分布初始化权值
        d_w4 = tf.get_variable('d_w4', [1024, 1], initializer=tf.truncated_normal_initializer(stddev=0.02))
        #初始化偏置
        d_b4 = tf.get_variable('d_b4', [1], initializer=tf.constant_initializer(0))
        #与权重相乘，增加偏置
        d4 = tf.matmul(d3, d_w4) + d_b4
        # d4 contains unscaled values
        #返回一个标量，可认为是置信值
        return d4

# Define the generator network
#定义生成网络
def generator(z, batch_size, z_dim):
    #输入为56x56大小，设置权重
    g_w1 = tf.get_variable('g_w1', [z_dim, 3136], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.02))
    #设置偏置，大小同上
    g_b1 = tf.get_variable('g_b1', [3136], initializer=tf.truncated_normal_initializer(stddev=0.02))
    #乘上权重+偏置
    g1 = tf.matmul(z, g_w1) + g_b1
    #向量转化为数组
    g1 = tf.reshape(g1, [-1, 56, 56, 1])
    #用于归一化，加快运算速度
    g1 = tf.contrib.layers.batch_norm(g1, epsilon=1e-5, scope='bn1')
    #激活函数
    g1 = tf.nn.relu(g1)

    # Generate 50 features
    #第二层网络权重
    g_w2 = tf.get_variable('g_w2', [3, 3, 1, z_dim/2], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.02))
    #第二层网络偏置
    g_b2 = tf.get_variable('g_b2', [z_dim/2], initializer=tf.truncated_normal_initializer(stddev=0.02))
    #引用标准网络
    g2 = tf.nn.conv2d(g1, g_w2, strides=[1, 2, 2, 1], padding='SAME')
    #加偏置
    g2 = g2 + g_b2
    #用于归一化，加快运算速度
    g2 = tf.contrib.layers.batch_norm(g2, epsilon=1e-5, scope='bn2')
    #激活函数
    g2 = tf.nn.relu(g2)
    #调整大小
    g2 = tf.image.resize_images(g2, [56, 56])

    # Generate 25 features
    #第三层网络权重
    g_w3 = tf.get_variable('g_w3', [3, 3, z_dim/2, z_dim/4], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.02))
    #第三层网络偏置
    g_b3 = tf.get_variable('g_b3', [z_dim/4], initializer=tf.truncated_normal_initializer(stddev=0.02))
    #引用标准网络
    g3 = tf.nn.conv2d(g2, g_w3, strides=[1, 2, 2, 1], padding='SAME')
    #加偏置
    g3 = g3 + g_b3
    # 用于归一化，加快运算速度
    g3 = tf.contrib.layers.batch_norm(g3, epsilon=1e-5, scope='bn3')
    #激活函数
    g3 = tf.nn.relu(g3)
    #调整大小
    g3 = tf.image.resize_images(g3, [56, 56])

    # Final convolution with one output channel
    #第四层权重
    g_w4 = tf.get_variable('g_w4', [1, 1, z_dim/4, 1], dtype=tf.float32, initializer=tf.truncated_normal_initializer(stddev=0.02))
    #第四层偏置
    g_b4 = tf.get_variable('g_b4', [1], initializer=tf.truncated_normal_initializer(stddev=0.02))
    #标准网络
    g4 = tf.nn.conv2d(g3, g_w4, strides=[1, 2, 2, 1], padding='SAME')
    #加偏置
    g4 = g4 + g_b4
    #激活函数使得图像变为灰度图像
    g4 = tf.sigmoid(g4)
    # Dimensions of g4: batch_size x 28 x 28 x 1
    #返回28x28图像数据
    return g4

#批个数定义
z_dimensions = 100

#设定维度大小
z_placeholder = tf.placeholder(tf.float32, [None, z_dimensions])

#生成器输出
generated_image_output = generator(z_placeholder, 1, z_dimensions)
#生成噪音
z_batch = np.random.normal(0, 1, [1, z_dimensions])

with tf.Session() as sess:
    #初始化变量
    sess.run(tf.global_variables_initializer())
    #生成图片
    generated_image = sess.run(generated_image_output,
                                feed_dict={z_placeholder: z_batch})
    #生成的向量重塑
    generated_image = generated_image.reshape([28, 28])
    plt.imshow(generated_image, cmap='Greys')

#设定张量图
tf.reset_default_graph()
#设定包大小
batch_size = 50
#生成器噪音
z_placeholder = tf.placeholder(tf.float32, [None, z_dimensions], name='z_placeholder')
# z_placeholder is for feeding input noise to the generator
#判别器输入
x_placeholder = tf.placeholder(tf.float32, shape = [None,28,28,1], name='x_placeholder')
# x_placeholder is for feeding input images to the discriminator
#存储生成器图片
Gz = generator(z_placeholder, batch_size, z_dimensions)
# Gz holds the generated images
#存储判别器的输出
Dx = discriminator(x_placeholder)
# Dx will hold discriminator prediction probabilities
# for the real MNIST images
#存储生成器图片的判别后的概率
Dg = discriminator(Gz, reuse_variables=True)
# Dg will hold discriminator prediction probabilities for generated images

#判别器真实图片输出与1的交叉熵
d_loss_real = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits = Dx, labels = tf.ones_like(Dx)))
#判别器生成图片输出与0的交叉熵
d_loss_fake = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits = Dg, labels = tf.zeros_like(Dg)))

g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits = Dg, labels = tf.ones_like(Dg)))

#存储训练变量
tvars = tf.trainable_variables()
#判别器权重、偏置
d_vars = [var for var in tvars if 'd_' in var.name]
#生成器权重、偏置
g_vars = [var for var in tvars if 'g_' in var.name]
#输出判别器name
print([v.name for v in d_vars])
#输出生成器name
print([v.name for v in g_vars])

# Train the discriminator
#训练判别器（生成图片）
d_trainer_fake = tf.train.AdamOptimizer(0.0003).minimize(d_loss_fake, var_list=d_vars)
#训练判别器（真实图片）
d_trainer_real = tf.train.AdamOptimizer(0.0003).minimize(d_loss_real, var_list=d_vars)

# Train the generator
#训练生成器
g_trainer = tf.train.AdamOptimizer(0.0001).minimize(g_loss, var_list=g_vars)

# From this point forward, reuse variables
#获取变量
tf.get_variable_scope().reuse_variables()

#生成器损失
tf.summary.scalar('Generator_loss', g_loss)
#判别器对真实图片的损失
tf.summary.scalar('Discriminator_loss_real', d_loss_real)
#判别器对生成图片的损失
tf.summary.scalar('Discriminator_loss_fake', d_loss_fake)
#获取生成图
images_for_tensorboard = generator(z_placeholder, batch_size, z_dimensions)
#图像写入summary便于查看
tf.summary.image('Generated_images', images_for_tensorboard, 5)
#管理summary
merged = tf.summary.merge_all()
#图像名设定
logdir = "tensorboard/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S") + "/"
#结果写入tensorboard
writer = tf.summary.FileWriter(logdir, sess.graph)

#'''
#设定会话
sess = tf.Session()
#启动会话
sess.run(tf.global_variables_initializer())

# Pre-train discriminator
#预训练，便于设定权重和偏置
for i in range(300):
    #初始化zbatch用于预训练
    z_batch = np.random.normal(0, 1, size=[batch_size, z_dimensions])
    #真实图片的遍历
    real_image_batch = mnist.train.next_batch(batch_size)[0].reshape([batch_size, 28, 28, 1])
    #获取真实图片损失和生成图片损失
    _, __, dLossReal, dLossFake = sess.run([d_trainer_real, d_trainer_fake, d_loss_real, d_loss_fake],
                                           {x_placeholder: real_image_batch, z_placeholder: z_batch})
    #每100批进行一次输出
    if(i % 100 == 0):
        print("dLossReal:", dLossReal, "dLossFake:", dLossFake)

# Train generator and discriminator together
#同时进行生成器和判别器的训练
for i in range(100000):
    #提取真实图片批
    real_image_batch = mnist.train.next_batch(batch_size)[0].reshape([batch_size, 28, 28, 1])
    #初始化zbatch用于预训练
    z_batch = np.random.normal(0, 1, size=[batch_size, z_dimensions])

    # Train discriminator on both real and fake images
    #获取真实图片损失和生成图片损失
    _, __, dLossReal, dLossFake = sess.run([d_trainer_real, d_trainer_fake, d_loss_real, d_loss_fake],
                                           {x_placeholder: real_image_batch, z_placeholder: z_batch})

    # Train generator
    #初始化zbatch用于预训练
    z_batch = np.random.normal(0, 1, size=[batch_size, z_dimensions])
    #启动会话训练
    _ = sess.run(g_trainer, feed_dict={z_placeholder: z_batch})
    #每10次更新一次
    if i % 10 == 0:
        # Update TensorBoard with summary statistics
        #zbatch初始化
        z_batch = np.random.normal(0, 1, size=[batch_size, z_dimensions])
        #赋值summary便于管理
        summary = sess.run(merged, {z_placeholder: z_batch, x_placeholder: real_image_batch})
        #写入summary
        writer.add_summary(summary, i)
    #每100次输出一次
    if i % 100 == 0:
        # Every 100 iterations, show a generated image
        #输出遍历次数、时间
        print("Iteration:", i, "at", datetime.datetime.now())
        #初始化zbatch用于预训练
        z_batch = np.random.normal(0, 1, size=[1, z_dimensions])
        #生成图像
        generated_images = generator(z_placeholder, 1, z_dimensions)
        #启动会话
        images = sess.run(generated_images, {z_placeholder: z_batch})
        #图像组织
        plt.imshow(images[0].reshape([28, 28]), cmap='Greys')
        #图像显示
        plt.show()

        # Show discriminator's estimate
        #组织图像
        im = images[0].reshape([1, 28, 28, 1])
        #图像判别
        result = discriminator(x_placeholder)
        #估计结果
        estimate = sess.run(result, {x_placeholder: im})
        #输出结果
        print("Estimate:", estimate)
#'''
#调用存储器
saver = tf.train.Saver()
#开始会话
with tf.Session() as sess:
    #获取存储的模型
    saver.restore(sess, 'pretrained-model/pretrained_gan.ckpt')
    #设定批大小
    z_batch = np.random.normal(0, 1, size=[10, z_dimensions])
    #存储模型
    z_placeholder = tf.placeholder(tf.float32, [None, z_dimensions], name='z_placeholder')
    #运用已有模型生成图像
    generated_images = generator(z_placeholder, 10, z_dimensions)
    #启动会话
    images = sess.run(generated_images, {z_placeholder: z_batch})
    #遍历输出图像
    for i in range(10):
        #提取灰度图像
        plt.imshow(images[i].reshape([28, 28]), cmap='Greys')
        #图像显示
        plt.show()


#!usr/bin/env python

def swap_unique_keys_values(d):
    s = {}
    for k in d:
        if d[k] in s:
            del(s[d[k]])
        else:
            s[d[k]] = k
    return s


from typing import List, Optional, Tuple

import networkx as nx
import pennylane as qml
from pennylane import numpy as np

def clustered_chain_graph(
    n: int, r: int, k: int, q1: float, q2: float, seed: Optional[int] = None
) -> Tuple[nx.Graph, List[List[int]], List[List[int]]]:
    """
    Function to build clustered chain graph

    Args:
        n (int): number of nodes in each cluster
        r (int): number of clusters
        k (int): number of vertex separators between each cluster pair
        q1 (float): probability of an edge connecting any two nodes in a cluster
        q2 (float): probability of an edge connecting a vertex separator to any node in a cluster
        seed (Optional[int]=None): seed for fixing edge generation

    Returns:
        nx.Graph: clustered chain graph
    """

    if r <= 0 or not isinstance(r, int):
        raise ValueError("Number of clusters must be an integer greater than 0")

    clusters = []
    for i in range(r):
        _seed = seed * i if seed is not None else None
        cluster = nx.erdos_renyi_graph(n, q1, seed=_seed)
        nx.set_node_attributes(cluster, f"cluster_{i}", "subgraph")
        clusters.append(cluster)

    separators = []
    for i in range(r - 1):
        separator = nx.empty_graph(k)
        nx.set_node_attributes(separator, f"separator_{i}", "subgraph")
        separators.append(separator)

    G = nx.disjoint_union_all(clusters + separators)

    cluster_nodes = [
        [n[0] for n in G.nodes(data="subgraph") if n[1] == f"cluster_{i}"] for i in range(r)
    ]
    separator_nodes = [
        [n[0] for n in G.nodes(data="subgraph") if n[1] == f"separator_{i}"] for i in range(r - 1)
    ]

    rng = np.random.default_rng(seed)

    for i, separator in enumerate(separator_nodes):
        for s in separator:
            for c in cluster_nodes[i] + cluster_nodes[i + 1]:
                if rng.random() < q2:
                    G.add_edge(s, c)

    return G, cluster_nodes, separator_nodes

def get_qaoa_circuit(
    G: nx.Graph,
    cluster_nodes: List[List[int]],
    separator_nodes: List[List[int]],
    params: Tuple[Tuple[float]],
    layers: int = 1,
) -> qml.tape.QuantumTape:
    """
    Function to build QAOA max-cut circuit tape from graph including `WireCut`
    operations

    Args:
        G (nx.Graph): problem graph to be solved using QAOA
        cluster_nodes (List[List[int]]): nodes of the clusters within the graph
        separator_nodes (List[List[int]]): nodes of the separators in the graph
        params (Tuple[Tuple[float]]): parameters of the QAOA circuit to be optimized
        layers (int): number of layer in the QAOA circuit

    Returns:
        QuantumTape: the QAOA tape containing `WireCut` operations
    """
    wires = len(G)
    r = len(cluster_nodes)

    cost, _ = qml.qaoa.maxcut(G)

    with qml.tape.QuantumTape() as tape:
        for w in range(wires):
            qml.Hadamard(wires=w)

        for l in range(layers):
            gamma, beta = params[l]

            for i, c in enumerate(cluster_nodes):
                if i == 0:
                    current_separator = []
                    next_separator = separator_nodes[0]
                elif i == r - 1:
                    current_separator = separator_nodes[-1]
                    next_separator = []
                else:
                    current_separator = separator_nodes[i - 1]
                    next_separator = separator_nodes[i]

                for cs in current_separator:
                    qml.WireCut(wires=cs)

                nodes = c + current_separator + next_separator
                subgraph = G.subgraph(nodes)

                for edge in subgraph.edges:
                    qml.IsingZZ(2*gamma, wires=edge) # multiply param by 2 for consistency with analytic cost

            # mixer layer
            for w in range(wires):
                qml.RX(2*beta, wires=w)

            # reset cuts
            if l < layers - 1:
                for s in separator_nodes:
                    qml.WireCut(wires=s)

        [qml.expval(op) for op in cost.ops if not isinstance(op, qml.ops.identity.Identity)]

    return tape


import cv2
import numpy as np

from skill_scraping.image_matcher import ImageMatcher

class SkillClassifier:
    def __init__(self, images):
        self.image_locator = ImageMatcher()

        self.spells = {}
        self.point_history = []

        for filename, image in images.items():
            preprocessed = self.image_locator.preprocess(image)
            kp, desc = self.image_locator.kp_desc(preprocessed)

            self.spells[filename] = {
                "img_org": cv2.resize(image, (64, 64)),
                "img_pre": preprocessed,
                "kp": kp,
                "desc": desc,
                "hist": self.calc_hist(cv2.cvtColor(image, cv2.COLOR_BGR2HSV))
            }

    def calc_hist(self, img1_hsv):
        hist_img1 = cv2.calcHist([img1_hsv], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])
        hist_img1 = cv2.normalize(hist_img1, None, norm_type=cv2.NORM_MINMAX).flatten()

        return hist_img1

    def comp_hist(self, h1, h2):
        return cv2.compareHist(h1, h2, cv2.HISTCMP_CORREL)

    def template_match(self, i1, i2):
        res = cv2.matchTemplate(i1, i2, cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

        return max_val

    def get_spell_name(self, skill_img):
        i1 = cv2.resize(skill_img, (64, 64))

        img1_hsv = cv2.cvtColor(skill_img, cv2.COLOR_BGR2HSV)
        h, s, v = cv2.split(img1_hsv)

        mean_s = np.mean(s)
        mean_v = np.mean(v)

        mean_t = (mean_s / 80 + mean_v / 60) / 2

        if mean_v < 25 or mean_t < 0.95:
            return None

        hist = self.calc_hist(img1_hsv)

        result_hist = {k: self.comp_hist(v["hist"], hist) for k, v in self.spells.items()}
        result_hist = {k: v for k, v in sorted(result_hist.items(), reverse=True, key=lambda item: item[1])}
        result_hist = dict(list(result_hist.items())[:100])

        results_match = {k: self.template_match(v["img_org"], i1) for k, v in self.spells.items() if k in result_hist}

        results_comb = {k: (v + result_hist[k] * 0.75) / 2 for k, v in results_match.items()}

        results = {k: v for k, v in sorted(results_comb.items(), reverse=True, key=lambda item: item[1])}

        spellname, score = list(results.items())[0]

        if score < 0.4:
            return None

        return spellname

    def find_spells(self, top_img):
        found_spells = []

        preprocessed_top = self.image_locator.preprocess(top_img)
        kp_top, desc_top = self.image_locator.kp_desc(preprocessed_top)

        for spell, data in self.spells.items():
            matches = self.image_locator.match_descriptors(data["desc"], desc_top)
            good = self.image_locator.good_matches(matches, 0.5)

            if len(good) > 4:
                points = self.image_locator.get_points(data["img_pre"], data["kp"], kp_top, good)

                if points is not None:
                    found_spells.append(spell)
                    self.point_history.append(points)

        return found_spells

    def get_skill_image(self, top_img, avg):
        pts2 = np.float32([[0, 0], [0, 64 - 1], [64 - 1, 64 - 1], [64 - 1, 0]]).reshape(-1, 1, 2)
        M = cv2.getPerspectiveTransform(avg.astype(np.float32), pts2)
        return cv2.warpPerspective(top_img, M, (64, 64))

    def get_skill_images(self, top_img, averages):
        skill_images = []

        for avg in averages:
            skill_images.append(self.get_skill_image(top_img, avg))

        return skill_images


import paho.mqtt.client as mqtt
import time
import RPi.GPIO as GPIO
import datetime
GPIO.setmode(GPIO.BOARD)
GPIO.setup(18,GPIO.OUT)
GPIO.setup(22,GPIO.OUT)
a=open("sensor.txt","w")
def led1act():
        GPIO.output(18,True)
        time.sleep(0.5)
        a.write(hactual+str("LED 1 ENCENDIDO")+"\n")
        c=("LED 1 ACTIVADO")
        mqtt.publish("mdpilatuna.fie@unach.edu.ec/servidor",str(c))
def led1dest():
        GPIO.output(18,False)
        time.sleep(1)
        a.write(hactual+str("LED 1 PAGADO")+"\n")
        c=("LED 1 APAGADO")
        mqtt.publish("mdpilatuna.fie@unach.edu.ec/servidor",str(c))
def led2act():
        GPIO.output(22,True)
        time.sleep(0.5)
        a.write(hactual+str("LED 2 ENCENDIDO")+"\n")
        c=("LED 2 ACTIVADO")
        mqtt.publish("mdpilatuna.fie@unach.edu.ec/servidor",str(c))
def led2dest():
        GPIO.output(22,False)
        time.sleep(1)
        a.write(hactual+str("LED 2 PAGADO")+"\n")
        c=("LED 2 APAGADO")
        mqtt.publish("mdpilatuna.fie@unach.edu.ec/servidor",str(c))
def on_message(client,obj,msg):
        accion=(msg.payload.decode("utf").split("")[0])
        intclave=(msg.payload.decode("utf-8").split("")[1])
        inttext=(msg.payload.decode("utf-8").split("")[2])
        print(accion)
        if intclave1==inttext1:
            if accion=="led1encendida":
                 led1act()
        print(intclave1)
        print(inttext1)
        if intclave1==inttext1:
            if accion=="led1apagada":
                 led1dest()
        print(intclave1)
        print(inttext1)
        if intclave1==inttext1:
            if accion=="led2encendida":
                 led2act()
        print(intclave1)
        print(inttext1)
        if intclave1==inttext1:
            if accion=="led2apagada":
                 led2dest()
        print(intclave1)
        print(inttext1)
mqttc = mqtt.Client()
mqttc.on_message = on_message
mqttc.username_pw_set("mdpilatuna.fie@unach.edu.ec","quitociudadhermosa")
mqttc.connect("maqiatto.com", 1883)
mqttc.subscribe("mdpilatuna.fie@unach.edu.ec/dispositivo", 0)
rc=0
print("iniciando.....")
i=0
while rc ==0:
        time.sleep(2)
        rc=mqttc.loop()
        i=i+1
        hactual=datetime.datetime.now().strftime("%a,%d,%b,%Y,%H,%S")
        print(hactual)


import argparse
import string

import utils
import filerepair
import logger

def ParseCommandLineArguments():
	rtn = utils.DefaultOpts()

	parser = argparse.ArgumentParser(description='construct a "RAID" file for the given input-file')
	parser.add_argument( '-C', nargs=1, type=str, help='read opts file' )
	parser.add_argument( '-L', nargs=1, type=str, help='send output to log file' )
	parser.add_argument( '-b', nargs=1, type=str, help='set the block size (default='+
		str(rtn['block_size'])+')' )
	parser.add_argument( '-c', nargs=1, type=str, help='set the cksum algorithm (default='+
		rtn['cksum_algo']+')' )
	parser.add_argument( '-p', nargs=1, type=str, help='set the number of parity disks (default='+
		str(rtn['num_parity_disks'])+')' )
	parser.add_argument( '-i', action='count', help='use interleaved parity' )
	parser.add_argument( '-r', action='count', help='use Reed-Solomon parity' )
	parser.add_argument( '-X', action='count', help='use hypercube-raid system' )
	parser.add_argument( '-v', action='count', help='verbose output' )
	parser.add_argument( '-V', action='count', help='really verbose output' )
	parser.add_argument( 'command', nargs=1, help='command to execute (create, verify, repair)' )
	parser.add_argument( 'filelist', nargs='+', help='file(s) to work with' )

	#
	# parse the command-line arguments
	params = vars( parser.parse_args() )

	# set a new opts file
	if( params['C'] != None ):
		#rtn['opts_file'] = params['C'][0]
		# parse the opts file
		rtn = utils.read_config_file( params['C'][0], rtn )

	# set the number of stripes
	if( params['p'] != None ):
		rtn['num_parity_disks'] = int( params['p'][0] )

	if( params['b'] != None ):
		rtn['block_size'] = utils.convert_from_kmgt( params['b'][0] )

	# XOR/RAID-4/5 parity or Reed-Solomon
	if( params['i'] != None ):
		rtn['parity_type'] = 'i'
	elif( params['r'] != None ):
		rtn['parity_type'] = 'r'
	elif( params['X'] != None ):
		rtn['parity_type'] = 'x'

	# set cksum algorithm (if needed)
	if( params['c'] != None ):
		rtn['cksum_algo'] = string.upper(params['c'][0])

	# make the code a bit more readable
	if( params['v'] != None ):
		rtn['verbose'] = params['v']
	if( params['V'] != None ):
		rtn['verbose'] += 10*params['V']

	# log to file?
	if( params['L'] != None ):
		rtn['log_file'] = params['L'][0]

	# pass the command through
	rtn['command'] = params['command'][0]

	# pass any filenames through
	rtn['file_list'] = params['filelist']

	return rtn

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

def main():
	# parse the command-line arguments (starts with DefaultOpts() )
	opts = ParseCommandLineArguments()

	# open the log (to either stdout or file)
	logger.openLog( opts )

	# parse the opts file
	#if( opts['opts_file'] != None ):
	#	opts = read_config_file( opts['opts_file'], opts )

	err = -200
	command = opts['command']

	if( command == 'create' ):
		# create cksum-data for a file
		infile = opts['file_list'][0]
		chkfile = utils.calc_chk_filename( infile, opts )
		err = filerepair.create_from_file( infile, chkfile, opts )

	elif( command == 'verify' ):
		# to verify a file, we need a cksum-file to compare to
		infile = opts['file_list'][0]
		if( len(opts['file_list']) >= 2 ):
			chkfile = opts['file_list'][1]
		else:
			chkfile = utils.calc_chk_filename( infile, opts )
		err = filerepair.verify_file( infile, chkfile, opts )

	elif( command == 'repair' ):
		# to repair a file, we need a cksum-file to compare to
		infile = opts['file_list'][0]
		if( len(opts['file_list']) >= 2 ):
			chkfile = opts['file_list'][1]
		else:
			chkfile = utils.calc_chk_filename( infile, opts )
		if( len(opts['file_list']) >= 3 ):
			repfile = opts['file_list'][2]
		else:
			repfile = utils.calc_rep_filename( infile, opts )
		err = filerepair.repair_file( infile, chkfile, repfile, opts )

	elif( command == 'createall' ):
		# create cksum-data for all files in dir (per opts file)
		utils.go_nice( opts )
		inpath = opts['file_list'][0]
		def cmd_create( infile, _opts ):
			chkfile = utils.calc_chk_filename( infile, _opts )
			err = filerepair.create_from_file( infile, chkfile, _opts )
			return err

		err = utils.walk_directory_tree( inpath, opts, cmd_create )

	elif( command == 'verifyall' ):
		# verify all files in a dir (per opts file)
		utils.go_nice( opts )
		inpath = opts['file_list'][0]
		def cmd_verify( infile, _opts ):
			chkfile = utils.calc_chk_filename( infile, _opts )
			err = filerepair.verify_file( infile, chkfile, _opts )
			return err

		err = utils.walk_directory_tree( inpath, opts, cmd_verify )

	elif( command == 'repairall' ):
		# repair all files in a dir (per opts file)
		utils.go_nice( opts )
		inpath = opts['file_list'][0]
		def cmd_repair( infile, _opts ):
			chkfile = utils.calc_chk_filename( infile, _opts )
			repfile = utils.calc_rep_filename( infile, _opts )
			err = filerepair.repair_file( infile, chkfile, repfile, _opts )
			return err

		err = utils.walk_directory_tree( inpath, opts, cmd_repair )

	elif( command == 'updateall' ):
		# create or verify all files in a dir (per opts file)
		utils.go_nice( opts )
		inpath = opts['file_list'][0]
		def cmd_update( infile, _opts ):
			chkfile = utils.calc_chk_filename( infile, _opts )
			# if cksum file exists, then verify it
			if( file_exists(chkfile) ):
				err = filerepair.verify_file( infile, chkfile, _opts )
			# else create it
			else:
				err = filerepair.create_from_file( infile, chkfile, _opts )
			return err

		err = utils.walk_directory_tree( inpath, opts, cmd_update )

	else:
		# shouldn't be able to get here!
		print( "* Error: unknown command" )
		err = -100

	# close/clean-up the log file
	logger.closeLog()

	exit( err )

if __name__ == '__main__':
	main()


'''
Created on Dec 19, 2017

@author: ghazy
'''

from root.nested.dataAccess.quandl_data_object import QuandlDataObject
from root.nested.interestRateModeling.interest_rates import HeathJarrowMortonModel

import pandas as pd
import statsmodels.tsa.api as smt
import statsmodels.api as sm
import scipy.stats as scs

import matplotlib.pyplot as plt

p=print

def ts_plot(y, lags=None, figsize=(10, 8), style='bmh', title='Time Series Analysis Plots'):
    if not isinstance(y, pd.Series):
        y = pd.Series(y)
    with plt.style.context(style):
        fig = plt.figure(figsize=figsize)
        layout = (3,2)
        ts_ax = plt.subplot2grid(layout, (0,0), colspan=2)
        acf_ax = plt.subplot2grid(layout, (1,0))
        pacf_ax = plt.subplot2grid(layout, (1,1))
        qq_ax = plt.subplot2grid(layout, (2,0))
        pp_ax = plt.subplot2grid(layout, (2,1))
        y.plot(ax=ts_ax)
        ts_ax.set_title(title)
        smt.graphics.plot_acf(y, lags=lags, ax=acf_ax, alpha=0.5)
        smt.graphics.plot_pacf(y, lags=lags, ax=pacf_ax, alpha=0.5)
        sm.qqplot(y, line='s', ax=qq_ax)
        qq_ax.set_title('QQ Plot')
        scs.probplot(y, sparams=(y.mean(), y.std()), plot=pp_ax)
        plt.tight_layout()
        plt.show()
    return

qdo = QuandlDataObject('INTEREST_RATES',
                       'US_TREASURY_YIELD_CURVE',
                       '.csv')

yield_curve_df = qdo.get_df()
yield_curve_df.columns = [c.replace(' ', '_') for c in yield_curve_df.columns]
print(yield_curve_df.info())
#yield_curve_df.dropna(subset=[yield_curve_df.columns[0]], inplace=True) # drop any rows where first column is nan
#yield_curve_df.dropna(inplace=True)
two_yr_y = yield_curve_df['10_YR']
#_ = ts_plot(two_yr_y, lags=30)

hjm = HeathJarrowMortonModel(yield_curve_df)
hjm.get_df_info()
yield_curve_df = hjm.vectorized_create_yield_curve() # the returned Dataframe here contains the yield curve object for each date

# interpolate first with Piecewise Cubic hermite spline funciton, just as the treasury.gov data does.
# this is the first step toward getting the spot curve from the par curve in treasury.gov data
hjm.do_interpolation(interp_method='PCS') # PCS is the default, but just for clarity sake, we pass in the arguement
# once we have the interpolated par yield curve, now we can bootstrap to get spot rates.
hjm.do_bootstrap_spot()
#hjm.do_interpolation(interp_method='NSS')
hjm.do_NSS_params_analysis()
# at this point, we've got the spot rates of the interoplated maturities
# now we can continue with NSS and the forecasting process.
#hjm.calc_fmin_stats()


Import("env", "app_env", "rom_env", "c_runtime", "app_startup", "rom_startup", "ipcfg")

env = env.Clone()
env.Append(CPPPATH=["uip/uip", "."])

app_env = app_env.Clone()
app_env.Append(CPPPATH=["uip/uip", "."])

uip = env.Object(Split('uip/uip/uip.c uip/uip/uip_arp.c uip/uip/uiplib.c uip/uip/timer.c uip/ccpu/uip_buf.asm uip/ccpu/chksum.asm'))

# Apps
httpd_app = app_env.Program('httpd', Split('main.c httpd.c') + c_runtime + app_startup + uip + ipcfg, LIBS=['c', 'sys'])

Return('httpd_app')


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul  2 15:42:35 2020

@author: sahyadri
"""

from astroquery.vizier import Vizier
import requests
from bs4 import BeautifulSoup
from astroquery.simbad import Simbad
import numpy as np
from astropy.table import Table, vstack
from astropy.io import ascii
from astropy import units as u
from astropy.coordinates import SkyCoord, get_constellation
import pandas as pd
import kaggle
from astroquery.gaia import Gaia
import glob, os

print('Downloading constellation_borders.csv...')
catalogue_list = Vizier.find_catalogs("Constellation")#This loads all the catalogs by the keyword "constellation"
Vizier.ROW_LIMIT = -1
catalog = Vizier.get_catalogs("VI/49")[1]#This selects the 2nd of three tables that were found by the key-word search. This table contains relevant data
catalog.remove_columns(['cst','type'])
coords = SkyCoord(catalog['RAJ2000'],catalog['DEJ2000'],unit="deg")
const = coords.get_constellation()
catalog.add_column(const,name="Constellation", index = 2)
catalog.write("constellation_borders.csv",format="csv",overwrite="True")
print('\n')
print('Done')
print('\n')
print('Downloading Messier Catalogue...')

#the next three lines are to simplify the output table
Simbad.reset_votable_fields()
Simbad.remove_votable_fields('coordinates')
Simbad.add_votable_fields('otype(3)', 'ra(d;A;ICRS;J2000;2000)', 'dec(d;D;ICRS;J2000;2000)','flux(B)','flux(V)')#These are all the columns added to the table

result_table = Simbad.query_catalog("Messier")#This asks the SIMBAD database to list all objects from the messier catalog
result_table['FLUX_V'].name = 'V'
result_table['OTYPE_3']=[x.decode('utf8') for x in result_table['OTYPE_3']]
result_table['MAIN_ID']=[x.decode('utf8') for x in result_table['MAIN_ID']]
result_table['RA_d_A_ICRS_J2000_2000'].name = "RAJ2000"
result_table['DEC_d_D_ICRS_J2000_2000'].name = "DEJ2000"
result_table['B-V'] = result_table['FLUX_B'] - result_table['V']
result_table.remove_column('FLUX_B')

coords = SkyCoord(result_table['RAJ2000'],result_table['DEJ2000'],unit="deg")
const = coords.get_constellation()
const_abr = coords.get_constellation(short_name = "True")
result_table.add_column(const,name="Constellation", index = 2)

otype = result_table['OTYPE_3']
internal_id = [otype[i]+'_'+const_abr[i]+'_'+str(i+1) for i in range(len(const))]
result_table.add_column(internal_id, name = "Internal ID Number", index = 0)

result_table.write("messier_objects.csv",format="csv",overwrite="True")#creates a csv file

Simbad.reset_votable_fields()#renders the prev changes to simbad class temporary.
print('\n')
print('Done')
print('\n')
print('Downloading NGC catalogue...')

#CHANGE GET_CONSTELLATION EQUINOX FROM B1875 TO 2000
v = Vizier(columns = ['Name','Type','mag','RA (deg)','Dec (deg)'])#Columns added to table
v.ROW_LIMIT = -1
result_table = v.get_catalogs("VII/118/ngc2000")[0]

result_table['Name'] = ['IC '+x[1:] if x[0]=='I' else 'NGC '+x for x in result_table['Name']]
result_table['Type'] = ['Gal' if x=='Gx' else 'OpC' if x=='OC' else 'GlC' if x=='Gb' else 'PN' if x=='Pl' else 'Str' if x=='*' or x=='D*' or x=='***' else '-' if x == '' or x=='-' or x=='?' else x for x in result_table['Type']]

coords = SkyCoord(result_table['_RAJ2000'],result_table['_DEJ2000'],unit="deg")
const = coords.get_constellation()
const_abr = coords.get_constellation(short_name = "True")
result_table.add_column(const,name="Constellation", index = 2)

otype = result_table['Type']
internal_id = [otype[i]+'_'+const_abr[i]+'_'+str(i+1) if otype[i]!='-' else 'notype'+'_'+const_abr[i]+'_'+str(i+1) for i in range(len(const))]
result_table.add_column(internal_id, name = "Internal ID Number", index = 0)
result_table.write("NGC.csv",format="csv",overwrite="True")

#cross catalogue for NGC
v = Vizier(columns = ['Object','Name'])
v.ROW_LIMIT = -1
v.TIMEOUT = 1000
cross_catalog = v.get_catalogs('VII/118/names')[0]
cross_catalog['Name'] =  ['IC '+x.split()[1] if len(x.split())==2 and x.split()[0]=="I" else 'IC'+x.split()[0][1:] if len(x.split())==1 and x.split()[0]=="I" else 'NGC '+x for x in cross_catalog['Name']]
cross_catalog.write("DsCrossCatalog.csv",format='csv',overwrite="True")

ccat = pd.read_csv('DsCrossCatalog.csv')
ccat = pd.DataFrame(ccat)
ccat = ccat.loc[~ccat.Name.duplicated(keep='first')]
ntable= pd.read_csv('NGC.csv')
ntable = pd.DataFrame(ntable)
ntable.insert(2,"Common Name",np.zeros(len(ntable['_RAJ2000'])))
ntable['Common Name'] = ntable.Name.map(ccat.set_index('Name').Object,na_action="ignore")
ntable.to_csv('NGC.csv')
ntable = Table.read('NGC.csv')
ntable.remove_columns(['col0'])
ntable.write('NGC.csv',format='csv',overwrite="True")

print('\n')
print('Done')
print('\n')

#Download the star name file
kaggle.api.authenticate()
kaggle.api.dataset_download_files('ecotner/named-stars/IAU-CSN.csv', path='/home/sahyadri/Desktop/Star-Hopping', unzip=True)

#CROSS CATALOG
v = Vizier(columns = ['HD','TYC','HIP','Vmag','Fl','Bayer','Cst'])
v.ROW_LIMIT = -1
v.TIMEOUT = 1000
cross_catalog = v.get_catalogs('IV/27A/catalog')[0]
bayer_const = [x['Bayer']+' '+x['Cst'] for x in cross_catalog]
cross_catalog.remove_columns("Bayer")
cross_catalog['BayerConst'] = bayer_const
cross_catalog.write("CrossCatalog.csv",format='csv',overwrite="True")

print('Tycho-2 Catalogue')

run_count = 0
run = True
last_id = 0
while run:

    MinVmag = input('(INT ONLY) Input minimum value of Vmag (skippable) ',)
    MaxVmag = int(input('(INT ONLY) Input maximum value of Vmag ',))

    if type(MaxVmag)!=int:
        print("invalid entry")
        continue
    if MinVmag!='':
        MinVmag = int(MinVmag)

    run_count = run_count +1
    if MinVmag=='':
        filter_input = "<{}".format(MaxVmag)
    else:
        filter_input = "{}..{}".format(MinVmag, MaxVmag)

    v = Vizier(columns = ['HIP','TYC','HD','_RAJ2000','DECJ2000','+Vmag','B-V'], column_filters = {"Vmag":"{}".format(filter_input)})
    v.ROW_LIMIT = 1000000000
    v.TIMEOUT = 1000
    catalog_stars = v.get_catalogs("I/239/tyc_main")[0]
    catalog_stars['Vmag'].name = "V"

    coords = SkyCoord(catalog_stars['_RAJ2000'],catalog_stars['_DEJ2000'],unit="deg")
    const = coords.get_constellation()
    const_abr = coords.get_constellation(short_name = "True")

    catalog_stars.add_column(const,name="Constellation", index = 0)

    internal_id = ["Str_"+const_abr[i]+"_"+f"{i+last_id+1:08d}" for i in range(len(catalog_stars['_RAJ2000']))]
    catalog_stars.add_column(internal_id, name="Internal ID Number", index = 0)

    catalog_stars.write("tycho_{}.csv".format(run_count),format="csv",overwrite = "True")
    last_id = last_id + len(catalog_stars['_RAJ2000'])

    #Adding common names to the stars
    names_table = pd.read_csv('IAU-CSN.csv')
    names_table = pd.DataFrame(names_table)
    ttable = pd.read_csv('tycho_{}.csv'.format(run_count))
    ttable = pd.DataFrame(ttable)
    names_table["HIP"] = [x if x!='-' else 0 for x in names_table["HIP"]]
    ttable.insert(1,"Name",np.zeros(len(ttable['TYC'])))
    names_table["HIP"] = pd.to_numeric(names_table['HIP'],errors='coerce')
    ttable['Name'] = ttable.HIP.map(names_table.set_index('HIP').Name)
    ttable.to_csv('tycho_{}.csv'.format(run_count))

    #The cross cataloguing part
    ccat = pd.read_csv('CrossCatalog.csv')
    ccat = pd.DataFrame(ccat)
    ccat["HIP"].fillna("0", inplace = True)
    ttable = pd.read_csv('tycho_{}.csv'.format(run_count))
    ttable = pd.DataFrame(ttable)
    ccat = ccat.loc[~ccat.HIP.duplicated(keep='first')]
    ttable.insert(4,"Bayer",np.zeros(len(ttable['_RAJ2000'])))
    ttable['Bayer'] = ttable.HIP.map(ccat.set_index('HIP').BayerConst,na_action="ignore")
    ttable.to_csv('tycho_{}.csv'.format(run_count))
    ttable = Table.read('tycho_{}.csv'.format(run_count))
    ttable.remove_columns(['col0','Unnamed: 0'])
    ttable.write('tycho_{}.csv'.format(run_count),format='csv',overwrite="True")

    while True:
        status = input("Another run of Tycho database download? (y/n)",)
        if status == "n":
            run = False
            break
        elif status == "y":
            run = True
            break
        else:
            print("invalid answer")

name_list = []
for file in glob.glob("tycho_*.csv"):
    name_list.append(file)
name_list.sort()
t = pd.concat([pd.read_csv(i) for i in name_list])
t.to_csv('tycho.csv')

print('Done')
print('\n')
g_status = input('Gaia - Do you want to skip? (y/n)',)
while True:
    if g_status == "y":
        g_run = False
        break
    elif g_status == "n":
        g_run = True
        break
    else:
        print('invalid answer')

run_count = 0
while g_run:
    print('Gaia dr1 catalogue')

    MinVmag = input('(INT ONLY) Input minimum value of Vmag (skippable)',)
    MaxVmag = int(input('(INT ONLY) Input maximum value of Vmag',))
    if type(MaxVmag)==int:
        break
    else:
        print("invalid entry")
        continue
    if MinVmag!='':
        MinVmag = int(MinVmag)

    if MinVmag=='':
        filter_input = "<{}".format(MaxVmag)
    else:
        filter_input = "between {} and {}".format(MinVmag, MaxVmag)
    run_count = run_count + 1

    Gaia.ROW_LIMIT = -1

    job = Gaia.launch_job_async("select ra,dec,phot_g_mean_mag from gaiadr1.gaia_source where (phot_g_mean_mag {}) order by phot_g_mean_mag".format(filter_input))
    r = job.get_results()
    r.write('gaia.csv',format='csv',overwrite="True")
    while True:
        status = input("Another run of Gaia database download? (y/n)",)
        if status == "n":
            g_run = False
            break
        elif status == "y":
            g_run = True
            break
        else:
            print("invalid answer")
print('Done')


# -*- coding: latin-1 -*-
import itertools
import numpy

import invariant_finder
import pddl
import timers

def expand_group(group, task, reachable_facts):
    result = []
    for fact in group:
        try:
            pos = list(fact.args).index("?X")
        except ValueError:
            result.append(fact)
        else:
            # NOTE: This could be optimized by only trying objects of the correct
            #       type, or by using a unifier which directly generates the
            #       applicable objects. It is not worth optimizing this at this stage,
            #       though.

            if len([a for a in fact.args if a == "?X"]) > 1:
                for pred in task.predicates:
                    if fact.predicate == pred.name:
                        predicate = pred
                        break

                arg_instanciated_obj = []
                index = 0
                for arg in fact.args:
                    arg_instanciated_obj.append([])
                    if arg == "?X":
                        for obj in task.objects:
                            if obj.type == predicate.arguments[index].type:
                                arg_instanciated_obj[index].append(obj.name)
                    else:
                        arg_instanciated_obj[index].append(arg)
                    index = index + 1

                all_possible_args = list(itertools.product(*arg_instanciated_obj))

                for newargs in all_possible_args:
                    atom = pddl.Atom(fact.predicate, newargs)
                    if atom in reachable_facts:
                        result.append(atom)

            else:
                for obj in task.objects:
                    newargs = list(fact.args)
                    newargs[pos] = obj.name
                    atom = pddl.Atom(fact.predicate, newargs)
                    if atom in reachable_facts:
                        result.append(atom)
    return result

def obtaing_const_args(groups):
    const_args = []
    for group in groups:
        const_group_args = []
        for atom in group:
            for arg in atom.args:
                if "?" not in arg and arg not in const_group_args:
                    const_group_args.append(arg)
        const_args.append(const_group_args)
    return const_args

def obtaing_const_args_funcs(groups, arguments):
    for group in groups:
        const_group_args = []
        if isinstance(group[0].predicate, pddl.f_expression.Increase) or \
                isinstance(group[0].predicate, pddl.f_expression.Decrease) or \
                isinstance(group[0].predicate, pddl.f_expression.Assign) or \
                isinstance(group[0].predicate, pddl.f_expression.GreaterThan) or \
                isinstance(group[0].predicate, pddl.f_expression.LessThan):
            name = group[0].predicate.fluent.symbol
            for arg in group[0].predicate.fluent.args:
                name = name + "-" + arg.name
            const_group_args.append(name)
            arguments.append(const_group_args)
    return arguments

def obtaing_const_args_extra(groups, arguments, reachable_facts):
    arguments_extra = []
    arguments_extra_list = []
    to_remove_list = []
    for group in groups:
        if not isinstance(group[0].predicate, str):
            arguments_extra.append([group[0].predicate.fluent.symbol])
            to_remove_list.append([])
            continue
        cands = {}
        to_remove = []
        for atom in group:
            if atom.predicate not in cands.keys():
                cands[atom.predicate] = []
                for arg in atom.args:
                    cands[atom.predicate].append(arg)
            else:
                if "_curr" in atom.predicate:
                    for arg in atom.args:
                        if arg not in cands[atom.predicate]:
                            cands[atom.predicate].append(arg)
                else:
                    arg_index = 0
                    for arg in atom.args:
                        if cands[atom.predicate][arg_index] != arg:
                            # if arg in cands[atom.predicate]:
                            #    cands[atom.predicate].remove(arg)
                            exists = False
                            for elem in to_remove:
                                if elem[0] == atom.predicate and elem[1] == arg:
                                    exists = True
                            if not exists:
                                to_remove.append([atom.predicate, cands[atom.predicate][arg_index]])
                                to_remove.append([atom.predicate, arg])
                        arg_index = arg_index + 1
        arguments_extra.append(cands)
        to_remove_list.append(to_remove)

    group_index = 0
    for arg_group in arguments_extra:
        arg_list = []
        if isinstance(arg_group, list):
            arguments_extra_list.append(arg_group)
            group_index = group_index + 1
            continue
        for pred, args in arg_group.items():
            for arg in args:
                if arg not in arg_list:
                    arg_list.append(arg)

        for arg in to_remove_list[group_index]:
            if arg[1] in arg_list:
                arg_list.remove(arg[1])

        arguments_extra_list.append(arg_list)
        group_index = group_index + 1

    return arguments_extra_list

def instantiate_groups(groups, task, reachable_facts):
    return [expand_group(group, task, reachable_facts) for group in groups]

def instantiate_function_groups(groups, task, functions):
    function_group_names = {}
    for func in functions:
        key = func.predicate.fluent.symbol + str(*func.predicate.fluent.args)
        if key not in function_group_names:
            function_group_names[key] = len(groups)
            groups.append([])
        if func not in groups[function_group_names[key]]:
            groups[function_group_names[key]].append(func)
    return groups

class GroupCoverQueue:
    def __init__(self, groups, arguments, partial_encoding):
        self.partial_encoding = partial_encoding
        if groups:
            self.max_size = max([len(group) for group in groups])
            self.groups_by_size = [[] for i in range(self.max_size + 1)]
            self.arguments = [[] for i in range(self.max_size + 1)]
            self.groups_by_fact = {}
            i = 0
            for group in groups:
                group = set(group)  # Copy group, as it will be modified.
                self.groups_by_size[len(group)].append(group)
                self.arguments[len(group)].append(arguments[i])
                for fact in group:
                    self.groups_by_fact.setdefault(fact, []).append(group)
                i = i + 1
            self._update_top()
        else:
            self.max_size = 0

    def __bool__(self):
        return self.max_size > 1

    def pop(self):
        result = list(self.top)  # Copy; this group will shrink further.
        if self.partial_encoding:
            for fact in result:
                for group in self.groups_by_fact[fact]:
                    group.remove(fact)
        self._update_top()
        return result

    def _update_top(self):
        while self.max_size > 1:
            max_list = self.groups_by_size[self.max_size]
            while max_list:
                candidate = max_list.pop()
                if len(candidate) == self.max_size:
                    self.top = candidate
                    return
                self.groups_by_size[len(candidate)].append(candidate)
            self.max_size -= 1

# I don't want to remove facts that have already been covered
# Thus, partial encoding is set to false for all cases
def choose_groups(groups, reachable_facts, functions, arguments, partial_encoding=False):
    queue = GroupCoverQueue(groups, arguments, partial_encoding=partial_encoding)
    uncovered_facts = reachable_facts.copy()

    # uncovered_funcs = functions.copy()
    result = []
    i = 0
    arguments_aux = []
    while queue:
        group = queue.pop()
        uncovered_facts.difference_update(group)
        result.append(group)

    for dummy in queue.arguments:
        if len(dummy):
            for arg in dummy:
                arguments_aux.append(arg)
    arguments_aux.reverse()

    for group in groups:
        if len(group) == 1 and isinstance(group[0].predicate, pddl.f_expression.Increase) and group not in result:
            result.append(group)

    print(len(uncovered_facts), "uncovered facts")
    # for fact in uncovered_facts:
    #  print fact
    result += [[fact] for fact in uncovered_facts]
    # result += [[func] for func in uncovered_funcs]
    return result, arguments_aux

def remove_func_redundant(groups, mutex_groups):
    index = 0
    removed = 0
    length = len(mutex_groups)
    for _ in range(length):
        if index >= len(groups):
            mutex_groups.pop(index - removed)
            removed = removed + 1
        index = index + 1

def build_translation_key(groups):
    group_keys = []
    for group in groups:
        group_key = [str(fact) for fact in group]
        group_key.append("<none of those>")
        group_keys.append(group_key)
    return group_keys

def collect_all_mutex_groups(groups, atoms, functions):
    # NOTE: This should be functionally identical to choose_groups
    # when partial_encoding is set to False. Maybe a future
    # refactoring could take that into account.
    all_groups = []
    uncovered_facts = atoms.copy()
    for group in groups:
        uncovered_facts.difference_update(group)
        all_groups.append(group)
    all_groups += [[fact] for fact in uncovered_facts]

    uncovered_funcs = functions.copy()
    all_groups += [[func] for func in uncovered_funcs]
    return all_groups

def compute_groups(task, atoms, functions, reachable_action_params, partial_encoding=False):
    groups = invariant_finder.get_groups(task, reachable_action_params)
    with timers.timing("Instantiating groups"):
        arguments = obtaing_const_args(groups)
        groups = instantiate_groups(groups, task, atoms)
    with timers.timing("Instantiating function groups"):
        groups = instantiate_function_groups(groups, task, functions)
        arguments = obtaing_const_args_funcs(groups, arguments)
    # TODO: I think that collect_all_mutex_groups should do the same thing
    #       as choose_groups with partial_encoding=False, so these two should
    #       be unified.
    with timers.timing("Collecting mutex groups"):
        mutex_groups = collect_all_mutex_groups(groups, atoms, functions)
    with timers.timing("Choosing groups", block=True):
        groups, arguments = choose_groups(groups, atoms, functions, arguments, partial_encoding=partial_encoding)
        arguments_ex = obtaing_const_args_extra(groups, arguments, atoms)
    with timers.timing("Removing redundant functional propositions"):
        remove_func_redundant(groups, mutex_groups)
    with timers.timing("Building translation key"):
        translation_key = build_translation_key(groups)
    return groups, mutex_groups, translation_key, arguments_ex, arguments

def get_fluents_in_runtime(groups):
    fluents_in_runtime = []
    dict_fluents_in_runtime = {}
    index = 0
    for group in groups:
        for item in group:
            if isinstance(item.predicate, pddl.f_expression.Increase) or \
                    isinstance(item.predicate, pddl.f_expression.Decrease) or \
                    isinstance(item.predicate, pddl.f_expression.Assign):
                fluents_in_runtime.append(item.predicate.fluent)
                dict_fluents_in_runtime[str(item.predicate.fluent)] = index
                break
        index = index + 1

    return fluents_in_runtime, dict_fluents_in_runtime


from ctypes import c_size_t
from dataclasses import dataclass
from typing import ClassVar
from pytest import fixture
from puft.core.ie.ie import Ie
from puft.core.test.mock import Mock

@dataclass
class CustomIe(Ie):
    name: str
    age: int
    tags: set[str]

@dataclass
class CustomIeMock(Mock):
    name: str
    age: int
    tags: set[str]

@fixture
def custom_ie_mock() -> CustomIeMock:
    return CustomIeMock(name='Test', age=12, tags={'hero', 'reckless'})

@fixture
def custom_ie(custom_ie_mock: CustomIeMock) -> CustomIe:
    return CustomIe(
        name=custom_ie_mock.name,
        age=custom_ie_mock.age,
        tags=custom_ie_mock.tags)

class TestIe():
    def test_custom(self, custom_ie: CustomIe, custom_ie_mock: CustomIeMock):
        expected_json: dict = {
            'custom': {
                'name': custom_ie_mock.name,
                'age': custom_ie_mock.age,
                'tags': custom_ie_mock.tags
            }
        }

        assert custom_ie.name == custom_ie_mock.name
        assert custom_ie.age == custom_ie_mock.age
        assert custom_ie.tags == custom_ie_mock.tags

        assert custom_ie.formatted_name == 'custom'
        assert custom_ie.get_json() == expected_json

        # Validate self through class method
        custom_ie.validate(custom_ie.get_json())

        json_custom_name: dict = custom_ie.get_json('testname')
        assert 'testname' in json_custom_name


'''
5. Provide a program to create tables (Employee, Department,
Project) in database Sqlite and insert the data.
• Make sure to add basic field, with employee to department and project relation.
• Make sure maintain M2M relation between employee and project.
'''

import sqlite3
from sqlite3 import Error

def create_connection(db_file):
    conn = None
    try:
        conn = sqlite3.connect(db_file)
        return conn
    except Error as e:
        print(e)

    return conn

def create_table(conn, create_table_sql):
    try:
        c = conn.cursor()
        c.execute(create_table_sql)
    except Error as e:
        print(e)

import sqlite3

def insertVaribleIntoEmployee(conn, Employee_id, name, city, DEPT_NO):
    try:
        c = conn.cursor()
        print("Connected to SQLite")

        sqlite_insert_with_param = """INSERT INTO Employee
                          ( Employee_id, name, city, DEPT_NO)
                          VALUES (?, ?, ?, ?);"""

        data_tuple = (Employee_id, name, city, DEPT_NO)
        c.execute(sqlite_insert_with_param, data_tuple)
        conn.commit()
        print("Python Variables inserted successfully into Employee table")

        c.close()

    except sqlite3.Error as error:
        print("Failed to insert Python variable into sqlite table", error)
    finally:
        if c:
            c.close()
            print("The SQLite connection is closed")

def insertVaribleIntoProjects(conn, Project_id, Project_name, Employee_id):
    try:
        c = conn.cursor()
        print("Connected to SQLite")

        sqlite_insert_with_param = """INSERT INTO projects
                          (Project_id ,Project_name,Employee_id)
                          VALUES (?, ?, ?);"""

        data_tuple = (Project_id, Project_name, Employee_id)
        c.execute(sqlite_insert_with_param, data_tuple)
        conn.commit()
        print("Python Variables inserted successfully into Projects table")

        c.close()

    except sqlite3.Error as error:
        print("Failed to insert Python variable into sqlite table", error)
    finally:
        if c:
            c.close()
            print("The SQLite connection is closed")

def insertVaribleIntoDepartment(conn, DEPT_NO, DEPT_NAME, LOCATION):
    try:
        c = conn.cursor()
        print("Connected to SQLite")

        sqlite_insert_with_param = """INSERT INTO Department
                          (DEPT_NO, DEPT_NAME, LOCATION)
                          VALUES (?, ?, ?);"""

        data_tuple = (DEPT_NO, DEPT_NAME, LOCATION)
        c.execute(sqlite_insert_with_param, data_tuple)
        conn.commit()
        print("Python Variables inserted successfully into Department table")

        c.close()

    except sqlite3.Error as error:
        print("Failed to insert Python variable into sqlite table", error)
    finally:
        if c:
            c.close()
            print("The SQLite connection is closed")

def main():
    database = r"pythonsqlite.db"

    sql_create_Employee_table = """ CREATE TABLE IF NOT EXISTS Employee(
                                     Employee_id integer(5) PRIMARY KEY,
                                     name char(30)NOT NULL,
                                     city char(35),
                                     DEPT_NO char(3)
                                     );"""
    sql_create_projects_table = """ CREATE TABLE IF NOT EXISTS projects (
                                         Project_id integer(10) PRIMARY KEY,
                                         Project_name char(40),
                                         Employee_id integer(5)
                                     );"""

    sql_create_Department_table = """
                                CREATE TABLE IF NOT EXISTS Department(
                                DEPT_NO char(3) NOT NULL,
                                DEPT_NAME  char(29) NOT NULL,
                                LOCATION  char(16) PRIMARY KEY
                                );"""

    # create a database connection
    conn = create_connection(database)

    # create tables
    if conn is not None:
        # create Employ table
        create_table(conn, sql_create_Employee_table)
        insertVaribleIntoEmployee(conn, 2, 'Joe', 'ghazipur', '02')
        insertVaribleIntoEmployee(conn, 3, 'Ben', 'varanasi', '04')
        # create projects table
        create_table(conn, sql_create_projects_table)
        insertVaribleIntoProjects(conn,232,"My4C",2)
        insertVaribleIntoProjects(conn, 242, "Bd's", 3)
        # create tasks table
        create_table(conn, sql_create_Department_table)
        insertVaribleIntoDepartment(conn,'34','Dilivery','Jaipur')
        insertVaribleIntoDepartment(conn, '30', 'Dev', 'Gurgava')
    else:
        print("Error! cannot create the database connection.")

if __name__ == '__main__':
    main()


import networkx as nx
import torch
from torch_geometric.data import Batch, Data

def increasing_mask(
    batch_size: int, seq_len: int, start_with_zero: bool = False
) -> torch.Tensor:
    """
    Return an increasing mask. Useful for tests. For example:
    batch_size = 3, seq_len = 2, start_with_zero = False
    [
        [1, 0],
        [1, 1],
        [1, 1],
    ]
    batch_size = 3, seq_len = 2, start_with_zero = True
    [
        [0, 0],
        [1, 0],
        [1, 1],
    ]
    """
    data: list[list[int]] = []
    for i in range(batch_size):
        if i < seq_len:
            if start_with_zero:
                data.append([1] * i + [0] * (seq_len - i))
            else:
                data.append([1] * (i + 1) + [0] * (seq_len - i - 1))
        else:
            data.append([1] * seq_len)
    return torch.tensor(data, dtype=torch.float)

class EqualityDiGraph(nx.DiGraph):
    def __eq__(self, o: object) -> bool:
        if not isinstance(o, EqualityDiGraph):
            return False

        return self.nodes.data() == o.nodes.data() and list(self.edges.data()) == list(
            o.edges.data()
        )

class EqualityData(Data):
    def __eq__(self, o: object) -> bool:
        if not isinstance(o, EqualityData):
            return False

        return (
            self.x.equal(o.x)
            and self.node_label_mask.equal(o.node_label_mask)
            and self.node_last_update.equal(o.node_last_update)
            and self.edge_index.equal(o.edge_index)
            and self.edge_attr.equal(o.edge_attr)
            and self.edge_label_mask.equal(o.edge_label_mask)
            and self.edge_last_update.equal(o.edge_last_update)
        )

class EqualityBatch(Batch):
    def __eq__(self, o: object) -> bool:
        if not isinstance(o, EqualityBatch):
            return False

        return (
            self.batch.equal(o.batch)
            and self.x.equal(o.x)
            and self.node_label_mask.equal(o.node_label_mask)
            and self.node_last_update.equal(o.node_last_update)
            and self.edge_index.equal(o.edge_index)
            and self.edge_attr.equal(o.edge_attr)
            and self.edge_label_mask.equal(o.edge_label_mask)
            and self.edge_last_update.equal(o.edge_last_update)
        )


import ldap3
changes_done = "test2"
changes_done = "test3"
SERVER='80.0.0.108'
BASEDN="OU=Delhi AISGlass,OU=AIS Users,DC=asahiindia,DC=com"
USER="test3@asahiindia.com"
CURREENTPWD="P@ssword@1234"
NEWPWD="P@ssword@12345679"

SEARCHFILTER='(&(userPrincipalName='+USER+')(objectClass=person))'
print(SEARCHFILTER)
USER_DN=""
USER_CN=""

ldap_server = ldap3.Server(SERVER, get_info=ldap3.ALL)
conn = ldap3.Connection(ldap_server, USER, CURREENTPWD, auto_bind=True)
conn.start_tls()
print(f"conn is = {conn}")
conn.search(search_base = BASEDN,
         search_filter = SEARCHFILTER,
         search_scope = ldap3.SUBTREE,
         attributes = ['cn', 'givenName', 'userPrincipalName'],
         paged_size = 5)

print(conn.entries)
for entry in conn.response:
    print(f"entry is {entry}")
    if entry["dn"] and entry["attributes"]:
        if entry.get("attributes").get("userPrincipalName"):
            if entry.get("attributes").get("userPrincipalName") == USER:
                USER_DN=entry.get("dn")
                USER_CN=entry.get("attributes").get("cn")

print("Found user:", USER_CN)

if USER_DN:
    print(USER_DN)
    print(ldap3.extend.microsoft.modifyPassword.ad_modify_password(conn, USER_DN, NEWPWD, CURREENTPWD,  controls=None))
else:
    print("User DN is missing!")


import pandas as pd
import version
# version : fileNo : bugNo

fileNums = []
vers = version.get_version_short_list()
for ver in vers:
    fileNum = []
    fileNum.append(ver)

    # get the number of module
    df = pd.read_csv('./../org/solr-' + ver + '/containment.txt', header=None)
    num = df.size
    fileNum.append(num)

    # get the number of bug module
    df = pd.read_csv('./../metrics/numBug/slr_' + ver + '_bgmd.csv', header=None)
    num = df.size
    fileNum.append(num)
    fileNums.append(fileNum)
records = pd.DataFrame(fileNums)
records.columns = ['version', 'moduls', 'bugs']
pd.DataFrame(records).to_csv( './../SOLR-INFORMATION.csv', index=False, cols=None )


# a = input("Enter the number: ")
# print(f"Multiplication tav]ble of {a} is: ")
# try:
#     for i in range(1, 11):
#         print(f"{int(a)} X {i} = {int(a)*i}")
# except:
#     print("Invalid Input!")

# print("Some imp lines of code")
# print("End of program")

# finally is used when we want to print something even
# if the function returns

# def func1():
#     try:
#       l = [1, 5, 6, 7]
#       i = int(input("Enter the index: "))
#       print(l[i])
#       return 1
#     except:
#         print("Some error occurred")
#         return 0

#     finally:
#         print("I am always executed")

#     #print("I am always executed")

# x = func1()
# print(x)

a = int(input("Enter any value between 5 and 9"))

if(a<5 or a>9):
    raise ValueError("Value should be between 5 and 9")


import argparse
import csv
from collections import OrderedDict
from datetime import date, datetime
from jira import JIRA
from prettytable import PrettyTable

JIRA_LOCATIONS = OrderedDict([
    ('JBOSS', 'https://issues.jboss.org'),
    ('HIBERNATE', 'https://hibernate.atlassian.net'),
    ('APACHE', 'https://issues.apache.org/jira')
])
FIELDS = ['project', 'summary', 'key', 'status', 'reporter', 'assignee', 'updated', 'comment']

_first_csv_domain = True

def check_negative_int(value):
    try:
        ret_value = int(value)
    except ValueError:
        raise argparse.ArgumentTypeError("Invalid input '{}', --jira-limit parameter must be a valid integer")

    if ret_value < 1:
        raise argparse.ArgumentTypeError("invalid input '{}', --jira-limit parameter must be > 0".format(value))
    return ret_value

def valid_date(string):
    try:
        return datetime.strptime(string, "%Y-%m-%d").date()
    except ValueError:
        raise argparse.ArgumentTypeError("Not a valid date: '{0}'.".format(string))

def create_ascii_table(headers):
    table = PrettyTable(headers)
    table.align = 'l'
    table.max_width = 12
    table.max_width['Title'] = table.max_width['Link'] = 60
    table.align['#User Comments'] = 'r'
    return table

def print_ascii_row(table, row_data, empty_row=None):
    if table is not None:
        table.add_row(row_data)
        if empty_row is not None:
            table.add_row(empty_row)

def write_csv_row(csv_writer, row_data):
    if csv_writer is not None:  # Only write headers if csv writer exists
        csv_writer.writerow(row_data)

def write_csv_headers(domain, headers, **kwargs):
    global _first_csv_domain
    if not _first_csv_domain:
        write_csv_row(kwargs.get('csv_writer'), [])
    write_csv_row(kwargs.get('csv_writer'), [domain + ' issues'])
    write_csv_row(kwargs.get('csv_writer'), headers)
    _first_csv_domain = False

def output_issue(domain, username, issue, table=None, **kwargs):
    user_roles = list(kwargs.get('user_roles', []))
    if issue.fields.reporter.name == username:
        user_roles.append('Reporter')

    link = domain + "/browse/" + issue.key
    updated_time = issue.fields.updated[:10].replace('-', '/')
    comments = [comment for comment in issue.fields.comment.comments if comment.author.name == username]

    row_content = [issue.key, issue.fields.project.name, issue.fields.summary, ','.join(user_roles),
                   issue.fields.status.name, len(comments), link, updated_time]

    # Add to ascii table if enabled
    print_ascii_row(table, row_content, [''] * 8)

    # Write to csv file
    write_csv_row(kwargs.get('csv_writer'), row_content)

def process_issues(domain, username, issues, **kwargs):
    headers = ['ID', 'Project', 'Title', 'Role', 'Status', '#Comments', 'Link', 'Updated On']
    table = create_ascii_table(headers) if kwargs.get('ascii') else None
    write_csv_headers(domain, headers, **kwargs)

    for issue in issues:
        output_issue(domain, username, issue, table=table, **kwargs)

    if table is not None:
        print(table)

def search_jira_domains(domains, username, **kwargs):
    search_field = ','.join(FIELDS)
    search_str = "(assignee = {0} OR reporter = {0})" \
                 "AND (updated >= '{1}' OR created >= '{1}')" \
                 "AND (updated < '{2}' OR created < '{2}')" \
                 "ORDER BY updated {3}".format(username, kwargs.get('start_date', date(1990, 1, 1)),
                                               kwargs.get('end_date', date.today()), kwargs.get('order', 'ASC'))

    for key, domain in domains.items():
        jira = JIRA(domain)
        issues = jira.search_issues(search_str, fields=search_field, maxResults=kwargs.get('jira_limit', 50))

        if issues:
            if kwargs.get('ascii'):
                print("{0} issues".format(key))

            process_issues(domain, username, issues, **kwargs)

def get_program_args():
    parser = argparse.ArgumentParser(description='Returns JIRA issues associated with a given user')
    parser.add_argument('usernames', nargs='+', help='At least one JIRA username must be specified.')

    parser.add_argument('-s', '--startDate', dest='start_date', type=valid_date, default=date(1990, 1, 1),
                        metavar='YYYY-MM-DD', help="The date from which JIRAs are returned.")

    parser.add_argument('-e', '--endDate', dest='end_date', type=valid_date, default=date.today(), metavar='YYYY-MM-DD',
                        help="The date of the most recent JIRA to be returned.")

    parser.add_argument('-d', '--domains', nargs='+', choices=JIRA_LOCATIONS.keys(), default=JIRA_LOCATIONS,
                        help="A list of the JIRA keys associated with the domain(s) that should be searched.")

    parser.add_argument('-jl', '--jira-limit', dest='jira_limit', type=check_negative_int, default=50,
                        help="The maximum number of JIRA issues that will be returned for each domain.")

    parser.add_argument('--lifo', dest='order', action='store_const', const='DESC', default='ASC',
                        help="JIRA issues are output from the most recently updated issue.")

    parser.add_argument('--no-ascii', dest='ascii', action='store_false',
                        help="JIRA issues will not be output to the console.")

    parser.add_argument('-c', '--csv', dest='csv', nargs='?', type=str, choices=csv.list_dialects(), const='excel',
                        help="JIRA issues are output to a csv file 'jira.csv'. This flag takes an optional keyword "
                             "parameter that determines the format of the generated csv file.")

    args = parser.parse_args()

    # Convert list of domain keys into OrderedDict
    if isinstance(args.domains, list):
        domains = OrderedDict()
        for domain_key in args.domains:
            domains[domain_key] = JIRA_LOCATIONS[domain_key]
        args.domains = domains

    return args

if __name__ == '__main__':
    a = get_program_args()
    options = {'start_date': a.start_date, 'end_date': a.end_date, 'jira_limit': a.jira_limit, 'order': a.order,
               'user_roles': ['Assignee'], 'ascii': a.ascii}

    for user in a.usernames:
        if a.ascii:
            print("JIRA Issues Associated with {} at domains {}".format(user, list(a.domains)))

        # Only create a file if absolutely necessary
        if a.csv is not None:
            filename = "{}-jira.csv".format(user)
            with open(filename, mode='w') as csvfile:
                options['csv_writer'] = csv.writer(csvfile, dialect=a.csv)
                search_jira_domains(a.domains, user, **options)
        else:
            search_jira_domains(a.domains, user, **options)