import os
import sublime
import unittest

from ..consts import INFO, WARNING, ERROR
from ..utils import (
    find,
    get_default_python_command,
    get_severity_status_string,
    get_error_count,
)

def merge_two_lists(fst, snd):
    return fst + list(set(snd) - set(fst))

class TestUtils(unittest.TestCase):
    def setUp(self):
        self.real_path_environ = os.environ["PATH"]
        self.subl_error_message = sublime.error_message
        self.message_info = {}
        self.message_info[INFO] = 11
        self.message_info[WARNING] = 7
        self.message_info[ERROR] = 4

    def test_find_success(self):
        errors = [
            {"id": 1, "region": range(123, 222)},
            {"id": 2, "region": range(389, 562)},
        ]
        point = 437
        elem = find(point, errors)
        self.assertEqual(elem.get("id"), 2)

    def test_find_failure(self):
        errors = [
            {"id": 1, "region": range(123, 222)},
            {"id": 2, "region": range(389, 562)},
        ]
        point = 837
        elem = find(point, errors)
        self.assertRaises(Exception)

    def test_get_default_python_command_success(self):
        return_val = get_default_python_command()
        self.assertEqual(return_val, 'python3')

    def test_get_default_python_command_fail(self):
        os.environ["PATH"] = os.path.sep
        sublime.error_message = print
        return_val = get_default_python_command()
        self.assertIsNone(return_val)
        os.environ["PATH"] = self.real_path_environ
        sublime.error_message = self.subl_error_message

    def test_merge_two_lists_both_empty(self):
        result = merge_two_lists([], [])
        self.assertEqual(len(result), 0)

    def test_merge_two_lists_one_empty(self):
        result = merge_two_lists(["one", "two", 3], [])
        self.assertEqual(len(result), 3)
        self.assertIn("one", result)

    def test_merge_two_lists_both_with_elements(self):
        result = merge_two_lists(["one", "two", 3], ["blue", True, "something"])
        self.assertEqual(len(result), 6)
        self.assertIn("one", result)
        self.assertIn("something", result)
        self.assertIn(True, result)

    def test_merge_two_lists_with_overlapping_elements(self):
        result = merge_two_lists(["one", "two", 3, True], ["blue", True, "one"])
        self.assertEqual(len(result), 5)
        self.assertIn("one", result)
        self.assertIn("blue", result)
        self.assertIn(True, result)

    def test_get_severity_status_string_info(self):
        result = get_severity_status_string(INFO)
        self.assertEqual(result, "   ⓘ")

    def test_get_severity_status_string_warning(self):
        result = get_severity_status_string(WARNING)
        self.assertEqual(result, "   ⚠")

    def test_get_severity_status_string_error(self):
        result = get_severity_status_string(ERROR)
        self.assertEqual(result, "   ⛔")

    def test_get_error_count(self):
        result = get_error_count(self.message_info, "something something ")
        self.assertEqual(result, "something something ⛔ 4 ⚠ 7 ⓘ 11 ")

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


import json, pytz
from dotenv import load_dotenv
from datetime import datetime
from dagster import sensor, RunRequest, SkipReason, get_dagster_logger
from models.cancel_queue import CancelQueue
from ops.helpers.db_config import db_conn

conn = db_conn()
load_dotenv()

my_logger = get_dagster_logger()

@sensor(job_name="amz_submit_cancel_orders", minimum_interval_seconds=60)
def process_submit_cancel_orders():
    pacific_zone = pytz.timezone('US/Pacific')
    orders_list = (
        conn.query(CancelQueue.order_number)
        .where(
            CancelQueue.desktopshipper_cancel == 1,
            CancelQueue.skubana_cancel == 1,
            CancelQueue.amazon_cancel == 0,
            CancelQueue.last_processed_at <= datetime.now(pacific_zone),
            CancelQueue.processing_status.in_(tuple(['PENDING', 'FAILED']))
        )
        .distinct()
        .all()
    )

    if len(orders_list) < 1:
        yield SkipReason("No New Order ")
        return
    result = []
    for order in orders_list:
        print('\n\n', 'order.order_number', order.order_number)
        item_list = (
            conn.query(
                CancelQueue.cancel_id,
                CancelQueue.order_item_id,
                CancelQueue.buyer_cancellation_reason
            )
            .where(
                CancelQueue.order_number == order.order_number)
            .all()
        )
        order_items = []
        for item in item_list:
            order_items.append({
                "cancel_id": item.cancel_id,
                "order_item_id": item.order_item_id,
                "buyer_cancellation_reason": item.buyer_cancellation_reason
            })
        result.append({
            order.order_number: order_items
        })
    record_timestamp = datetime.now().timestamp()
    run_key = str(record_timestamp) + "_orders_" + str(len(orders_list))
    yield RunRequest(
        run_key,
        run_config={
            "resources": {
                "report_details": {"config": {"id": json.dumps({"cqs": result})}}
            },
        },
        tags={"job_type": 'amz_submit_cancel_orders'},
    )


from turtle import Turtle, Screen
import random

