import doctest

def mean(alist):
    '''
    (list)-> float

    Takes a list of numbers and returns the mean as a float

    Examples of code:
    >>>mean([1,2,3,4,5])
    3.0
    >>>mean([4,56,7,99,8,0])
    29.0
    '''
    mean=sum(alist)/len(alist)
    return mean

def median(alist):
    '''
    (list)-> int

    Takes a list of numbers and returns the median as an integer

    Examples of code:
    >>>median([1,2,3,4,5])
    3
    >>>median([4,56,7,99,8,0])
    7.5
    '''
    copylist=alist[:]
    copylist.sort()
    if isEven(len(alist)): #REVISION TO MEDIAN FUNCTION- CALLS isEven function now
        rightmid = len(copylist)//2
        leftmid = rightmid-1
        median = (copylist[leftmid] + copylist[rightmid])/2
    else:
        mid = len(copylist)//2
        median = copylist[mid]
    return median

def mode(alist):
    '''
    (list)-> list

    Takes a list of numbers and returns the mode as an integer. Returns
    first integers in the list if nothing else occurs more often.

    Examples of code:
    >>>mode([1,1,2,3,4])
    1
    >>>mode([4,56,7,99,8,0])
    4
    '''
    '''
    max_count = (0,0)
    for num in alist:
        occurences = alist.count(num)
        if occurences>max_count[0]:
            max_count = (occurences,num)
    return max_count[1]
    '''

#REVISION TO mode function to call genFrequencyTable
    dictionary = genFrequencyTable(alist)
    marker = []
    key = list(dictionary.values())
    maxValue = max(key)
    for item in dictionary:
        if dictionary.get(item) == maxValue:
            marker.append(item)
    return marker

def frequencyTable(alist):
    '''
    (list)-> table

    Takes a list of numbers and returns a table that shows all of the integers
    that appear in the list, as well as the number of times they show up in
    the list.

    Examples of code:
    >frequencyTable([1,3,3,2])
    ITEM FREQUENCY
    1          1
    2          1
    3          2
    '''
    countdict = {}
    '''
    for item in alist:
        if item in countdict:
            countdict[item] = countdict[item]+1
        else:
            countdict[item] = 1

    itemlist = list(countdict.keys())
    itemlist.sort()

    print('ITEM', 'FREQUENCY')

    for item in itemlist:
        print (item, '        ', countdict[item])
    '''

#REVISION TO frequencyTable function to call genFrequencyTable
    dictionary = genFrequencyTable(alist)
    print('ITEM',  'FREQUENCY')
    for item in dictionary:
        print (item, '      ' ,dictionary.get(item))

def isEven(n):
    '''
    (int)-> boolean

    Takes an integer n, and returns True if even, False if odd.

    Examples of code:
    >>>isEven(4)
    True
    >>>isEven(5)
    False
    '''
    if (n%2==0):
        return True
    else:
        return False

#I'M NOT SURE HOW TO DO THE DOCTEST.TESTMOD()

def genFrequencyTable(alist):
    '''
    (list)-> table

    Takes a list of numbers and generates the dictionary frequency counts that
    are currently being generated in the mode and frequency table function.
    The function will return a dictionary.

    Examples of code:
    >>> genFrequencyTable([1, 2, 3, 3, 1, 4, 5])
    {1:2, 2:1, 3:2, 4:1, 5:1}
    >>> genFrequencyTable([4,5,0,0,89,3,44])
    {4: 1, 5: 1, 0: 2, 89: 1, 3: 1, 44: 1}
    '''
    newDictionary={}
    countdict={}
    for item in alist:
        if item in countdict:
            countdict[item] = countdict[item]+1
        else:
            countdict[item] = 1

    for item in alist:
        newDictionary[item] = countdict[item]
    return newDictionary

def main():
    alist = [5.3, 3.0, 2.6, 4.4, 2.9, 4.8, 4.3,
    2.6, 2.9, 4.9, 2.5, 4.8, 4.2, 2.6,
    4.8, 2.7, 5.0, 2.7, 2.8, 4.3, 3.1,
    4.1, 2.8, 5.8, 2.5, 3.9, 4.8, 2.9,
    2.5, 4.9, 5.0, 2.5, 3.2, 2.6, 2.7,
    4.8, 4.1, 5.1, 4.7, 2.6, 2.9, 2.7,
    3.3, 3.0, 4.4, 2.7, 5.7, 2.5, 5.1,
    2.5, 4.4, 4.6, 5.7, 4.5, 4.7, 5.1,
    2.9, 3.3, 2.7, 2.8, 2.9, 2.6, 5.3,
    6.0, 3.0, 5.3, 2.7, 4.3, 5.4, 4.4,
    2.6, 2.8, 4.4, 4.3, 4.7, 3.3, 4.0,
    2.5, 4.9, 4.9, 2.5, 4.8, 3.1, 4.9,
    4.4, 6.6, 3.3, 2.5, 5.0, 4.8, 2.5,
    4.2, 4.5, 2.6, 4.0, 3.3, 3.1, 2.6,
    2.7, 2.9, 2.7, 2.9, 3.3, 2.8, 3.1,
    2.5, 4.3, 3.2, 4.6, 2.8, 4.8, 5.1,
    2.7, 2.6, 3.1, 2.9, 4.2, 4.8, 2.5,
    4.5, 4.5, 2.8, 4.7, 4.6, 4.6, 5.1,
    4.2, 2.8, 2.5, 4.5, 4.6, 2.6, 5.0,
    2.8, 2.9, 2.7, 3.1, 2.6, 2.5, 3.2,
    3.2, 5.2, 2.8, 3.2, 2.6, 5.3, 5.5,
    2.7, 5.2, 6.4, 4.2, 3.1, 2.8, 4.5,
    2.9, 3.1, 4.3, 4.9, 5.2, 2.6, 6.7,
    2.7, 4.9, 3.0, 4.9, 4.7, 2.6, 4.6,
    2.5, 3.2, 2.7, 6.2, 4.0, 4.6, 4.9,
    2.5, 5.1, 3.3, 2.5, 4.7, 2.5, 4.1,
    3.1, 4.6, 2.8, 3.1, 6.3]

    x = mean(alist)
    print(x)

    j = median(alist)
    print(j)

    y = mode(alist)
    print(y)
    print()
    frequencyTable(alist)


class Asistencia():
    def __int__(self,id,fecha):
        self.id=id
        self.fecha=fecha
while True:
    nombre = input("Ingrese un nombre (o presione Enter para salir): ")
    if nombre == "":
        break
    Asistencia.nombre

print("Los nombres ingresados son:")
for x in nombre:
    print(x)

Taller de programacion aplicada/Actividades y Tareas/Tarea 2/Asistencia (cri y benja).py


"""
  Solution managers actually walk a model through all the steps to solve
"""
import multiprocess
import numpy as np

import tqdm

from srlife import solverparams, thermal

def merge_dicts(idict):
    """
    Merge an iterator over dictionaries into a single dict
    """
    return {k: v for d in idict for k, v in d.items()}

class SolutionManager:
    """Solution manager

    High level solution manager walking through the thermal, structural,
    and damage calculations.

    Args:
      receiver (receiver.Receiver): receiver object to solve
      thermal_solver (thermal.ThermalSolver): how to solve the heat transport
      thermal_material (materials.ThermalMaterial): solid thermal properties
      fluid_material (materials.FluidMaterial): fluid thermal properties
      structural_solver (structural.TubeSolver):  how to solve the mechanics problem
      deformation_material (materials.DeformationMaterial):  how things deform with time
      damage_material (materials.StructuralMaterial):  how to calculate creep damage
      system_solver (system.SystemSolver):  how to tie tubes into the structural system
      damage_model (damage.DamageCalculator): how to calculate damage from the results
      pset (Optional[solverparams.ParameterSet]): optional set of solver parameters
    """

    def __init__(
        self,
        receiver,
        thermal_solver,
        thermal_material,
        fluid_material,
        structural_solver,
        deformation_material,
        damage_material,
        system_solver,
        damage_model,
        pset=solverparams.ParameterSet(),
    ):
        self.receiver = receiver
        self.thermal_solver = thermal_solver
        self.thermal_material = thermal_material
        self.fluid_material = fluid_material
        self.structural_solver = structural_solver
        self.deformation_material = deformation_material
        self.damage_material = damage_material
        self.system_solver = system_solver
        self.damage_model = damage_model

        self.pset = pset
        self.nthreads = pset.get_default("nthreads", 1)
        self.progress = pset.get_default("progress_bars", False)

        self.page = pset.get_default("page_results", False)
        self.receiver.set_paging(self.page)

        self.heuristics = []

    def add_heuristic(self, heuristic):
        """Add a heuristic to use during the solve

        Args:
          heuristics (list): new heuristic to add
        """
        self.heuristics.append(heuristic)

    @property
    def tubes(self):
        """Direct iterator over tubes

        Returns:
          iterator over tubes
        """
        return self.receiver.tubes

    @property
    def ntubes(self):
        """Pass through to get the number of tubes that need to be analyzed

        Returns:
          int:  total number of tubes in entire receiver
        """
        return len(list(self.tubes))

    def progress_decorator(self, base, ntotal):
        """Either wrap with a progress bar decorator or return a dummy

        Args:
          base (function): base function to wrap
          ntotal (int): total number in iterator, needed for wrapping iterators

        Returns:
          either function wrapped with decorator or base function
        """
        if self.progress:
            return tqdm.tqdm(base, total=ntotal)
        else:
            return base

    def solve_life(self):
        """User interface: solve everything and return receiver life

        The trigger for everything: solve the complete problem and report the
        best-estimate life.

        Returns:
          float:  Number of allowed daily cycles
        """
        self.solve_heat_transfer()
        self.solve_structural()

        return self.calculate_damage()

    def calculate_damage(self):
        """Calculate damage from the results

        Returns:
          float:    Number of allowed daily cycles
        """
        if self.progress:
            print("Calculating damage:")
        return self.damage_model.determine_life(
            self.receiver,
            self.damage_material,
            nthreads=self.nthreads,
            decorator=self.progress_decorator,
        )

    def solve_reliability(self, time):
        """User interface: solve everything and return receiver reliability

        The trigger for everything: solve the complete problem and report the
        best-estimate reliability.

        Args:
            time (float): time at which to report reliability

        Returns:
          float:  Reliability between 0 and 1
        """
        self.solve_heat_transfer()
        self.solve_structural()

        return self.calculate_reliability(time)

    def calculate_reliability(self, time):
        """Calculate reliability from the results

        Args:
            time (float): time at which to report reliability

        Returns:
          float:    Reliability between 0 and 1
        """
        if self.progress:
            print("Calculating reliability :")
        return self.damage_model.determine_reliability(
            self.receiver,
            self.damage_material,
            time,
            nthreads=self.nthreads,
            decorator=self.progress_decorator,
        )

    def solve_heat_transfer(self):
        """Solve heat transfer for the receiver

        Adds thermal results in each tube
        """
        if isinstance(self.thermal_solver, thermal.ThermohydraulicsThermalSolver):
            if self.progress:
                print("Running thermohydraulic analysis")
            self.thermal_solver.solve_receiver(
                self.receiver,
                self.thermal_material,
                self.fluid_material,
                decorator=self.progress_decorator,
                nthreads=self.nthreads,
                **merge_dicts(
                    h.args_for_thermohydraulic_solver(self.receiver)
                    for h in self.heuristics
                )
            )
        else:
            self.solve_heat_transfer_tube()

    def solve_heat_transfer_tube(self):
        """Solve the heat transfer problem for each tube

        Adds the thermal results to each receiver.Tube object
        """
        # pylint: disable=no-member
        if self.progress:
            print("Running thermal analysis:")
        with multiprocess.Pool(self.nthreads) as p:
            temps = list(
                self.progress_decorator(
                    p.imap(
                        lambda x: self.thermal_solver.solve(
                            x,
                            self.thermal_material,
                            self.fluid_material,
                            **merge_dicts(
                                h.args_for_thermal_solver(self.receiver, x)
                                for h in self.heuristics
                            )
                        ),
                        self.tubes,
                    ),
                    self.ntubes,
                )
            )
        for tube, temps in zip(self.tubes, temps):
            tube.add_results("temperature", temps)

    def solve_structural(self):
        """Solve the structural problem for the complete system

        Adds the structural results to each tube.
        """
        if self.progress:
            print("Running structural analysis:")
        self.system_solver.solve(
            self.receiver,
            self.deformation_material,
            self.structural_solver,
            nthreads=self.nthreads,
            decorator=self.progress_decorator,
            verbose=self.progress,
        )

