__author__ = 'dmyung'

#taken from the django debug toolbar sql panel
import six.moves.socketserver
import os
import traceback
import django
from django.conf import settings

# -*- coding: utf-8 -

# Figure out some paths
django_path = os.path.realpath(os.path.dirname(django.__file__))
socketserver_path = os.path.realpath(os.path.dirname(six.moves.socketserver.__file__))

SQL_WARNING_THRESHOLD = getattr(settings, 'DEBUG_TOOLBAR_CONFIG', {}) \
                            .get('SQL_WARNING_THRESHOLD', 500)

UNKOWN_INFO = {}

DEFAULT_UUID_BATCH_COUNT = 1000

couch_view_queries = []

def process_key(key_obj):

    if isinstance(key_obj, list):
        key_obj = [six.text_type(x).encode('utf-8') for x in key_obj]
    else:
        key_obj = key_obj.encode('utf-8')
    return key_obj

def tidy_stacktrace(strace):
    """
    Clean up stacktrace and remove all entries that:
    1. Are part of Django (except contrib apps)
    2. Are part of SocketServer (used by Django's dev server)
    3. Are the last entry (which is part of our stacktracing code)
    """
    trace = []
    for s in strace[:-1]:
        s_path = os.path.realpath(s[0])
        if getattr(settings, 'DEBUG_TOOLBAR_CONFIG', {}).get('HIDE_DJANGO_SQL', True) \
            and django_path in s_path and 'django/contrib' not in s_path:
            continue
        if socketserver_path in s_path:
            continue
        trace.append((s[0], s[1], s[2], s[3]))
    return trace

def ms_from_timedelta(td):
    """
    Given a timedelta object, returns a float representing milliseconds
    """
    return (td.seconds * 1000) + (td.microseconds / 1000.0)

FORMAT_VIEW = 'view'
FORMAT_OPEN_DOC = 'open_doc'

VIEW_OUTPUT_HEADERS = [
    'view_path',
    'duration',
    'offset',
    'rows',
    'total_rows',
    'result_cached',
    'include_docs',
    # 'params',
]

OPEN_DOC_OUTPUT_HEADERS = [
    'doc_id',
    'duration',
    'doc_type',
    'response',
    # 'params',
]


from kivy.app import App
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.window import Window

from pages.DirPathPage import DirPathPage
from pages.FilePathPage import FilePathPage
from pages.FinishPage import FinishPage
from pages.ResultPage import ResultPage

Window.size = 1200, 800

class MainWindow(App):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.finish_screen = None
        self.result_screen = None
        self.file_path_screen = None
        self.screen_manager = None
        self.dir_path_screen = None
        self.data = None
        self.restore_data = None

    def build(self):
        """
        self.window = GridLayout()
        self.window.cols = 1
        self.window.size_hint = (0.6, 0.7)
        self.window.pos_hint = {"center_x": 0.5, "center_y": 0.5}
        self.window.add_widget(Image(source="resources/images/logo_image.jpg"))

        self.date = TextInput(
            multiline=False,
            # padding_y=(30, 30),
            size_hint=(1, 0.7),
            font_size=30
        )
        self.window.add_widget(self.date)
        """
        self.title = 'ASR System'

        # self.theme_cls.theme_style = "Dark"
        self.screen_manager = ScreenManager()
        Builder.load_file('resources/screen_elements.kv')

        self.dir_path_screen = DirPathPage(main_parent=self)
        screen = Screen(name="Directory")
        screen.add_widget(self.dir_path_screen)
        self.screen_manager.add_widget(screen)

        self.file_path_screen = FilePathPage(main_parent=self)
        screen = Screen(name="File")
        screen.add_widget(self.file_path_screen)
        self.screen_manager.add_widget(screen)

        self.result_screen = ResultPage(main_parent=self)
        screen = Screen(name="Result")
        screen.add_widget(self.result_screen)
        self.screen_manager.add_widget(screen)

        self.finish_screen = FinishPage(main_parent=self)
        screen = Screen(name="Finish")
        screen.add_widget(self.finish_screen)
        self.screen_manager.add_widget(screen)

        # self.file_path_screen = ResultPage(main_parent=self)
        # screen = Screen(name="Result")
        # screen.add_widget(self.file_path_screen)
        # self.screen_manager.add_widget(screen)

        return self.screen_manager

    def restart(self):
        self.root.clear_widgets()
        self.stop()
        return MainWindow().run()

if __name__ == "__main__":
    MainWindow().run()


# -*- coding: utf-8 -*-
"""
Created on Sat Dec 06 11:44:28 2014

@author: Konstantin
"""

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def main():
    mu = np.array([1, 10, 20])
    sigma = np.matrix([[20, 10, 10],
                       [10, 25, 1],
                       [10, 1, 50]])
    np.random.seed(100)
    data = np.random.multivariate_normal(mu, sigma, 1000)
    print(data.shape)
    values = data.T
    print(values.shape)

    kde = stats.gaussian_kde(values)
    density = kde(values)

    fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
    x, y, z = values
    #print(x.shape)
    #print(y.shape)
    #print(z.shape)
    ax.scatter(x, y, z, c=density)
    plt.show()

if __name__ == '__main__':
    main()


import onemsdk
import datetime
import jwt
import pytz
import random
import requests
import string

from ago import human

from django.conf import settings
from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.urls import reverse
from django.views.generic import View as _View

from onemsdk.schema.v1 import (
    Response, Menu, MenuItem, Form, FormItem, FormItemType, FormMeta
)

class View(_View):
    @method_decorator(csrf_exempt)
    def dispatch(self, *a, **kw):
        return super(View, self).dispatch(*a, **kw)

    def get_user(self):
        token = self.request.headers.get('Authorization')
        if token is None:
            raise PermissionDenied

        data = jwt.decode(token.replace('Bearer ', ''), key='87654321')
        user, created = User.objects.get_or_create(id=data['sub'])

        return user

    def to_response(self, content):
        response = Response(content=content)

        return HttpResponse(response.json(), content_type='application/json')

class HomeView(View):
    http_method_names = ['get','post', 'put']

    def get(self, request, post_id=None):
        user = self.get_user()
        if user.username == '':
            form_items = [
                FormItem(type=FormItemType.string,
                                name='username',
                                description='Please choose a username',
                                header='MENU',
                                footer='Send username')
            ]
            content = Form(body=form_items,
                           method='POST',
                           path=reverse('home'),
                           meta=FormMeta(confirmation_needed=False,
                                         completion_status_in_header=False,
                                         completion_status_show=False))
        else:
            menu_items = [
                MenuItem(description='Add post',
                         method='GET',
                         path=reverse('add_post')),
                MenuItem(description='My posts',
                         method='GET',
                         path=reverse('my_posts'))
            ]

            content = Menu(body=menu_items)

        if not cache.get('posts'):
            cache.set('posts', [])

        return self.to_response(content)

    def post(self, request):
        user = self.get_user()
        User.objects.filter(id=user.id).update(username=request.POST['username'])
        return HttpResponseRedirect(reverse('home'))

class AddPostView(View):
    http_method_names = ['get', 'post']

    def get(self, request):
        form_items = [
            FormItem(type=FormItemType.string,
                     name='title',
                     description='Give your new post a title (maximum 64 characters)',
                     header='add',
                     footer='Reply with post title or BACK'),
            FormItem(type=FormItemType.string,
                     name='description',
                     description='Send post content (max 50 words)',
                     header='add',
                     footer='Reply with post content or BACK'),
        ]
        form = Form(body=form_items,
                    method='POST',
                    path=reverse('add_post'),
                    meta=FormMeta(confirmation_needed=False,
                                  completion_status_in_header=False,
                                  completion_status_show=False))

        return self.to_response(form)

    def post(self, request):
        now = datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
        expires_at = now + datetime.timedelta(days=14)
        user_id = self.get_user().id

        # since we don't create DB records, we don't have a post id to use it
        # for hashids encoding thus we generate a random code
        code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))

        new_post = {
            'user': self.get_user(),
            'title': request.POST['title'],
            'description': request.POST['description'],
            'expires_at': expires_at,
            'code': code
        }

        # save post in cache
        existing_posts = cache.get('posts')
        if existing_posts:
            cache.set('posts', cache.get('posts') + [new_post])
        else:
            cache.set('posts', [new_post])
        cache.set('new_post', True)

        return HttpResponseRedirect(reverse('post_detail', args=[new_post['code']]))

class MyPostsListView(View):
    http_method_names = ['get']

    def get(self, request):
        menu_items = []

        posts = cache.get('posts')
        if posts:
            for post in posts:
                menu_items.append(
                    MenuItem(description=u'{}..'.format(post['title'][:15]),
                             method='GET',
                             path=reverse('post_detail', args=[post['code']]))
                )
        else:
            menu_items.append(
                MenuItem(description='You currently have no posts.')
            )
        content = Menu(body=menu_items, footer='Reply MENU')

        return self.to_response(content)

class PostDetailView(View):
    http_method_names = ['get']

    def get(self, request, code):
        post = [post for post in cache.get('posts') if post['code'] == code][0]

        menu_items = []
        body_pre = [
            post['description'],
            'Author: {}'.format(post['user'].username),
            'Expires in: {}'.format(human(post['expires_at'])),
            'Code: {}'.format(post['code']),
        ]

        # check to see if we have notifications set in cache for this post
        if cache.get('new_post'):
            body_pre.insert(0, 'Post successfuly created!')
            cache.delete('new_post')

        menu_items.extend([MenuItem(description=u'\n'.join(body_pre))])

        # TODO: get the post title from cache
        content = Menu(body=menu_items, header=post['title'], footer='Reply MENU')

        return self.to_response(content)


"""This module contains all the functions needed to identify the tags and data
for web scraping. It is assisted by the Helper class to populate
a dictionary of dictionaries with the scraped weather data.
"""
#Name: Dahnia Simon, Lok Yee Harriet Chiu, Kiet Lam
#Course: Programming in Python - ADEV - 3005 (228331)
#Date Due - Milestone 1: November 25, 2022
#Term 5 - Final Project
# pylint - 9.59

from html.parser import HTMLParser