scr = Screen()
scr.setup(width=500, height=400)
user_bet = scr.textinput(title="Make your bet", prompt="Which color turtle will win the race? red,orange,yellow,"
                                                       "green,blue,purple: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
turtles = []
for color in colors:
    turtles.append(Turtle(shape="turtle"))
for turtle in turtles:
    turtle.speed(0)
    turtle.penup()
    turtle.color(colors[turtles.index(turtle)])
    turtle.goto(-230, -100 + 50 * turtles.index(turtle))
race_on = True
while race_on:
    for turtle in turtles:
        if turtle.xcor() > 230:
            race_on = False
            winner = turtle.pencolor()
            if winner == user_bet:
                print(f"You've won! The {winner} turtle is the winner!")
            else:
                print(f"You've lost! The {winner} turtle is the winner!")
            break
        turtle.forward(random.randint(0, 10))

scr.exitonclick()


# https://leetcode.com/problems/jump-game/
# Solved Date: 20.04.25.

def fast_can_jump(nums):
    # https://leetcode.com/problems/jump-game/discuss/596266/Python-simple-O(N)-time-O(1)-space-solution
    max_pos = 0
    for index in range(len(nums)):
        max_pos = max(max_pos, index + nums[index])
        if max_pos == index or max_pos >= len(nums) - 1:
            break
    return max_pos >= len(nums) - 1

def can_jump(nums):
    # dp와 비슷하나, time out남
    possible = {}
    for index in range(len(nums)-1, -1, -1):
        length = len(nums) - 1 - index
        for jump in range(nums[index] + 1):
            if jump == length:
                possible[length] = 1
                break
            elif length - jump in possible:
                possible[length] = 1
                break
    if len(nums) - 1 in possible:
        return True
    else:
        return False

def main():
    nums = [int(x) for x in input().split()]
    print(fast_can_jump(nums))

if __name__ == '__main__':
    main()


"""Command line interface"""
import os
import os.path
import time
import buildver
from buildver import error

__all__ = []

HELP = """\
Build and versioning tool for Python projects.

Check a project
===============
$ buildver check

Set a new version
=================
$ buildver set <version>

Build your project
==================
$ buildver build

Build then set a new version
============================
$ buildver build then <version>

Note: Use "+maj", "+min" and "+rev" to increment
the current version of your project. These version
modifiers increment the "major", "minor", and "revision"
numbers respectively.

 Current | Modifier | Next   |
---------|----------|--------|
 1.0.0   | +rev     | 1.0.1  |
 1.0.1   | +min     | 1.1.0  |
 1.1.0   | +maj     | 2.0.0  |

By default, the command "build" will build a distribution
package, then automatically increment the revision number
of the current version. If you don't want the version number
incremented automatically, use the "pass" modifier:
$ buildver build then pass

Read more online:
https://github.com/pyrustic/buildver
"""

def print_help(*args, project_dir=None):
    print(HELP)

def check_project(*args, project_dir=None):
    project_dir = project_dir if project_dir else os.getcwd()
    try:
        project_version = buildver.get_version(project_dir)
    except error.MissingVersionFileError as e:
        print("Missing VERSION file.")
        return
    else:
        if not project_version:
            project_version = "0.0.0"
            buildver.set_version(project_version, project_dir)
    project_name = os.path.basename(project_dir)
    print("{} v{} (source)".format(project_name, project_version))
    # Latest build
    latest_build_info = buildver.get_latest_build(project_dir)
    if not latest_build_info:
        return
    version, timestamp = latest_build_info
    time_elapsed = _stringify_time_elapsed(timestamp)
    time_elapsed = "{}".format(time_elapsed) if time_elapsed else ""
    print(".whl v{} (package) built {}".format(version, time_elapsed))

def set_version(*args, project_dir=None):
    if not args:
        print("Missing version number.")
        return
    if len(args) > 1:
        print("Wrong usage of the command.")
        return
    project_dir = project_dir if project_dir else os.getcwd()
    new_version = args[0]
    if " " in new_version:
        print("Invalid version.")
        return
    current_version = None
    try:
        current_version = buildver.get_version(project_dir)
    except error.MissingVersionFileError as e:
        pass
    current_version = current_version if current_version else "0.0.0"
    if new_version:
        try:
            new_version = buildver.interpret_version(current_version, new_version)
        except ValueError as e:
            print("Failed to set the version. Please check the VERSION file.")
            return
        except Exception as e:
            print("Failed to set the version.")
            return
    else:
        new_version = "0.0.1"
    if current_version == new_version:
        print("VERSION file not updated")
    else:
        buildver.set_version(new_version, project_dir)
        print("VERSION file updated from {} to {}".format(current_version,
                                                          new_version))

def build_project(*args, project_dir=None):
    if not args:
        next_version = "+rev"
    elif len(args) == 1:
        print("Wrong usage of the command.")
        return
    else:
        if args[0] == "then":
            next_version = args[1]
        else:
            print("Wrong usage of the command.")
            return
    project_dir = project_dir if project_dir else os.getcwd()
    try:
        cur_version = buildver.get_version(project_dir)
    except error.MissingVersionFileError as e:
        print("Missing VERSION file.")
        return
    # BUILD
    print("building v{} ...".format(cur_version))
    success, _ = buildver.build_project(project_dir)
    if success:
        buildver.update_build_report(cur_version, project_dir)
    else:
        print("Failed to build a distribution package")
        return
    project_name = os.path.basename(project_dir)
    print("Successfully built '{}' v{} !".format(project_name, cur_version))
    # set next version
    set_version(next_version, project_dir=project_dir)

def _stringify_time_elapsed(timestamp):
    if not timestamp:
        return ""
    timestamp = int(timestamp)
    now = time.time()
    seconds_elapsed = int(now - timestamp)
    years, days, hours, minutes, seconds = _time_elapsed(seconds_elapsed)
    if years:
        return _x_ago(years, "year")
    if days:
        return _x_ago(days, "day")
    if hours:
        return _x_ago(hours, "hour")
    if minutes:
        return _x_ago(minutes, "min")
    if seconds:
        return _x_ago(seconds, "sec")

def _x_ago(x, name):
    plural = ""
    if x > 1:
        plural = "s"
    return "{} {}{} ago".format(x, name, plural)

def _time_elapsed(seconds_elapsed):
    s_in_min = 60
    s_in_hour = s_in_min * 60
    s_in_day = s_in_hour * 24
    s_in_year = s_in_day * 365
    years, remainder = divmod(seconds_elapsed, s_in_year)
    days, remainder = divmod(seconds_elapsed, s_in_day)
    hours, remainder = divmod(remainder, s_in_hour)
    minutes, seconds = divmod(remainder, s_in_min)
    return years, days, hours, minutes, seconds


"""
Contains the abstract class of a probability distrobution and associated marginals.
"""
import numpy as np
from ..utilities import utils
from ..utilities.profiler import profile
from .variable import RandomVariableCollection
from . import variable_sort
from functools import reduce
import math
from ..utilities.constants import *

class ProbDist():

    def __init__(self, rvc, support):
        self._support = np.asarray(support)
        if (self._support.size == 0):
            self.__is_null = True
        else:
            self.__is_null = False
        # print(self._support > 0)
        if not np.all(self._support >= 0):
            if not np.all(self._support >= -mach_tol):
                print(self._support)
                raise Exception("Some of the support is negative.")
            else:
                # print(self._support)
                self._support[np.where(self._support <= mach_tol)] = 0.0
        sum_support = np.sum(self._support)
        if utils.is_close(sum_support,1.0):
            self.__impossible = False
        elif utils.is_close(sum_support,0.0):
            self.__impossible = True
        else:
            raise ValueError("Probability distribution does not sum to 1.0 or 0.0. Sums to {0}".format(sum_support))
        self._rvc = rvc
        self._num_variables = len(self._rvc)
        # if axis_map is not None:
        #     self._axis_map = axis_map
        # else:
        # Assume order matches canonical order
        self._correlation_settings = {'method': 'same'}
        self._axis_map = self._rvc.names.dict

    def _multi_axis_map(self, names):
        return tuple(self._axis_map[name] for name in names)

    @staticmethod
    def distance(pd_a, pd_b):
        assert(pd_a._rvc == pd_b._rvc), "Random Variables don't match."
        dist = 0.0
        for a, b in zip(pd_a.canonical_ravel(), pd_b.canonical_ravel()):
            dist += (b - a)**2
        return math.sqrt(dist)

    @staticmethod
    def from_callable_support(rvc, callable_support):
        array_dims = tuple(rv.num_outcomes for rv in rvc)
        # print(array_dims)
        support = np.zeros(array_dims)
        for _, outcome_index, outcome in rvc.iter_named_outcomes():
            p = callable_support(*outcome)
            support[outcome_index] = p
        return ProbDist(rvc, support)

    @staticmethod
    def product_marginals(*args, **kwargs):
        pds = [pd for pd in args if not pd.__is_null]
        if len(pds) == 0:
            raise Exception("Distributions are empty.")
        if len(pds) == 1:
            return pds[0]
        rvcs = [pd._rvc for pd in pds]
        supports = [pd._support for pd in pds]
        joint_support = reduce(lambda a,b: np.tensordot(a,b,axes=0), supports)
        assert(joint_support.shape == sum([s.shape for s in supports], ()))
        # print("---------")
        # print(joint_support.ravel())
        if kwargs.get('transpose_sort', True):
            variable_names = sum([rvs.names.list for rvs in rvcs], [])
            variable_names_sort = variable_sort.argsort(variable_names)
            joint_support = np.transpose(joint_support, axes=variable_names_sort)
        # print(variable_names_sort)
        # print(sorted_support.ravel())
        return joint_support

    def __mul__(A,B):
        if A._rvc.intersection(B._rvc):
            raise Exception("Can't multiply distributions that share random variables.")
        AB_rvc = A._rvc.union(B._rvc)
        AB = A.__new_child(AB_rvc, ProbDist.product_marginals(A,B, transpose_sort=True))
        return AB

    def _sub_support(self, outcome_dict):
        outcome_association = []
        slice_obj = [slice(None)] * self._num_variables
        for rv_name, outcome_label in outcome_dict.items():
            rv = self._rvc.get_rv(rv_name)
            outcome_index = rv.outcomes.index(outcome_label)
            slice_obj[self._axis_map[rv_name]] = outcome_index
            outcome_association.append((rv, outcome_index))
        sub_support = self._support[tuple(slice_obj)]
        return sub_support, outcome_association

    def prob(self, outcome_dict):
        sub_support, _ = self._sub_support(outcome_dict)
        prob = np.sum(sub_support)
        return prob

    def _dev_slice(self, slice):
        return self._support[slice]

    def _total_prob(self, selectors):
        total = 0.0
        for i in selectors:
            total += self._support[i]
        return total

    def correlation(self, rvc_names):
        rvc = self._rvc.sub(rvc_names)
        return self._correlation(rvc)

    def update_correlation_settings(self, settings):
        self._correlation_settings.update(settings)

    def _correlation(self, rvc):
        s = self._correlation_settings
        method = s['method']
        mpd = self._marginal(rvc)
        additive = []
        subtractive = []
        for names, outcome_indices, outcome in rvc.iter_named_outcomes():
            slice_indices = tuple(outcome_indices[i] for i in mpd._multi_axis_map(names))
            if method=='same':
                is_additive = False
                if 'mod' in s:
                    is_additive = utils.all_equal(utils.list_mod(outcome, mod=s['mod']))
                else:
                    is_additive = utils.all_equal(outcome)
                if is_additive:
                    additive.append(slice_indices)
                else:
                    subtractive.append(slice_indices)
            if method=='two_expect':
                # assume outcomes mean {-1, +1}
                product_outcome = (-1)**(len(outcome) - sum(outcome))
                if product_outcome == 1:
                    additive.append(slice_indices)
                else:
                    subtractive.append(slice_indices)
        add_prob = mpd._total_prob(additive)
        sub_prob = mpd._total_prob(subtractive)
        return add_prob - sub_prob

    def __new_child(self, rvc, support):
        child = ProbDist(rvc, support)
        child.update_correlation_settings(self._correlation_settings)
        return child

    def condition(self, cond_outcome_dict):
        sub_support, outcome_association = self._sub_support(cond_outcome_dict)
        prob = np.sum(sub_support)
        if prob != 0.0:
            sub_support = sub_support / prob
        rvs = [rv_assoc[0] for rv_assoc in outcome_association]
        d_rvc = self._rvc - RandomVariableCollection(rvs)
        conditioned_pd = self.__new_child(d_rvc, sub_support)
        return conditioned_pd

    def marginal(self, rvc_names):
        rvc = self._rvc.sub(rvc_names)
        return self._marginal(rvc)

    def _marginal(self, rvc):
        rv_to_sum = self._rvc - rvc
        if not rv_to_sum:
            return self
        else:
            axis_to_keep = [self._axis_map[rv.name] for rv in rvc]
            axis_to_sum = tuple(set(range(self._support.ndim)) - set(axis_to_keep))
            marginal_support = np.sum(self._support, axis=axis_to_sum)
            marginal_pd = self.__new_child(rvc, marginal_support)
            return marginal_pd

    def H(self, *args):
        return self.entropy(*args)

    def entropy(self, X_names, Y_names=()):
        X = self._rvc.sub(X_names)
        Y = self._rvc.sub(Y_names)
        return self._entropy(X, Y)

    def _entropy(self, X, Y):
        XY = X.union(Y)
        p_XY = self._marginal(XY)
        p_Y = self._marginal(Y)
        H_XY = utils.entropy(p_XY._support)
        H_Y = utils.entropy(p_Y._support)
        # Chain rule H(X|Y) = H(Y, X) - H(Y)
        return H_XY - H_Y

    def I(self, *args):
        return self.mutual_information(*args)

    def mutual_information(self, Xs_names, Y_names=[]):
        Xs = tuple(self._rvc.sub(X_names) for X_names in Xs_names)
        Y = self._rvc.sub(Y_names)
        return self._mutual_information(Xs, Y)

    def _mutual_information(self, Xs, Y):
        if len(Xs) > 1:
            Xs_reduced = Xs[0:-1]
            Y_expanded = Y.union(Xs[-1])

            return self._mutual_information(Xs_reduced, Y) - \
                   self._mutual_information(Xs_reduced, Y_expanded)
        elif len(Xs) == 1:
            return self._entropy(Xs[0], Y)
        else:
            return 0

    def _unpack_prob_space(self):
        for names, indices, outcome in self._rvc.iter_named_outcomes():
            axis_desc = self._multi_axis_map(names)
            support_slice = [0]*len(names)
            for i, slice_index in enumerate(axis_desc):
                support_slice[slice_index] = indices[i]
            p = self._support[tuple(support_slice)]
            yield outcome, p

    def canonical_ravel(self):
        for outcome, p in self._unpack_prob_space():
            yield p

    def __str__(self):
        fs = "{outcome} -> {probability}"
        print_list = ["=== ProbDist ==="]
        # print_list.append(self.__repr__())
        print_list.append(str(self._rvc))
        print_list.append("{0} Achievable outcomes.".format(np.count_nonzero(self._support)))
        print_list.append(fs)
        for outcome, p in self._unpack_prob_space():
            if p > 1e-5:
                print_list.append(fs.format(outcome=outcome, probability=p))
        print_list.append("================")
        return '\n'.join(print_list)

@profile
def perform_tests():
    rvc = RandomVariableCollection({})
    support = []
    pd = ProbDist(rvc, support)
    print(pd)
    print(pd.prob({}))

if __name__ == '__main__':
    perform_tests()


import tornado.web
import mallory

class HeartbeatHandler(tornado.web.RequestHandler):
    def initialize(self, circuit_breaker):
        self.circuit_breaker = circuit_breaker

    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self):
        if self.circuit_breaker.is_tripped():
            self.set_status(503)
            status_message = "Circuit Breaker Tripped"
        else:
            self.set_status(200)
            status_message = "OK"

        self.write("Mallory " + mallory.Version + "\n")
        self.write(status_message)
        self.finish()


from selenium import webdriver
from time import sleep
import csv
from selenium.webdriver.chrome.options import Options
import threading
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from MyClasses import LinkPDF

browsers = []
threads = []
lock = threading.Lock()
chrome_options = Options()
chrome_options.add_argument("--headless")
sleep(2)
links =[]
for i in range(1, 2):
    links.append(LinkPDF(f"https://www.centralbankbahamas.com/bank-supervision/warning-notices"))
def thread_task(url) :
    browser = webdriver.Chrome()
    browser.get(url)
    sleep(4)
    for i in range(1,1000) :
        try :
            linkElement = WebDriverWait(browser, 10).until(
                EC.presence_of_element_located((By.XPATH,f'/html/body/div[5]/section[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/table/tbody/tr[{i}]/td[1]/div/span/a')))
        except :
            print("cant find element")
            break
        link = linkElement.get_attribute("href")
        print(link)
    file_path = f'links_{i}.csv'
    #with lock:
        #with open(file_path, 'a', encoding="utf-8") as txt:
            #txt.write(f'{link}\n')
    browser.quit()

for link in links:
    thread = threading.Thread(target=thread_task, args=(link.URL,))
    thread.start()
    threads.append(thread)

# Chờ cho tất cả các luồng hoàn thành
for thread in threads:
    thread.join()


import requests
from bs4 import BeautifulSoup
import time, uuid
from datetime import datetime, timedelta
from database import connectToDatabase

def time24hrsback():             #gives the timestamp before 24 hrs
    before24Hours = datetime.today() - timedelta(days=1)
    return before24Hours

def alreadycrawled(link):        #to check if the link is already cralwed between last 24 hrs
    db = connectToDatabase()
    condition = { '$and' : [{"link":link},{"time": {"$gte": time24hrsback()}}] }
    if (db.Links.count_documents(condition) > 0) :
        db.Links.update_many({"link":link}, {"$set" : { 'isCrawled': True,
                'lastCrawlDt': datetime.today().replace(microsecond=0)}})

        return True
    else :
        return False