class Heuristic:
    """Solution heuristic superclass

    Class that defines a heuristic to modify the basic 3D solve process in some
    way.

    To implement a specific heuristic override the appropriate pure virtual
    methods.
    """

    def args_for_tube_thermal_solver(self, receiver, tube):
        """Add tube solver args

        Args:
          receiver (receiver.receiver):       receiver object affected
          tube (receiver.tube):               tube object affected

        """
        return {}

    def args_for_thermohydraulic_solver(self, receiver):
        """Add tube solver args

        Args:
          receiver (receiver.receiver):       receiver object affected

        """
        return {}

class CycleResetHeuristic(Heuristic):
    """
    Reset the tube temperatures each cycle to the initial values
    """

    def args_for_tube_thermal_solver(self, receiver, tube):
        """Modify the tube solver before the solve

        Args:
          receiver (receiver.receiver):       receiver object affected
          tube (receiver.tube):               tube object affected
        """
        resetter = thermal.TemperatureResetter(
            lambda t: np.isclose(t % receiver.period, 0), tube.T0
        )

        return {"resetters": [resetter]}

    def args_for_thermohydraulic_solver(self, receiver):
        """Add tube solver args

        Args:
          receiver (receiver.receiver):       receiver object affected

        """
        resetter = thermal.ReceiverResetter(
            lambda t: np.isclose(t % receiver.period, 0)
        )

        return {"resetters": [resetter]}


from cgi import test
from datetime import datetime
from datetime import timedelta
import random
import re
from unittest import result
from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from app import exam
from app.auth import configured_required, login_required

from app.db import get_db

practice_blueprint = Blueprint('practice', __name__, url_prefix='/practice')

@practice_blueprint.route('/result/<test_id>/', methods=['POST', 'GET'])
@login_required
def show_result(test_id):
    db = get_db()

    test_questions = db.execute('SELECT question_id FROM test_details\
        WHERE test_id = ?', (test_id,)).fetchall()

    # print(test_questions['question_id'])
    test_question_list = []
    for question in test_questions:
        test_question_list.append(question['question_id'])

    print(test_question_list)

    # return test_question_list

    # question_answers_in_db = db.execute('SELECT * FROM questions\
    #     WHERE id in ?',(tuple(test_question_list),))
    questions_in_db = db.execute(
        "SELECT * FROM questions\
                WHERE id in {}".format(tuple(test_question_list))
    ).fetchall()

    question_answers = {}

    for q_a in questions_in_db:
        question_answers[q_a['id']] = {
            "statement": q_a['question_statement'],
            "answer": q_a['answer'],
            "option_a": q_a['a'],
            "option_b": q_a['b'],
            "option_c": q_a['c'],
            "option_d": q_a['d']
        }

    # return question_answers

    right_answers = []
    wrong_answers = []
    skipped_answers = []

    test_details_in_db = db.execute('SELECT * FROM test_details\
        WHERE test_id = ?', (test_id,)).fetchall()

    for test_detail in test_details_in_db:
        if (test_detail['answer'] is None):
            answer = question_answers[test_detail['question_id']]
            answer['your_answer'] = None
            skipped_answers.append(answer)
            continue

        if (test_detail['answer'] == question_answers[test_detail['question_id']]['answer']):
            answer = question_answers[test_detail['question_id']]
            answer['your_answer'] = test_detail['answer']
            right_answers.append(answer)
        else:
            answer = question_answers[test_detail['question_id']]
            answer['your_answer'] = test_detail['answer']
            wrong_answers.append(answer)

    test_result_data = {
        "right": right_answers,
        "wrong": wrong_answers,
        "skipped": skipped_answers,
        "right_count": len(right_answers),
        "wrong_count": len(wrong_answers),
        "skipped_count": len(skipped_answers)
    }
    # for test_details in

    return render_template('practice/result.html', test_result_data=test_result_data)

@practice_blueprint.route('/submit-test', methods=["POST"])
@login_required
def submit_test():
    db = get_db()

    test_id = request.form['test_id']
    submit_time = datetime.now().replace(microsecond=0).isoformat()
    email = session['email']
    test_in_db = db.execute("SELECT * FROM test\
        where id = ?", (test_id,)).fetchone()

    if test_in_db is None:
        error = "no test exist"
        flash(error)
        return redirect(url_for('practice.config_test'))

    if test_in_db['is_submitted'] == True:
        error = "test already submitted"
        flash(error)
        return redirect(url_for('practice.config_test'))

    if test_in_db['email'] != email:
        error = "no auth to access test"
        flash(error)
        return redirect(url_for('practice.config_test'))

    print("test_id", test_id)
    print("submit_time", submit_time)

    test_questions = db.execute('SELECT question_id FROM test_details\
        WHERE test_id = ?', (test_id,)).fetchall()

    test_question_list = []
    for question in test_questions:
        test_question_list.append(question['question_id'])

    questions_in_db = db.execute(
        "SELECT * FROM questions\
                WHERE id in {}".format(tuple(test_question_list))
    ).fetchall()

    question_answers = {}

    for q_a in questions_in_db:
        question_answers[q_a['id']] = {
            "answer": q_a['answer'],
            "topic_id": q_a['topic_id'],
            "question_id": q_a['id']
        }
    right_answers = []
    wrong_answers = []
    skipped_answers = []

    test_details_in_db = db.execute('SELECT * FROM test_details\
        WHERE test_id = ?', (test_id,)).fetchall()

    for test_detail in test_details_in_db:
        if (test_detail['answer'] is None):
            answer = question_answers[test_detail['question_id']]
            answer['your_answer'] = None
            skipped_answers.append(answer)
            continue

        if (test_detail['answer'] == question_answers[test_detail['question_id']]['answer']):
            answer = question_answers[test_detail['question_id']]
            answer['your_answer'] = test_detail['answer']
            right_answers.append(answer)
        else:
            answer = question_answers[test_detail['question_id']]
            answer['your_answer'] = test_detail['answer']
            wrong_answers.append(answer)

    test_result_data = {
        "right": right_answers,
        "wrong": wrong_answers,
        "skipped": skipped_answers
    }

    db.execute("UPDATE test \
        SET is_submitted=1, submit_time=?, marks=? WHERE id=?", (submit_time, len(right_answers), test_id))

    print(test_result_data)

    result_time = submit_time.split('T')[0]

    for right_answer in right_answers:
        db.execute("INSERT INTO result_details (email, test_id, question_id, topic_id, result_time, result) \
            VALUES(?,?,?,?,?,?)", (email, test_id, right_answer['question_id'], right_answer['topic_id'], result_time, 1))

    for wrong_answer in wrong_answers:
        db.execute("INSERT INTO result_details (email, test_id, question_id, topic_id, result_time, result) \
            VALUES(?,?,?,?,?,?)", (email, test_id, wrong_answer['question_id'], wrong_answer['topic_id'], result_time, -1))

    for skipped_answer in skipped_answers:
        db.execute("INSERT INTO result_details (email, test_id, question_id, topic_id, result_time, result) \
            VALUES(?,?,?,?,?,?)", (email, test_id, skipped_answer['question_id'], skipped_answer['topic_id'], result_time, 0))

    db.commit()
    return redirect(url_for('practice.show_result', test_id=test_id))

@practice_blueprint.route('/save-answer', methods=['POST'])
@login_required
def save_answer():
    db = get_db()
    test_id = request.form['test_id']
    sequence_number = int(request.form['sequence_number'])
    answer = request.form.get('answer')

    print("save answer", answer)
    db.execute("UPDATE test_details \
        SET answer=?\
            WHERE test_id = ? AND sequence_number = ?", (answer, test_id, sequence_number))
    db.commit()
    return redirect(url_for('practice.show_test', test_id=test_id, sequence_number=sequence_number+1))

@practice_blueprint.route('/test/<test_id>/<sequence_number>', methods=['GET', 'POST'])
@login_required
def show_test(test_id, sequence_number):
    db = get_db()

    email = session['email']

    test_in_db = db.execute("SELECT * FROM test\
        where id = ?", (test_id,)).fetchone()

    if test_in_db is None:
        error = "no test exist"
        flash(error)
        return redirect(url_for('practice.config_test'))

    if test_in_db['is_submitted'] == True:
        error = "test already submitted"
        flash(error)
        return redirect(url_for('practice.config_test'))

    if test_in_db['email'] != email:
        error = "no auth to access test"
        flash(error)
        return redirect(url_for('practice.config_test'))

    number_of_questions = test_in_db['number_of_questions']

    # check for date time condition
    # end_time = test_in_db['end_time']
    # print('end_time',end_time)

    if int(sequence_number) == 0:
        error = "can't move previous"
        flash(error)
        return redirect(url_for('practice.show_test', test_id=test_id, sequence_number=1))

    if int(sequence_number) > (number_of_questions):
        error = "moved to start of test"
        flash(error)
        unanswered_questions_in_db = db.execute("SELECT count(*) as skipped_count FROM test_details\
        WHERE answer is NULL AND test_id = ? ", (test_id,)).fetchone()
        skipped_count = unanswered_questions_in_db['skipped_count']
        return redirect(url_for('practice.show_test', test_id=test_id, sequence_number=1, submit_flag=True, skipped_count=skipped_count))

    test_details_in_db = db.execute("SELECT * FROM test_details \
        WHERE test_id = ? AND sequence_number = ?", (test_id, sequence_number)).fetchone()

    answered_questions = {}
    answered_questions_in_db = db.execute("SELECT * FROM test_details\
        WHERE answer is not NULL AND test_id = ? ", (test_id,)).fetchall()

    for answer in answered_questions_in_db:
        answered_questions[answer["sequence_number"]] = answer['answer']

    if test_details_in_db is None:
        error = "question does not exist"
        flash(error)
        return redirect(url_for('practice.config_test'))

    question_id = test_details_in_db["question_id"]

    print("question_id", question_id)

    question_in_db = db.execute("SELECT * FROM questions\
        WHERE id = ? ", (question_id,)).fetchone()

    question_statement = question_in_db['question_statement']
    options = {
        'a': question_in_db['a'],
        'b': question_in_db['b'],
        'c': question_in_db['c'],
        'd': question_in_db['d'],
    }
    return render_template('practice/test.html', sequence_number=int(sequence_number), question_statement=question_statement, options=options, test_id=test_id, number_of_questions=number_of_questions, answered_questions=answered_questions)
    # return [sequence_number, question_statement, options, test_id, number_of_questions]