class WeatherScraper(HTMLParser):
    """The WeatherScraper class contains all methods needed to identify the
    correct weather data to be scraped."""
    def __init__(self):
        """Initializes variables to be used through the class."""
        HTMLParser.__init__(self)
        self.tbody = False
        self.a_tag = False
        self.td_tag = False
        self.th_tag = False
        self.count = 0
        self.user_year = ""
        self.user_month = ""
        self.last_month = False
        self.daily_temps = {}
        self.weather = {}
        self.day = ""
        self.date = ""
        self.complete_date = ""
        self.format = '%Y/%m/%d'
        self.daily_temps_complete = {}

    def handle_starttag(self, tag, attrs):
        """Test for specific start tags to the min, max and mean data and
        checks for attributes in tags to identify the last available month and
        year on the website."""
        if tag == "tbody":
            self.tbody = True
        if tag == "a":
            self.a_tag = True
        if tag == "td":
            self.td_tag = True
        if tag == "th":
            self.th_tag = True

        #used to find the page with missing previous button and stop loop
        if len(attrs) == 2:
            if attrs[1][1] == "previous disabled":
                self.last_month = True

    def handle_endtag(self, tag):
        """Tests for the end tags to find where the min, max and mean data ends."""
        if tag == "a":
            self.a_tag = False
        if tag == "tbody":
            self.tbody = False
        if tag == "td":
            self.td_tag = False
        if tag == "th":
            self.th_tag = False

    def handle_data(self, data):
        """Identifies all valid max, min and mean data and populates
        the corresponding dictionaries with values."""
        if self.tbody:
            if self.th_tag:
                try:
                    int(data)
                    self.count = 0
                    self.day = data
                except ValueError:
                    return False
            if self.td_tag:
                self.count+=1
                if self.a_tag:
                    if "M" in data:
                        self.count = 4
                if self.a_tag:
                    if "E" in data:
                        self.count-=1
                if self.count <= 3:
                    try:
                        float(data)
                        if self.count == 1:
                            self.daily_temps["Max"] = float(data.strip())
                        elif self.count == 2:
                            self.daily_temps["Min"] = float(data.strip())
                        elif self.count == 3:
                            self.daily_temps["Mean"] = float(data.strip())
                            self.daily_temps_complete = self.daily_temps
                            self.daily_temps = {}
                            self.date = f"{self.user_year}/{self.user_month}/{self.day}"
                            self.complete_date = self.date
                            self.weather[self.complete_date] = self.daily_temps_complete
                    except ValueError:
                        return False


import random as rd

import math
import numpy as np

import Reporter

def mutate_inversion(candidate):
    """Mutate a candidate solution in place using inversion mutation."""
    size = candidate.size
    if size <= 1:
        return
    first_pos = rd.randint(0, size - 2)
    second_pos = rd.randint(first_pos, size - 1)
    candidate[first_pos:second_pos + 1] = np.flip(candidate[first_pos:second_pos + 1])

def recombine_PMX(parent1, parent2):
    """Use two parent candidates to produce one offspring using partially mapped crossover.
    See p.70-71 in Eiben & Smith.
    Note: this operator can technically produce two offspring, but we forgot about
    this during our implementation.
    """
    size = parent1.size
    offspring = np.zeros_like(parent1)
    # We must initialize offspring with -1's, to identify whether a spot is not yet filled.
    for i in range(size):
        offspring[i] = -1
    # 1.
    first_pos = rd.randint(0, size - 2)
    second_pos = rd.randint(first_pos, size - 1)
    offspring[first_pos:second_pos + 1] = parent1[first_pos:second_pos + 1]
    # 2. -  5.
    for elem in parent2[first_pos:second_pos + 1]:
        if elem in parent1[first_pos:second_pos + 1]:
            continue  # elem already occurs in offspring
        # elem is not yet in offspring, find the index to place it
        index = 0
        value = elem
        while value != -1:
            index = index_of(parent2, value)
            value = offspring[index]
        offspring[index] = elem
    # 6.
    for i in range(size):
        if offspring[i] == -1:
            offspring[i] = parent2[i]
    return offspring

def index_of(array, value):
    """Return the first index at which value occurs in array."""
    return np.where(array == value)[0][0]

def length(candidate, distance_matrix):
    """Calculate the length of the path of candidate."""
    result = 0.0
    size = candidate.size
    for i in range(size - 1):
        result += distance_matrix[candidate[i]][candidate[i + 1]]
    result += distance_matrix[candidate[size - 1]][candidate[0]]  # Order matters.
    return result

def monte_carlo(distance_matrix, population_size):
    """Initializes the population at random."""
    population = []
    for i in range(population_size):
        gene = np.array(list(range(len(distance_matrix))))
        np.random.shuffle(gene)
        population.append(gene)
    return population

def avoid_inf(distance_matrix, population_size):
    """Initializes the population using a heuristic which tries to avoid infinite values."""
    population = []
    for i in range(population_size):
        start = rd.randrange(0, len(distance_matrix))
        candidate = [start]
        for j in range(len(distance_matrix) - 1):
            possible_next = [
                x for x in range(len(distance_matrix))
                if x not in candidate and distance_matrix[candidate[-1]][x] != math.inf
            ]
            if len(possible_next) == 0:  # If there is no next city without inf distance, pick random.
                # TODO Modify the previous value / pick different start when this happens.
                possible_next = [x for x in range(len(distance_matrix)) if x not in candidate]
            next_city = rd.choice(possible_next)
            candidate.append(next_city)
        population.append(np.array(candidate))
    return population

def k_tournament(population, k, fitness_function, distance_matrix):
    """Performs a k-tournament on the population. Returns one candidate."""
    selected = []
    for i in range(k):
        selected.append(rd.choice(population))
    return min(selected, key=lambda x: fitness_function(x, distance_matrix))

# Modify the class name to match your student number.
class r0758170:

    def __init__(self):
        self.reporter = Reporter.Reporter(self.__class__.__name__)
        # rd.seed(2023)  # During testing, set the seed for reproducible results.
        self.k = 5
        self.population = []
        self.population_size = 100
        self.mu = 20  # Must be even.
        self.mutate_chance = 0.05
        self.mutation_function = mutate_inversion
        self.recombine_function = recombine_PMX
        self.fitness_function = length
        self.init_function = avoid_inf
        self.selection = k_tournament

    # The evolutionary algorithm's main loop
    def optimize(self, filename):
        # Read distance matrix from file.
        file = open(filename)
        distanceMatrix = np.loadtxt(file, delimiter=",")
        file.close()

        # Initialization
        self.population = self.init_function(distanceMatrix, self.population_size)
        # print(f'Initial pop: \n{[self.fitness_function(x, distanceMatrix) for x in self.population]}')

        # maxIt = 500
        # current_it = 0
        # while current_it < maxIt:
        bestObjective = math.inf
        bestSolution = self.population[0]
        while True:
            # Selection
            # Perform a certain number of k-tournaments; this depends on self.mu
            # and whether the recombination operator returns one or two offspring.
            # One offspring: need 2 * self.mu selected.
            # Two offspring: need self.mu selected.
            selected = []
            for i in range(2 * self.mu):
                selected.append(k_tournament(self.population, self.k, self.fitness_function, distanceMatrix))

            # Variation
            # Recombination will produce self.mu new offspring.
            new_offspring = []
            it = iter(selected)
            for p1 in it:
                p2 = next(it)
                offspring = self.recombine_function(p1, p2)
                new_offspring.append(offspring)
            self.population.extend(new_offspring)

            # Mutation will happend on the entire population and new offspring, with a certain probability.
            for candidate in self.population:
                if rd.random() < self.mutate_chance:
                    self.mutation_function(candidate)

            # Elimination
            # Lambda + mu elimination: keep only the lambda best candidates.
            self.population.sort(key=lambda x: self.fitness_function(x, distanceMatrix))
            self.population = self.population[:self.population_size]

            # print(f'New pop: \n{[self.fitness_function(x, distanceMatrix) for x in self.population]}')

            # Recalculate mean and best.
            meanObjective = 0.0
            currentBestObjective = math.inf
            currentBestSolution = self.population[0]
            for candidate in self.population:
                candidate_fitness = self.fitness_function(candidate, distanceMatrix)
                meanObjective += candidate_fitness
                if candidate_fitness < currentBestObjective:
                    currentBestObjective = candidate_fitness
                    currentBestSolution = candidate
            meanObjective = meanObjective / self.population_size
            if currentBestObjective < bestObjective:
                bestObjective = currentBestObjective
                bestSolution = currentBestSolution

            # Call the reporter with:
            #  - the mean objective function value of the population
            #  - the best objective function value of the population
            #  - a 1D numpy array in the cycle notation containing the best solution
            #    with city numbering starting from 0
            timeLeft = self.reporter.report(meanObjective, bestObjective, bestSolution)
            if timeLeft < 0:
                break
            # current_it += 1

        # Your code here.
        return 0


import pyro.mesh.boundary as bnd
import pyro.simulation_null as sn
from pyro.mesh import patch
from pyro.util import runparams

class TestSimulation:

    @classmethod
    def setup_class(cls):
        """ this is run once for each class before any tests """

    @classmethod
    def teardown_class(cls):
        """ this is run once for each class after all tests """

    def setup_method(self):
        """ this is run before each test """
        self.rp = runparams.RuntimeParameters()
        self.rp.params["driver.tmax"] = 1.0
        self.rp.params["driver.max_steps"] = 100
        self.rp.params["driver.init_tstep_factor"] = 0.5
        self.rp.params["driver.max_dt_change"] = 1.2
        self.rp.params["driver.fix_dt"] = -1.0

        self.sim = sn.NullSimulation("test", "test", self.rp)

        myg = patch.Grid2d(8, 16)
        myd = patch.CellCenterData2d(myg)
        bc = bnd.BC()
        myd.register_var("a", bc)
        myd.create()

        self.sim.cc_data = myd

    def teardown_method(self):
        """ this is run after each test """
        self.rp = None
        self.sim = None

    def test_finished_n(self):
        self.sim.n = 1000
        assert self.sim.finished()

    def test_finished_t(self):
        self.sim.cc_data.t = 2.0
        assert self.sim.finished()

    def test_compute_timestep(self):

        # set a dt and n = 0, then init_tstep_factor should kick in
        self.sim.dt = 2.0
        self.sim.n = 0
        self.sim.compute_timestep()
        assert self.sim.dt == 1.0

        # now set dt_old and a new dt and see if the max_dt_change kicks in
        self.sim.n = 1.0
        self.sim.dt_old = 1.0
        self.sim.dt = 2.0
        self.sim.compute_timestep()
        assert self.sim.dt == 1.2

        # now test what happens if we go over tmax
        self.sim.cc_data.t = 0.75
        self.sim.dt = 0.5
        self.sim.compute_timestep()
        assert self.sim.dt == 0.25