def getResponse(link):
    response = requests.get(link)
    return(response)

def saveFile(link):
    response = getResponse(link)
    soup = BeautifulSoup(response.content, 'html5lib')
    random_file = str(uuid.uuid4())           #gives random name to the file
    with open ("html/{}.html".format(random_file), 'w') as file:
       file.write(soup.prettify())
    filePath= ("html/{}.html".format(random_file))
    return filePath

def validLinks(link):
    response = requests.get(link)
    soup = BeautifulSoup(response.content, 'html5lib')
    atags = soup.find_all("a", href=True)             #to find all anchor tags with 'href' attribute

    links =[]
    no_of_links = 0

    for i in atags:
        href = i['href']

        if(i.get('href') == '#' ):
            #invalid Link
            continue

        if(i.get('href') =='javascript:'):
           #invalid Link
           continue

        if(i.get('href') ==''):
           #Invalid Link
           continue

        if(i.get('href') =='#xyz'):
           #Invalid Link
           continue

        if(i.get('href') =='http://'):
           #valid Link
           #absolute Link
           links.append(href)
           no_of_links += 1
           continue

        if(i.get('href') =='//'):
           #valid link
           #append
           links.append('https:' + href)
           no_of_links += 1
           continue

    if(no_of_links == 0):
        print('All links crawled')
    return links

time.sleep(10)


import PySimpleGUI as sg
from signup import sign_up_gui
def driver_gui(db):
    sg.theme('LightGrey1')   # Add a touch of color
    # All the stuff inside your window.
    # get the list of cars that belong to the driver
    username = db.get_username()
    print(username)

    user_data = db.get_driver_info(username)
    print(user_data)
    cars = db.get_cars(username)
    cars = [car[0] for car in cars]
    trip = db.get_driver_trip(username)
    print(trip)
    state_list = ['Waiting for approval',  'On the way', 'Passenger in the car', 'Delivered', 'Cancelled']
    if cars == []:
        layout = [  [sg.Image(r'logo50.png')],
                    [sg.Text('Hey! You have no cars registered yet!')],
                    [sg.Button('Register a car'), sg.Button('Cancel')] ]
    elif len(cars)>0:
        layout = [[sg.Image(r'logo50.png')],
                [sg.Text('Hey! Here is your trip information.',visible=len(trip)>0), sg.Checkbox("Availability", user_data[-3], checkbox_color="blue", key="availability", visible=len(cars)>0)],
                [sg.Text('Hey! You have no trips registered yet! Wait for a passenger to request a trip. Your trips will appear here.', visible=len(trip)==0)],
                [sg.Listbox(values=trip, size=(60, 6), key='trip', visible=len(trip)>0)],
                [sg.Button('Select Trip',visible=len(trip)>0), sg.Button('Set Availability', visible = len(cars)>0), sg.Button('Exit')]]

    # Create the Window
    window = sg.Window('RideLink - Driver', layout)

    # Event Loop to process "events" and get the "values" of the inputs
    while True:
        event, values = window.read()

        if event == 'Register a car':
            register_car_gui(db)
            break
        elif event == 'Start':
            driver_gui(db)
            break
        elif event == 'Select Trip':
            if values['trip'] == []:
                sg.popup('Please select a trip!')
                continue
                #['21, 1, 34 ALP 64, 2023-05-21 21:13:11, Waiting for approval', '7, 2, 35 FT 454, 2023-04-27 07:06:39, Passenger in the car']
            selected_trip = values['trip'][0].split(', ') # Get the first selected item
            layout = [[sg.Image(r'logo50.png')],
                    [sg.Text('Hey! Here is your trip information.')],
                    [sg.Text('Trip ID: ' + selected_trip[0])],
                    [sg.Text('Car Plate: ' + selected_trip[2])],
                    [sg.Text('Start Time: ' + selected_trip[3])],
                    [sg.Combo(state_list[state_list.index(selected_trip[4]):int(state_list.index(selected_trip[4]))+1 if state_list.index(selected_trip[4])>2   else int(len(state_list))], default_value=selected_trip[4], key='status')],
                    [sg.Button('Change Status'), sg.Button('Cancel')]]
            window.close()
            window = sg.Window('RideLink - Driver', layout)

        elif event == 'Change Status':
            if values['status'] == selected_trip[4]:
                sg.popup('Status not changed!')
                continue
            db.update_trip_status(selected_trip[0], values['status'])
            sg.popup('Status changed!')
            driver_gui(db)
            break
        elif event == 'Set Availability':
            if values['availability'] == user_data[-3]:
                sg.popup('Availability not changed!')
                continue
            db.update_driver_availability(username, values['availability'])
            sg.popup('Availability changed!')
            driver_gui(db)
            break
        elif event == 'Cancel':
            driver_gui(db)
            break
        elif event == 'Exit':
            break

    window.close()

def register_car_gui(db):
    print('s')


from django.urls import path

from . import views

app_name = "api"
urlpatterns = [
    path("create/", views.create, name="create"),
    path("read/", views.read, name="read"),
    path("update/", views.update, name="update"),
    path("delete/", views.delete, name="delete"),
    path("read/<int:transaction_id>/", views.read_by_id, name="read_by_id"),
]


import speech_recognition as sr # recognise speech
import playsound # to play an audio file
from gtts import gTTS # google text to speech
import random
from time import ctime # get time details
import webbrowser # open browser
import ssl
import certifi
import time
import os # to remove created audio files
import datetime
import requests, json

BASE_URL = "https://api.openweathermap.org/data/2.5/weather?"
r = sr.Recognizer() # initialise a recogniser

def there_exists(terms):
    for term in terms:
        if term in voice_data:
            return True

def there_exists1(terms):
    for term in terms:
        if term in voice_data1:
            return True

# listen for audio and convert it to text:
def record_audio(ask=False):
    with sr.Microphone() as source: # microphone as source
        voice_data = ''
        if ask:
            speak(ask)
        audio = r.listen(source, 10, 10)  # listen for the audio via source
        print("Done Listening")

        try:
            voice_data = r.recognize_google(audio)  # convert audio to text
        except sr.UnknownValueError: # error: recognizer does not understand
            speak('I did not get that')
        except sr.RequestError:
            speak('Sorry, the service is down') # error: recognizer is not connected
        return voice_data.lower()

# get string and make a audio file to be played
def speak(audio_string):
    tts = gTTS(text=audio_string, lang='en') # text to speech(voice)
    r = random.randint(1,20000000)
    audio_file = 'audio' + str(r) + '.mp3'
    tts.save(audio_file) # save as mp3
    playsound.playsound(audio_file) # play the audio file
    #print(audio_string) # print what app said
    os.remove(audio_file) # remove audio file

def respond(voice_data):
    if there_exists(["what is your name","what's your name","tell me your name"]):
        speak("My Name is Test. what's your name?")
    if there_exists(["my name is"]):
        speak("nice to meet you i will remember that ,so do you want to eat or watch something!")

    if there_exists(["eat"]):
        speak("Here are some of the foods I recommend for you today")

    if there_exists(["watch"]):
        speak("What if we remember the old days and watch the Titanic ! ")

    if there_exists(["what's the time","tell me the time","what time is it","what is the time"]):
        speak(ctime())

    if there_exists(['hey','hi','hello','Good morning','Good afternoon','Good evening']):
        speak("What's your mood today?")

    elif there_exists(['happy','nice']):
        speak("What if we go to walk ?")

    elif there_exists(["sick","got cold","got a temperatare"]):
        speak('Do you want me to call a doctor ?')
    elif there_exists(['hungry']):
        speak('Do you want to eat some delicious food')
    elif there_exists(["bad","sad","ugly","angry","i'm not ok","stressed","upset"]):
        speak('what if we read some books !')

    if "yes" in voice_data:
        print('call doctor')
    elif "no" in voice_data:
        speak('so try to eat some healthy food')

    if there_exists(["it's good outside"]):
        search_term = voice_data.split("for")[-1]
        url = "https://www.google.com/search?sxsrf=ACYBGNSQwMLDByBwdVFIUCbQqya-ET7AAA%3A1578847393212&ei=oUwbXtbXDN-C4-EP-5u82AE&q=weather&oq=weather&gs_l=psy-ab.3..35i39i285i70i256j0i67l4j0i131i67j0i131j0i67l2j0.1630.4591..5475...1.2..2.322.1659.9j5j0j1......0....1..gws-wiz.....10..0i71j35i39j35i362i39._5eSPD47bv8&ved=0ahUKEwiWrJvwwP7mAhVfwTgGHfsNDxsQ4dUDCAs&uact=5"
        webbrowser.get().open(url)
        speak("I think it's a good day,but you can do some excercise in you'r room")

    if'search'in voice_data:
        search = record_audio('what do you want to search for ?')
        url = 'https://google.com/search?q=' + search
        webbrowser.get().open(url)
        speak('Here is what I found for ' + search)

    if there_exists(["what is my exact location"]):
        url = "https://www.google.com/maps/search/Where+am+I+?/"
        webbrowser.get().open(url)
        speak("You must be somewhere near here, as per Google maps")
    if there_exists(["exit", "quit", "goodbye"]):
        speak("Have a nice day ,good bye")
        exit()

time.sleep(1)
currentTime = datetime.datetime.now()
currentTime.hour
if currentTime.hour < 12:
    speak("Good morning")
    print('Good morning.')
elif 12 <= currentTime.hour < 18:
    speak("Good afternoon")
    print('Good afternoon.')
else:
    speak("Good evening")
    print('Good evening.')

while 1:
    voice_data = record_audio() # get the voice input
    respond(voice_data) # respond


# Task 29 - 05/08/2022
""" Write a Python program to input a natural number and check whether the
    number is palindromic or not. """
# Vevan O Narain S6- C

n = input("Enter a natural number: ")

if (n == n[::-1]):
    print("Number is a palindrome.")

else:
    print("Number is not a palindrome.")


from operator import itemgetter
from utils import *