@practice_blueprint.route('/config', methods=['GET', 'POST'])
@login_required
def config_test():
    db = get_db()
    if request.method == 'POST':
        exam_id = request.form['exam']
        topics_in_db = db.execute(
            "SELECT * FROM exam_details \
            WHERE exam_id = ?", (exam_id,)
        ).fetchall()
        exam_name = db.execute(
            "SELECT * FROM exam WHERE id = ?", (exam_id,)
        ).fetchone()["exam_name"]
        topics = {}
        for topic in topics_in_db:
            topic_id = topic["id"]
            topic_name = topic["topic_name"]
            subject_name = topic["subject_name"]
            if subject_name in topics:
                topics[subject_name].append({
                    "topic_id": topic_id, "topic_name": topic_name
                })
            else:
                topics[subject_name] = [{
                    "topic_id": topic_id, "topic_name": topic_name
                }]

        print(topics)
        print(exam_name)
        return render_template('practice/configure.html', topics=topics, topic_keys=list(topics.keys()), exam_name=exam_name)
    else:
        exams_in_db = db.execute(
            "SELECT * FROM exam"
        ).fetchall()

        exams = []

        for exam in exams_in_db:
            exams.append({"id": exam["id"], "exam_name": exam["exam_name"]})
        print(exams)
        return render_template('practice/configure.html', exams=exams)

@practice_blueprint.route('/demo/config', methods=["POST", "GET"])
def config_demo_test():
    db = get_db()
    if request.method == "POST":
        # fetch questions from db

        pass
    else:
        exams_in_db = db.execute(
            "SELECT * FROM exam"
        ).fetchall()

        exams = []

        for exam in exams_in_db:
            exams.append({"id": exam["id"], "exam_name": exam["exam_name"]})
        print(exams)
        return render_template('practice/demo_configure.html', exams=exams)

@practice_blueprint.route('/make', methods=["POST"])
@login_required
def make_test():
    db = get_db()
    if request.method == "POST":
        test_topics = request.form.getlist('test_topics')

        if len(test_topics) < 1:
            error = "too less topics"
            flash(error)
            return redirect(url_for('practice.config_test'))
        number_of_questions = int(request.form["number_of_questions"])
        minutes_per_question = 3

        start_time = datetime.now().replace(microsecond=0).isoformat()
        end_time = (datetime.now() + timedelta(minutes=minutes_per_question *
                    number_of_questions)).replace(microsecond=0).isoformat()
        email = session['email']
        print(start_time)
        print(end_time)

        print(test_topics)

        # make a test
        test_id = db.execute(
            "INSERT INTO test (email, start_time, end_time, number_of_questions, marks) \
                VALUES(?,?,?,?,?)",
            (email, start_time, end_time, number_of_questions, 0)
        ).lastrowid

        print("test_id", test_id)
        print("test topics", test_topics)
        questions_in_db = db.execute(
            "SELECT * FROM questions\
                WHERE topic_id in (%s)" % ("?," * len(test_topics))[:-1], test_topics
        ).fetchall()
        questions = []
        for question in questions_in_db:
            questions.append(question["id"])

        random.shuffle(questions)
        questions = questions[0:number_of_questions]
        sequence_number = 1
        for question_id in questions:

            db.execute(
                "INSERT INTO test_details(sequence_number,test_id,question_id)\
                    VALUES(?,?,?)", (sequence_number, test_id, question_id,)
            )

            sequence_number += 1

        db.commit()
        return redirect(url_for('practice.show_test', test_id=test_id, sequence_number=1))


# encoding: utf-8
"""
@author:  l1aoxingyu
@contact: sherlockliao01@gmail.com
"""

import os

import torch
from torch._six import container_abcs, string_classes, int_classes
from torch.utils.data import DataLoader

from fastreid.utils import comm
from . import samplers
from .common import CommDataset
from .datasets import DATASET_REGISTRY
from .transforms import build_transforms

_root = os.getenv("FASTREID_DATASETS", "datasets")

def build_reid_train_loader(cfg, mapper=None, **kwargs):
    cfg = cfg.clone()

    train_items = list()
    for d in cfg.DATASETS.NAMES:
        dataset = DATASET_REGISTRY.get(d)(root=_root, combineall=cfg.DATASETS.COMBINEALL, **kwargs)
        if comm.is_main_process():
            dataset.show_train()
        train_items.extend(dataset.train)

    if mapper is not None:
        transforms = mapper
    else:
        transforms = build_transforms(cfg, is_train=True)

    train_set = CommDataset(train_items, transforms, relabel=True)

    num_workers = cfg.DATALOADER.NUM_WORKERS
    num_instance = cfg.DATALOADER.NUM_INSTANCE
    mini_batch_size = cfg.SOLVER.IMS_PER_BATCH // comm.get_world_size()

    if cfg.DATALOADER.PK_SAMPLER:
        if cfg.DATALOADER.NAIVE_WAY:
            data_sampler = samplers.NaiveIdentitySampler(train_set.img_items, mini_batch_size, num_instance)
        else:
            data_sampler = samplers.BalancedIdentitySampler(train_set.img_items, mini_batch_size, num_instance)
    else:
        data_sampler = samplers.TrainingSampler(len(train_set))
    batch_sampler = torch.utils.data.sampler.BatchSampler(data_sampler, mini_batch_size, True)

    train_loader = torch.utils.data.DataLoader(
        train_set,
        num_workers=num_workers,
        batch_sampler=batch_sampler,
        collate_fn=fast_batch_collator,
        pin_memory=True,
    )
    return train_loader

def build_reid_test_loader(cfg, dataset_name, mapper=None, **kwargs):
    cfg = cfg.clone()

    dataset = DATASET_REGISTRY.get(dataset_name)(root=_root, **kwargs)
    if comm.is_main_process():
        dataset.show_test()
    test_items = dataset.query + dataset.gallery

    if mapper is not None:
        transforms = mapper
    else:
        transforms = build_transforms(cfg, is_train=False)

    test_set = CommDataset(test_items, transforms, relabel=False)

    mini_batch_size = cfg.TEST.IMS_PER_BATCH // comm.get_world_size()
    data_sampler = samplers.InferenceSampler(len(test_set))
    batch_sampler = torch.utils.data.BatchSampler(data_sampler, mini_batch_size, False)
    test_loader = DataLoader(
        test_set,
        batch_sampler=batch_sampler,
        num_workers=4,  # save some memory
        collate_fn=fast_batch_collator,
        pin_memory=True,
    )
    return test_loader, len(dataset.query)

def trivial_batch_collator(batch):
    """
    A batch collator that does nothing.
    """
    return batch

def fast_batch_collator(batched_inputs):
    """
    A simple batch collator for most common reid tasks
    """
    elem = batched_inputs[0]
    if isinstance(elem, torch.Tensor):
        out = torch.zeros((len(batched_inputs), *elem.size()), dtype=elem.dtype)
        for i, tensor in enumerate(batched_inputs):
            out[i] += tensor
        return out

    elif isinstance(elem, container_abcs.Mapping):
        return {key: fast_batch_collator([d[key] for d in batched_inputs]) for key in elem}

    elif isinstance(elem, float):
        return torch.tensor(batched_inputs, dtype=torch.float64)
    elif isinstance(elem, int_classes):
        return torch.tensor(batched_inputs)
    elif isinstance(elem, string_classes):
        return batched_inputs


from itertools import product

def load_instructions(fname):
    with open(fname) as fid:
        lines = fid.readlines()

    instructions = []
    for line in lines:
        if line.startswith('mask'):
            mask = line.split('=')[1].strip()
            instructions.append(('mask', mask))
        elif line.startswith('mem'):
            start = line.index('[') + 1
            stop = line.index(']')
            address = line[start:stop]
            val = line.split('=')[1].strip()
            instructions.append(('mem', int(address), int(val)))
    return instructions

def apply_bit_mask(mask, val):
    bits = '{0:036b}'.format(val)
    bits_out = ''
    for i, m in enumerate(mask):
        if m != 'X':
            bits_out += m
        else:
            bits_out += bits[i]
    return int(bits_out, 2)

def apply_floating_bit_mask(mask, val):
    bits = '{0:036b}'.format(val)
    bits_out = ''
    for i, m in enumerate(mask):
        if m == '0':
            bits_out += bits[i]
        elif m in ['1', 'X']:
            bits_out += m
        else:
            ValueError('Unrecognised value')
    return bits_out

def generate_combos(bits):
    f_indx = [i for i, bit in enumerate(bits) if bit == 'X']

    bits_out_combos = []
    for combo in product(('0','1'),repeat=len(f_indx)):
        new_bits = list(bits)
        for i, b in enumerate(combo):
            new_bits[f_indx[i]] = b
        bits_out_combos.append(''.join(new_bits))

    return [int(b, 2) for b in bits_out_combos]

def run_instructions(instructions):
    mem = {}
    for i in instructions:
        if i[0] == 'mask':
            curr_mask = i[1]
        elif i[0] == 'mem':
            _, addr, val = i
            mem[addr] = apply_bit_mask(curr_mask, val)
        else:
            ValueError('Instruction not recognised, got {i[0]}')
    return mem

def run_instructions2(instructions):
    mem = {}
    for i in instructions:
        if i[0] == 'mask':
            curr_mask = i[1]
        elif i[0] == 'mem':
            _, addr, val = i
            b = apply_floating_bit_mask(curr_mask, addr)
            addrs = generate_combos(b)
            for addr in addrs:
                mem[addr] = val
        else:
            ValueError('Instruction not recognised, got {i[0]}')
    return mem

instructions = load_instructions('advent_day14.txt')
mem = run_instructions(instructions)

print('Part 1')
print(f'Sum of all values in memory = {sum(mem.values())}')

mem = run_instructions2(instructions)
print('Part 2')
print(f'Sum of all values in memory = {sum(mem.values())}')


from DataEngine.Data import get_pro_stock_basic, get_pro_daily, get_pro_monthly
import prettytable as pt
from time import sleep

def CycleObservation(code='600900.SH',sdate='20100101',edate='20210101',name='万科A'):
    data = get_pro_daily(code, sdate, edate)
    date = list(data['trade_date'])
    date.reverse()
    close_price = list((data['close'] - data['open'])/data['open'])
    close_price.reverse()
    length = len(close_price)
    year_mon = date[0][:6]
    mon = date[0][4:6]
    price = close_price[0]
    month_change = {}
    table = pt.PrettyTable(['name', 'Month', 'Change'])
    for x in range(length):
        if  date[x][:6] != year_mon :
            year_mon = date[x][:6]
            mon = date[x][4:6]
            table.add_row([name, year_mon, round(close_price[x-1] - price,2)])
            price = close_price[x]
            if not month_change.get(mon):
                month_change[mon] = [round(close_price[x-1] - price,2)]
            else:
                month_change[mon].append(round(close_price[x-1] - price,2))
    # print(table)
    ret_m_c = {}
    for x in month_change.keys():
        # print(x,' ---> ', month_change[x], '==>', round(sum(month_change[x])/ len(month_change[x]),4))
        ret_m_c[x] = round(sum(month_change[x])/ len(month_change[x]),4)
    return ret_m_c

if __name__ == '__main__':
    stocks = get_pro_stock_basic()
    codes = [x for x in stocks['ts_code'] if x[0] != 3 and x[:2] != '68']
    names = [x for x in stocks['name']]
    rate = {}
    for x in range(len(codes)):
        if names[x].find('ST') != -1 or x % 100 == 0:
            continue
        # print("\n\n模拟%s 周期观察" % names[x])
        sleep(0.1)
        d = CycleObservation(codes[x], '20150101', '20210110', names[x])
        for x in d.keys():
            if not rate.get(x):
                rate[x] = [d[x]]
            else:
                rate[x].append(d[x])
    for x in rate.keys():
        print(x, '-->', sum(rate[x]))