def test_grid_setup():

    rp = runparams.RuntimeParameters()
    rp.params["mesh.nx"] = 8
    rp.params["mesh.ny"] = 16
    rp.params["mesh.xmin"] = 0.0
    rp.params["mesh.xmax"] = 1.0
    rp.params["mesh.ymin"] = 0.0
    rp.params["mesh.ymax"] = 2.0

    g = sn.grid_setup(rp)

    assert g.nx == 8
    assert g.ny == 16
    assert g.dx == 1.0/8
    assert g.dy == 1.0/8


import mariadb
import requests
from price import config
from price import mail
import time
import datetime
from price import insert1_12 as insert

headers = {
    'X-CMC_PRO_API_KEY': config.key_coinmarketcap,
    'Accepts': 'application/json.json',
}

params = {
    'start': '1',
    'limit': '50',
    'convert': 'USD'
}
# see docsc https://coinmarketcap.com/api/documentation/v1/#tag/cryptocurrency
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'

if 1 == 1 :
    def run(fetch_id):
        try:
            json_data = requests.get(url, params=params, headers=headers).json()
            coins = json_data['data']
            a=""
            insert.delete('coins')
            for i in coins:
                if i['symbol'] in ('BTC', 'ETH', 'WBTC', 'BNB', 'MATIC', 'ATOM', 'DOGE'):
                    a = str.lower(str(i['symbol']))
                    insert.html(str(i['id']), a)
                else:
                    insert.html(str(i['id']), str(i['symbol']))
                coinid = i['id']
                for userid in insert.getAlertsUsid():
                    try:
                        if i['quote']['USD']['price'] > insert.getconf('upper', userid[0], coinid) and int(
                                insert.getconf('new', userid[0], coinid)) == 1:
                            print('ueber')
                            mail.mail(
                                f"Hallo {insert.getusname(userid[0])}, \n\nDer Preis von {i['symbol']} ist ueber {insert.getconf('upper', userid[0], coinid)} gestiegen!\n\nDein Alert wurde deaktiviert, du kannst auf unserer Webseite einen neuen Alert einrichten oder diesen erneut aktivieren.\n\nViele Gruesse \ndein CryptoAlert Team :)",
                                config.subject, config.mailfrom, insert.getmail(userid[0]),
                                config.smtp, config.mail_usr, config.mail_pwd)
                            insert.updateconf(userid[0], coinid)
                        elif i['quote']['USD']['price'] < insert.getconf('lower', userid[0], coinid) and int(
                                insert.getconf('new', userid[0], coinid)) == 1:
                            print('unter')
                            mail.mail(
                                f"Hallo {insert.getusname(userid[0])}, \n\nDer Preis von {i['symbol']} ist unter {insert.getconf('lower', userid[0], coinid)} USD gefallen!\n\nDein Alert wurde deaktiviert, du kannst auf unserer Webseite einen neuen Alert einrichten oder diesen erneut aktivieren.\n\nViele Gruesse \ndein CryptoAlert Team :)",
                                config.subject, config.mailfrom, insert.getmail(userid[0]),
                                config.smtp, config.mail_usr, config.mail_pwd)
                            insert.updateconf(userid[0], coinid)
                        else:
                            print(f"\nKeine E-Mail zu Alert von {insert.getusname(userid[0])} bei {i['symbol']} versendet.\n")
                    except:
                        None

                try:
                    insert.insert(i['quote']['USD']['price'], str(i['quote']['USD']['last_updated']), str(i['symbol']).upper(), str(i['quote']['USD']['volume_24h']), str(i['quote']['USD']['volume_change_24h']), str(i['quote']['USD']['percent_change_1h']), str(i['quote']['USD']['percent_change_24h']), str(i['quote']['USD']['percent_change_7d']), str(i['quote']['USD']['percent_change_30d']), str(i['quote']['USD']['percent_change_60d']), str(i['quote']['USD']['percent_change_90d']), str(i['quote']['USD']['market_cap']), str(i['quote']['USD']['market_cap_dominance']), str(i['cmc_rank']), str(fetch_id))

                except mariadb.ProgrammingError:

                    insert.create(str(i['symbol']))
                    insert.insert(i['quote']['USD']['price'], str(i['quote']['USD']['last_updated']), str(i['symbol']), str(i['quote']['USD']['volume_24h']), str(i['quote']['USD']['volume_change_24h']), str(i['quote']['USD']['percent_change_1h']), str(i['quote']['USD']['percent_change_24h']), str(i['quote']['USD']['percent_change_7d']), str(i['quote']['USD']['percent_change_30d']), str(i['quote']['USD']['percent_change_60d']), str(i['quote']['USD']['percent_change_90d']), str(i['quote']['USD']['market_cap']), str(i['quote']['USD']['market_cap_dominance']), str(i['cmc_rank']), str(fetch_id))
            now = datetime.datetime.now()
            now = now.strftime('%Y-%m-%d %H:%M:%S')
            print(now)

            #insert.log(now)

        except requests.exceptions.ConnectionError:
            time.sleep(3)