memo = []
if __name__ == '__main__':

    img_src = cv2.imread('files/adv.jpg')
    size = img_src.shape

    cap = cv2.VideoCapture("files/foglio.MOV")

    vid_writer = cv2.VideoWriter("result_lines.avi", cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 28, #(int(cap.get(3)),int(cap.get(4))))
                                (round(2 * cap.get(cv2.CAP_PROP_FRAME_WIDTH)), round(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))))

    prova = []
    frame_number=0

    while cap.isOpened():
        ret, orig_frame = cap.read()
        if not ret:
            cap = cv2.VideoCapture("c1.mp4")
            continue
        frame_number+=1
        print(frame_number)

        frame = cv2.GaussianBlur(orig_frame, (5, 5), 0)
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        low_yellow = np.array([0, 128, 0])
        up_yellow = np.array([255, 255, 255])
        mask = cv2.inRange(hsv, low_yellow, up_yellow)
        edges = cv2.Canny(mask, 75, 150)

        lines = cv2.HoughLines(edges, 1, np.pi / 180, 120)  # , maxLineGap=50) #80
        #lines2 = cv2.HoughLines(edges, 1, np.pi / 180, 100)  # , maxLineGap=50) #220

        # utils
        tmp_dst = []
        tmp_sort = []
        new_pts_dst = []

        Hp = []
        Hp.append([(1, 0), (0, 0)])
        Hp.append([(1, 0), (0, 0)])
        Vp = []
        Vp.append([(1, 0), (0, 0)])
        Vp.append([(1, 0), (0, 0)])

        if lines is not None:
            for line in lines:
                for rho, theta in line:
                    a = np.cos(theta)
                    b = np.sin(theta)
                    x0 = a * rho
                    y0 = b * rho
                    x1 = int(x0 + 1000 * (-b))
                    y1 = int(y0 + 1000 * (a))
                    x2 = int(x0 - 1000 * (-b))
                    y2 = int(y0 - 1000 * (a))

                    m=(y2-y1)/(x2-x1)

                    if m > 0:
                        q = y1 - (m * x1)
                        if q > 200:
                            Vp[0] = [(x1, y1), (x2, y2)]
                        else:
                            Vp[1] = [(x1, y1), (x2, y2)]
                    else:
                        q = y1 - (m * x1)
                        if q > 2700:
                            Hp[0] = [(x1, y1), (x2, y2)]
                        else:
                            Hp[1] = [(x1, y1), (x2, y2)]

        for lh in Hp:
            for lv in Vp:
                Ax1 = lh[0][0]
                Ay1 = lh[0][1]
                Ax2 = lh[1][0]
                Ay2 = lh[1][1]

                Bx1 = lv[0][0]
                By1 = lv[0][1]
                Bx2 = lv[1][0]
                By2 = lv[1][1]

                x, y = line_intersection(Ax1, Ay1, Ax2, Ay2, Bx1, By1, Bx2, By2)

                if x > 0 and y > 0:
                    tmp_dst.append([int(x),int(y)])
                    tmp_dst = remove_duplicates(tmp_dst)

        tmp_dst = np.array(tmp_dst)
        tmp_dst = sorted(tmp_dst, key=itemgetter(0))

        #punti tmp
        p1 = tmp_dst[0]
        p2 = tmp_dst[1]
        p3 = tmp_dst[2]
        p4 = tmp_dst[3]
        print(p1, p2, p3, p4)

        tmp_sort.append(p2)
        tmp_sort.append(p4)
        tmp_sort.append(p3)
        tmp_sort.append(p1)

        # --
        p_d = np.array(tmp_sort)

        # retta orizzontale in basso
        distance0 = 90000

        m0, q0 = create_line(p_d[2][0], p_d[2][1], p_d[3][0], p_d[3][1])
        p_left = (p_d[2][0] - dx(distance0, m0), p_d[2][1] - dy(distance0, m0))  # invertendo + e - l'img è esterna o interna
        p_right = (p_d[3][0] + dx(distance0, m0), p_d[3][1] + dy(distance0, m0))

        # cv2.circle(frame, (int(p_left[0]), int(p_left[1])), 3, (0, 0, 255), 5, 16)
        # cv2.circle(frame, (int(p_right[0]), int(p_right[1])), 3, (0, 0, 255), 5, 16)

        distance = 40000

        # retta verticale 1
        m1, q1 = create_line(p_d[0][0], p_d[0][1], p_d[3][0], p_d[3][1])

        # retta verticale 2
        m, q = create_line(p_d[1][0], p_d[1][1], p_d[2][0], p_d[2][1])

        d1 = 1000

        pp1 = (p_right[0] - dx(d1, m1), p_right[1] - dy(d1, m1))
        pp2 = (p_left[0] - dx(d1, m), p_left[1] - dy(d1, m))
        pp3 = (p_left[0] - dx(distance, m), p_left[1] - dy(distance, m))
        pp4 = (p_right[0] - dx(distance, m1), p_right[1] - dy(distance, m1))
        # other_possible_point_b = (A[0] - dx(distance, m), A[1] - dy(distance, m))  # going the other way

        new_pts_dst.append([int(pp1[0]), int(pp1[1])])
        new_pts_dst.append([int(pp2[0]), int(pp2[1])])
        new_pts_dst.append([int(pp3[0]), int(pp3[1])])
        new_pts_dst.append([int(pp4[0]), int(pp4[1])])

        print("NPD")
        print(new_pts_dst)

        new_pts_dst = np.vstack(new_pts_dst).astype(float)
        # --

        # new_pts_dst = np.vstack(tmp_sort).astype(float)

        # Processo di omorgafia
        pts_src = np.array([[0, 0], [size[1] - 1, 0], [size[1] - 1, size[0] - 1], [0, size[0] - 1]], dtype=float)
        # Calculate Homography between source and destination points
        h, status = cv2.findHomography(pts_src, new_pts_dst)
        # Warp source image
        frame_tmp = cv2.warpPerspective(img_src.copy(), h, (frame.shape[1], frame.shape[0]))
        frame_copy = frame.copy()
        # Black out polygonal area in destination image
        cv2.fillConvexPoly(frame, new_pts_dst.astype(int), 0, 16)
        # Add warped source image to destination frame
        output = cv2.add(frame, frame_tmp)

        concatenatedOutput = cv2.hconcat([frame_copy, output])

        # Display frame
        cv2.imshow("frame", output) #frame
        #cv2.waitKey(00) == ord('k')
        #cv2.imshow("edges", edges)

        vid_writer.write(concatenatedOutput.astype(np.uint8))  # frame)

        # quit on ESC button
        if cv2.waitKey(1) & 0xFF == 27:
            break

    cap.release()
    vid_writer.release() #per salvare il video
    print('Video writer released..')

    cv2.destroyAllWindows()


#!/usr/bin/python3
"""
prints the first State object from the database hbtn_0e_6_us
"""
from model_state import Base, State
from sqlalchemy import (create_engine)
from sys import argv
from sqlalchemy.orm import sessionmaker

if __name__ == "__main__":
    engine = create_engine(
        'mysql+mysqldb://{}:{}@localhost/{}'
        .format(argv[1], argv[2], argv[3]), pool_pre_ping=True)
    Base.metadata.create_all(engine)

    Session = sessionmaker(bind=engine)
    session = Session()

    states = session.query(State).filter(State.name.like('%a%'))
    for state in states:
        print("{}: {}".format(state.id, state.name))


# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import logging

from django.utils.translation import ugettext_lazy as _

from horizon import exceptions
from horizon import tables
from horizon import tabs

from openstack_dashboard.dashboards.project. \
    data_processing.utils import workflow_helpers as helpers

from openstack_dashboard.api import glance
from openstack_dashboard.api import network
from openstack_dashboard.api import neutron
from openstack_dashboard.api import nova

from openstack_dashboard.api import sahara as saharaclient

LOG = logging.getLogger(__name__)

class GeneralTab(tabs.Tab):
    name = _("General Info")
    slug = "cluster_details_tab"
    template_name = "project/data_processing.clusters/_details.html"

    def get_context_data(self, request):
        cluster_id = self.tab_group.kwargs['cluster_id']
        cluster_info = {}
        try:
            sahara = saharaclient.client(request)
            cluster = sahara.clusters.get(cluster_id)

            for info_key, info_val in cluster.info.items():
                for key, val in info_val.items():
                    if str(val).startswith(('http://', 'https://')):
                        cluster.info[info_key][key] = build_link(val)

            base_image = glance.image_get(request,
                                          cluster.default_image_id)

            if getattr(cluster, 'cluster_template_id', None):
                cluster_template = helpers.safe_call(
                    sahara.cluster_templates.get,
                    cluster.cluster_template_id)
            else:
                cluster_template = None

            if getattr(cluster, 'neutron_management_network', None):
                net_id = cluster.neutron_management_network
                network = neutron.network_get(request, net_id)
                net_name = network.name_or_id
            else:
                net_name = None

            cluster_info.update({"cluster": cluster,
                                 "base_image": base_image,
                                 "cluster_template": cluster_template,
                                 "network": net_name})
        except Exception as e:
            LOG.error("Unable to fetch cluster details: %s" % str(e))

        return cluster_info

def build_link(url):
    return "" + url + ""

class NodeGroupsTab(tabs.Tab):
    name = _("Node Groups")
    slug = "cluster_nodegroups_tab"
    template_name = (
        "project/data_processing.clusters/_nodegroups_details.html")

    def get_context_data(self, request):
        cluster_id = self.tab_group.kwargs['cluster_id']
        try:
            sahara = saharaclient.client(request)
            cluster = sahara.clusters.get(cluster_id)
            for ng in cluster.node_groups:
                if ng["flavor_id"]:
                    ng["flavor_name"] = (
                        nova.flavor_get(request, ng["flavor_id"]).name)
                if ng["floating_ip_pool"]:
                    ng["floating_ip_pool_name"] = (
                        self._get_floating_ip_pool_name(
                            request, ng["floating_ip_pool"]))

                if ng.get("node_group_template_id", None):
                    ng["node_group_template"] = helpers.safe_call(
                        sahara.node_group_templates.get,
                        ng["node_group_template_id"])
        except Exception:
            cluster = {}
            exceptions.handle(request,
                              _("Unable to get node group details."))

        return {"cluster": cluster}

    def _get_floating_ip_pool_name(self, request, pool_id):
        pools = [pool for pool in network.floating_ip_pools_list(
            request) if pool.id == pool_id]

        return pools[0].name if pools else pool_id

class Instance(object):
    def __init__(self, name=None, id=None, internal_ip=None,
                 management_ip=None):
        self.name = name
        self.id = id
        self.internal_ip = internal_ip
        self.management_ip = management_ip

class InstancesTable(tables.DataTable):
    name = tables.Column("name",
                         link=("horizon:project:instances:detail"),
                         verbose_name=_("Name"))

    internal_ip = tables.Column("internal_ip",
                                verbose_name=_("Internal IP"))

    management_ip = tables.Column("management_ip",
                                  verbose_name=_("Management IP"))

    class Meta:
        name = "cluster_instances"
        # Just ignoring the name.
        verbose_name = _(" ")

class InstancesTab(tabs.TableTab):
    name = _("Instances")
    slug = "cluster_instances_tab"
    template_name = "project/data_processing.clusters/_instances_details.html"
    table_classes = (InstancesTable, )

    def get_cluster_instances_data(self):
        cluster_id = self.tab_group.kwargs['cluster_id']

        try:
            sahara = saharaclient.client(self.request)
            cluster = sahara.clusters.get(cluster_id)

            instances = []
            for ng in cluster.node_groups:
                for instance in ng["instances"]:
                    instances.append(Instance(
                        name=instance["instance_name"],
                        id=instance["instance_id"],
                        internal_ip=instance.get("internal_ip",
                                                 "Not assigned"),
                        management_ip=instance.get("management_ip",
                                                   "Not assigned")))
        except Exception:
            instances = []
            exceptions.handle(self.request,
                              _("Unable to fetch instance details."))
        return instances

class ClusterDetailsTabs(tabs.TabGroup):
    slug = "cluster_details"
    tabs = (GeneralTab, NodeGroupsTab, InstancesTab, )
    sticky = True


import streamlit as st
import cv2
from PIL import Image
import numpy as np
import copy