from sys import stdin, setrecursionlimit
input = stdin.readline

from bisect import bisect_left, bisect_right
from collections import deque
from functools import lru_cache, reduce
from heapq import heappush, heappop
from math import sqrt, ceil, floor, log2

def rl(t = int):
    return list(map(t, input().split()))

n, k = rl()
b = rl()
carry = 0
ret = 0
lastK = 0
d = deque()
# [2, 0,
# carry = 2
# lastK = 2
for i in range(n - 1, -1, -1):
    #print(b[i], carry, ret)
    need = max(0, b[i] - carry)
    #print(need)
    val = min(k, i+1)
    add = ceil(need / val)
    ret += add

    d.append(add)
    if len(d) > k:
        lastK -= d.popleft()
    carry += (val - 1) * add
    carry -= lastK

    lastK += add

print(ret)


from PyQt5.QtWidgets import QSizePolicy
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib import ticker
import numpy as np

import Meta
import Utils

class MatplotlibWidget(FigureCanvas):
	def __init__(self, parent=None, width=14, height=10, dpi=100):
		fig = Figure(figsize=(width, height), dpi=dpi)
		FigureCanvas.__init__(self, fig)
		self.setParent(parent)
		FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding)
		FigureCanvas.updateGeometry(self)

	def updatePlot(self, molec_name, nuMin, nuMax, T, p, cutoff):
		molec_id = Meta.MOLECULE_NAME[molec_name]['molec_id']
		table = self.fetchTable(molec_name, nuMin, nuMax)
		printName = Meta.MOLECULE_NUMBER[table[0][0]]["formula"]
		Utils.getLineStrength(table, T)
		Utils.getPressureShift(table, p)
		_nu, _S = Utils.getColumns(table, ('nu', 's'))
		_nu, _S = Utils.applyCutoff(_nu, _S, cutoff)
		n = len(_nu)
		nu = np.zeros(n * 3)
		S = np.zeros(n * 3)
		std_nu = np.std(nu)
		for i in range(n):
			S[3 * i] = 0
			S[3 * i + 1] = _S[i]
			S[3 * i + 2] = 0
			nu[(3 * i):(3 * i + 3)] = _nu[i]

		# Main Plot
		plot = self.figure.add_subplot(111)
		plot.plot(nu, S)
		plot.axes.set_yscale('log')
		plot.axes.set_ylabel(r'$\chi_i *$Linestrength, [$\frac{cm^{-2}}{atm}$]')
		plot.axes.set_xlabel(r'Wavenumber [cm$^{-1}$]')
		self.figure.gca().yaxis.set_major_formatter(ticker.FormatStrFormatter('%0.e'))
		self.figure.gca().xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.f'))

		self.draw()

	# Scale to x +- 0.1 sigma, y from 0 to max sw + 0.1 sigma
	# ax1.axis([min(nu) - 0.1 * std_nu, max(nu) + 0.1 * std_nu, cutoff, 2 * max(S)])
	# ax1.set_title(r"{0}: {1:.0f} < $\nu$ < {2:.0f}".format(printName, min(nu), max(nu)), y = 1.10)
	def fetchTable(self, molec_name, nuMin, nuMax):
		table = Utils.searchDB_NU(Utils.readFile(molec_name + ".txt"), nuMin, nuMax)
		return table

	def clearPlot(self):
		self.figure.clf()
		self.draw()


# routines for spherical geometry

from numpy import *

# returns distance in radians
def dist_between(loc1,loc2):

    # everything is radians
    f1 = loc1[0]
    f2 = loc2[0]
    l12 = loc2[1] - loc1[1]

    return arccos(sin(f1) * sin(f2) + cos(f1) * cos(f2) * cos(l12))

def loc_at_dist(loc1,loc2,ds):

    # ds is great-circle distance in radians
    l12 = loc2[1] - loc1[1]
    l1 = loc1[1]
    f1 = loc1[0]
    f2 = loc2[0]

    a1 = arctan2(sin(l12), (cos(f1) * tan(f2) - sin(f1) * cos(l12)))

    a0 = arcsin(sin(a1) * cos(f1))

    # calculationg l0
    s1 = arctan2(tan(f1), cos(a1))
    l01 = arctan2(sin(a0) * sin(s1), cos(s1))
    l0 = l1 - l01

    # coordinates of a point on the line segment at a distance s from P0
    f = arcsin(cos(a0) * sin(s1 + ds))
    l = l0 + arctan2(sin(a0) * sin(s1 + ds) , cos(s1 + ds))

    return f,l,a0,a1


def count_sort(arr):
    """Time complexity: O(n), Auxiliary space complexity: O(n)"""

    max_val = max(arr)

    num_count = [0 for i in range(max_val + 1)]
    for element in arr:
        num_count[element] += 1

    nums_of_items_before = 0
    for idx, count in enumerate(num_count):
        num_count[idx] = nums_of_items_before
        nums_of_items_before += count

    sorted_arr = [None] * len(arr)
    for element in arr:
        sorted_arr[num_count[element]] = element
        num_count[element] += 1

    return sorted_arr

def radix_sort(arr):
    """Time complexity: O(), Auxiliary space complexity: O()"""

if __name__ == "__main__":
    print(count_sort([1, 4, 1, 2, 7, 5, 2]))


"""
https://leetcode.com/contest/weekly-contest-221/problems/determine-if-string-halves-are-alike/
1704. Determine if String Halves Are Alike
User Accepted:4128
User Tried:4248
Total Accepted:4229
Total Submissions:5264
Difficulty:Easy
You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b be the second half.

Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s contains uppercase and lowercase letters.

Return true if a and b are alike. Otherwise, return false
"""