"""Add has_assigned_courses to hod table

Revision ID: 3e4649d3af3d
Revises: 085dfd884e1d
Create Date: 2019-08-24 12:46:19.631062

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '3e4649d3af3d'
down_revision = '085dfd884e1d'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('hods', sa.Column('has_assigned_courses', sa.Boolean(), nullable=True))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('hods', 'has_assigned_courses')
    # ### end Alembic commands ###


# 3. Напишите программу,
# которая будет преобразовывать десятичное число в двоичное.
# Без использования встроенной функции преобразования, без строк.

def dec_to_bin(n):
    result = 0
    i = 0
    while n > 0:
        result += (n % 2) * 10 ** i
        n //= 2
        i += 1
    return result

num = int(input("Введите целое число:\n"))
print(f"{num} в десятичной системе равно {dec_to_bin(num)} в двоичной")


def check_project_search_supported(sg_connection):
    """
    A compatibility check to see if the current version of SG has the fix
    that allows text_search to be run for projects.

    :returns: ``True`` if project search is possible, ``False`` otherwise.

    .. warning::

        This method is not part of the public API. It will be removed without
        warning in the future.
    """

    server_caps = sg_connection.server_caps

    # make sure we're greater than or equal to SG v7.0.2
    return (
        hasattr(sg_connection, "server_caps")
        and server_caps.version
        and server_caps.version >= (7, 0, 2)
    )


import sys
sys.path.append("..")
import os
from utils import all_losses, all_folds, all_datasets, convert_to_valid_path
import pickle
import numpy as np
from multiprocessing import Pool
import argparse
import pandas as pd
from scipy.spatial.distance import jensenshannon

def calculate_stats(grads):
    grad1, grad2 = grads
    grad1 = grad1.flatten()
    grad2 = grad2.flatten()

    corr = np.corrcoef(grad1, grad2)[0, 1]

    grad1 /= np.sum(grad1)
    grad2 /= np.sum(grad2)
    jsd = np.square(jensenshannon(grad1, grad2))

    return {
        "correlation": corr,
        "jensenshannondiv": jsd
    }

if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument("--loss1", type=str, help="First loss to use for the comparison")
    parser.add_argument("--loss2", type=str, help="Second loss to use for the comparison")
    parser.add_argument("--dataset", type=str, help="Dataset to use")
    parser.add_argument("--fold", type=int, help="Fold of dataset")
    args = parser.parse_args()

    print(f"Comparing {args.loss1} and {args.loss2} on {args.dataset} (fold {args.fold})")

    loss1_path = f"results/{convert_to_valid_path(args.loss1)}/{args.dataset}/{args.fold}.p"
    loss2_path = f"results/{convert_to_valid_path(args.loss2)}/{args.dataset}/{args.fold}.p"
    results_dir = f"stats/{args.dataset}/{args.fold}/"
    results_path = results_dir + f"{convert_to_valid_path(args.loss1)}_{convert_to_valid_path(args.loss2)}.csv"

    if os.path.exists(results_path):
        print(f"This combination was already checked.")
        sys.exit(0)

    with open(loss1_path, "rb") as f:
        grads1 = pickle.load(f)
        print(f"Loaded grads for {args.loss1}")

    if not os.path.exists(loss1_path) or not os.path.exists(loss2_path):
        print("Not all files are available.")
        sys.exit("Not all files are available.")

    with open(loss2_path, "rb") as f:
        grads2 = pickle.load(f)
        print(f"Loaded grads for {args.loss2}")

    print("Starting statistic generation")
    with Pool(processes=4) as pool:
        stats = pool.map(calculate_stats, zip(grads1, grads2))

    del grads1
    del grads2

    print("Creating DataFrame")
    stats = pd.DataFrame(stats)

    os.makedirs(results_dir, exist_ok=True)
    print("Saving DataFrame")
    stats.to_csv(results_path, index=False)

    print("Finished:")
    print(stats.describe())


import pandas as pd
import surprise
import torch
from surprise import Dataset
from typing import Tuple
import numpy as np
import torch.utils.data

def get_movielens_1m() -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
    movielens = Dataset.load_builtin("ml-1m", prompt=False)

    movies_file = f"{surprise.get_dataset_dir()}/ml-1m/ml-1m/movies.dat"
    users_file = f"{surprise.get_dataset_dir()}/ml-1m/ml-1m/users.dat"
    ratings_file = f"{surprise.get_dataset_dir()}/ml-1m/ml-1m/ratings.dat"

    movies_df = pd.read_csv(
        movies_file, sep="::", names=["MovieID", "Title", "Genres"], engine="python"
    )

    users_df = pd.read_csv(
        users_file,
        sep="::",
        names=["UserID", "Gender", "Age", "Occupation", "Zip-code"],
        engine="python",
    )
    ratings_df = pd.read_csv(
        ratings_file,
        sep="::",
        names=["UserID", "MovieID", "Rating", "Timestamp"],
        engine="python",
    )

    return movies_df, users_df, ratings_df

class MovieLens1MDataset(torch.utils.data.Dataset):

    def __init__(self):
        _, _, ratings_df = get_movielens_1m()

        self.items = ratings_df.iloc[:, :2].astype(np.longlong) - 1  # -1 because ID begins from 1
        self.ratings = ratings_df.iloc[:, 2]

        self.dims = np.max(self.items, axis=0) + 1

        self.user_field_idx = np.array((0,), dtype=np.longlong)
        self.item_field_idx = np.array((1,), dtype=np.longlong)

    def __len__(self):
        return self.ratings.shape[0]

    def __getitem__(self, index):
        return np.array(self.items.iloc[index]), np.array(self.ratings.iloc[index])


import storm_execution.config as config
from storm_commons.plugins.packages import PluginManager, plugin_factory

from storm_execution.execution.services.service import ExecutionTaskManagementService
from storm_execution.execution.resources.resource import ExecutionTaskManagementResource
from storm_execution.execution.services.config import ExecutionTaskManagementServiceConfig
from storm_execution.execution.resources.config import ExecutionTaskManagementResourceConfig

class StormExecution(object):
    """storm-execution extension."""

    def __init__(self, app=None):
        """Extension initialization."""
        if app:
            self.init_app(app)

    def init_app(self, app):
        """Flask application initialization."""
        self.init_config(app)

        self.init_plugins(app)
        self.init_services(app)
        self.init_resources(app)

        app.extensions["storm-execution"] = self

    def init_config(self, app):
        """Initialize configuration."""
        for k in dir(config):
            if k.startswith("STORM_EXECUTION_"):
                app.config.setdefault(k, getattr(config, k))

    def init_plugins(self, app):
        """Initialize the avaliable service plugins for the deposit operations."""
        available_plugin_services = plugin_factory(app, "storm_execution.plugins")

        self.plugin_manager = PluginManager(available_plugin_services)

    def init_services(self, app):
        """Initialize the execution runner services."""
        self.execution_task_management_service = ExecutionTaskManagementService(
            self.plugin_manager, ExecutionTaskManagementServiceConfig
        )

    def init_resources(self, app):
        """Initialize the execution runner resources."""
        self.execution_task_management_resource = ExecutionTaskManagementResource(
            ExecutionTaskManagementResourceConfig,
            self.execution_task_management_service,
        )

__all__ = "StormExecution"


import os
from collections import defaultdict
from glob import glob

import imageio as imageio
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from matplotlib.colors import Normalize
import seaborn as sns
from exprimo import PLOT_STYLE
sns.set(style=PLOT_STYLE)

def plot_event_trace(events, simulator, show_transfer_lines=True, show_memory_usage=True, cmap='Paired',
                     plot_op_time_distribution=False, save_path=None):
    op_done_events = [e for e in events if e.type == 'op_done']
    transfer_done_events = [e for e in events if e.type == 'transfer_done']
    batches = max(events, key=lambda e: e.batch).batch + 1
    devices = sorted(list({e.device for e in op_done_events}))
    run_time = max(events, key=lambda e: e.end_time).end_time

    fig, gnt = plt.subplots()

    gnt.set_ylabel('Device')
    gnt.set_xlabel('Time (ms)')

    gnt.set_ylim(0, 10 + 10 * len(devices))
    gnt.set_xlim(0, run_time)

    gnt.set_yticks([5 + 5 + 10 * i for i in range(len(devices))])
    gnt.set_yticklabels(devices)

    gnt.patch.set_alpha(0)

    gnt.grid(True)

    if show_memory_usage:
        _, memory_x, memory_y = simulator.calculate_memory_usage(events, return_memory_history=True)

        plot_height = 1 / (len(devices) + 1)
        for d, device in enumerate(devices):
            # max_memory = simulator.device_graph.devices[device].device.memory * 10**9
            ax = gnt.inset_axes((0, plot_height * (d + 1), 1, plot_height / 2), sharex=gnt, zorder=1)
            # ax.set_ylim(0, max_memory)
            ax.axis('off')
            ax.fill_between(memory_x, memory_y[device], facecolor='grey', alpha=0.2)
            ax.set(ylim=(0, None))

    cmap_func = matplotlib.cm.get_cmap(cmap, 2*batches)
    cmap_norm = Normalize(vmin=0, vmax=2*batches)
    for event in op_done_events:
        color = cmap_func(cmap_norm(2*event.batch + int(event.backward)))
        device_index = devices.index(event.device)
        gnt.broken_barh([(event.start_time, event.end_time - event.start_time)], (5 + 2 + 10 * device_index, 6),
                        color=color, zorder=10, alpha=0.9)

    if show_transfer_lines:
        for event in transfer_done_events:
            from_device_index = devices.index(event.from_device)
            to_device_index = devices.index(event.to_device)
            gnt.plot([event.start_time, event.end_time], [10 + 10 * from_device_index, 10 + 10 * to_device_index],
                     color='red', alpha=0.4)

    if save_path:
        plt.savefig(os.path.expanduser(save_path), bb_inches='tight')

    plt.show()
    plt.close(fig)

    if plot_op_time_distribution:
        op_times = defaultdict(lambda: 0)

        for event in op_done_events:
            op_times[event.op_name] += event.end_time - event.start_time

        plt.figure(figsize=(15, 10))
        plt.xticks(rotation='vertical')
        plt.bar(op_times.keys(), op_times.values())
        plt.show()
        plt.close()

def plot_map_elites_archive(archive_scores, n_devices=None, max_jumps=None, axes=(1, 2), save_path=None,
                            return_fig=False, vmin=None, vmax=None, title=None):
    assert min(axes) >= 0 and max(axes) < len(archive_scores.shape), 'Axes out of range!'

    dimension_sizes = archive_scores.shape
    if n_devices == None:
        n_devices = dimension_sizes[0]

    if max_jumps == None:
        max_jumps = dimension_sizes[2]

    AXIS_NAMES = ['Most common device', 'No. of used devices', 'No. of jumps']
    AXIS_TICKS = [
        [int(i * (n_devices / dimension_sizes[0])) for i in range(dimension_sizes[0])],
        [int(i * (n_devices / dimension_sizes[1])) + 1 for i in range(dimension_sizes[1])],
        [int(i * (max_jumps / dimension_sizes[2])) for i in range(dimension_sizes[2])]
    ]

    if len(axes) < len(archive_scores.shape):
        avg_axes = [i for i in range(len(archive_scores.shape)) if i not in axes]
        avg_batch_times = 1 / np.nanmean(archive_scores, axis=tuple(avg_axes))
    else:
        avg_batch_times = 1 / archive_scores

    mask = np.isnan(avg_batch_times)

    min_time = np.nanmin(avg_batch_times)
    max_time = np.nanmax(avg_batch_times)

    n_plots = int(len(axes) == 2 or archive_scores.shape[0])

    plotted_axes = tuple(reversed(sorted(ax for ax in axes if len(axes) == 2 or ax != 0)))

    figsize = (10 * min(3, n_plots), 8 * ((n_plots - 1) // 3 + 1))
    fig, axs = plt.subplots((n_plots - 1) // 3 + 1, min(3, n_plots), figsize=figsize)
    axs = np.reshape(axs, (-1,))
    for i, ax in enumerate(axs):
        if i >= avg_batch_times.shape[0]:
            ax.axis('off')
            break

        cmap = sns.cm.rocket_r
        data = avg_batch_times[i, :, :] if len(axes) > 2 else avg_batch_times
        mask1 = mask[i, :, :] if len(axes) > 2 else mask
        if np.all(mask1):
            ax.axis('off')
            continue
        plot = sns.heatmap(data, ax=ax, mask=mask1, square=True, cmap=cmap,
                           xticklabels=AXIS_TICKS[plotted_axes[0]], yticklabels=AXIS_TICKS[plotted_axes[1]],
                           vmin=vmin if vmin else min_time, vmax=vmax if vmax else min(max_time, 5*10**4))
        plot.invert_yaxis()

        ax.set_xlabel(AXIS_NAMES[plotted_axes[0]])
        ax.set_ylabel(AXIS_NAMES[plotted_axes[1]])
        if len(axes) > 2:
            ax.set_title(f'{AXIS_NAMES[0]} = {AXIS_TICKS[0][i]}', pad=80)

    if title:
        fig.suptitle(title)

    if save_path:
        plt.savefig(os.path.expanduser(save_path), bb_inches='tight')

    if return_fig:
        return fig

    plt.show()
    plt.close(fig)

def plot_archive_animation(paths, save_path, dimension_sizes, n_devices=None, max_jumps=None, axes=(1, 2), fps=1):
    archives = []

    max_time = -np.inf
    min_time = np.inf

    step_names = []

    paths = sorted(paths)

    for path in paths:
        file_name = path.split('/')[-1]
        step = file_name.replace('step_', '').replace('.csv', '')
        step_names.append(step)
        archive = np.empty(dimension_sizes)
        archive[:] = np.NaN
        with open(path) as f:
            for l, line in enumerate(f):
                if l == 0: # Skip header row
                    continue
                niche, time, _ = line.split(';')
                niche = eval(niche)
                time = float(time)

                max_time = max(max_time, time)
                min_time = min(min_time, time)

                archive[niche[0], niche[1], niche[2]] = 1 / time

        archives.append(archive)

    images = []

    for i, archive in enumerate(archives):
        fig = plot_map_elites_archive(archive, n_devices, max_jumps, axes, vmin=min_time, vmax=max_time,
                                      return_fig=True, title=f'Step {step_names[i]}')
        fig.canvas.draw()
        image = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')
        image = image.reshape(fig.canvas.get_width_height()[::-1] + (3, ))
        plt.close()
        images.append(image)

    if isinstance(save_path, list) or isinstance(save_path, tuple):
        for path in save_path:
            imageio.mimsave(path, images, fps=fps)
    else:
        imageio.mimsave(save_path, images, fps=fps)


import imp
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import ListView, TemplateView

from accounts.forms import CustomUserCreationForm, LoginForm
from resume.models import Resume

class IndexView(TemplateView):
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data()
        context['form'] = CustomUserCreationForm
        context['form_log'] = LoginForm
        context['vacancies'] = ''
        context['yeap'] = False
        context['resumes'] = ''
        if self.request.user.is_authenticated:
            user = self.request.user
            if user.is_worker:
                context['vacancies'] = 'Help me!'
            else:
                context['resumes'] = Resume.objects.all()
        return context

    def get(self, request, *args, **kwargs):
        cont = super().get(request, *args, **kwargs)
        return cont


from django import forms
from .models import Items, Members,MembersList,Sendler
from django.template import loader
from django.utils.safestring import mark_safe
from django.contrib.admin.widgets import AdminFileWidget

from django.conf import settings

class BootstrapInputWidget(AdminFileWidget):
    '''custom widget for display image in change_form.html'''
    def render(self, name, value, attrs=None, renderer=None):
        output = []
        if value and getattr(value, "url", None):
            image_url = value.url
            file_name = str(value)
            output.append(
                ''.
                    format(image_url, image_url, file_name))
        output.append(super().render(name, value, attrs))
        return mark_safe(u''.join(output))

class ItemForm(forms.ModelForm):
    class Meta:
        model = Items
        fields = ('caption', 'image', 'description', 'type','cost','link')
        widgets = {'caption': forms.TextInput,
                   'description': forms.Textarea,
                   'image': BootstrapInputWidget()
                   }
class MembersListForm(forms.ModelForm):
    class Meta:
        model = MembersList
        fields = ('name',)

class SendlerForm(forms.ModelForm):
    class Meta:
        model = Sendler
        fields = ('header', 'text', 'members_list','send_date', 'image')
        widgets = {'text': forms.Textarea, }

class MessageForm(forms.Form):
    msg = forms.CharField()

class MembersForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MembersForm, self).__init__(*args, **kwargs)
        for i in self.fields:
            self.fields[i].widget.attrs['readonly'] = True
    class Meta:
        model = Members
        fields = ('image', 'name', 'id_t', 'user_state', 'link_id')
        widgets = {
                   'image': BootstrapInputWidget()
                   }


"""
A three digit number is called Armstrong number if sum of cube of its digit is equal to number itself.