st.markdown("
Color Image
", unsafe_allow_html=True)
st.markdown("
Praktikum 1 Pengolahan Citra Digital
", unsafe_allow_html=True)

image = cv2.imread("./Tugas/Meeting 4/Images/gambar.jpeg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
r, g, b = cv2.split(image)
r_dup = copy.deepcopy(r)
g_dup = copy.deepcopy(g)
b_dup = copy.deepcopy(b)
r_dup[:] = 0
g_dup[:] = 0
b_dup[:] = 0

tab1, tab2, tab3, tab4, tab5= st.tabs(["RGB", "BGR", "Red", "Green", "Blue"])

with tab1:
  st.markdown("
RGB
", unsafe_allow_html=True)
  st.image(image)

with tab2:
  st.markdown("
BGR
", unsafe_allow_html=True)
  st.image(cv2.cvtColor(image, cv2.COLOR_RGB2BGR))

with tab3:
  st.markdown("
Red
", unsafe_allow_html=True)
  merged = cv2.merge([r, g_dup, b_dup])
  pil_032 = Image.fromarray(merged)
  st.image(pil_032)

with tab4:
  st.markdown("
Green
", unsafe_allow_html=True)
  merged = cv2.merge([r_dup, g, b_dup])
  pil_032 = Image.fromarray(merged)
  st.image(pil_032)

with tab5:
  st.markdown("
Blue
", unsafe_allow_html=True)
  merged = cv2.merge([r_dup, g_dup, b])
  pil_032 = Image.fromarray(merged)
  st.image(pil_032)


from collections import OrderedDict
from collections import namedtuple
from itertools import product
from numpy.random import gamma
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import gym
import time
from tensorboardX import SummaryWriter

# Hyper Parameters
params = OrderedDict(
            SEED = [x+1 for x in range(5)],
            BATCH_SIZE = [32],
            LR = [0.001],                  # learning rate
            EPSILON = [0.9],               # greedy policy
            GAMMA = [0.9],                 # reward discount
            TARGET_REPLACE_ITER = [100],    # target update frequency
            MEMORY_CAPACITY = [2000],
            EPOCH = [2000]
)
env = gym.make('CartPole-v0') # CartPole-v1
env = env.unwrapped # to step by self setting instead 200
N_ACTIONS = env.action_space.n
N_STATES = env.observation_space.shape[0]
ENV_A_SHAPE = 0 if isinstance(env.action_space.sample(), int) else env.action_space.sample().shape     # to confirm the shape

class RunBuilder():
    @staticmethod
    def get_runs(params):
        Run = namedtuple('run',params.keys())
        runs = []
        for v in product(*params.values()):
            runs.append(Run(*v))
        return runs

class Net(nn.Module):
    def __init__(self, ):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(N_STATES, 40)
        self.fc1.weight.data.normal_(0, 0.1)   # initialization
        self.out = nn.Linear(40, N_ACTIONS)
        self.out.weight.data.normal_(0, 0.1)   # initialization

    def forward(self, x):
        x = self.fc1(x)
        x = F.relu(x)
        actions_value = self.out(x)
        return actions_value

class DQN(object):
    def __init__(self):
        self.eval_net, self.target_net = Net(), Net()

        self.learn_step_counter = 0                                     # for target updating
        self.memory_counter = 0                                         # for storing memory
        self.memory = np.zeros((run.MEMORY_CAPACITY, N_STATES * 2 + 2))     # initialize memory
        self.optimizer = torch.optim.Adam(self.eval_net.parameters(), lr=run.LR)
        self.loss_func = nn.MSELoss()
        self.writer = SummaryWriter(comment=f'-{run}',flush_secs=60)

    def choose_action(self, x):
        x = torch.unsqueeze(torch.FloatTensor(x), 0)
        # input only one sample
        if np.random.uniform() < run.EPSILON:   # greedy
            actions_value = self.eval_net.forward(x)
            action = torch.max(actions_value, 1)[1].data.numpy()
            action = action[0] if ENV_A_SHAPE == 0 else action.reshape(ENV_A_SHAPE)  # return the argmax index
        else:   # random
            action = np.random.randint(0, N_ACTIONS)
            action = action if ENV_A_SHAPE == 0 else action.reshape(ENV_A_SHAPE)
        return action

    def store_transition(self, s, a, r, s_):
        transition = np.hstack((s, [a, r], s_))
        # replace the old memory with new memory
        index = self.memory_counter % run.MEMORY_CAPACITY
        self.memory[index, :] = transition
        self.memory_counter += 1

    def learn(self, gamma):
        # target parameter update
        if self.learn_step_counter % run.TARGET_REPLACE_ITER == 0:
            self.target_net.load_state_dict(self.eval_net.state_dict())
        self.learn_step_counter += 1

        # sample batch transitions
        sample_index = np.random.choice(run.MEMORY_CAPACITY, run.BATCH_SIZE)
        b_memory = self.memory[sample_index, :]
        b_s = torch.FloatTensor(b_memory[:, :N_STATES])
        b_a = torch.LongTensor(b_memory[:, N_STATES:N_STATES+1].astype(int))
        b_r = torch.FloatTensor(b_memory[:, N_STATES+1:N_STATES+2])
        b_s_ = torch.FloatTensor(b_memory[:, -N_STATES:])

        # q_eval w.r.t the action in experience
        q_eval = self.eval_net(b_s).gather(1, b_a)  # shape (batch, 1)
        q_next = self.target_net(b_s_).detach()     # detach from graph, don't backpropagate
        # q_target = b_r + run.GAMMA * q_next.max(1)[0].view(run.BATCH_SIZE, 1)   # shape (batch, 1)
        q_target = b_r + gamma * q_next.max(1)[0].view(run.BATCH_SIZE, 1)
        loss = self.loss_func(q_eval, q_target)

        # self.optimizer = torch.optim.Adam(self.eval_net.parameters(), lr=lr)
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()
        self.writer.add_scalar('loss', loss, self.learn_step_counter)

print('\nCollecting experience...')
timer = {}
for run in RunBuilder.get_runs(params):
    gamma = 0
    lr = 0.001
    start = time.time()
    torch.manual_seed(run.SEED)
    dqn = DQN()
    for i_episode in range(run.EPOCH):
        s = env.reset()
        ep_r = 0
        # if i_episode > 200 and i_episode % 200 == 0:
        #     lr = lr * 0.95
        while True:
            env.render()
            a = dqn.choose_action(s)

            # take action
            s_, r, done, info = env.step(a)

            # s
            # Num     Observation               Min                     Max
            # 0       Cart Position             -4.8                    4.8
            # 1       Cart Velocity             -Inf                    Inf
            # 2       Pole Angle                -0.418 rad (-24 deg)    0.418 rad (24 deg)
            # 3       Pole Angular Velocity     -Inf                    Inf

            # modify the reward
            x, x_dot, theta, theta_dot = s_
            r1 = (env.x_threshold - abs(x)) / env.x_threshold - 0.8
            r2 = (env.theta_threshold_radians - abs(theta)) / env.theta_threshold_radians - 0.5
            r = r1 + r2

            dqn.store_transition(s, a, r, s_)

            ep_r += r

            if dqn.memory_counter > run.MEMORY_CAPACITY:
                dqn.learn(gamma)
                if done:
                    print('Ep: ', i_episode,
                        '| Ep_r: ', round(ep_r, 2))
                    dqn.writer.add_scalar('reward', ep_r, i_episode)
                    dqn.writer.add_scalar('gamma', gamma, i_episode)
                    # dqn.writer.add_scalar('lr', lr, i_episode)
                    if gamma <= run.GAMMA:
                        gamma = 0.02 + 0.98*gamma
                    else:
                        gamma = run.GAMMA
                    print(gamma, lr)

            if done:
                break
            s = s_
    end = time.time() - start
    timer[run] = end
    print(timer)

    # dynamic gamma running time
    # {run(SEED=2, BATCH_SIZE=32, LR=0.001, EPSILON=0.9, GAMMA=0.9, TARGET_REPLACE_ITER=100, MEMORY_CAPACITY=2000, EPOCH=2000): 3581.828322172165, run(SEED=3, BATCH_SIZE=32, LR=0.001, EPSILON=0.9, GAMMA=0.9, TARGET_REPLACE_ITER=100, MEMORY_CAPACITY=2000, EPOCH=2000): 3571.677481651306, run(SEED=4, BATCH_SIZE=32, LR=0.001, EPSILON=0.9, GAMMA=0.9, TARGET_REPLACE_ITER=100, MEMORY_CAPACITY=2000, EPOCH=2000): 3853.927928209305, run(SEED=5, BATCH_SIZE=32, LR=0.001, EPSILON=0.9, GAMMA=0.9, TARGET_REPLACE_ITER=100, MEMORY_CAPACITY=2000, EPOCH=2000): 3656.3851256370544}


#
# Solved Date: 20.04.22.

import sys
import collections
sys.setrecursionlimit(10 ** 4)

read = sys.stdin.readline
DXY = ((1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1))

def dfs(land, y, x):
    land[y][x] = 0
    count = 1
    for dy, dx in DXY:
        new_y = y + dy
        new_x = x + dx
        if 0 <= new_y < len(land) and 0 <= new_x < len(land[0]) and land[new_y][new_x]:
            count += dfs(land, new_y, new_x)
    return count

def bfs(land, y, x):
    queue = collections.deque()
    queue.append((y, x))
    land[y][x] = 0
    count = 1
    while queue:
        y, x = queue.popleft()
        for dy, dx in DXY:
            new_y = y + dy
            new_x = x + dx
            if 0 <= new_y < len(land) and 0 <= new_x < len(land[0]) and land[new_y][new_x]:
                land[new_y][new_x] = 0
                count += 1
                queue.append((new_y, new_x))
    return count

def main(mode=''):
    while True:
        width, height = (int(x) for x in read().split())
        land = []
        if not width and not height:
            break
        for _ in range(height):
            land.append([int(x) for x in read().split()])
        ans = []
        if mode == 'dfs':
            for y in range(len(land)):
                for x in range(len(land[0])):
                    if land[y][x] == 1:
                        ans.append(dfs(land, y, x))
        else:
            for y in range(len(land)):
                for x in range(len(land[0])):
                    if land[y][x] == 1:
                        ans.append(bfs(land, y, x))
        print(len(ans))

if __name__ == '__main__':
    main('dfs')


# Title: 내 생각에 A번인 단순 dfs 문제가 이 대회에서 E번이 되어버린 건에 관하여(Easy)
# Link: https://www.acmicpc.net/problem/18251

import sys

sys.setrecursionlimit(10 ** 6)

read_single_int = lambda: int(sys.stdin.readline().strip())
read_list_int = lambda: list(map(int, sys.stdin.readline().strip().split(' ')))

INF = 10**10
MIN = -INF

def get_maximum_subarray(ns: list, d: int, u: int):
    res = MIN
    sub_sums = MIN
    for n in ns:
        if d <= n[1] <= u:
            sub_sum = max(sub_sums + n[0], n[0])
            res = max(res, sub_sum)
            sub_sums = sub_sum
    return res

def solution(n: int, ws: list):
    ns = [None for _ in range(n)]
    n += 1
    c = 0
    j = 0
    while n != 1:
        c += 1
        n = n//2
        i = -1
        while True:
            i += n
            if i < len(ns):
                if ns[i] == None:
                    ns[i] = (ws[j], c)
                    j += 1
                else:
                    continue
            else:
                break

    max_weight = MIN

    for d in range(1, c+1):
        for u in range(d, c+1):
            max_weight = max(get_maximum_subarray(ns, d, u), max_weight)

    return max_weight

def main():
    n = read_single_int()
    ws = read_list_int()
    print(solution(n, ws))

if __name__ == '__main__':
    main()


from datetime import datetime, timedelta

from discord import Embed
from discord.ext import commands
import re
import discord
from discord.ext.commands import Cog
from discord.ext.commands import command, has_permissions

from ..db import db

time_regex = re.compile(r"(?:(\d{1,5})(h|s|m|d))+?")
time_dict = {'h': 3600, 's': 1, 'm': 60, 'd': 86400}

class TimeConverter(commands.Converter):
    async def convert(self, ctx, argument):
        args = argument.lower()
        matches = re.findall(time_regex, args)
        time = 0
        for key, value in matches:
            try:
                time += time_dict[value] * float(key)
            except KeyError:
                raise commands.BadArgument(f"{value} is an invalid time key! h|m|s|d are valid arguments")
            except ValueError:
                raise commands.BadArgument(f"{key} is not a number!")
        return time

# Here are all the number emotes.
# 0⃣ 1⃣ 2⃣ 3⃣ 4⃣ 5⃣ 6⃣ 7⃣ 8⃣ 9⃣

# numbers = ("1⃣", "2⃣", "3⃣", "4⃣", "5⃣",
# 		   "6⃣", "7⃣", "8⃣", "9⃣", "🔟")

numbers = ("⬆","⬇")

class Reactions(Cog):

	def __init__(self, bot):
		self.bot = bot
		self.polls = []
	def custom_check():
            def predicate(ctx):
                cog = ctx.bot.get_cog("Fun")
                command  =  db.field("SELECT commandname FROM command WHERE channelid = ?", ctx.channel.id)
                if command is not None:
                    command.split(',')
                    if  len(command)> 1 and ctx.command.name in command :
                        return
                    elif ctx.command.name in command :
                        return
                return True
            return commands.check(predicate)

	@Cog.listener()
	async def on_ready(self):
		if not self.bot.ready:

			self.bot.cogs_ready.ready_up("reactions")

	@command(name="createpoll", aliases=["poll"], description = 'start a poll', usage = '+poll <time> <question>')
	@custom_check()
	# @has_permissions(manage_guild=True) new
	async def create_poll(self, ctx, time: TimeConverter, *, question:str):
		'''+poll 1m kya mai cute hu '''
		try:

                    embed = Embed(title="Poll",
                                            colour=ctx.author.colour,
                                            timestamp=datetime.utcnow())

                    embed.add_field(name = 'Question', value = question,inline = False)
                    embed.add_field(name = 'Time', value = time, inline = False)

                    message = await ctx.send(embed=embed)

                    for emoji in numbers:
                            await message.add_reaction(emoji)

                    self.polls.append((message.channel.id, message.id))

                    self.bot.scheduler.add_job(self.complete_poll, "date", run_date=datetime.now()+timedelta(seconds =time),args=[message.channel.id, message.id])
		except:
                    await ctx.send(f'type {ctx.prefix}help createpoll')

	async def complete_poll(self, channel_id, message_id):
                try:
                    message = await self.bot.get_channel(channel_id).fetch_message(message_id)

                    most_voted = max(message.reactions, key=lambda r: r.count)
                    for reaction in message.reactions :
                            if str(reaction.emoji) =='⬆':
                                    x = reaction.count
                            if str(reaction.emoji) =='⬇':
                                    y = reaction.count
                    if x == y :
                            await message.channel.send(" The results are in and oops it's a tie ")
                    else:
                            await message.channel.send(f"The results are in and option {most_voted.emoji} was the most popular with {most_voted.count-1:,} votes!")
                    self.polls.remove((message.channel.id, message.id))
                    await message.delete()
                except :
                    pass

	# @Cog.listener()
	# async def on_raw_reaction_add(self, payload):
	# 	if self.bot.ready and payload.message_id == self.reaction_message.id:
	# 		current_colours = filter(lambda r: r in self.colours.values(), payload.member.roles)
	# 		await payload.member.remove_roles(*current_colours, reason="Colour role reaction.")
	# 		await payload.member.add_roles(self.colours[payload.emoji.name], reason="Colour role reaction.")
	# 		await self.reaction_message.remove_reaction(payload.emoji, payload.member)

	# 	elif payload.message_id in (poll[1] for poll in self.polls):
	# 		message = await self.bot.get_channel(payload.channel_id).fetch_message(payload.message_id)

	# 		for reaction in message.reactions:
	# 			if (not payload.member.bot
	# 				and payload.member in await reaction.users().flatten()
	# 				and reaction.emoji != payload.emoji.name):
	# 				await message.remove_reaction(reaction.emoji, payload.member)

	# 	elif payload.emoji.name == "⭐":
	# 		message = await self.bot.get_channel(payload.channel_id).fetch_message(payload.message_id)

	# 		if not message.author.bot and payload.member.id != message.author.id:
	# 			msg_id, stars = db.record("SELECT StarMessageID, Stars FROM starboard WHERE RootMessageID = ?",
	# 									  message.id) or (None, 0)

	# 			embed = Embed(title="Starred message",
	# 						  colour=message.author.colour,
	# 						  timestamp=datetime.utcnow())

	# 			fields = [("Author", message.author.mention, False),
	# 					  ("Content", message.content or "See attachment", False),
	# 					  ("Stars", stars+1, False)]

	# 			for name, value, inline in fields:
	# 				embed.add_field(name=name, value=value, inline=inline)

	# 			if len(message.attachments):
	# 				embed.set_image(url=message.attachments[0].url)

	# 			if not stars:
	# 				star_message = await self.starboard_channel.send(embed=embed)
	# 				db.execute("INSERT INTO starboard (RootMessageID, StarMessageID) VALUES (?, ?)",
	# 						   message.id, star_message.id)

	# 			else:
	# 				star_message = await self.starboard_channel.fetch_message(msg_id)
	# 				await star_message.edit(embed=embed)
	# 				db.execute("UPDATE starboard SET Stars = Stars + 1 WHERE RootMessageID = ?", message.id)

	# 		else:
	# 			await message.remove_reaction(payload.emoji, payload.member)

def setup(bot):
	bot.add_cog(Reactions(bot))


#!/usr/bin/python3

import os
import time
import numpy as np
import matplotlib.pyplot as plt
import system
import compute
import heat_capacity
import styles
import glob
from mytimer import Timer

T = np.linspace(0.001, 0.01, 175)

max_interesting_E = -1.442360888736597957e-01
E = np.linspace(-system.h_small, max_interesting_E, 100000)
E = 0.5*(E[1:] + E[:-1])
dE = E[1] - E[0]
hist = None

lowest_interesting_E = -1.07
highest_interesting_E = -0.5

indices_for_err = np.array([i for i in range(
    len(E)) if lowest_interesting_E <= E[i] <= highest_interesting_E])
E_for_err = E[indices_for_err]

def normalize_S(S):
    S = S - max(S)
    total = np.sum(np.exp(S)*dE)
    return S - np.log(total)

fig_S, ax_S = plt.subplots(figsize=[5, 4], num='latest-entropy')
ax_S.set_xlim(-system.h_small*1.005, max_interesting_E)
ax_S.set_ylim(-60, 2)

axins_S = ax_S.inset_axes(np.array([0.22, 0.08, 0.7, 0.7]))
axins_S.set_xlim(-1.01,-0.992)
axins_S.set_ylim(-50,-15)

# axins.set_xticklabels('')
# axins.set_yticklabels('')
#ax_S.set_ylim(0, 119)
#ax_S.set_xlim(0, Tmax)

correct_S = normalize_S(system.S(E))

correct_S_for_err = correct_S[indices_for_err]

fig_S, ax_Cv = plt.subplots(figsize=[5, 4], num='latest heat capacity')
# [0.005, 0.012, 25, 140])
axins_Cv = ax_Cv.inset_axes(np.array([0.27, 0.27, 0.7, 0.7]))
# axins.set_xticklabels('')
# axins.set_yticklabels('')
Tmax = 0.25
ax_Cv.set_ylim(0, 119)
ax_Cv.set_xlim(0, Tmax)

paths = ['wl-tiny-0.0001+0.001-lnw.dat',
        #  'wl-tiny-1e-05+0.001-lnw.dat',
         'itwl-tiny-0.0001+0.001-lnw.dat',
         'sad-tiny-0.0001+0.001-lnw.dat',
        #  'wl-tiny-1e-05+0.0001-lnw.dat',
        #  'wl-tiny-1e-05+0.01-lnw.dat',
         'z-i16-tiny-lnw.dat',
]

minimum_moves = 1e6

for fname in paths:
    print()
    timer_fname = Timer(f'Everything for {fname}')
    base = fname[:-8]
    method = base[:base.find('-')]

    energy_boundaries, mean_e, my_lnw, my_system, p_exc = compute.read_file(
        base)

    # Create a function for the entropy
    l_function, eee, sss = compute.linear_entropy(
        energy_boundaries, mean_e, my_lnw)
    plt.figure('latest-entropy')
    #plt.plot(E, normalize_S(l_function(E)), label=base)
    if method in {'wl', 'itwl', 'sad'}:
        pass # just the ZMC plot for here
        # ax_S.plot(E, normalize_S(l_function(E)),
        #             label=styles.pretty_label(base), marker=styles.marker(base),
        #          color=styles.color(base), linestyle=styles.linestyle(base), markevery=100)
        # axins_S.plot(E, normalize_S(l_function(E)),
        #             label=styles.pretty_label(base), marker=styles.marker(base),
        #          color=styles.color(base), linestyle=styles.linestyle(base), markevery=100)
    elif method == 'z':
        for e in energy_boundaries:
            ax_S.axvline(e, color='g', alpha=0.25, linewidth=0.5)
            axins_S.axvline(e, color='g', alpha=0.25, linewidth=0.5)
        ax_S.plot(E, normalize_S(l_function(E)),
                    label=styles.pretty_label(base),
                 color=styles.color(base), linestyle=styles.linestyle(base))
        axins_S.plot(E, normalize_S(l_function(E)),
                    label=styles.pretty_label(base),
                 color=styles.color(base), linestyle=styles.linestyle(base))

    plt.figure('latest heat capacity')
    if 'z-' in fname:
        heat_capacity.plot(l_function, fname=fname, ax=ax_Cv, axins=axins_Cv, Tmax=Tmax)
    # correct_Cv = [heat_capacity.C(t,l_function) for t in T]
    # if method in {'wl','itwl','sad'}:
    #     plt.plot(T, correct_Cv, label=base, marker = markers[precision], color = colors[method], linestyle= linestyles[method], markevery=5)
    # elif method == 'z':
    #     plt.plot(T, correct_Cv, label=base, color = colors[method], linestyle= linestyles[method])

    start_well_histogram = time.process_time()
    plt.figure('fraction-well')
    mean_which = np.loadtxt(f'{base}-which.dat')
    plt.plot(mean_e, mean_which,
                    label=styles.pretty_label(base), )

    if os.path.exists(f'{base}-histogram.dat'):
        hist = np.loadtxt(f'{base}-histogram.dat')
        plt.figure('histogram')
        plt.plot(mean_e, hist,
                    label=styles.pretty_label(base), )
    print(f'Plotting fraction and histogram {fname} took %.2g' % (
        time.process_time() - start_well_histogram))

    start_conv = time.process_time()
    try:
        errors = np.loadtxt(f'{base}-errors-saved.txt')
        errors_Cv = np.loadtxt(f'{base}-errors-Cv-saved.txt')
        moves = np.loadtxt(f'{base}-moves-saved.txt')
    except:
        errors = []
        errors_Cv = []
        moves = []
        for frame_fname in sorted(glob.glob(f'{base}/*-lnw.dat'))[::2]:
            frame_base = frame_fname[:-8]

            try:
                frame_moves = int(frame_fname[len(base)+1:-8])
                if frame_moves < minimum_moves:
                    continue
                energy_boundaries, mean_e, my_lnw, my_system, p_exc = compute.read_file(
                    frame_base)
                l_function, eee, sss = compute.linear_entropy(
                    energy_boundaries, mean_e, my_lnw)
                moves.append(frame_moves)
                err = np.max(np.abs(normalize_S(l_function(E))[
                            indices_for_err] - correct_S_for_err))
                # print(f'err is {err} for {frame_base}')
                errors.append(err)
                errors_Cv.append(np.abs(heat_capacity.C(
                    heat_capacity.T_peak, system.S) - heat_capacity.C(heat_capacity.T_peak, l_function)))
            except:
                pass
        np.savetxt(f'{base}-errors-saved.txt', errors)
        np.savetxt(f'{base}-errors-Cv-saved.txt', errors_Cv)
        np.savetxt(f'{base}-moves-saved.txt', moves)
    print(f'Heat capacity convergence {fname} took %.2g' % (
        time.process_time() - start_conv))

    plt.figure('convergence')
    plt.loglog(moves, errors,
               label=styles.pretty_label(base), marker=styles.marker(base),
               color=styles.color(base), linestyle=styles.linestyle(base), markevery=2)

    plt.figure('convergence_heat_capacity')
    plt.loglog(moves, errors_Cv,
               label=styles.pretty_label(base), marker=styles.marker(base),
               color=styles.color(base), linestyle=styles.linestyle(base), markevery=2)

    del timer_fname
    print()
    # print(base[:base.find('-')]) #for debugging

plt.figure('latest-entropy')
ax_S.plot(E, correct_S,
            label=styles.pretty_label(None),
            marker = styles.marker(None),
            color = styles.color(None),
            linestyle= styles.linestyle(None),
            markevery=10)
axins_S.plot(E, correct_S,
            label=styles.pretty_label(None),
            marker = styles.marker(None),
            color = styles.color(None),
            linestyle= styles.linestyle(None),
            markevery=10)
ax_S.indicate_inset_zoom(axins_S, edgecolor="black", label=None)

ax_S.axvline(-system.h_small, color='r', linestyle='--', linewidth=0.5)
ax_S.axvline(-1, color='r', linestyle='--', linewidth=0.5)
# ax_S.axvline(-133.10462, color='k', linestyle=':')

axins_S.axvline(-system.h_small, color='r', linestyle='--', linewidth=0.5)
axins_S.axvline(-1, color='r', linestyle='--', linewidth=0.5)
plt.xlabel(r'$E$')
plt.ylabel(r'$S(E)$')
axins_S.legend()#bbox_to_anchor = [0.7, 0.])
plt.savefig(system.system+'-entropy.pdf', transparent=True)

plt.figure('fraction-well')
plt.xlabel(r'E')
plt.ylabel(r'Proportion in Small Well')
plt.legend()
plt.savefig(system.system+'-which.svg')

if hist is not None:
    plt.figure('histogram')
    plt.xlabel(r'$E$')
    plt.ylabel(r'# of Visitors')
    plt.legend()
    plt.savefig(system.system+'-histogram.svg')

plt.figure('convergence')
plt.xlabel(r'# of Moves')
plt.ylabel(
    rf'max error in entropy between {lowest_interesting_E} and {highest_interesting_E}')
plt.ylim(1e-2, 1e2)
plt.legend()
# make diagonal lines for convergence
x = np.linspace(1e-10, 1e20, 2)
y = 1/np.sqrt(x)
for i in range(40):
    plt.loglog(x, y*10**(4*i/5-3), color='g', alpha=0.25)
plt.savefig(system.system+'-convergence.svg')
plt.savefig(system.system+'-convergence.pdf', transparent=True)

plt.figure('convergence_heat_capacity')
plt.xlabel(r'# of Moves')
plt.ylabel(rf'max error in heat capacity')
heat_capacity_convergence_minimum = 1e-3
plt.ylim(heat_capacity_convergence_minimum, 2e2)
plt.xlim(xmin=minimum_moves, xmax=1e12)
plt.legend()
# make diagonal lines for convergence
x = np.linspace(1e-10, 1e20, 2)
for i in range(1, 40, 2):
    plt.loglog(x, heat_capacity_convergence_minimum*np.sqrt(heat_capacity_convergence_minimum*10**i/x), color='xkcd:gray',
               alpha=0.25, linewidth=0.5)
plt.savefig(system.system+'-heat-capacity-convergence.svg')
plt.savefig(system.system+'-heat-capacity-convergence.pdf')

plt.figure('latest heat capacity')
heat_capacity.plot(system.S, ax=ax_Cv, axins=axins_Cv, Tmax=Tmax)

ax_Cv.legend()
plt.xlabel('$T$')
# axins.set_xlabel('$T$')
plt.ylabel('heat capacity')
plt.savefig(system.system+'-heat-capacity.svg')
plt.savefig(system.system+'-heat-capacity.pdf')

# plt.show()


from flask import Flask
import requests
import json
import requests
from bs4 import BeautifulSoup
from flask_restful import Api, Resource
from flask_cors import CORS

#Api inicializacion
app = Flask(__name__)
CORS(app)
api = Api(app)

#headers
headers = {
    'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36'
}
websiteLinks = " "

class Scrap_selected(Resource):

    #Apis get method
    def get(self, websiteLinks):

        #fetch data from json file
        f = open('data.json')
        data = json.load(f)
        check_urls = data["scrap_all"]["check_right_urls"]
        wideo_link = data["scrap_all"]["Wideo_link"]
        wiadomosc_link = data["scrap_all"]["Wiadomosc_link"]
        tvn_link = data["scrap_all"]["tvn_link"]

        #Validation input from UI
        if(websiteLinks == "polsat"):
            URL_1 = data["scrap_all"]["URL_1"]
            find_1 = data["scrap_all"]["find_1"]
            find_all_1 = data["scrap_all"]["find_all_1"]
            content_class = data["scrap_all"]["content_class_polsat"]
            json_data = Scraping(URL_1,find_all_1,find_1,content_class,check_urls,wideo_link,wiadomosc_link,tvn_link)
            return {
            "MatchedNews":{
                "Polsat":  (json_data.polsat_scrap())
                }
            }

        elif(websiteLinks == "tvn"):
            URL_1 = data["scrap_all"]["URL_3"]
            find_1 = data["scrap_all"]["find_3"]
            find_all_1 = data["scrap_all"]["find_all_3"]
            content_class = data["scrap_all"]["content_class_tvn24"]
            json_data = Scraping(URL_1,find_all_1,find_1,content_class,check_urls,wideo_link,wiadomosc_link,tvn_link)
            return {
            "MatchedNews":{
                "Tvn":  (json_data.tvn24_scrap())
                }
            }

        elif(websiteLinks == "dziennik"):
            URL_1 = data["scrap_all"]["URL_2"]
            find_1 = data["scrap_all"]["find_2"]
            find_all_1 = data["scrap_all"]["find_all_2"]
            content_class = data["scrap_all"]["content_class_dziennik"]
            json_data = Scraping(URL_1,find_all_1,find_1,content_class,check_urls,wideo_link,wiadomosc_link,tvn_link)
            return {
            "MatchedNews":{
                "Dziennik":  (json_data.dziennik_scrap())
                }
            }

        elif(websiteLinks == "wszystkie"):
            URL_1 = data["scrap_all"]["URL_1"]
            find_1 = data["scrap_all"]["find_1"]
            find_all_1 = data["scrap_all"]["find_all_1"]
            content_class = data["scrap_all"]["content_class_polsat"]
            json_data_1 = Scraping(URL_1,find_all_1,find_1,content_class,check_urls,wideo_link,wiadomosc_link,tvn_link)

            URL_1 = data["scrap_all"]["URL_3"]
            find_1 = data["scrap_all"]["find_3"]
            find_all_1 = data["scrap_all"]["find_all_3"]
            content_class = data["scrap_all"]["content_class_tvn24"]
            json_data_2 = Scraping(URL_1,find_all_1,find_1,content_class,check_urls,wideo_link,wiadomosc_link,tvn_link)

            URL_1 = data["scrap_all"]["URL_2"]
            find_1 = data["scrap_all"]["find_2"]
            find_all_1 = data["scrap_all"]["find_all_2"]
            content_class = data["scrap_all"]["content_class_dziennik"]
            json_data_3 = Scraping(URL_1,find_all_1,find_1,content_class,check_urls,wideo_link,wiadomosc_link,tvn_link)
            return{
                "MatchedNews":{
                    "Tvn": (json_data_2.tvn24_scrap()),
                    "Dziennik": (json_data_3.dziennik_scrap()),
                    "Polsat": (json_data_1.polsat_scrap())
                }
            }

        #WebScraping itself
class Scraping:
    def __init__(self, URL_1, find_all_1, find_1, content_class, check_urls,wideo_link,wiadomosc_link,tvn_link):
        #basic scraping
        self.page = requests.get(URL_1,headers=headers)
        self.soup = BeautifulSoup(self.page.content, "html.parser")
        self.results = self.soup.find(class_=f'{find_1}')
        self.scraped = self.results.find_all( class_=f'{find_all_1}')

        #variables assigement
        self.content_class = content_class
        self.check_urls = check_urls
        self.wideo_link = wideo_link
        self.tvn_link = tvn_link
        self.wiadomosc_link = wiadomosc_link
        self.page_content = []
        self.content_urls = []
        self.final_urls = []
        self.lenght = len(self.scraped)
        self.particular_page_content = []
        self.particular_page_title = []
        self.data_collection = []

    # Scarping data with input equal to "polsat"
    def polsat_scrap(self):
        dictionary = {
                        1: ['\n', ' ']
        }
        #elimination of invalid scraps
        for link in self.results.find_all('a'):
            self.content_urls.append(link.get('href'))

        #elimiating duplicats
        unique_content = list(set(self.content_urls))

        #gather group of valid urls
        for filtred_urls in unique_content:
            wideo = filtred_urls.startswith(f'{self.wideo_link}')
            wiadomosc = filtred_urls.startswith(f'{self.wiadomosc_link}')
            if wideo == True:
                self.final_urls.append(filtred_urls)
            elif wiadomosc == True:
                self.final_urls.append(filtred_urls)

        #gather group of valid title and content of each url
        for content_url in self.final_urls:
            content_page = requests.get(content_url, headers=headers)
            content_soup = BeautifulSoup(content_page.content, "html.parser")

            content_title = content_soup.find("h1", class_="news__title")
            self.particular_page_title.append(content_title.text)

            content_results = content_soup.find("div", class_= f'{self.content_class}')
            def normalize():
                for i in dictionary:
                    text = content_results.text.replace(dictionary[i][0], dictionary[i][1])
                return text
            self.particular_page_content.append(normalize())

        #return data as json
        for x in range(0, len(self.particular_page_title)):
            data_set = {
                        "Title": self.particular_page_title[x],
                        "Content": self.particular_page_content[x],
                        "Url": self.final_urls[x]
                    }
            self.data_collection.append(data_set)

        return self.data_collection

    def tvn24_scrap(self):
        #words that are going to be deleted in url content section
        dictionary = {
                        1: ['\n', ''],
                        2: ['\r', '']}

        #elimination of invalid scraps
        for link in self.results.find_all('a'):
            scrapido = link.find_all(class_ = f'{self.check_urls}')
            if len(scrapido) != 0:
                self.content_urls.append(link.get('href'))

        unique_content = list(set(self.content_urls))

        for filtred_urls in unique_content:
            wideo = filtred_urls.startswith(f'{self.tvn_link}')
            if wideo == False:
                self.final_urls.append(filtred_urls)
            else:
                print(filtred_urls)

        #gather group of valid title and content of each url
        for content_url in self.final_urls:
            content_page = requests.get(content_url,headers=headers)
            content_soup = BeautifulSoup(content_page.content, "html.parser")

            content_results = content_soup.find("div", class_=f'{self.content_class}')
            def normalize():
                for i in dictionary:
                    text = content_results.text.replace(dictionary[i][0], dictionary[i][1])
                return text
            self.particular_page_content.append(normalize())

            content_title = content_soup.find("h1", class_="heading heading--size-36 article-top-bar__title")
            self.particular_page_title.append(content_title.text)

        for x in range(0, len(self.particular_page_title)):
            data_set = {
                        "Title": self.particular_page_title[x],
                        "Content": self.particular_page_content[x],
                        "Url": self.content_urls[x]
                    }
            self.data_collection.append(data_set)

        return self.data_collection

    # Scarping data with input equal to "dziennik"
    def dziennik_scrap(self):
        dictionary = {
                        1: ['\n', '']}
        #elimination of invalid scraps
        for link in self.results.find_all('a'):
                self.content_urls.append(link.get('href'))

        #gather group of valid content of each url
        for content_url in self.content_urls:
            content_page = requests.get(content_url,headers=headers)
            content_soup = BeautifulSoup(content_page.content, "html.parser")
            content_results = content_soup.find("div", class_=f'{self.content_class}')

            content_title = content_soup.find("h1", class_="mainTitle")
            delete_useless_chars = content_title.text.strip()
            self.particular_page_title.append(delete_useless_chars)

            def normalize():
                for i in dictionary:
                    text = content_results.text.replace(dictionary[i][0], dictionary[i][1])
                return text
            delete_spaces = " ".join(normalize().split())
            self.particular_page_content.append(delete_spaces)

        #return data as json

        # Loop to print exact amount of records in return statement
        for x in range(0, len(self.particular_page_title)):
            data_set = {
                        "Title": self.particular_page_title[x],
                        "Content": self.particular_page_content[x],
                        "Url": self.content_urls[x]
                    }
            self.data_collection.append(data_set)

        return self.data_collection

api.add_resource(Scrap_selected, "/main/GetNews/<string:websiteLinks>")

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


#---------------------------------IMPORT MODULES----------------------------------
#user modules
import modules.common as common

#built-in modules
import random

#Assigning variables
mode=''
word=''
hidden_word=''
hint=''
rand=0
hintGiven=''

#Creating lists
Index=[]
hidden_word_list=[]
guessed=[]

#----------------------------------DEFINING FUNCTIONS----------------------------------
#--------------------------------------FUNCTION 1--------------------------------------
def game_mode():
    '''
    This function will get the game mode the user wishes to play

    returns:
        Mode : Mode is a string value which contains the game mode chosen by the user

    '''

    #Defining global variables
    global mode

    #Assigning it an empty string
    mode=''

    #Getting the mode from the user
    while mode == '' :
        print ('\nWhich mode would you like to play?')
        mode = input('Enter "E" for easy, "M" for medium and "H" for hard mode: ').upper()

        common.clearConsole()
        common.Exit(mode)

        if mode == 'E' or mode == 'M' or mode == 'H':
            if mode== 'E' :
                Mode = 'EASY'
            elif mode == 'M' :
                Mode = 'MEDIUM'
            elif mode == 'H' :
                Mode = 'HARD'
        else:
            mode = ''
            print ('\n\nInvalid input! Please try again\n')
    return Mode

#--------------------------------------FUNCTION 2--------------------------------------

def random_word(word_1,word_2,word_3):
    '''
    This function will get a random word from the lists according to the game mode

    Parameters:
        word_1: A list of words
        word_2: A list of words
        word_3: A list of words

    Returns:
        word: The string value which contains the random word
    '''

    #Defining global variables
    global mode,word,hidden_word,rand

    #getting a random number from 0-20
    rand=random.randrange(0,20)

    #getting the random word from the respective list
    if mode == 'E':
        word = word_1[rand].upper()
    if mode == 'M':
        word = word_2[rand].upper()
    if mode == 'H':
        word = word_3[rand].upper()

    return word

#--------------------------------------FUNCTION 3--------------------------------------

def hide_word():
    '''This function will hide the word with underscores'''

    #Defining global variables
    global hidden_word_list,word

    #Creating an empty list
    hidden_word_list=[]

    #Replaces the letter with underscores
    for i in range(len(word)):

        #checks if the character is space
        if ord(word[i]) == 32:
            hidden_word_list.append(' ')

        else:
            hidden_word_list.append('_')

#--------------------------------------FUNCTION 4--------------------------------------

def find_index(word,guess):
    '''
    This function will find the index of guess in word

    Parameters:
        word: The string value in which the index of guess should be found
        guess: The string value to get the index of

    Returns:
        Index: A list which contains the index/indexes of guess in word
    '''

    #Defining global variables
    global Index

    #Creating an empty list
    Index = []

    #Getting the index of guess
    for i in range(len(word)):

        if guess == word[i] :

            #Appending the index to the list
            Index.append(i)

    return Index

#--------------------------------------FUNCTION 5--------------------------------------

def get_hint(hint_1,hint_2,hint_3):
    '''
    This function will display  a hint for the respective word

    Parameters:
        hint_1: A list of hints
        hint_2: A list of hints
        hint_3: A list of hints
    '''

    #defining global variables
    global mode,hint_count,hintGiven,hint

    #checks if user has already taken a hint
    if hint_count==1:

        #asks the user if he/she needs a hint
        need_hint = input('If you need a hint, type "YES": ')

        common.Exit(need_hint)

        if need_hint.upper() == 'YES':
            hintGiven='YES'

            #makes hint_count=0, indicating the user has already taken a hint
            hint_count = 0

            #gets the hint according to the respective word
            if mode == 'E':
                hint = hint_1[rand].upper()
            if mode == 'M':
                hint = hint_2[rand].upper()
            if mode == 'H':
                hint = hint_3[rand].upper()

        else:
            hintGiven='NO'
            hint=''

        #if a hint is provided, prints the hint
        if hint:
            print('hint: ',hint)

    #if hint is already given, prints the hint
    elif hint_count==0:
        hintGiven='YES'
        print('hint: ',hint)

#--------------------------------------FUNCTION 6--------------------------------------

def find_word(hint_1,hint_2,hint_3):
    '''
    This function will allow the user to guess the word

    Parameters:
        hint_1: A list of hints
        hint_2: A list of hints
        hint_3: A list of hints

    Returns:
        Turns: Contains the number of turns provided
        TurnsUsed: Contains the number of turns used
        hintGiven: Contains a yes/no stating if a hint was provided or not
        result: Contains win/loss stating if the user won or lost in the game

    '''

    #Assigning global variables
    global Index,guessed,word,hidden_word_list,hint_count

    #Assigning variables
    tries = len(word)
    Turns=len(word)
    stop = 'no'
    guessed=[]
    hint_count=1
    hidden_word = ''.join(hidden_word_list)
    result=''

    print()

    #Prints the number of letters the word has
    print('The word has',len(word),'letters')

    while stop == 'no':

        #Checks if the word guessed by the user matches the exact word
        if hidden_word == word:

            #Turns used is the number of turns provided minus the tries remaining
            TurnsUsed=Turns-tries
            tries = 0
            print()

            #displays the congratulations message
            print('Congratulations!!\nYou have guessed the word\n\nThe word is: ',word)
            result = 'WIN'
            stop = 'yes'

        #checks if all the tries have exhausted
        elif tries == 0:
            print()

            #displays the message that the user has lost
            print('Sorry you have run out of tries!\n\nThe word is: ',word)
            result = 'LOSS'
            stop = 'yes'
            TurnsUsed=Turns-tries

        #if the user hasnt won or lost the game continues
        else:

            print()

            #the hidden word with underscores is displayed with a space
            print("  ",' '.join(hidden_word))
            print()

            get_hint(hint_1,hint_2,hint_3)

            #a letter is taken from the user as a guess
            guess=input('Enter the letter: ').upper()
            print()

            common.Exit(guess)

            #checks if the letter is already guessed
            if guess in guessed:
                print('You have already guessed this letter, letter: ',guess)

                #a try is exhausted
                tries -= 1
                print('You have',tries,'tries remaining')

            #checks if the input is not a letter, or if it is a blank value
            elif common.is_letter(guess) == False or guess == '' :
                print('Invalid input')

            #checks if the guessed letter is not in the word
            elif guess not in word:
                print('Wrong guess!')

                #the guessed letter is appended to the list of guessed letters
                guessed.append(guess)

                #a try is exhausted
                tries -= 1

                print('You have',tries,'tries remaining')

            #checks if the guessed letter is in the word
            elif guess in word:
                print('Correct guess!')

                #the guessed letter is appended to the list of guessed letters
                guessed.append(guess)

                #finds the index of the guessed letter in the word
                I=(find_index(word,guess))

                #replaces the underscore with the respective guessed letter
                for i in (I):
                    hidden_word_list[i]=guess
                hidden_word = ''.join(hidden_word_list)

                if hidden_word == word:
                    print()
                else:
                    print('You have',tries,'tries remaining')

    return Turns,TurnsUsed,hintGiven,result


class Salary:
    def __init__(self, name, monry):
        self.name = name
        self.money = monry
    def __str__(self):
        return self.name + ' ' + str(self.money)
    def __add__(self, n):
        self.money = self.money + n

if __name__ == '__main__':
    s1 = Salary('Mary', 40000)
    s2 = Salary('Jhon', 50000)
    print(s1, s2)
    s1 + 5000
    s2 + 6000
    print(s1, s2)


import csv

class InputExample(object):
    def __init__(self, text_a, text_b=None, label=None):
        self.text_a = text_a
        self.text_b = text_b
        self.label = label

class InputFeature(object):
    def __init__(self, input_ids, attention_mask, token_type_ids, label):
        self.input_ids = input_ids
        self.attention_mask = attention_mask
        self.token_type_ids = token_type_ids
        self.label = label

class Sst2Processor(object):
    def __init__(self):
        self.train_file = "data/SST-2/train.tsv"
        self.dev_file = "data/SST-2/dev.tsv"

    def get_train_examples(self):
        examples = []
        for line in self._read_tsv(self.train_file):
            examples.append(InputExample(text_a=line[0], text_b=None, label=line[1]))
        return examples

    def get_dev_examples(self):
        examples = []
        for line in self._read_tsv(self.dev_file):
            examples.append(InputExample(text_a=line[0], text_b=None, label=line[1]))
        return examples

    def get_labels(self):
        return ["0", "1"]

    @classmethod
    def _read_tsv(cls, input_file):
        with open(input_file, "r", encoding="utf-8") as fr:
            reader = csv.reader(fr, delimiter="\t")
            lines = []
            for line in reader:
                lines.append(line)
        return lines[1:]

def convert_examples_to_features(examples, tokenizer, label_list,
                                 max_length=512):
    label_map = {label: i for i, label in enumerate(label_list)}
    features = []
    for (ex_index, example) in enumerate(examples):
        inputs = tokenizer.encode_plus(example.text_a,
                                       example.text_b,
                                       add_special_tokens=True,
                                       max_length=max_length)
        input_ids, token_type_ids = inputs["input_ids"], inputs["token_type_ids"]
        attention_mask = [1] * len(input_ids)

        padding_length = max_length - len(input_ids)
        input_ids = input_ids + [0] * padding_length
        attention_mask = attention_mask + [0] * padding_length
        token_type_ids = token_type_ids + [0] * padding_length
        label = label_map[example.label]

        features.append(InputFeature(input_ids=input_ids,
                                     attention_mask=attention_mask,
                                     token_type_ids=token_type_ids,
                                     label=label))
    return features