class Solution:

    def halvesAreAlike(self, s: str) -> bool:
        n = len(s)

        left = s[0:n//2]
        right = s[n//2:]

        left_c = Counter(left)
        right_c = Counter(right)

        vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
        left_count = 0
        right_count = 0

        for vowel in vowels:
            if vowel in left_c:
                left_count += left_c[vowel]
            if vowel in right_c:
                right_count += right_c[vowel]
        return left_count == right_count


# import io
# import os

# Imports the Google Cloud client library
from google.cloud import speech
from google.cloud.speech import enums
from google.cloud.speech import types

# Instantiates a client
client = speech.SpeechClient()

# # The name of the audio file to transcribe
# file_name = os.path.join(
#     os.path.dirname(__file__),
#     'testAudio3.wav')

# # Loads the audio into memory
# with io.open(file_name, 'rb') as audio_file:
# 	content = audio_file.read()
# 	audio = types.RecognitionAudio(content=content)

def getSpeechTranscript(uri):
	audio = types.RecognitionAudio(uri=uri)

	config = types.RecognitionConfig(
	    encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
	    sample_rate_hertz=8000,
	    language_code='en-US')

	# Detects speech in the audio file
	response = client.recognize(config, audio)

	print(response.results)
	return response.results[0].alternatives[0].transcript
	# for result in response.results:
	# 	print('Transcript: {}'.format(result.alternatives[0].transcript))
	# 	print('Transcript: {}'.format(result.alternatives[0].transcript))
	# return 0

transcript = getSpeechTranscript("gs://bostonhack_elmingo/Test_audio/REda6f2ceae1670fe734e2f1b0b13b07df.wav")

print("result:")
print(transcript)


'''
After passing through the Tiles Room and getting the Cradle of Life, now Indiana
Croft faces a new challenge before being able to leave the Temple Cursed. It's found
on a bridge under which there is deep darkness. Fortunately, this place
It also appears in the diary. The bridge crosses the so-called Valley of Shadows, which begins
with a descent slope (the slope is not necessarily constant) for later
to reach the lowest point start to climb to the other end of the bridge (again,
not necessarily with constant slope). Right at the bottom of the valley there is a river,
but the newspaper does not specify its location with respect to the bridge (for example, you do not know
if the river is 53 meters from the beginning of the bridge) or the distance in height (it is
say, it is not known if the river is 228 meters below, for example). On the slopes
there are sharp rocks.

If Indiana Croft had time, he could easily find the point where
get off the bridge to get exactly to the river, as it has a laser pointer
to measure heights that tells you how many meters there are from the bridge to the ground at a point
determined. The problem is that the priests of the temple have found out that they have been robbed
the Cradle of Life, they are chasing Indiana Croft and they will reach you right away. He
Adventurer must quickly find the position of the river to get off and flee safely.

Design the algorithm that Indiana Croft should use to find the valley's minimum point
in the indicated conditions. The algorithm must be efficient: at least in the best case
it must have a logarithmic order. You can consider how long Indiana Croft takes in
move along the bridge is null and that the estimate of the point of the river where
Picking off can have an approximation error of E meters (E is a given constant).
'''

import math

### FUNCTIONS ###

# Function that returns the distance to the valley from a position of the bridge
def laserPointer(x):
    return math.pow(x, 2) - 10

# Recursive function that receives the bridge interval[p] and the error[e]
# and returns an interval that contains the x so LASERPOINTER(X)=MIN with the error < e
def lookForRiver(p, e):
    laserPointer_p0 = laserPointer(p[0])
    # laserPointer_p1 = laserPointer(p[1])

    if abs(p[1] - p[0]) < e:
        # Valid interval
        return p
    else:
        # divide by 3 and check in which is definitely not minimum
        oneThird = p[0] + (p[1] - p[0]) * (1/3)
        twoThirds = p[0] + (p[1] - p[0]) * (2/3)
        laserPointer_oneThird = laserPointer(oneThird)
        laserPointer_twoThirds = laserPointer(twoThirds)

        # if 1/3 decreases and 2/3 decreases we can discard the first part,
        # if 2/3 increases we can discard the last
        if laserPointer_p0 > laserPointer_oneThird > laserPointer_twoThirds:
            interval = [oneThird, p[1]]
        else:
            interval = [p[0], twoThirds]

        return lookForRiver(interval, e)

### MAIN ###
bridge = [-2, 3]
err = 0.05

resultado = lookForRiver(bridge, err)
print('The bridge starts in', bridge[0], 'and ends in', bridge[1], 'the river is in', resultado)


"""
Пожалуйста, приступайте к этой задаче после того, как вы сделали и получили ревью ко всем остальным задачам
в этом репозитории. Она значительно сложнее.

Есть набор сообщений из чата в следующем формате:

```
messages = [
    {
        "id": "efadb781-9b04-4aad-9afe-e79faef8cffb",
        "sent_at": datetime.datetime(2022, 10, 11, 23, 11, 11, 721),
        "sent_by": 46,  # id пользователя-отправителя
        "reply_for": "7b22ae19-6c58-443e-b138-e22784878581",  # id сообщение, на которое это сообщение является ответом (может быть None)
        "seen_by": [26, 91, 71], # идентификаторы пользователей, которые видели это сообщение
        "text": "А когда ревью будет?",
    }
]
```

1. Вывести айди пользователя, который написал больше всех сообщений.
2. Вывести айди пользователя, на сообщения которого больше всего отвечали.
3. Вывести айди пользователей, сообщения которых видело больше всего уникальных пользователей.
4. Определить, когда в чате больше всего сообщений: утром (до 12 часов), днём (12-18 часов) или вечером (после 18 часов).
5. Вывести идентификаторы сообщений, который стали началом для самых длинных тредов (цепочек ответов).

Весь код стоит разбить на логические части с помощью функций.
"""

messages = [
    {
        "id": "efadb781-9b04-4aad-9afe-e79faef8cffb",
        "sent_at": datetime.datetime(2022, 10, 11, 23, 11, 11, 721),
        "sent_by": 46,  # id пользователя-отправителя
        "reply_for": "7b22ae19-6c58-443e-b138-e22784878581",  # id сообщение, на которое это сообщение является ответом (может быть None)
        "seen_by": [26, 91, 71], # идентификаторы пользователей, которые видели это сообщение
        "text": "А когда ревью будет?",
    }
]
import random
import uuid
import datetime
from typing import List, Dict, Any
import lorem
from collections import Counter

message_counts = Counter(messages ['sent_by'] for message in messages)
# Находим пользователя с максимальным количеством сообщений
most_active_user_id = max(message_counts, key=message_counts.get)

print(f"Пользователь {most_active_user_id} написал больше всех сообщений: {message_counts[most_active_user_id]}")

#Генерирует историю чата с заданным количеством сообщений.
def get_user_with_most_replies(messages: List[Dict[str, Any]]) -> int:
    """
    Возвращает идентификатор пользователя, на сообщения которого больше всего отвечали.

    :param messages: список сообщений
    :return: идентификатор пользователя
    """
    user_reply_count = {}
    for message in messages:
        reply_for = message["reply_for"]
        if reply_for is not None:
            user_id = messages[0]["sent_by"]
            if user_id not in user_reply_count:
                user_reply_count[user_id] = 0
            user_reply_count[user_id] += 1
    return max(user_reply_count, key=user_reply_count.get)

def get_users_with_most_views(messages: List[Dict[str, Any]]) -> List[int]:
    """
    Возвращает список идентификаторов пользователей, сообщения которых видело больше всего уникальных пользователей.

    :param messages: список сообщений
    :return: список идентификаторов пользователей
    """
    user_view_count = {}
    for message in messages:
        seen_by = message["seen_by"]
        for user_id in seen_by:
            if user_id not in user_view_count:
                user_view_count[user_id] = 0
            user_view_count[user_id] += 1
    max_views = max(user_view_count.values())
    return [user_id for user_id, views in user_view_count.items() if views == max_views]

def get_message_count_by_time_of_day(messages: List[Dict[str, Any]]) -> Dict[str, int]:
    """
    Возвращает словарь с количеством сообщений в разное время дня.

    :param messages: список сообщений
    :return: словарь с количеством сообщений в разное время дня
    """
    message_count_by_time = {"утром": 0, "днём": 0, "вечером": 0}
    for message in messages:
        sent_time = message["sent_at"].time()
        if sent_time < datetime.time(12):
            message_count_by_time["утром"] += 1
        elif sent_time < datetime.time(18):
            message_count_by_time["днём"] += 1
        else:
            message_count_by_time["вечером"] += 1
    return message_count_by_time


import requests
from datetime import datetime
import smtplib
import time

MY_LAT = -6.263623 # Your latitude
MY_LONG = 106.891586 -0.127758 # Your longitude
MY_GMAIL=""
MY_PW=""
def cek_posisi_iss():
    response = requests.get(url="http://api.open-notify.org/iss-now.json")
    response.raise_for_status()
    data = response.json()

    iss_latitude = float(data["iss_position"]["latitude"])
    iss_longitude = float(data["iss_position"]["longitude"])
    if MY_LAT-5 <= iss_latitude <= MY_LAT+5 and MY_LONG-5 <= iss_longitude <= MY_LONG+5:
        return True

#Your position is within +5 or -5 degrees of the ISS position.

def cek_waktu():

    parameters = {
        "lat": MY_LAT,
        "lng": MY_LONG,
        "formatted": 0,
    }

    response = requests.get(
        "https://api.sunrise-sunset.org/json", params=parameters)
    response.raise_for_status()
    data = response.json()
    sunrise = int(data["results"]["sunrise"].split("T")[1].split(":")[0])
    sunset = int(data["results"]["sunset"].split("T")[1].split(":")[0])

    time_now = datetime.now().hour
    if time_now >= sunset or time_now <= sunrise:
        return True

while True:
    time.sleep(60)
    if cek_waktu() and cek_posisi_iss():
        koneksi = smtplib.SMTP("smtp.gmail.com")
        koneksi.starttls()
        koneksi.login(MY_GMAIL, MY_PW)
        koneksi.sendmail(
            from_addr=MY_GMAIL,
            to_addrs=MY_PW,
            msg="lihat tuh doatas ada satelite iss "
        )
    else:
        koneksi = smtplib.SMTP("smtp.gmail.com")
        koneksi.starttls()
        koneksi.login(MY_GMAIL, MY_PW)
        koneksi.sendmail(
            from_addr=MY_GMAIL,
            to_addrs=MY_GMAIL,
            msg="tidak ada satelite "
        )

#my_gmail and pw isi sendiri


from selenium import webdriver
import pyautogui,time
class Duck:
    def __init__(self,driver):

        self.driver=driver
        self.url='https://duckduckgo.com'
        self.search_bar_id="search_form_input_homepage"
        self.search_button="btnK"
        self.first_link_class="result__url__domain"
    def navigate (self):

         self.driver.get(self.url)

    def search(self,nome='None'):
        self.driver.find_element_by_id(self.search_bar_id).send_keys(nome)
        #self.driver.find_element_by_name(self.search_bar).send_keys()
        pyautogui.typewrite('\n')

    def textconvert(self):
        time.sleep(4)
        message=self.driver.find_element_by_class_name(self.first_link_class).text
        return str(message)

class Wiki:

    def __init__(self,driver):

        self.driver=driver
        self.url='https://pt.wikipedia.org/wiki/Wikip%C3%A9dia:P%C3%A1gina_principal'

ff=webdriver.Firefox()
g=Duck(ff)
with open (r"C:\Users\Dell\Documents\documentos\marcas.txt",'r') as f:
    with open (r"C:\Users\Dell\Documents\documentos\links.txt", 'w' ) as fw:
        for line in f :
            g.navigate()
            g.search(line)
            fw.write((line) + g.textconvert()+' \n')


#!/usr/bin/env python

import getopt
import sys

# Prepared by Salvatore Cascio, Cisco Systems
# May 31, 2017

def getdncsip():
    with open('dncsip','r') as f:
        dncsmap = dict([line.strip().split(",") for line in f])
        return dncsmap

def getqpmap():
    with open('qplist','r') as f:
        qpmap = dict([line.strip().split(",") for line in f])
        return qpmap

def getermmap():
    with open('ermlist','r') as f:
        ermmap = dict([line.strip().split(",") for line in f])
        return ermmap

def onlineprintstatic(onlinefile):

    qp_online = open(onlinefile,'w')

    template = """; enter DNCS IP address to connect to DNCS
;
"""
    qp_online.write(template)
    qp_online.close()
    return

def preconfigprintstatic(preconfigfile):

    qp_preconfig = open(preconfigfile,'w')

    template = """; QamProxy pre-config file
;
; configure Platform settings
;
object System
GratuitousArp Enabled
;
"""
    qp_preconfig.write(template)
    qp_preconfig.close()
    return

def printdefperIP_online(qp_online,dncsip,rfgwname):

    template = """object %s
DNCSIpAddress %s
;
""" %(rfgwname,dncsip)
    qp_online.write(template)
    return

def printdefperIP_preconfig(qp_preconfig,qpname,qpip,ermvip,qamrealip):

    template = """create GqiQamProxy %s
IpAddress %s
AdminState InService
DNCSConnectionRetry 5
DNCSIpAddress 0
ERMIpAddress %s
RealQamIP %s
;
""" %(qpname,qpip,ermvip,qamrealip)
    qp_preconfig.write(template)
    return

def main(argv):
    writelog = 1

    try:
        opts,args = getopt.getopt(argv,"hf:n:",["file=","dncsname="])
    except getopt.GetoptError as err:
        print (str(err))
        sys.exit(2)
    else:
        for opt,arg in opts:
            if opt == '-h':
                print (sys.argv[0] + " -f|--file <rfgw_file> -n|--dncsname <dncsname>")
                sys.exit(1)
            elif opt in ( "-f", "--file"):
                filename = arg
            elif opt in ( "-n", "--dncsname"):
                dncsname = arg
            else:
                assert False, "Unknown"
                sys.exit(2)

    if len(argv) == 0:
        print ("Usage: " +  sys.argv[0] + " -f|--file <rfgw_file> -n|--dncsname <dncsname> No arguments given")
        sys.exit(1)

    try:
        filename
    except NameError:
        print ("Filename not specified (-f or --file)")
        sys.exit(1)

    try:
        dncsname
    except NameError:
        print ("DNCS Name not specified (-n|--dncsname")
        sys.exit(1)

    dncsmap = getdncsip()
    qpmap   = getqpmap()
    ermmap  = getermmap()

    with open(filename,'r') as f:
        content = f.readlines()
    content = [x.strip() for x in content]
    num = len(content)
    content.sort()
    numqp = num / 20

    # 20 RFGW-1 per QP
    if num % 20 != 0:
        numqp = numqp + 1

    start = 0

    for y in range (1,numqp+1):
        suffix = "%02d" % y
        #gwprefix = "QP" + suffix + "_"
        qpname = dncsname.upper() + suffix
        onlinefile = "%s_QP_online.conf.%s" % (dncsname,suffix)
        preconfigfile = "%s_QP_preconfig.conf.%s" % (dncsname,suffix)
        onlineprintstatic(onlinefile)
        preconfigprintstatic(preconfigfile)
        qp_online = open(onlinefile,'a')
        qp_preconfig = open(preconfigfile,'a')
        end = start + 20
        if end > num:
            end = num
        for z in range(start,end):
            data =  content[z].split(",")
            #rfgwname = gwprefix + data[0]
            rfgwname = data[0]
            rfgwip   = data[1]
            printdefperIP_online(qp_online,dncsmap[dncsname.upper()],rfgwname)
            printdefperIP_preconfig(qp_preconfig,rfgwname,qpmap[qpname],ermmap[dncsname.upper()],rfgwip)
        qp_online.close()
        qp_preconfig.close()
        start = start + 20

if __name__ == '__main__':
    main(sys.argv[1:])


def girarHorizontal(x):
    temp = ""
    temp += x[0]+x[2]+x[4]+x[1]+x[3]+x[5]
    x = temp
    return x

def girarVertical(x):
    temp = ""
    temp += x[4]+x[0]+x[2]+x[3]+x[5]+x[1]
    x = temp
    return x

def cuboIgual(x, y):
    for m in range(4):
        for n in range(4):
            y = girarHorizontal(y)
            if x == y:
                return True
            y = girarHorizontal(y)
        y = girarVertical(y)
    return False

while(True):
    try:
        cube = input()
        cubo1 = cube[:6]
        cubo2 = cube[6:12]
        resultado = cuboIgual(cubo1, cubo2)
        if resultado:
            print("V")
        else:
            print("F")
    except EOFError:
        break


from LinkedList.ListNodeModule import listNodeConverter, compareListNode
from LinkedList.RemoveNthNodeFromEndOfList.HT019 import Solution as HashTable
from LinkedList.RemoveNthNodeFromEndOfList.TwoPointer019 import Solution as TwoPointer

linkedlist = []
linkedlist.append([1, 2, 3, 4, 5])
linkedlist.append([1])
linkedlist.append([1, 2])

n = []
n.append(2)
n.append(1)
n.append(2)

answer = []
answer.append(listNodeConverter([1, 2, 3, 5]))
answer.append(listNodeConverter([]))
answer.append(listNodeConverter([2]))

def test_hashtable():
    for i, ll in enumerate(linkedlist):
        assert compareListNode(HashTable().removeNthFromEnd(listNodeConverter(ll), n[i]), answer[i]) == True

def test_twopointer():
    for i, ll in enumerate(linkedlist):
        assert compareListNode(TwoPointer().removeNthFromEnd(listNodeConverter(ll), n[i]), answer[i]) == True


import pygame

import tkinter as tk
from tkinter import ttk
from Paddle import Paddle
from Ball import Ball
# from DropBox import DropBox
from DropBox2 import DropBox2

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
GREY = (169, 169, 169)
LIGHT_GREY = (109, 109, 109)

# Define school pride
PURPLE = (51, 0, 111)
CYAN = (0, 255, 255)
GOLD = (232, 211, 162)
Viking_Blue = (0, 63, 135, 40)

playerColors = [PURPLE, Viking_Blue, GOLD, RED]
playerLocations = [[20, 200], [680, 200]]
paddle_ups = {}
paddle_downs = {}

pygame.init()

players = DropBox2([' 2',
                    ' 4 (Singles)',
                    ' 4 (Duos)'])

players.draw()
num_players = int(players.value[1])

c_options = [
    ' Q A',
    ' E D',
    ' O L',
    ' W S',
    ' U J',
    ' ↑ ↓']
for i in range(0, num_players):
    controls = DropBox2(c_options)
    controls.draw()

    print(controls.value)
    if(controls.value[1] == '↑'):
        paddle_ups.update(
            {pygame.K_UP: str(i)})
        paddle_downs.update(
            {pygame.K_DOWN: str(i)})
    else:
        paddle_ups.update(
            {pygame.key.key_code(str(controls.value[1])): str(i)})
        paddle_downs.update(
            {pygame.key.key_code(str(controls.value[3])): str(i)})
    c_options.remove(controls.value)

# Set the width and height of the screen [width, height]
width = 700
height = 500
size = (width, height)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Dan and Brax Pong")

scoreA = 0
scoreB = 0

 # Give us some paddles UwU
# n = 1
paddle_dict = {}
for i in range(0, num_players):
    paddle_dict["v{}".format(i)] = Paddle(playerColors[i], 10, 100,
                                          playerLocations[i][0],
                                          playerLocations[i][1])

# paddle_ups = {pygame.K_w: '0'}
# paddle_downs = {pygame.K_s: '0'}

ball = Ball(WHITE, 10, 10)
ball.rect.x = 345
ball.rect.y = 195

sprite_list = pygame.sprite.Group()

for i in paddle_dict.keys():
    sprite_list.add(paddle_dict[i])
sprite_list.add(ball)

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

# Set up the Score Text

# -------- Main Program Loop -----------
while not done:
    # --- Main event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

    keys = pygame.key.get_pressed()
    for i in paddle_ups.keys():
        if keys[i]:
            paddle_dict["v{}".format(paddle_ups[i])].moveUp(5)
    for i in paddle_downs.keys():
        if keys[i]:
            paddle_dict["v{}".format(paddle_downs[i])].moveDown(5)
    # --- Game logic should go here

    # --- make sure the ball is not our of bounds
    if (ball.rect.y > height) or (ball.rect.y < 0):
        ball.bounceY()

        # player A scored
    if (ball.rect.x > width):
        goLeft = True
        ball.reset(goLeft)
        scoreA += 1

        # player B Scored
    if (ball.rect.x < 0):
        goLeft = False
        ball.reset(goLeft)
        scoreB += 1

    # Detect collisions between the ball and the paddles
    for paddle in paddle_dict.keys():
        if pygame.sprite.collide_mask(ball, paddle_dict[paddle]):
            ball.bounceX()
    # if pygame.sprite.collide_mask(ball, pad_1) or pygame.sprite.collide_mask(ball, pad_2):
    #     ball.bounceX()

    sprite_list.update()

    # --- Screen-clearing code goes here

    # Here, we clear the screen to white. Don't put other drawing commands
    # above this, or they will be erased with this command.

    # If you want a background image, replace this clear with blit'ing the
    # background image.
    screen.fill(GREY)

    # --- Drawing code should go here
    sprite_list.draw(screen)

    # Display scores:
    font = pygame.font.Font(None, 74)
    text = font.render(str(scoreA), 1, WHITE, LIGHT_GREY)
    screen.blit(text, (250, 10))
    text = font.render(str(scoreB), 1, WHITE, LIGHT_GREY)
    screen.blit(text, (420, 10))

    pygame.draw.line(screen, WHITE, [width/2, 0], [width/2, height], 5)

    # --- Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # --- Limit to 60 frames per second
    clock.tick(60)

# Close the window and quit.
pygame.quit()


# Licensed under a 3-clause BSD style license - see LICENSE
'''
Tests of full, end-to-end runs of the crossmatch process.
'''

import os
import numpy as np

from ..matching import CrossMatch
from .test_matching import _replace_line

__all__ = ['generate_random_data']

def generate_random_data(N_a, N_b, N_c, extent, n_a_filts, n_b_filts, a_astro_sig, b_astro_sig,
                         a_cat, b_cat, seed=None):
    '''
    Convenience function to allow for the generation of two test datasets.

    Parameters
    ----------
    N_a : integer
        The number of sources to be generated in catalogue "a".
    N_b : integer
        The number of catalogue "b" fake sources.
    N_c : integer
        The number of common, overlapping sources, in both catalogues.
    extent : list of integers
        The on-sky coordinates that mark out the rectangular limits over which
        sources should be generated. Should be of the form
        ``[lower_lon, upper_lon, lower_lat, upper_lat]``, in degrees.
    n_a_filts : integer
        The number of photometric filters catalogue "a" should have.
    n_b_filts : integer
        The number of catalogue "b" photometric filters.
    a_astro_sig : float
        The astrometric uncertainty of catalogue "a", in arcseconds.
    b_astro_sig : float
        Catalogue "b"'s astrometric uncertainty, in arcseconds.
    a_cat : string
        The folder path into which to save the binary files containing
        catalogue "a"'s astrometric and photometric data.
    b_cat : string
        Folder describing the save location of catalogue "b"'s data.
    seed : integer, optional
        Random number generator seed. If ``None``, will be passed to
        ``np.random.default_rng`` as such, and a seed will be generated
        as per ``default_rng``'s documentation.
    '''
    if N_a > N_b:
        raise ValueError("N_a must be smaller or equal to N_b.")
    if N_c > N_a:
        raise ValueError("N_c must be smaller or equal to N_a.")

    a_astro = np.empty((N_a, 3), float)
    b_astro = np.empty((N_b, 3), float)

    rng = np.random.default_rng(seed)
    a_astro[:, 0] = rng.uniform(extent[0], extent[1], size=N_a)
    a_astro[:, 1] = rng.uniform(extent[2], extent[3], size=N_a)
    if np.isscalar(a_astro_sig):
        a_astro[:, 2] = a_astro_sig
    else:
        # Here we assume that astrometric uncertainty goes quadratically
        # with magnitude
        raise ValueError("a_sig currently has to be an integer for all generated data.")

    a_pair_indices = np.arange(N_c)
    b_pair_indices = rng.choice(N_b, N_c, replace=False)
    b_astro[b_pair_indices, 0] = a_astro[a_pair_indices, 0]
    b_astro[b_pair_indices, 1] = a_astro[a_pair_indices, 1]
    inv_b_pair = np.delete(np.arange(N_b), b_pair_indices)
    b_astro[inv_b_pair, 0] = rng.uniform(extent[0], extent[1], size=N_b-N_c)
    b_astro[inv_b_pair, 1] = rng.uniform(extent[2], extent[3], size=N_b-N_c)
    if np.isscalar(b_astro_sig):
        b_astro[:, 2] = b_astro_sig
    else:
        # Here we assume that astrometric uncertainty goes quadratically
        # with magnitude
        raise ValueError("b_sig currently has to be an integer for all generated data.")

    a_circ_dist = rng.normal(loc=0, scale=a_astro[:, 2], size=N_a) / 3600
    a_circ_angle = rng.uniform(0, 2*np.pi, size=N_a)
    a_astro[:, 0] = a_astro[:, 0] + a_circ_dist * np.cos(a_circ_angle)
    a_astro[:, 1] = a_astro[:, 1] + a_circ_dist * np.sin(a_circ_angle)
    b_circ_dist = rng.normal(loc=0, scale=b_astro[:, 2], size=N_b) / 3600
    b_circ_angle = rng.uniform(0, 2*np.pi, size=N_b)
    b_astro[:, 0] = b_astro[:, 0] + b_circ_dist * np.cos(b_circ_angle)
    b_astro[:, 1] = b_astro[:, 1] + b_circ_dist * np.sin(b_circ_angle)

    # Currently all we do, given the only option available is a naive Bayes match,
    # is ignore the photometry -- but we still require its file to be present.
    a_photo = rng.uniform(0.9, 1.1, size=(N_a, n_a_filts))
    b_photo = rng.uniform(0.9, 1.1, size=(N_b, n_b_filts))

    # Similarly, we need magref for each catalogue, but don't care what's in it.
    amagref = rng.choice(n_a_filts, size=N_a)
    bmagref = rng.choice(n_b_filts, size=N_b)

    for f in [a_cat, b_cat]:
        os.makedirs(f, exist_ok=True)
    np.save('{}/con_cat_astro.npy'.format(a_cat), a_astro)
    np.save('{}/con_cat_astro.npy'.format(b_cat), b_astro)
    np.save('{}/con_cat_photo.npy'.format(a_cat), a_photo)
    np.save('{}/con_cat_photo.npy'.format(b_cat), b_photo)
    np.save('{}/magref.npy'.format(a_cat), amagref)
    np.save('{}/magref.npy'.format(b_cat), bmagref)

    # Fake uninformative "overlap" flag data, where no sources are in the
    # halo of the chunk.
    np.save('{}/in_chunk_overlap.npy'.format(a_cat), np.zeros(N_a, bool))
    np.save('{}/in_chunk_overlap.npy'.format(b_cat), np.zeros(N_b, bool))

    np.save('{}/test_match_indices.npy'.format(a_cat), a_pair_indices)
    np.save('{}/test_match_indices.npy'.format(b_cat), b_pair_indices)

def do_naive_bayes_match(use_memmap_files):
    # Generate a small number of sources randomly, then run through the
    # cross-match process.
    N_a, N_b, N_c = 40, 50, 35
    n_a_filts, n_b_filts = 3, 4
    a_astro_sig, b_astro_sig = 0.3, 0.5
    r = 5 * np.sqrt(a_astro_sig**2 + b_astro_sig**2)
    extent = [131, 131 + np.sqrt(N_b * np.pi * r**2)/3600, 0, np.sqrt(N_b * np.pi * r**2)/3600]

    a_cat, b_cat = 'a_cat', 'b_cat'

    generate_random_data(N_a, N_b, N_c, extent, n_a_filts, n_b_filts, a_astro_sig, b_astro_sig,
                         a_cat, b_cat, seed=9999)

    # Ensure output chunk directory exists
    os.makedirs(os.path.join(os.path.dirname(__file__), "data/chunk0"), exist_ok=True)

    ol, nl = 'run_auf = no', 'run_auf = yes\n'
    f = open(os.path.join(os.path.dirname(__file__),
                          'data/crossmatch_params.txt')).readlines()
    idx = np.where([ol in line for line in f])[0][0]
    _replace_line(os.path.join(os.path.dirname(__file__), 'data/crossmatch_params.txt'),
                  idx, nl, out_file=os.path.join(os.path.dirname(__file__),
                  'data/chunk0/crossmatch_params_.txt'))

    new_ext = [extent[0] - r/3600 - 0.1/3600, extent[1] + r/3600 + 0.1/3600,
               extent[2] - r/3600 - 0.1/3600, extent[3] + r/3600 + 0.1/3600]
    for ol, nl in zip(['run_group = no', 'pos_corr_dist = 11',
                       'cross_match_extent = 131 138 -3 3', 'joint_folder_path = test_path',
                       'cf_region_points = 131 134 4 -1 1 3'],
                      ['run_group = yes\n', 'pos_corr_dist = {:.2f}\n'.format(r),
                       'cross_match_extent = {:.3f} {:.3f} {:.3f} {:.3f}\n'.format(*new_ext),
                       'joint_folder_path = new_test_path\n',
                       'cf_region_points = 131 131 1 0 0 1\n']):
        f = open(os.path.join(os.path.dirname(__file__),
                              'data/crossmatch_params.txt')).readlines()
        idx = np.where([ol in line for line in f])[0][0]
        _replace_line(os.path.join(os.path.dirname(__file__), 'data/chunk0/crossmatch_params_.txt'),
                      idx, nl)

    ol, nl = 'auf_region_points = 131 134 4 -1 1 {}', 'auf_region_points = 131 131 1 0 0 1\n'
    for file_name in ['cat_a_params', 'cat_b_params']:
        _ol = ol.format('3' if '_a_' in file_name else '4')
        f = open(os.path.join(os.path.dirname(__file__),
                              'data/{}.txt'.format(file_name))).readlines()
        idx = np.where([_ol in line for line in f])[0][0]
        _replace_line(os.path.join(os.path.dirname(__file__), 'data/{}.txt'.format(file_name)),
                      idx, nl, out_file=os.path.join(os.path.dirname(__file__),
                      'data/chunk0/{}_.txt'.format(file_name)))

    for cat, ol, nl in zip(['cat_a_params', 'cat_b_params'], ['cat_folder_path = gaia_folder',
                           'cat_folder_path = wise_folder'], ['cat_folder_path = a_cat\n',
                           'cat_folder_path = b_cat\n']):
        f = open(os.path.join(os.path.dirname(__file__),
                              'data/{}.txt'.format(cat))).readlines()
        idx = np.where([ol in line for line in f])[0][0]
        _replace_line(os.path.join(os.path.dirname(__file__), 'data/chunk0/{}_.txt'.format(cat)),
                      idx, nl)

    cm = CrossMatch(os.path.join(os.path.dirname(__file__), 'data'), use_memmap_files)
    cm()

    ac = np.load('{}/pairing/ac.npy'.format(cm.joint_folder_path))
    bc = np.load('{}/pairing/bc.npy'.format(cm.joint_folder_path))
    assert len(ac) == N_c
    assert len(bc) == N_c

    a_right_inds = np.load('{}/test_match_indices.npy'.format(a_cat))
    b_right_inds = np.load('{}/test_match_indices.npy'.format(b_cat))

    for i in range(0, N_c):
        assert a_right_inds[i] in ac
        assert b_right_inds[i] in bc
        q = np.where(a_right_inds[i] == ac)[0][0]
        assert np.all([a_right_inds[i], b_right_inds[i]] == [ac[q], bc[q]])

def test_naive_bayes_match_no_memmap():
   # Test using standard numpy arrays for internal arrays.
   do_naive_bayes_match(False)

def test_naive_bayes_match_memmap():
    # Test using mapped files for internal arrays.
    do_naive_bayes_match(True)


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

# ## Use MCCE method without using the Data or RandomForest class

# In[15]:

import warnings
warnings.filterwarnings('ignore')

import sys
import os
# Tricks for loading data and libraries from parent directories.
grandparent = os.path.abspath('.')
parent = os.path.abspath('./mccepy')
sys.path.insert(1, parent)
sys.path.insert(2, grandparent)
print(os.getcwd())

import re
import numpy as np
import pandas as pd
pd.set_option('display.max_columns', None)

from sklearn import preprocessing, metrics
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

from mcce.mcce import MCCE
from mcce.metrics import distance, feasibility, constraint_violation, success_rate

# ## Load data

# In[16]:

feature_order = ['age', 'workclass', 'fnlwgt', 'education-num', 'marital-status', 'occupation',
                 'relationship', 'race', 'sex', 'hours-per-week',]

dtypes = {"age": "float",
          "workclass": "category",
          "fnlwgt": "float",
          "education-num": "float",
          "marital-status": "category",
          "occupation": "category",
          "relationship": "category",
          "race": "category",
          "sex": "category",
          "hours-per-week": "float",
          "income": "category"}

categorical = ['workclass', 'marital-status', 'occupation', 'relationship', 'race', 'sex']
continuous = ['age', 'fnlwgt', 'education-num', 'hours-per-week']
immutables = ['age', 'sex']
target = ['income']
features = categorical + continuous

path = 'mccepy/Data/adult_data.csv'

df = pd.read_csv(path)
df = df[features + target]

print(f"The immutable features are {immutables}")

# ## Scale the continuous features between 0 and 1. Encode the categorical features using one-hot encoding

# In[17]:

encoder = preprocessing.OneHotEncoder(drop="first", sparse=False).fit(df[categorical])
df_encoded = encoder.transform(df[categorical])

scaler = preprocessing.MinMaxScaler().fit(df[continuous])
df_scaled = scaler.transform(df[continuous])

categorical_encoded = encoder.get_feature_names_out(categorical).tolist()
df_scaled = pd.DataFrame(df_scaled, columns=continuous)
df_encoded = pd.DataFrame(df_encoded, columns=categorical_encoded)

df = pd.concat([df_scaled, df_encoded, df[target]], axis=1)

print(f"The encoded categorical features are {categorical_encoded}")

# ## Define an inverse_transform function to go easily back to the non-scaled/encoded feature version

# In[18]:

def inverse_transform(df,
                      scaler,
                      encoder,
                      continuous,
                      categorical,
                      categorical_encoded,
                      ):

    df_categorical = pd.DataFrame(encoder.inverse_transform(df[categorical_encoded]), columns=categorical)
    df_continuous = pd.DataFrame(scaler.inverse_transform(df[continuous]), columns=continuous)

    return pd.concat([df_categorical, df_continuous], axis=1)

# ## Find the immutable features in their encoded form

# In[19]:

immutables_encoded = []
for immutable in immutables:
    if immutable in categorical:
        for new_col in categorical_encoded:
            match = re.search(immutable, new_col)
            if match:
                immutables_encoded.append(new_col)
    else:
        immutables_encoded.append(immutable)

print(f"Encoded immutable features are: {immutables_encoded}")

# ## Create data object to feed into MCCE method

# In[20]:

class Dataset():
    def __init__(self,
                 immutables,
                 target,
                 categorical,
                 immutables_encoded,
                 continuous,
                 features,
                 encoder,
                 scaler,
                 inverse_transform,
                 ):

        self.immutables = immutables
        self.target = target
        self.feature_order = feature_order
        self.dtypes = dtypes
        self.categorical = categorical
        self.continuous = continuous
        self.features = self.categorical + self.continuous
        self.cols = self.features + [self.target]
        self.immutables_encoded = immutables_encoded
        self.encoder = encoder
        self.scaler = scaler
        self.inverse_transform = inverse_transform

dataset = Dataset(immutables,
                  target,
                  categorical,
                  immutables_encoded,
                  continuous,
                  features,
                  encoder,
                  scaler,
                  inverse_transform)

dtypes = dict([(x, "float") for x in continuous])
for x in categorical_encoded:
    dtypes[x] = "category"
df = (df).astype(dtypes)

# ## Train predictive model

# In[21]:

y = df[target]
X = df.drop(target, axis=1)
test_size = 0.33

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=42)
clf = RandomForestClassifier(max_depth=None, random_state=0)
ml_model = clf.fit(X_train, y_train)

pred_train = ml_model.predict(X_train)
pred_test = ml_model.predict(X_test)

fpr, tpr, _ = metrics.roc_curve(y_train, pred_train, pos_label=1)
train_auc = metrics.auc(fpr, tpr)

fpr, tpr, _ = metrics.roc_curve(y_test, pred_test, pos_label=1)
test_auc = metrics.auc(fpr, tpr)

model_prediction = clf.predict(X)

print(f"The out-of-sample AUC is {round(test_auc, 2)}")

# ## Select observations to generate counterfactuals for

# In[22]:

preds = ml_model.predict_proba(df.drop(target, axis=1))[:,1]
factual_id = np.where(preds < 0.5)
factuals = df.loc[factual_id]
test_factual = factuals.iloc[:5]

print(test_factual.head(2))

# ## Fit MCCE method

# In[23]:

mcce = MCCE(dataset=dataset, model=ml_model)

print("Fit trees")
mcce.fit(df.drop(target, axis=1), dtypes)

print("Sample observations for the specific test observations")
cfs = mcce.generate(test_factual.drop(target, axis=1), k=100)

print("Process the sampled observations")
mcce.postprocess(cfs=cfs, test_factual=test_factual, cutoff=0.5, higher_cardinality=False)

# ## Print counterfactuals

# In[24]:

cfs = mcce.results_sparse
cfs['income'] = test_factual['income'] # add back the original response

# invert the features to their original form
print("Original factuals:")
decoded_factuals = dataset.inverse_transform(test_factual,
                                             scaler,
                                             encoder,
                                             continuous,
                                             categorical,
                                             categorical_encoded)[feature_order]

decoded_factuals

# In[25]:

print("Generated counterfactuals:")
decoded_cfs = dataset.inverse_transform(cfs,
                                        scaler,
                                        encoder,
                                        continuous,
                                        categorical,
                                        categorical_encoded)[feature_order]
decoded_cfs

# In[26]:

print(decoded_cfs)

# ## Calculate some metrics

# In[27]:

# distance_pd = pd.DataFrame(distance(cfs, test_factual, dataset))

# feasibility_pd = pd.DataFrame(feasibility(cfs, df, categorical_encoded + continuous), columns=['feasibility'])

# const_pd = pd.DataFrame(constraint_violation(decoded_cfs, decoded_factuals, dataset), columns=['violation'])

# success_pd = pd.DataFrame(success_rate(cfs[categorical_encoded + continuous], ml_model), columns=['success'])

# # In[28]:

# results = pd.concat([decoded_cfs, distance_pd, feasibility_pd, const_pd, success_pd], axis=1)
# results


import cv2
import matplotlib.pyplot as plt

def main():

    imgpath="C:\\Users\\ASH\\Downloads\\Compressed\\standard_test_images\\lena_color_256.tif"
    img=cv2.imread(imgpath,1)

    plt.imshow(img)
    plt.title('Image with Default ColorMap') #giving title to plot
    plt.xticks([])
    plt.yticks([])      #remove x-y scaling
    plt.show()  #show image

    #To convert BGR-formatImageColor(used by cv2) to RGB-formatImageColor(used by matplotlib)
    img =cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

    plt.imshow(img)
    plt.title('Image with Default ColorMap') #giving title to plot
    plt.xticks([])
    plt.yticks([])      #remove x-y scaling
    plt.show()  #show image

if __name__=="__main__":
    main()

COLORSPACES(Correcting color issue bw matplotlib and cv2).py


import os
from subprocess import Popen, PIPE
import sys
import threading
import codecs
import locale

from .exceptions import Failure, PlatformError
from .platform import WINDOWS

def normalize_hide(val):
    hide_vals = (None, False, 'out', 'stdout', 'err', 'stderr', 'both', True)
    if val not in hide_vals:
        err = "'hide' got {0!r} which is not in {1!r}"
        raise ValueError(err.format(val, hide_vals))
    if val in (None, False):
        hide = ()
    elif val in ('both', True):
        hide = ('out', 'err')
    elif val == 'stdout':
        hide = ('out',)
    elif val == 'stderr':
        hide = ('err',)
    else:
        hide = (val,)
    return hide

class Runner(object):
    """
    Partially-abstract core command-running API.

    This class is not usable by itself and must be subclassed to implement, at
    minimum, ``run_direct`` and ``run_pty``. An explanation of its methods
    follows:

    ``run`` is the primary API call which handles high level logic (echoing the
    commands locally, constructing a useful `Result` object, etc) and
    wraps/delegates to the below methods for actual execution.

    ``select_method`` takes ``pty`` and ``fallback`` kwargs and returns the
    current object's ``run_direct`` or ``run_pty`` method, depending on those
    kwargs' values and environmental cues/limitations. `Runner` itself has a
    useful default implementation of this method, but overriding may be
    sometimes useful.

    ``run_direct`` and ``run_pty`` are fully abstract in `Runner`; in
    subclasses, they should perform actual command execution, hooking directly
    into a subprocess' stdout/stderr pipes and returning those pipes' eventual
    full contents as distinct strings.

    ``run_direct``/``run_pty`` both have a signature of ``(self, command, warn,
    hide, encoding)`` (see `run` for semantics of these) and must return a
    4-tuple of ``(stdout, stderr, exitcode, exception)`` (see `Result` for
    their meaning).

    ``run_pty`` differs from ``run_direct`` in that it should utilize a
    pseudo-terminal, and is expected to only return a useful ``stdout`` (with
    ``stderr`` usually set to the empty string.)

    For a subclass implementation example, see the source code for `.Local`.
    """
    def run(
        self,
        command,
        warn=False,
        hide=None,
        pty=False,
        fallback=True,
        echo=False,
        encoding=None,
    ):
        """
        Execute ``command``, returning a `Result` object.

        :param str command: The shell command to execute.

        :param bool warn:
            Whether to warn and continue, instead of raising `.Failure`, when
            the executed command exits with a nonzero status. Default:
            ``False``.

        :param hide:
            Allows the caller to disable ``run``'s default behavior of copying
            the subprocess' stdout and stderr to the controlling terminal.
            Specify ``hide='out'`` (or ``'stdout'``) to hide only the stdout
            stream, ``hide='err'`` (or ``'stderr'``) to hide only stderr, or
            ``hide='both'`` (or ``True``) to hide both streams.

            The default value is ``None``, meaning to print everything;
            ``False`` will also disable hiding.

            .. note::
                Stdout and stderr are always captured and stored in the
                ``Result`` object, regardless of ``hide``'s value.

        :param bool pty:
            By default, ``run`` connects directly to the invoked process and
            reads its stdout/stderr streams. Some programs will buffer (or even
            behave) differently in this situation compared to using an actual
            terminal or pty. To use a pty, specify ``pty=True``.

            .. warning::
                Due to their nature, ptys have a single output stream, so the
                ability to tell stdout apart from stderr is **not possible**
                when ``pty=True``. As such, all output will appear on your
                local stdout and be captured into the ``stdout`` result
                attribute. Stderr and ``stderr`` will always be empty when
                ``pty=True``.

        :param bool fallback:
            Controls auto-fallback behavior re: problems offering a pty when
            ``pty=True``. Whether this has any effect depends on the specific
            `Runner` subclass being invoked. Default: ``True``.

        :param bool echo:
            Controls whether `.run` prints the command string to local stdout
            prior to executing it. Default: ``False``.

        :param str encoding:
            Override auto-detection of which encoding the subprocess is using
            for its stdout/stderr streams. Defaults to the return value of
            ``locale.getpreferredencoding(False)``).

        :returns: `Result`

        :raises: `.Failure` (if the command exited nonzero & ``warn=False``)
        """
        hide = normalize_hide(hide)
        exception = False
        if echo:
            print("\033[1;37m{0}\033[0m".format(command))
        func = self.select_method(pty=pty, fallback=fallback)
        stdout, stderr, exited, exception = func(
            command=command,
            warn=warn,
            hide=hide,
            encoding=encoding
        )
        # TODO: make this test less gross? Feels silly to just return a bool in
        # select_method which is tantamount to this, though.
        func_name = getattr(func, 'func_name', getattr(func, '__name__'))
        used_pty = func_name == 'run_pty'
        result = Result(
            stdout=stdout,
            stderr=stderr,
            exited=exited,
            pty=used_pty,
            exception=exception,
        )
        if not (result or warn):
            raise Failure(result)
        return result

    def select_method(self, pty, fallback):
        # NOTE: fallback not used: no falling back implemented by default.
        return getattr(self, 'run_pty' if pty else 'run_direct')

    def run_direct(self, command, warn, hide, encoding):
        raise NotImplementedError

    def run_pty(self, command, warn, hide, encoding):
        raise NotImplementedError

class Local(Runner):
    """
    Execute a command on the local system in a subprocess.

    .. note::
        When Invoke itself is executed without a valid PTY (i.e.
        ``os.isatty(sys.stdin)`` is ``False``), it's not possible to present a
        handle on our PTY to local subprocesses. In such situations, `Local`
        will fallback to behaving as if ``pty=False``, on the theory that
        degraded execution is better than none at all, as well as printing a
        warning to stderr.

        To disable this behavior (i.e. if ``os.isatty`` is causing false
        negatives in your environment), say ``fallback=False``.
    """
    def select_method(self, pty=False, fallback=True):
        func = self.run_direct
        if pty:
            func = self.run_pty
            if not os.isatty(sys.stdin.fileno()) and fallback:
                sys.stderr.write("WARNING: stdin is not a pty; falling back to non-pty execution!\n") # noqa
                func = self.run_direct
        return func

    def run_direct(self, command, warn, hide, encoding):
        process = Popen(
            command,
            shell=True,
            stdout=PIPE,
            stderr=PIPE,
        )

        if encoding is None:
            encoding = locale.getpreferredencoding(False)

        def display(src, dst, cap, hide):
            def get():
                while True:
                    data = os.read(src.fileno(), 1000)
                    if not data:
                        break
                    yield data
            for data in codecs.iterdecode(get(), encoding, errors='replace'):
                if not hide:
                    dst.write(data)
                    dst.flush()
                cap.append(data)

        stdout = []
        stderr = []
        threads = []

        for args in (
            (process.stdout, sys.stdout, stdout, 'out' in hide),
            (process.stderr, sys.stderr, stderr, 'err' in hide),
        ):
            t = threading.Thread(target=display, args=args)
            threads.append(t)
            t.start()

        process.wait()
        for t in threads:
            t.join()

        stdout = ''.join(stdout)
        stderr = ''.join(stderr)
        if WINDOWS:
            # "Universal newlines" - replace all standard forms of
            # newline with \n. This is not technically Windows related
            # (\r as newline is an old Mac convention) but we only apply
            # the translation for Windows as that's the only platform
            # it is likely to matter for these days.
            stdout = stdout.replace("\r\n", "\n").replace("\r", "\n")
            stderr = stderr.replace("\r\n", "\n").replace("\r", "\n")

        return stdout, stderr, process.returncode, None

    def run_pty(self, command, warn, hide, encoding):
        # Sanity check: platforms that can't pexpect should explode usefully
        # here. (Without this, the pexpect import throws an inner
        # ImportException trying to 'import pty' which is unavailable on
        # Windows. Better to do this here than truly-fork pexpect.)
        if WINDOWS:
            err = "You seem to be on Windows, which doesn't support ptys!"
            raise PlatformError(err)
        # Proceed as normal for POSIX/etc platforms, with a runtime import
        from .vendor import pexpect

        out = []
        def out_filter(text):
            # Maybe use encoding here as in run() above...
            out.append(text.decode("utf-8", 'replace'))
            if 'out' not in hide:
                return text
            else:
                return b""
        p = pexpect.spawn("/bin/bash", ["-c", command])
        # Ensure pexpect doesn't barf with OSError if we fall off the end of
        # the child's input on some platforms (e.g. Linux).
        exception = None
        try:
            p.interact(output_filter=out_filter)
        except OSError as e:
            # Only capture the OSError we expect
            if "Input/output error" not in str(e):
                raise
            # Ensure it ties off the child, sets exitstatus, etc
            p.close()
            # Capture the exception in case it's NOT the OSError we think it
            # is and folks need to debug
            exception = e
        return "".join(out), "", p.exitstatus, exception

class Result(object):
    """
    A container for information about the result of a command execution.

    `Result` instances have the following attributes:

    * ``stdout``: The subprocess' standard output, as a multiline string.
    * ``stderr``: Same as ``stdout`` but containing standard error (unless
      the process was invoked via a pty; see `run`.)
    * ``exited``: An integer representing the subprocess' exit/return code.
    * ``return_code``: An alias to ``exited``.
    * ``ok``: A boolean equivalent to ``exited == 0``.
    * ``failed``: The inverse of ``ok``: ``True`` if the program exited with a
      nonzero return code.
    * ``pty``: A boolean describing whether the subprocess was invoked with a
      pty or not; see `run`.
    * ``exception``: Typically ``None``, but may be an exception object if
      ``pty`` was ``True`` and ``run()`` had to swallow an apparently-spurious
      ``OSError``. Solely for sanity checking/debugging purposes.

    `Result` objects' truth evaluation is equivalent to their ``ok``
    attribute's value.
    """
    # TODO: inherit from namedtuple instead? heh
    def __init__(self, stdout, stderr, exited, pty, exception=None):
        self.exited = self.return_code = exited
        self.stdout = stdout
        self.stderr = stderr
        self.pty = pty
        self.exception = exception

    def __nonzero__(self):
        # Holy mismatch between name and implementation, Batman!
        return self.exited == 0

    # Python 3 ahoy
    def __bool__(self):
        return self.__nonzero__()

    def __str__(self):
        ret = ["Command exited with status {0}.".format(self.exited)]
        for x in ('stdout', 'stderr'):
            val = getattr(self, x)
            ret.append("""=== {0} ===
{1}
""".format(x, val.rstrip()) if val else "(no {0})".format(x))
        return "\n".join(ret)

    @property
    def ok(self):
        return self.exited == 0

    @property
    def failed(self):
        return not self.ok

def run(command, **kwargs):
    """
    Invoke ``command`` in a subprocess and return a `Result` object.

    This function is simply a convenience wrapper for creating a `Runner`
    subclass (default: `Local`) and calling its `~.Runner.run` method. Please
    see `.Runner.run` for details on all behaviors & arguments, sans the below.

    :param runner: Class to use for command execution. Default: `Local`.
    """
    runner = kwargs.pop('runner', Local)()
    return runner.run(command, **kwargs)


import os

cards_folder = "assets/images/cards/fronts"

nums = [str(i) for i in range(1, 10)]
nums.extend(["X", "J", "Q", "K"])

suits = ["c", "h", "d", "s"]

with open("output.txt", "w") as f:
    for suit in suits:
        for num in nums:
            f.write("\"" + cards_folder + "/" + suit + num + ".png" + "\",\n")