E.g.- 153 is an Armstrong number because (1^3)+(5^3)+(3^3) = 153. Write all Armstrong numbers between 100 to 500

Find all the Armstrong number between two integers x and y.(both number inclusive)

Constraints:

x and y are 3 digits only
Input Format:

Two lines containing Positive integers x and y

Output Format:

All the Armstrong numbers one after the other in new lines.

Sample Input:

100
500
Sample Output:

153
370
371
407
"""

x = input()
y = input()
# Write your code here
for i in range(int(x),int(y) + 1):
	string_list = [str(j) for j in str(i)]
	sum = 0
	for numbers in string_list:
		sum = sum + (int(numbers) * int(numbers) * int(numbers))

	if sum == i:
		print(i)


import aiohttp
import json

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def get_code(station_name):

    url = 'https://suggests.rasp.yandex.net/all_suggests' \
          '?client_city=213' \
          '&field=from' \
          '&format=old' \
          '&lang=ru' \
          '&national_version=ru' \
          '&other_point=s9601782' \
          f'&part={station_name}'

    async with aiohttp.ClientSession() as session:
        html = await fetch(session, url)
        html_json = json.loads(html)
        stations = [s for s in html_json[1] if(s[2][:2] == 'пл')]
        print(f'stations - {len(stations)}')

    return stations


class Solution(object):
    def findMaxAverage(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: float
        """
        length = len(nums)
        max_sum = -1000000000000
        last_sum = None
        for position in range(0, length - k + 1):
            if position == 0:
                last_sum = sum(nums[position:position + k])
                max_sum = max(max_sum, last_sum)
            else:
                last_sum -= nums[position - 1]
                last_sum += nums[position + k - 1]
                max_sum = max(max_sum, last_sum)
        return max_sum

    def maxScore(self, cardPoints, k):
        """
        :type cardPoints: List[int]
        :type k: int
        :rtype: int
        """
        new_shuzu = cardPoints[-k:] + cardPoints[:k]
        return self.findMaxAverage(new_shuzu, k)


def chuyendoitrungtosanghauto(bieuthuctrungto):
    toantu = []
    bieuthuchauto = []
    thutuuutien = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3}
    for token in bieuthuctrungto:
        if token.isnumeric():
            bieuthuchauto.append(token)
        elif token in thutuuutien:
            while toantu and toantu[-1] != '(' and thutuuutien[token] <= thutuuutien.get(toantu[-1], 0):
                bieuthuc_hau_to.append(toantu.pop())
            toantu.append(token)
        elif token == '(':
            toantu.append(token)
        elif token == ')':
            while toantu and toantu[-1] != '(':
                bieuthuchauto.append(toantu.pop())
            toantu.pop()
    while toantu:
        bieuthuchauto.append(toan_tu.pop())
    return bieuthuchauto

bieuthuctrungto = input("Nhập biểu thức trung tố: ").split()
bieuthuchauto = chuyendoitrungtosanghauto(bieuthuctrungto)
print("Biểu thức hậu tố: ", " ".join(bieuthuchauto))

Học lập trình cùng tứn/bt chuong 5/bt nhom.py/bai123.py


# game_service.py

from model.models import Board
from model.dice import Dice

class SnakeAndLadder:
    _instance = None

    def __init__(self, blockCount, snakes, ladders, players, diceRollStrategy) -> None:
        if SnakeAndLadder._instance is not None:
            raise Exception("SnakeAndLadder is already initialized")
        self.blockCount = blockCount
        self.snakes = snakes
        self.ladders = ladders
        self.players = players
        self.board = Board(blockCount, ladders, snakes)
        self.dice = Dice(1, diceRollStrategy)
        self.winner = None

        SnakeAndLadder._instance = self

    @staticmethod
    def get_instance(*data):
        if SnakeAndLadder._instance is None:
            SnakeAndLadder(*data)
        return SnakeAndLadder._instance

    def announceWinner(self):
        print("Winner ::: ", self.winner.name, self.winner.id)

    def startGame(self):

        while self.winner is None:

            for player in self.players:

                moves = self.dice.roll()

                prev = player.position.number

                if prev + moves <= self.blockCount:

                    player.position = self.board.blocks[prev + moves]

                    if player.position.ladder:
                        player.position = self.board.blocks[player.position.ladder.toBlock]

                    if player.position.snake:
                        player.position = self.board.blocks[player.position.snake.tail]

                    print(str(player.name) + " rolled a " + str(moves) +
                          " and moved from " + str(prev) + " to " + str(player.position.number))

                    if player.position.number == self.blockCount:
                        self.winner = player
                        break
        self.announceWinner()


import cv2
from helper_files import cv_utils

image = cv2.imread("images/shape1.png")

img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
img_blurred = cv2.GaussianBlur(img_gray, (7, 7), 0)
img_edged = cv2.Canny(img_blurred, 30, 150)

(_, cntrs, _) = cv2.findContours(img_edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

print("I have found %d objects" %(len(cntrs)))

# for c in cntrs:
#     cv2.drawContours(image, [c], -1, (0,0,255), 2)

cv2.drawContours(image, cntrs, -1, (0,0,255), 2)

cv_utils.show_image(image)


import os
import copy
from collections import namedtuple, Counter, defaultdict
from .dict_config import infer_stage_name_class

def _load_yaml(filename):
    import yaml
    with open(filename, "r") as infile:
        cfg = yaml.safe_load(infile)
    return cfg

def config_dict_from_yaml(cfg_filename, output_dir=None, backend=None):
    cfg = _load_yaml(cfg_filename)

    this_dir = os.path.dirname(cfg_filename)
    cfg = expand_imports(cfg, this_dir=this_dir)

    # Override the output_dir in the config file if this function is given one
    if "general" not in cfg:
        cfg["general"] = {}
    if output_dir:
        cfg["general"]["output_dir"] = output_dir
    if backend:
        cfg["general"]["backend"] = backend

    return cfg

_StageDescription = namedtuple("_StageDescription", "name type config")

def expand_imports(cfg, this_dir):
    cfg = copy.deepcopy(cfg)
    stages = cfg.pop("stages")
    general = cfg.pop("general", None)

    internal_stage_list = preprocess_imports(stages, cfg, this_dir)
    expanded_cfg = build_config(internal_stage_list)
    if general is not None:
        expanded_cfg["general"] = general
    return expanded_cfg

def preprocess_imports(stages, configs, this_dir):
    expanded_stages = []
    for i, stage_cfg in enumerate(stages):
        name, target = infer_stage_name_class(i, stage_cfg)
        if name != "IMPORT":
            stage = _StageDescription(name, target, configs[name])
            expanded_stages.append(stage)
            continue

        expanded_stages += _handle_import(target.format(this_dir=this_dir))

    return expanded_stages

def _handle_import(cfg_filename):
    cfg = _load_yaml(cfg_filename)
    stages = cfg.pop("stages")
    this_dir = os.path.dirname(cfg_filename)
    return preprocess_imports(stages, cfg, this_dir=this_dir)

def build_config(internal_stage_list):
    # Count the number of unique stage names
    name_counts = Counter(s.name for s in internal_stage_list)
    stages_with_counter = {s for s, c in name_counts.items() if c > 1}

    out_stages = []
    out_config = {}
    stages_seen = defaultdict(int)
    for stage in internal_stage_list:
        name = stage.name
        if name in stages_with_counter:
            name += "." + str(stages_seen[name])
        stages_seen[stage.name] += 1

        out_stages.append({name: stage.type})
        out_config[name] = stage.config

    out_config["stages"] = out_stages
    return out_config


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

##################################################################
# PROGRAMMER: Pierre-Antoine Ksinant                             #
# DATE CREATED: 14/11/2018                                       #
# REVISED DATE: -                                                #
# PURPOSE: This file consists of a library of functions used the #
#          associated Jupyter Notebook, core of the project. Its #
#          main purpose is to manage the data and the generated  #
#          model.                                                #
##################################################################

##################
# Needed imports #
##################

import os
import pickle
import torch

#######################
# Constant dictionary #
#######################

SPECIAL_WORDS = {'PADDING': '<PAD>'}

######################
# Function load_data #
######################

def load_data(path):
    """
    Load dataset from file
    """

    input_file = os.path.join(path)

    with open(input_file, "r") as f:
        data = f.read()

    return data

#####################################
# Function preprocess_and_save_data #
#####################################

def preprocess_and_save_data(dataset_path, token_lookup, create_lookup_tables):
    """
    Preprocess text data
    """

    text = load_data(dataset_path)

    # Ignore notice (we don't use it for analysing the data):
    text = text[81:]

    token_dict = token_lookup()
    for key, token in token_dict.items():
        text = text.replace(key, ' {} '.format(token))

    text = text.lower()
    text = text.split()

    vocab_to_int, int_to_vocab = create_lookup_tables(text + list(SPECIAL_WORDS.values()))
    int_text = [vocab_to_int[word] for word in text]
    pickle.dump((int_text, vocab_to_int, int_to_vocab, token_dict), open('data/preprocessed_data.pickle', 'wb'))

############################
# Function load_preprocess #
############################

def load_preprocess():
    """
    Load the preprocessed training data and return them in batches of <batch_size> or less
    """

    return pickle.load(open('data/preprocessed_data.pickle', mode='rb'))

#######################
# Function save_model #
#######################

def save_model(filename, decoder):
    """
    Save the ENTIRE PyTorh model (not the recommended way to act)
    """

    torch.save(decoder, filename)

#######################
# Function load_model #
#######################

def load_model(filename):
    """
    Load an ENTIRE PyTorch model
    """

    return torch.load(filename)


# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import absolute_import, division, print_function, unicode_literals
from numpy.testing import assert_allclose
from astropy.units import Quantity
from ...utils.testing import assert_quantity_allclose
from ..powerlaw import (
    power_law_pivot_energy,
    power_law_energy_flux,
    power_law_integral_flux,
    power_law_compatibility,
)

def test_one():
    """Test one case"""
    I = power_law_integral_flux(f=1, g=2)

    assert_allclose(I, 1)

def test_powerlaw_energy_flux():
    """
    Test energy flux computation for power law against numerical solution.
    """
    e1 = Quantity(1, "TeV")
    e2 = Quantity(10, "TeV")
    e = Quantity(1, "TeV")
    g = 2.3
    I = Quantity(1e-12, "cm-2 s-1")

    val = power_law_energy_flux(I=I, g=g, e=e, e1=e1, e2=e2)

    ref = Quantity(2.1615219876151536e-12, "TeV cm-2 s-1")
    assert_quantity_allclose(val, ref)

def test_e_pivot():
    """Hard-coded example from fit example in survey/spectra.
    """
    e_pivot = power_law_pivot_energy(
        energy_ref=1, f0=5.35510540e-11, d_gamma=0.0318377, cov=6.56889442e-14
    )

    assert_allclose(e_pivot, 3.3540034240210987)

def test_compatibility():
    """
    Run a test case with hardcoded numbers:

    HESS J1912+101
    1FGL 1913.7+1007c

    We use the following symbols and units:
    e = pivot energy (MeV)
    f = flux density (cm^-2 s^-1 MeV^-1)
    g = "gamma" = spectral index
    """
    # Fermi power-law parameters
    e_fermi = 1296.2734
    f_fermi = 3.791907e-12
    f_err_fermi = 5.6907235e-13
    g_fermi = 2.3759267
    g_err_fermi = 0.08453985
    par_fermi = (e_fermi, f_fermi, f_err_fermi, g_fermi, g_err_fermi)

    # HESS power-law parameters
    e_hess = 1e6
    f_hess = 3.5 * 1e-12 * 1e-6
    f_err_hess = 0.6 * 1e-12 * 1e-6
    g_hess = 2.2
    g_err_hess = 0.2
    par_hess = (e_hess, f_hess, f_err_hess, g_hess, g_err_hess)

    compatibility = power_law_compatibility(par_fermi, par_hess)

    # Note: I just put the numbers here, didn't verify them!
    assert_allclose(compatibility["g_match"], 2.0901127509816506)
    assert_allclose(compatibility["sigma_low"], -3.380819211512078)
    assert_allclose(compatibility["sigma_high"], -0.5494362450917478)
    assert_allclose(compatibility["sigma_combined"], 3.4251742624791612)


from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.conf import settings

from .forms import ResumeForm

from easy_pdf.views import PDFTemplateView
import easy_pdf

# Create your views here.

class HelloPDFView(PDFTemplateView):
    template_name = 'pdf_generator/hello.html'

    base_url = 'file://' + str(settings.STATIC_ROOT)
    download_filename = 'hello.pdf'

    def get_context_data(self, **kwargs):
        return super(HelloPDFView, self).get_context_data(
            pagesize='letter',
            title='Hi there!',
            **kwargs
            )

def index(request):
    form = ResumeForm()
    if request.method == 'POST':
        form = ResumeForm(data=request.POST)
        if form.is_valid():
            context = {
            'name': request.POST.get('name'),
            }
            template = 'pdf_generator/hello.html'
            return easy_pdf.rendering.render_to_pdf_response(request,template,context,using=None,download_filename='Hello.pdf',content_type='application/pdf',response_class=HttpResponse)
    context = {
    'form': form,
    }
    return render(request, 'pdf_generator/index.html', context)


import os
import cmath
import json
import pytest
import timeit
import unittest
import numpy as np

import _SimpleNN

config = '''linear, 4, 4, relu
linear, 4, 2, sigmoid
CrossEntropy
'''

config2 = '''linear, 10, 10, relu
linear, 10, 4, sigmoid
CrossEntropy
'''

class TestInstance(unittest.TestCase):

	def load_weight(self, fp='w.txt'):

		with open(fp, 'r') as f:
			lines = f.readlines()

		d = json.loads(lines[0])
		layer1 = d['w']
		b1 = np.array(d['b'])
		w1 = np.zeros((4, 4))
		for i in range(4):
			for j in range(4):
				w1[i, j] = layer1[i*4+j]

		d = json.loads(lines[1])
		layer2 = d['w']
		b2 = np.array(d['b'])
		w2 = np.zeros((4, 2))
		for i in range(4):
			for j in range(2):
				w2[i, j] = layer2[i*2+j]

		return w1, b1, w2, b2

	def test_evaluate(self):

		np.random.seed(42)
		test_shape = (4, 4)
		x = np.random.random(test_shape).astype(np.float64)
		y_true = np.random.randint(0, 2, size=4).astype(np.float64)

		model = _SimpleNN.FNN(config)
		model.save('./w.txt')
		y_model = model.evaluate(x)

		w1, b1, w2, b2 = self.load_weight()

		_x = x.copy()
		_x = _x.dot(w1) + b1
		_x = np.where(_x>0, _x, 0)
		_x = _x.dot(w2) + b2
		_x = 1 / (1+np.exp(-_x))

		for i in range(4):
			for j in range(2):
				# somehow get error if count to 7 place
				self.assertAlmostEqual(_x[i, j], y_model[i, j], 6)

	def test_loss(self):

		def softmax_crossentropy_with_logits(logits,reference_answers):

			# Compute crossentropy from logits[batch,n_classes] and ids of correct answers
			logits_for_answers = logits[np.arange(len(logits)),reference_answers.astype(np.int32)]

			xentropy = - logits_for_answers + np.log(np.sum(np.exp(logits),axis=-1))

			return xentropy

		model = _SimpleNN.FNN(config)

		# n: number of data
		# p: number of demension
		n, p = 10, 4

		y = np.random.random(size=(n, p))
		y_true = np.random.randint(0, p, n).astype(np.float64)

		loss_model = model.getLoss(y, y_true)
		loss = softmax_crossentropy_with_logits(y, y_true).sum()

		self.assertAlmostEqual(loss, loss_model, 6)

	def test_loss_grad(self):

		def grad_softmax_crossentropy_with_logits(logits,reference_answers):

			# Compute crossentropy gradient from logits[batch,n_classes] and ids of correct answers
			ones_for_answers = np.zeros_like(logits)
			ones_for_answers[np.arange(len(logits)),reference_answers] = 1

			softmax = np.exp(logits) / np.exp(logits).sum(axis=-1,keepdims=True)

			return (- ones_for_answers + softmax) / logits.shape[0]

		model = _SimpleNN.FNN(config)

		# n: number of data
		# p: number of demension
		n, p = 10, 4

		y = np.random.random(size=(n,p))
		y_true = np.random.randint(0, p, n).astype(np.float64)

		grad_model = model.getGrad(y, y_true)
		grad = grad_softmax_crossentropy_with_logits(y, y_true.astype(np.int32))

		for i in range(grad.shape[0]):
			for j in range(grad.shape[1]):
				self.assertAlmostEqual(grad[i, j], grad_model[i, j])

	def test_backward(self):

		def grad_softmax_crossentropy_with_logits(logits,reference_answers):

			# Compute crossentropy gradient from logits[batch,n_classes] and ids of correct answers
			ones_for_answers = np.zeros_like(logits)
			ones_for_answers[np.arange(len(logits)),reference_answers] = 1

			softmax = np.exp(logits) / np.exp(logits).sum(axis=-1,keepdims=True)

			return (- ones_for_answers + softmax) / logits.shape[0]

		def sigmoid_df_dx(x):
			return (np.exp(-x))/((np.exp(-x)+1)**2)

		model = _SimpleNN.FNN(config)
		model.save('./w_init.txt')
		w1_init, b1_init, w2_init, b2_init = self.load_weight('./w_init.txt')

		X_train = np.random.random(size=(100, 4))
		y_train = np.random.randint(0, 2, 100)

		y_out = model.evaluate(X_train)
		model.fit(X_train, y_train.astype(np.float64), lr=0.1, epochs=1)

		model.save('./w_update.txt')
		w1_update, b1_update, w2_update, b2_update = self.load_weight('./w_update.txt')

		grad_loss = grad_softmax_crossentropy_with_logits(y_out, y_train)

		X_inter = X_train.dot(w1_init)+b1_init
		grad_output = grad_loss * sigmoid_df_dx(X_inter.dot(w2_init)+b2_init)
		grad_weights = np.dot(X_inter.T, grad_output)

		w2_true = w2_init - grad_weights * 0.1

		for i in range(w2_update.shape[0]):
			for j in range(w2_update.shape[1]):
				self.assertAlmostEqual(w2_update[i, j], w2_true[i,j], 6)


def is_visible(input:list, col:int, row:int, total_col:int, total_row:int):
    current_tree_value = int(input[row][col])
    # left
    left = max([int(input[row][i]) for i in range(0, col)])
    # right
    right = max([int(input[row][i]) for i in range(col+1, total_col)])
    # up
    up = max([int(input[i][col]) for i in range(0, row)])
    # down
    down = max([int(input[i][col]) for i in range(row+1, total_row)])
    if current_tree_value > left or current_tree_value > right or current_tree_value > up or current_tree_value > down:
        return True
    else:
        return False

def visibility_distance(input:list, col:int, row:int, total_col:int, total_row:int):
    current_tree_value = int(input[row][col])
    # left
    left_dist = 0
    left = [int(input[row][i]) for i in range(col-1, -1, -1)]
    if left:
        for x in left:
            left_dist += 1
            if x >= current_tree_value:
                break
    # right
    right_dist = 0
    right = [int(input[row][i]) for i in range(col+1, total_col)]
    if right:
        for x in right:
            right_dist += 1
            if x >= current_tree_value:
                break

    # up
    up_dist = 0
    up = [int(input[i][col]) for i in range(row - 1, -1, -1)]
    if up:
        for x in up:
            up_dist += 1
            if x >= current_tree_value:
                break
    # down
    down_dist = 0
    down = [int(input[i][col]) for i in range(row+1, total_row)]
    if down:
        for x in down:
            down_dist += 1
            if x >= current_tree_value:
                break

    return up_dist*down_dist*left_dist*right_dist

def test():
    input = [x.strip() for x in open("../Input/test_input.txt").readlines()]
    rows = len(input)
    cols = len(input[0])
    total_visible = 2 * (rows + cols) - 4
    for x in range(1, cols - 1):
        for y in range(1, rows - 1):
            if is_visible(input, y, x, cols, rows):
                total_visible += 1

    print(total_visible)

def challenge1():
    input = [x.strip() for x in open("../Input/day8_input.txt").readlines()]
    rows = len(input)
    cols = len(input[0])
    total_visible = 2 * (rows + cols) - 4
    for x in range(1, cols - 1):
        for y in range(1, rows - 1):
            if is_visible(input, y, x, cols, rows):
                total_visible += 1

    print(total_visible)

def challenge2():
    input = [x.strip() for x in open("../Input/day8_input.txt").readlines()]
    rows = len(input)
    cols = len(input[0])
    vis = [[0 for _ in range(cols)] for _ in range(rows)]
    for x in range(cols):
        for y in range(rows):
            vis[x][y] = visibility_distance(input, y, x, cols, rows)

    print(max([max(x) for x in vis]))

test()
challenge1()
challenge2()

2022/Day 8 - Treetop Tree House/Python/treetop_tree_house.py


# This file is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This file is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# See the GNU General Public License, <https://www.gnu.org/licenses/>.
#

# QueryParam (should be called form:->)
# Given a list of parameters (params) and current values (selected)
# and descriptions. Creates a form to turn on param options and
# add more to a param list and edit param values.
try:
    import wx
    import wx.lib.scrolledpanel
except Exception:
    print("Failed to import wx, install instructions:")
    print("sudo apt-get install -y libsdl2-2.0-0")
    print("sudo apt-get install libgtk-3-dev")
    print("pip3 install -U -f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-18.04 wxPython")
    exit(1)

class NamedButton(wx.Button):
    def __init__(self, parent, title: str, name:str):
        wx.Button.__init__(self, parent, label=title)
        self.name = name

class NamedComboBox(wx.ComboBox):
    def __init__(self, parent, choices: list, name: str):
        wx.Button.__init__(self, parent, choices=choices)
        self.name = name

class QueryParams(wx.Frame):
#class QueryParams(wx.Dialog):
    def __init__(self, parent, title: str, style: int, params: dict, selected: dict, verify: any, sample: any, descriptions: dict, getOptions: any, on_close: any = None, data: any = None):
        wx.Frame.__init__(self, parent=parent, title=title, style=wx.RESIZE_BORDER | wx.CLOSE_BOX)
        if on_close is not None:
            self.Bind(wx.EVT_CLOSE, on_close)
        self.title = title
        self.data = data
        self.verify = verify
        self.sample = sample
        self.getOptions = getOptions
        self.params = {}
        self.titles = {}
        self.desc = {}
        self.res = wx.OK
        self.panel = wx.Panel(self)
        self.vbox = wx.BoxSizer(wx.VERTICAL)
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        if style & wx.NO:
            self.noButton = wx.Button(self.panel, label="NO")
            self.noButton.Bind(wx.EVT_BUTTON, self.on_no)
            hbox.Add(self.noButton,proportion=1, flag=wx.EXPAND)
        if style & wx.CANCEL:
            self.deleteButton = wx.Button(self.panel, label="DELETE")
            self.deleteButton.Bind(wx.EVT_BUTTON, self.on_delete)
            hbox.Add(self.deleteButton, proportion=1, flag=wx.EXPAND)
        if style & wx.OK:
            self.okButton = wx.Button(self.panel, label="OK")
            self.okButton.Bind(wx.EVT_BUTTON, self.on_ok)
            hbox.Add(self.okButton, proportion=1, flag=wx.EXPAND)
        if style & wx.YES:
            self.yesButton = wx.Button(self.panel, label="YES")
            self.yesButton.Bind(wx.EVT_BUTTON, self.on_yes)
            hbox.Add(self.yesButton, proportion=1, flag=wx.EXPAND)
        if style & wx.CAPTION:
            self.verifyButton = wx.Button(self.panel, label="VERIFY")
            self.verifyButton.Bind(wx.EVT_BUTTON, self.on_verify)
            hbox.Add(self.verifyButton, proportion=1, flag=wx.EXPAND)
        self.vbox.Add(hbox, proportion=0, flag=wx.EXPAND)
        self.spanel = wx.lib.scrolledpanel.ScrolledPanel(self.panel)
        self.spanel.SetupScrolling()
        self.svbox = wx.BoxSizer(wx.VERTICAL)
        self.spanel.SetSizer(self.svbox)
        self.vbox.Add(self.spanel, proportion=1, flag=wx.EXPAND)
        self.descriptions = {}
        self.updateParams("", params, selected, descriptions)
        self.spanel.Layout()
        self.panel.SetSizer(self.vbox)
        self.panel.Layout()
        self.showFields()

    def updateParams(self, after: str, params: dict, selected: dict, descriptions: dict) -> None:
        for name in descriptions:
            if name not in self.descriptions:
                self.descriptions[name] = descriptions[name]
        pos = 0
        for i, n in enumerate(self.params.keys()):
            if n.startswith(after):
                pos = i
        beforeparams = {}
        for i, n in enumerate(self.params.keys()):
            beforeparams[n] = self.params[n]
            if i == pos:
                break
        afterparams = {}
        for i, n in enumerate(self.params.keys()):
            if i <= pos:
                continue
            afterparams[n] = self.params[n]
        self.params = {}
        for name, typ in params.items():
            if name in beforeparams or name in afterparams:
                continue  # Param already in params, only update new params.
            pos += 1
            value = str(selected.get(name, ""))
            flags = wx.ALL | wx.EXPAND
            proportion = 0
            descname = name
            if typ == "str":
                proportion = 1
                if value is None:
                    hint = selected.get("default"+name,"enter value")
                    self.params[name] = wx.TextCtrl(self.spanel, style=wx.TE_MULTILINE)
                    if hint:
                        self.params[name].SetHint(hint)
                else:
                    self.params[name] = wx.TextCtrl(self.spanel, style=wx.TE_MULTILINE, value=value)
            elif typ == "option":
                if selected[name]:
                    label = "OPTION OFF"
                else:
                    label = "OPTION ON"
                self.params[name] = NamedButton(self.spanel, label, name)
                self.params[name].Bind(wx.EVT_BUTTON, self.on_optButton)
            elif typ == "addbutton":
                self.params[name] = NamedButton(self.spanel, "ADD", name)
                self.params[name].Bind(wx.EVT_BUTTON, self.on_addButton)
            elif typ == "deletebutton":
                self.params[name] = NamedButton(self.spanel, "DELETE", name)
                self.params[name].Bind(wx.EVT_BUTTON, self.on_deleteButton)
            elif typ == "samplebutton":
                self.params[name] = NamedButton(self.spanel, "SAMPLE", value)
                self.params[name].Bind(wx.EVT_BUTTON, self.on_sampleButton)
            elif typ == "int":
                proportion = 1
                self.params[name] = wx.TextCtrl(self.spanel, value=value)
            elif typ == "YYYYMMDD HH:MM:SS":
                proportion = 1
                self.params[name] = wx.TextCtrl(self.spanel, value=value)
            elif typ == "password":
                proportion = 1
                self.params[name] = wx.TextCtrl(self.spanel, value=value)
            elif isinstance(typ, list):  # Choice
                if len(value) == 0:
                    value = typ[0]  # No selection, default to first choice.
                self.params[name] = NamedComboBox(self.spanel, choices=typ,name=name)
                self.params[name].SetValue(value)
                self.params[name].Bind(event=wx.EVT_COMBOBOX, handler=self.on_choice)
                descname = value
            else:
                raise Exception("Exception unknown type=" + str(typ))
            hbox = wx.BoxSizer(wx.HORIZONTAL)
            self.titles[name] = wx.StaticText(self.spanel, -1, name)
            hbox.Add(self.titles[name], proportion=0, flag=wx.ALIGN_LEFT)
            hbox.Add(self.params[name], proportion=proportion, flag=wx.ALL | wx.EXPAND)
            if descname in descriptions:
                self.desc[name] = wx.TextCtrl(self.spanel, value=descriptions[descname], style=wx.TE_MULTILINE|wx.TE_READONLY)
                hbox.Add(self.desc[name], proportion=1, flag=flags)
            if pos < self.svbox.GetItemCount():
                self.svbox.Insert(pos, hbox, flag=flags)
            else:
                self.svbox.Add(hbox, proportion=proportion, flag=flags)
        newparams = {}
        for n, e in beforeparams.items():
            newparams[n] = e
        for n, e in self.params.items():
            newparams[n] = e
        for n, e in afterparams.items():
            newparams[n] = e
        self.params = newparams

    def showFields(self) -> None:
        show = [True]  # Whether to show or hide the next field.
        nested = []  # name to match to pop the stack.
        choice = []  # name to match to start the choice selection
        for name in self.params.keys():
            e = self.params[name]
            # Pop end of field group
            while len(nested) > 0 and not name.startswith(nested[-1]):
                del show[-1]
                del nested[-1]
            # Look out for the start of chosen fields.
            if (len(choice) > 0 and
                (len(nested) == 0 or nested[-1] != choice[-1]) and
                name.startswith(choice[-1])):
                nested.append(name)
                show.append(True)
            showfield = show[-1]
            if isinstance(e, NamedButton) and e.GetLabel().startswith("OPTION"):
                nested.append(name[:name.rfind(".")])
                # OFF means turn it off, and it is currently ON!
                if self.params[name].GetLabel() == "OPTION OFF":
                    show.append(show[-1])
                else:
                    show.append(False)
            elif isinstance(e, wx.ComboBox):  # Choice
                if showfield:
                    nested.append(name)
                    show.append(False)
                    choice.append(name+"."+self.params[name].GetValue())
            if showfield:
                self.params[name].Show()
                self.titles[name].Show()
                if name in self.desc:
                    self.desc[name].Show()
            else:
                self.params[name].Hide()
                self.titles[name].Hide()
                if name in self.desc:
                    self.desc[name].Hide()
        self.panel.Layout()
        self.Layout()
        self.Show()

    def getSelected(self) -> dict:
        selected = {}
        for name, e in self.params.items():
            if e.IsShown():
                if isinstance(e,NamedButton):
                    selected[name] = e.GetLabel().endswith("OFF")
                else:
                    selected[name] = e.GetValue()
                    if e.GetHint() and not selected[name]:
                        selected[name] = None
                        selected["default"+name] = e.GetHint()
        return selected

    def getValue(self, name: str, typ: str) -> (any, str):
        if typ == "str":
            return self.params[name].GetValue(), typ
        elif typ == "int":
            # noinspection PyBroadException
            try:
                return int(self.params[name].GetValue()), typ
            except Exception:
                return -1
        elif typ == "YYYYMMDD HH:MM:SS":
            return self.params[name].GetValue(), typ
        elif typ == "password":
            v = self.params[name].GetValue()
            if v:
                # Cut'n'paste the password adds a return to the end.
                if v[-1] == "\n":
                    return v[0:-1], typ
            return v, typ
        else:
            raise ("Exception unknown type=" + typ)

    def on_no(self, _event):
        self.res = wx.NO
        self.Close()
        self.Destroy()

    def on_delete(self, _event):
        if wx.MessageBox("", "Confirm delete of command", wx.YES | wx.NO, self) == wx.YES:
            self.res = wx.CANCEL
            self.Close()
            self.Destroy()

    def on_yes(self, _event):
        self.res = wx.YES
        self.Close()
        self.Destroy()

    def on_ok(self, _event):
        if self.verify is not None:
            error = self.verify(self)
            if error:
                wx.MessageBox(
                    "Failed:"+error,
                    "verification",
                    wx.OK, self)
                return
        self.res = wx.OK
        self.Close()
        self.Destroy()

    def on_verify(self, _event):
        if self.verify is None:
            raise Exception("No verify callback method")
        error = self.verify(self)
        if error:
            wx.MessageBox(
                "Faild:"+error,
                "verification",
                wx.OK, self)
            return
        wx.MessageBox("Passed", "verification", wx.OK, self)

    def on_choice(self, event):
        cb = event.GetEventObject()
        value = cb.GetValue()
        name = cb.name
        if name in self.desc:
            if value in self.descriptions:
                self.desc[name].SetValue(self.descriptions[value])
            else:
                self.desc[name].SetValue("")
        self.showFields()

    def on_sampleButton(self, event) -> None:
        if self.sample is None:
            return
        cb = event.GetEventObject()
        self.sample(cb.name)

    def on_deleteButton(self, event) -> None:
        b = event.GetEventObject()
        if wx.MessageBox("", "Confirm delete of parameters", wx.YES | wx.NO, self) != wx.YES:
            return
        d = []
        for i, n in enumerate(self.params.keys()):
            if n.startswith(b.name):
                d.append((i, n))
        for i, n in reversed(d):
            self.params[n].Hide()
            del self.params[n]
            self.titles[n].Hide()
            del self.titles[n]
            if n in self.desc:
                self.desc[n].Hide()
                del self.desc[n]
            self.svbox.Remove(i)
        self.showFields()

    def on_addButton(self, event) -> None:
        b = event.GetEventObject()
        (params, selected, desc) = self.getOptions(cmd=None,at=b.name)
        prev = None
        for n in self.params.keys():
            if n.startswith(b.name):
                if self.params[n].GetLabel() == "DELETE":
                   prev = n
        if prev:
            x = prev[len(b.name)+1:]  # Cut main title and first dot.
            oldname = b.name + ".0"
            newname = b.name + "." + str(int(x) + 1)
            newparams = {}
            newselected = {}
            newdesc = {}
            for n, t in params.items():
                newn = n.replace(oldname,newname)
                newparams[newn] = params[n]
                if n in selected:
                    newselected[newn] = selected[n]
                if n in desc:
                    newdesc[newn] = desc[n]
            self.updateParams(b.name, newparams, newselected, newdesc)
        else:
            self.updateParams(b.name, params, selected, desc)
        self.showFields()

    def on_optButton(self, event) -> None:
        b = event.GetEventObject()
        if b.GetLabel().endswith("ON"):
            b.SetLabel("OPTION OFF")
            n = b.name
            if n.rindex("."):
                n = n[0:n.rindex(".")]
            (params, selected, desc) = self.getOptions(cmd=None, at=n)
            self.updateParams(n, params, selected, desc)
        else:
            b.SetLabel("OPTION ON")
        self.showFields()


# the start and end of the range are accepted from the user using the input function

start = int(input("Enter start of range: "))
end = int(input("Enter end of range: "))

positive_numbers = []

#A for loop is then used to iterate through the numbers in the range, and an if statement checks if each number is greater than 0
#If it is greater than 0, then it is added to the positive_numbers list
for num in range(start, end + 1):
    if num > 0:
        positive_numbers.append(num)

print("Positive numbers:", positive_numbers)


"""
========================
Extracted Data Directory
========================

An extracted data directory is a project subdirectory for storing data extracted from
external sources.

"""
from pathlib import Path

from git import Repo

from steamfitter.app.directory_structure.version import VersionDirectory
from steamfitter.lib.exceptions import SteamfitterException
from steamfitter.lib.filesystem import ARCHIVE_POLICIES, Directory, templates

class ExtractionSourceDirectory(Directory):
    DEFAULT_ARCHIVE_POLICY = ARCHIVE_POLICIES.archive

    NAME_TEMPLATE = "{source_count:>06}-{source_name}"

    DEFAULT_EMPTY_ARGS = {
        ("last_updated", lambda: ""),
        ("latest_version", lambda: ""),
        ("best_version", lambda: ""),
    }

    SUBDIRECTORY_TYPES = (VersionDirectory,)

    @classmethod
    def make_name(cls, root: Path, **kwargs) -> str:
        if "source_count" not in kwargs:
            raise ValueError("Must provide a source count.")
        if "source_name" not in kwargs:
            raise ValueError("Must provide a source name.")
        return cls.NAME_TEMPLATE.format(**kwargs)

    @classmethod
    def add_initial_content(cls, path: Path, **kwargs):
        source_name = kwargs["source_name"]
        extraction_template_path = path / "extraction_template.py"

        extraction_template_path.touch(mode=0o664)
        with open(extraction_template_path, "w") as f:
            f.write(templates.EXTRACTION.format(source_name=source_name))

class ExtractedDataDirectory(Directory):
    IS_INITIAL_DIRECTORY = True

    NAME_TEMPLATE = "extracted_data"
    DESCRIPTION_TEMPLATE = "Extracted data for the {project_name} project."

    DEFAULT_EMPTY_ARGS = {
        ("source_count", lambda: 0),
        ("sources", lambda: {}),
        ("columns", lambda: {}),
    }

    SUBDIRECTORY_TYPES = (ExtractionSourceDirectory,)

    def add_source(self, source_name: str, description: str):
        """Add a source to the extracted data directory."""
        sources = self["sources"].copy()
        if source_name in sources:
            raise SteamfitterException(f"Source {source_name} already exists.")

        source_count = self["source_count"] + 1
        ExtractionSourceDirectory.create(
            root=self.path,
            parent=self,
            source_count=source_count,
            source_name=source_name,
            description=description,
        )
        self.update(
            {
                "source_count": source_count,
                "sources": {**sources, source_name: source_count},
            }
        )
        self._metadata.persist()

        repo = Repo(self.path)
        repo.git.add(".")
        repo.index.commit(f"Added source {source_name}.")

    def remove_source(self, source_name: str):
        """Remove a source from the extracted data directory."""
        sources = self["sources"].copy()
        if source_name not in sources:
            raise SteamfitterException(f"Source {source_name} does not exist.")

        source_count = sources.pop(source_name)
        source_path = self.path / ExtractionSourceDirectory.make_name(
            root=self.path,
            source_count=source_count,
            source_name=source_name,
        )
        source_path.rmdir()
        source_path.touch(mode=0o600)

        # Preserve the count so we can keep adding new sources to the end.
        self.update(
            {
                "sources": self["sources"],
            }
        )
        self._metadata.persist()

        repo = Repo(self.path)
        repo.git.add(".")
        repo.index.commit(f"Removed source {source_name}.")

    def add_source_column(
        self,
        source_column_name: str,
        source_column_type: str,
        is_nullable: bool,
        description: str,
    ):
        """Add a source column to the extracted data directory."""
        if source_column_name in self["columns"].values():
            raise SteamfitterException(f"Source column {source_column_name} already exists.")
        self.update(
            {
                "columns": {
                    **self["columns"],
                    source_column_name: (source_column_type, is_nullable, description),
                },
            }
        )
        self._metadata.persist()

        repo = Repo(self.path)
        repo.git.add(".")
        repo.index.commit(f"Added source column {source_column_name}.")

    @classmethod
    def add_initial_content(cls, path: Path, **kwargs):
        repo = Repo.init(path)
        gitignore_path = path / ".gitignore"
        gitignore_path.touch(mode=0o664)
        with open(gitignore_path, "w") as f:
            f.write(templates.GITIGNORE)

        repo.git.add(".")
        repo.index.commit("Initial commit.")