import re
import requests
from bs4 import BeautifulSoup

MP_LIST_URL = "https://www.tbmm.gov.tr/develop/owa/milletvekillerimiz_sd.liste"

def get_mp_list_response(is_verify:bool=False):
    response = requests.get(MP_LIST_URL, verify=is_verify)
    return response

def get_mp_page_response(url:str, is_verify:bool=False):
    response = requests.get(url, verify=is_verify)
    return response

def create_parser(response):
    bs = BeautifulSoup(response.text, 'html.parser')
    return bs

def get_title(bs) -> str:
    title = bs.find('span', {'class':'AltKonuBaslikB16Gri'}).text.strip()
    return title

def parse_mp_list(bs, is_verbose:bool=False):
    rows = bs.find('table')
    cities = []
    for i, row in enumerate(rows):

        if is_verbose:
            print(i)
            print(row)

        is_city = row.find('span')

        if is_verbose:
            print('is city', is_city)

        if is_city is not None and is_city != -1:
            city = is_city.text
            city_dict = {'city': city, 'city_mps': []}
            cities.append(city_dict)

            if is_verbose:
                print("CITY: {}".format(city))

        else:
            is_mp = row.find('a')

            if is_verbose:
                print('is_mp', is_mp)

            if is_mp is not None and is_mp != -1:
                mp_name = is_mp.text
                mp_url = is_mp.attrs['href']
                mp_party = row.findAll('td')[-1].text

                if is_verbose:
                    print("MP: {}, Party: {}".format(mp_name, mp_party))
                    print(mp_url)

                m = re.match("https://www.tbmm.gov.tr/develop/owa/milletvekillerimiz_sd.bilgi\?p_donem=(\d+)&p_sicil=(\d+)", mp_url)
                mp_term = m.group(1) # p_donem
                mp_registery = m.group(2) # p_sicil
                mp_dict = {
                            'name': mp_name,
                            'term': mp_term,
                            'party': mp_party,
                            'registery': mp_registery,
                            'url': mp_url,
                        }
                cities[-1]['city_mps'].append(mp_dict)

    return cities

def parse_mp_page(bs):
    mp_name = bs.find('div', {'id': 'mv_isim'}).text.strip()
    mp_term = bs.find('div', {'id': 'mv_ili'}).text.strip().split(' ')[0][:-1]
    mp_city = bs.find('div', {'id': 'mv_ili'}).text.strip().split(' ')[2]
    mp_task = bs.find('div', {'id': 'mv_gorev'}).text.strip().split('\xa0')
    mp_photo_url = bs.find('div', {'id': 'fotograf_alani'}).find('img')['src']
    mp_party_logo_url = bs.find('div', {'id': 'parti_logo'}).find('img')['src']
    mp_contact = [m.text.strip() for m in bs.find('div', {'id': 'iletisim_bilgi'}).findAll('tr') if len(m.text.strip()) > 0]
    mp_cv = bs.find('div', {'id': 'ozgecmis_icerik'})
    mp_dict = {
        'name': mp_name,
        'term': mp_term,
        'city': mp_city,
        'tasks': mp_task,
        'photo_url': mp_photo_url,
        'party_logo_url': mp_party_logo_url,
        'contact': mp_contact,
        # 'mp_cv': mp_cv,
    }
    return mp_dict

def get_mp_list():
    r = get_mp_list_response()
    parser = create_parser(r)
    title = get_title(parser)
    cities = parse_mp_list(parser)
    return title, cities

def get_mp_page(url:str):
    mp_page_response = get_mp_page_response(url)
    parser = create_parser(mp_page_response)
    mp_dict = parse_mp_page(parser)
    return mp_dict

def get_city_list(cities):
    return list(map(lambda x: x['city'], cities))

def get_party_list(cities):
    return list(set([item for lst in list(map(lambda x: list(set(map(lambda y: y['party'], x['city_mps']))), cities)) for item in lst]))

if __name__ == '__main__':
    # Return title and cities
    title, cities = get_mp_list()
    print(cities)

    # Get mp page
    url = "https://www.tbmm.gov.tr/develop/owa/milletvekillerimiz_sd.bilgi?p_donem=27&p_sicil=7542"
    print(get_mp_page(url))

    # Get city list
    print(get_city_list(cities))

    # Get party list
    print(get_party_list(cities))


"""
The module in which they are implemented
    pages for post administration (creation, editing, deletion)
    post list page
    post details page
"""

from datetime import datetime

from flask import Flask, render_template, abort, url_for, Markup
from flask_admin import Admin, form

from flask_admin.contrib.sqla import ModelView
from flask_sqlalchemy import SQLAlchemy
import os

app = Flask(__name__, static_url_path="/static")
app.config["FLASK_ADMIN_SWATCH"] = "cerulean"
app.config["SECRET_KEY"] = "anykey"
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///db/blog.sqlite"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
app.config['STORAGE'] = "static/storage/post_img"
db = SQLAlchemy(app)

class Post(db.Model):
    """
        A class of Post

        ORM class of db

        Attributes
        -------
         id : Integer
            id of record
        title : String(100)
            title of post
        content : String
            content of post
        image : String
            the path to the saved image
        create_date : DateTime
            date and time of post creation
        is_active : Boolean
            a sign of active post

        Methods
        -------
        __repr__(self)
            Representative of post record

        """

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.String(), nullable=False)
    image = db.Column(db.String())
    create_date = db.Column(db.DateTime(), default=datetime.now)
    is_active = db.Column(db.Boolean, default=False, nullable=False)

    def __repr__(self):
        return f"<Post(id={self.id}, title={self.title}," \
               f" create_date={self.create_date})>"

file_path = os.path.abspath(os.path.dirname(__name__))

def name_gen_image(model, file_data):
    """Generate name of image from save to db

       Parameters
       ----------
       model :
           the model object
       file_data :
           upload file data

       Returns
       -------
       hash_name
           a name of file
       """

    hash_name = f'{model.title}/{file_data.filename}'
    return hash_name

class PostView(ModelView):
    """
        A class of Post View

        Methods
        -------
        _list_thumbnail(view, context, model, name)
            Return tumbnail url

        create_form(self, obj)
            Return admin create form

        edit_form(self, obj):
            Return admin edit form
        """
    column_display_pk = True
    can_create = True
    can_edit = True
    can_delete = True

    def _list_thumbnail(view, context, model, name):
        if not model.image:
            return ''

        url = url_for('static', filename=os.path.join('storage/', model.image))
        if model.image.split('.')[-1] in ['jpg', 'jpeg', 'png', 'svg', 'gif']:
            return Markup(f'<img src={url} width="100">')

    column_formatters = {
        'image': _list_thumbnail
    }

    form_extra_fields = {

        "image": form.ImageUploadField('',

                                        base_path=
                                        os.path.join(file_path, 'static/storage'),
                                        url_relative_path='storage',
                                        namegen=name_gen_image,
                                        max_size=(1200, 780, True),
                                        thumbnail_size=(100, 100, True),

                                        )}

    def create_form(self, obj=None):
        return super(PostView, self).create_form(obj)

    def edit_form(self, obj=None):
        return super(PostView, self).edit_form(obj)

admin = Admin(app, name='microblog', template_mode='bootstrap3')
admin.add_view(PostView(Post, db.session, name="Posts"))

@app.get("/")
def index():
    """Index page renderer

        Returns
        -------
        render template
            render template of index.html
        """
    return render_template("index.html")

@app.route("/posts")
def posts():
    """Posts page renderer

            Returns
            -------
            render template
                render template of blog.html
            """
    posts_qry = db.session.query(Post).all()
    return render_template("blog.html", posts=posts_qry)

@app.route("/posts/<int:post_id>")
def get_post(post_id):
    """Post page renderer

            Parameters
            ----------
            post_id : int
                The id of record in post db

            Returns
            -------
            render template
                render template of post.html
            """
    posts_qry = db.session.query(Post).all()
    image_qry = db.session.query(Post.image).filter(Post.id == post_id).all()
    image_name = str(image_qry[0])
    image_file = url_for('static', filename='storage/' + image_name)
    post = next(filter(lambda p: p.id == post_id, posts_qry), None)
    if post is None:
        abort(404)
    return render_template("post.html", post=post, image_url=image_file)

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


from __future__ import division
from collections import Counter
import math, random

# -*- coding: cp1252 -*-
#***************************************************************************************************
# **********************Chapter 6. Probability***************************************************

# We could also ask about the probability of the event 'both children are girls' conditional on the event 'at least one
# of the children is a girl' (L). Surprisingly, the answer is different from before!
# As before, the event B and L ('both children are girls and at least one of the children is a girl') is just the event B.
# This means we have:
# P(B|L)=P(B,L)/P(L)= P(B)/P(L)=1/3
# My solution:
# P(B/L)=P(L/B)*P(B)/P(L)
# P(L/B)=1 probability at least 1 is girl given both are girls 1.
# P(B)=(1/2)*(1/2)=1/4 Probability that both are girls.
# P(L)=GirlGirl+BoyGirl+GirlBoy=1/4+1/4+1/4=3/4
# So P(B)/P(L)=(1/4)*(4/3)=1/3

#Prove through program
def randon_kid():
    return random.choice(['boy','girl'])
'''
older_girl=0
both_girls=0
either_girl=0
random.seed(0)
for _ in xrange(10000):
    older=randon_kid()
    younger=randon_kid()
    if older=='girl':
        older_girl+=1
    if older=='girl' or younger=='girl':
        either_girl+=1
    if older=='girl' and younger=='girl':
        both_girls+=1
print 'P(both girls/older girl ', both_girls/older_girl
print 'P(both girls/either girl ', both_girls/either_girl
'''

# Expected value:
# We will sometimes talk about the expected value of a random variable, which is the average of its values weighted
# The coin flip variable has an expected value of 1/2 (= 0 * 1/2 + 1 * 1/2),
# by their probabilities. P1*outcome+P2*outcome...Pn*outcome
# and the range(10) variable has an expected value of 4.5=(.1*0+.1*1...+.1*9)

def uniform_pdf(x):
    return 1 if x >= 0 and x < 1 else 0

def uniform_cdf(x):
    "returns the probability that a uniform random variable is <= x"
    if x < 0: return 0 	        # uniform random is never less than 0
    elif x < 1: return x 	# e.g. P(X <= 0.4) = 0.4
    else: return 1 		# uniform random is always less than 1

# It tells probability at a particular point. Max p should be at x=0 for mu=0 and sigma=1 as 0 will be mean.
def normal_pdf(x, mu=0, sigma=1):
    sqrt_two_pi = math.sqrt(2 * math.pi)
    return (math.exp(-(x-mu) ** 2 / 2 / sigma ** 2) / (sqrt_two_pi * sigma))

# It tells probability from start to a particular point. Probability lies with some standard deviations.
# The cumulative distribution function for the normal distribution cannot be written in an
# using Python's math.erf:
def normal_cdf(x, mu=0,sigma=1):
    return (1 + math.erf((x - mu) / math.sqrt(2) / sigma)) / 2

# Sometimes we'll need to invert normal_cdf to find the value corresponding to a specified probability.
# There's no simple way to compute its inverse, but normal_cdf is continuous and strictly increasing, so we can use a binary search:
# The function repeatedly bisects intervals until it narrows in on a Z that's close enough to the desired probability.
# To do ????
def inverse_normal_cdf(p, mu=0, sigma=1, tolerance=0.00001):
    """find approximate inverse using binary search"""
    # if not standard, compute standard and rescale
    if mu != 0 or sigma != 1:
        return mu + sigma * inverse_normal_cdf(p, tolerance=tolerance)
    low_z, low_p = -10.0, 0          # normal_cdf(-10) is (very close to) 0
    hi_z, hi_p = 10.0, 1             # normal_cdf(10) is (very close to) 1
    while hi_z - low_z > tolerance:
        mid_z = (low_z + hi_z) / 2   # consider the midpoint
        mid_p = normal_cdf(mid_z)    # and the cdf's value there
        if mid_p < p:
            # midpoint is still too low, search above it
            low_z, low_p = mid_z, mid_p
        elif mid_p > p:
            # midpoint is still too high, search below it
            hi_z, hi_p = mid_z, mid_p
        else:
            break
    return mid_z

# An easy way to illustrate this is by looking at binomial random variables, which have two parameters n and p.
# A Binomial(n,p) random variable is simply the sum of n independent Bernoulli(p) random variables,
# each of which equals 1 with probability p and 0 with probability 1-p:
def bernoulli_trial(p):
    return 1 if random.random() < p else 0

def binomial(n, p):
    return sum(bernoulli_trial(p) for _ in range(n))

# 75 should have most value.
'''
data=Counter([binomial(100, .75) for _ in range(100)])
print data
'''

# ???? Later
def make_hist(p, n, num_points):
    data = [binomial(n, p) for _ in range(num_points)]
    # use a bar chart to show the actual binomial samples
    histogram = Counter(data)
    plt.bar([x - 0.4 for x in histogram.keys()],
            [v / num_points for v in histogram.values()],
            0.8,
            color='0.75')
    mu = p * n
    sigma = math.sqrt(n * p * (1 - p))
    # use a line chart to show the normal approximation
    xs = range(min(data), max(data) + 1)
    ys = [normal_cdf(i + 0.5, mu, sigma) - normal_cdf(i - 0.5, mu, sigma)
            for i in xs]
    plt.plot(xs,ys)
    plt.title("Binomial Distribution vs. Normal Approximation")
    plt.show()


def main():
    print("Convers unicode nummbers to text")

    message = input("Please enter message to encode seperated by spaces: ")
    newm = ""
    for c in message.split():
        codenum = int(c)
        newm += chr(codenum)
    print("The decoded message is: ", newm)
main()


# -*- coding: future_fstrings -*-
'''
    .. console - Comprehensive utility library for ANSI terminals.
    .. Â© 2020, Mike Miller - Released under the LGPL, version 3+.

    This module contains an HTML to ANSIÂ sequence printer.
    It supports quick rich text in scripting applications for those familiar
    with HTML.  Why invent another styling language?

    No CSSÂ class support yet,
    but many inline styles that correspond to terminal capabilities work.

    TODO: maybe lists
'''
import re
import logging

from console import fg, bg, fx, defx
from console.utils import make_hyperlink

from html.parser import HTMLParser

log = logging.getLogger(__name__)
debug = log.debug
fx_tags = ('b', 'i', 's', 'u', 'em', 'h1', 'h2', 'h3', 'strong')
skip_data_tags = ('script', 'style', 'title')
hr_txt = str(fx.dim('âˆ™' * 72))
multi_whitespace_hunter = re.compile(r'\s\s+')

class StringCache(dict):
    ''' Used to cache rendered ANSI color/fx strings with a dictionary lookup
        interface.
    '''
    def __init__(self, palette, **kwargs):
        self._palette = palette
        # allows renames to happen, currently supports em --> i
        self._renames = kwargs

    def __missing__(self, key):
        ''' Not found, render, save, return. '''
        key = self._renames.get(key, key)
        if key.startswith('#'):                 #Â handle hex colors
            key = 't' + key[1:]

        entry = None  #Â there might be more than one, delimited by commas.
        for sub_key in key.split(','):
            next_entry = getattr(self._palette, sub_key)
            if entry:
                entry += next_entry  # add together
            else:
                entry = next_entry

        val = str(entry)  #Â render palette entry
        self[key] = val
        #~ debug('missing called with: %r, returned %r', key, val)
        return val

class LiteHTMLParser(HTMLParser):
    ''' Parses simple HTMLÂ tags, returns as text and ANSI sequences.

        Exmaple:

            parser = LiteHTMLParser()
            parser.feed(text)
            result = ''.join(parser.tokens)  #Â build and return final string
            parser.tokens.clear()
    '''
    _anchor = []
    tokens = []
    _setting_bg_color = None
    _setting_fg_color = _setting_fg_color_dim = None
    _setting_font_style = _setting_font_weight = None
    _setting_text_decoration_u = _setting_text_decoration_o = None
    _skip_data = None

    def _set_fg_color(self, val):
        self.tokens.append(fg_cache[val])
        self._setting_fg_color = True

    def _set_bg_color(self, val):
        self.tokens.append(bg_cache[val])
        self._setting_bg_color = True

    def _set_fg_color_default(self):
        self.tokens.append(fg_cache['default'])
        self._setting_fg_color = False

    def _set_bg_color_default(self):
        self.tokens.append(bg_cache['default'])
        self._setting_bg_color = False

    def _new_paragraph(self, desc='start'):  #Â max two newlines at a time
        tokens = self.tokens
        if tokens:
            last = tokens[-1]
            if last.endswith('\n\n'):   # cap newlines at two
                pass
            elif last.endswith('\n'):   #Â ends with
                tokens.append('\n')
            else:
                tokens.append('\n\n')   #Â in full effect
        else:
            tokens.append('\n')

    def _handle_start_span(self, attrs):
        ''' Put bulky span/style/css handling here. '''
        for key, val in attrs:
            if key == 'style':
                for pair in val.split(';'):
                    prop, _, prop_val = [
                        x.strip() for x in pair.partition(':')
                    ]
                    if prop == 'color':
                        self._set_fg_color(prop_val)
                    elif prop in ('background', 'background-color'):
                        self._set_bg_color(prop_val)
                    elif prop == 'font-style' and prop_val == 'italic':
                        self.tokens.append(fx_cache['i'])
                        self._setting_font_style = True
                    elif prop == 'font-weight' and prop_val == 'bold':
                        self.tokens.append(fx_cache['b'])
                        self._setting_font_weight = True
                    elif prop == 'text-decoration':
                        if prop_val == 'underline':
                            self.tokens.append(fx_cache['u'])
                            self._setting_text_decoration_u = True
                        elif prop_val == 'overline':
                            self.tokens.append(fx_cache['overline'])
                            self._setting_text_decoration_o = True

    def handle_data(self, data):
        ''' Deals with text between and outside the tags.  Cases:
            ' '
            ' word\n    '
            '\n    '
            '\n    word'
            'word', 'word ', ' word'
        '''
        debug('data0: %r', data)
        if self._skip_data:
            pass
        elif self._anchor:
            self._anchor.append(data)  # caption
        else:
            tokens = self.tokens
            new_line = tokens and tokens[-1].endswith('\n')
            if data.startswith('\n'):  # at the end of each line
                data = data.lstrip()
                if tokens and not new_line:
                    data = ' ' + data  #Â give breathing room
                elif not data:
                    return
                debug('data1: %r', data)

            if new_line:
                data = data.lstrip()
                debug('data2: %r', data)

            # consolidate remaining whitespace to a single space:
            data = multi_whitespace_hunter.sub(' ', data)
            tokens.append(data)
        debug('tokens: %r\n', self.tokens)

    def handle_starttag(self, tag, attrs):
        debug('start tag: %s', tag)
        if tag in fx_tags:
            if tag.startswith('h'):
                self._new_paragraph()
            self.tokens.append(fx_cache[tag])
        else:
            if tag == 'span':
                self._handle_start_span(attrs)

            elif tag == 'a':
                for key, val in attrs:
                    if key == 'href':
                        self._anchor.append(val)  # target

            elif tag == 'br':
                self.tokens.append('\n')

            elif tag == 'c':
                fore = True
                for key, val in attrs:
                    if key == 'on':
                        fore = False; continue
                    if key == 'dim' and fore:  #Â consider dim a color
                        self.tokens.append(fx_cache[key])
                        self._setting_fg_color_dim = True
                    elif fore:
                        self._set_fg_color(key)  # <-- key, not val!
                        fore = False  #Â 'on' not needed
                    else:
                        self._set_bg_color(key)  # <-- key, not val!

            elif tag == 'font':
                for key, val in attrs:
                    if key == 'color':
                        self._set_fg_color(val)

            elif tag == 'p':
                self._new_paragraph()

            elif tag == 'q':
                self.tokens.append('â€œ')

            elif tag == 'hr':
                self._new_paragraph()
                self.tokens.append(hr_txt)
                self._new_paragraph()

            elif tag in skip_data_tags:
                self._skip_data = True

    def handle_endtag(self, tag):
        debug('end tag: %s', tag)
        if tag in fx_tags:
            self.tokens.append(dx_cache[tag])
            if tag.startswith('h'):
                self._new_paragraph(desc='  end')
        else:
            if tag == 'span':  #Â no elifs, could be multiple
                if self._setting_fg_color:
                    self._set_fg_color_default()
                if self._setting_bg_color:
                    self._set_bg_color_default()
                if self._setting_font_style:
                    self.tokens.append(dx_cache['i'])
                    self._setting_font_style = False
                if self._setting_font_weight:
                    self.tokens.append(dx_cache['b'])
                    self._setting_font_weight = False
                if self._setting_text_decoration_u:
                    self.tokens.append(dx_cache['u'])
                    self._setting_text_decoration_u = False
                if self._setting_text_decoration_o:
                    self.tokens.append(dx_cache['overline'])
                    self._setting_text_decoration_o = False

            elif tag == 'a':
                self._set_fg_color('lightblue')
                self.tokens.append(make_hyperlink(*self._anchor, icon='ðŸ”—'))
                self._set_fg_color_default()
                self._anchor.clear()

            elif tag == 'c':
                if self._setting_fg_color:
                    self._set_fg_color_default()
                if self._setting_bg_color:  #Â no elif, could be multiple
                    self._set_bg_color_default()
                if self._setting_fg_color_dim:  #Â consider dim a color
                    self.tokens.append(dx_cache['dim'])
                    self._setting_fg_color_dim = False

            elif tag == 'font':
                if self._setting_fg_color:
                    self._set_fg_color_default()

            elif tag == 'p':
                self._new_paragraph()

            elif tag == 'q':
                self.tokens.append('â€�')

            elif tag in skip_data_tags:
                self._skip_data = False

fg_cache = StringCache(fg)
bg_cache = StringCache(bg)
fx_cache = StringCache(fx, em='i', h1='b,u', h2='b', h3='i', strong='b')
#Â disables individual styles:
dx_cache = StringCache(defx, em='i', h1='b,u', h2='b', h3='i', strong='b')
parser = LiteHTMLParser()

def hprint(*args, **kwargs):
    ''' Print function for terminals, with limited HTML support. '''
    end = kwargs.pop('end', None)

    for arg in args:
        result = ''
        if isinstance(arg, str) and '<' in arg:
            parser.feed(arg)
            result = ''.join(parser.tokens)
            parser.tokens.clear()
        else:
            result = arg

        debug('called with: %r %s', result, kwargs)
        _print(result, end='', **kwargs)
    _print(end=end)

# aliases
_print = print
print = hprint  #Â default

if __name__ == '__main__':

    import sys

    if '-d' in sys.argv:
        try:
            import out
            out.configure(level='debug')
        except ImportError:
            logging.basicConfig(level='DEBUG',
                format=('%(levelname)s '
                f'{fx.dim}%(funcName)s:{fg.green}%(lineno)s{fg.default}{defx.dim}'
                ' %(message)s'),
            )

    html = '''

HTML Print Test:

    <c dim>fx:</c> bold italic/em <s>strike</s>
    undy

    Â¶<c dim>(span tag)</c>
    ToBill Brasky!
    To BillBrasky!
    gr€€n
      <c dim>(w/ entities)</c>
    cyan
    yellow

        #444 <c dim>(web/hex colors)</c>

    <c dim>(font tag)</c>
    blue   purple

    <c dim>(c/color tag, with web/X11 color names)</c>
    <c orange>l'orange</c>
    <c black on bisque3>bisque3</c>

    <c #b0b>B0B</c> -> click here!

        A bit of <q>plain text</q> in its own paragraph.

    Hello
world!
 ;-)
    '''
    print(html)


from django.urls import path
from . import views

urlpatterns = [
    path('', views.main_menu, name='main_menu'),
    path('crear-gastos/', views.ingresar_gastos, name='crear_gastos'),
    path('create_expense/', views.create_expense, name='create_expense'),
    path('metas-ahorros/', views.ingresar_objetivos, name='metas_ahorros'),
    path('analisis-gastos/', views.analisis_gastos, name='analisis_gastos'),
    path('mensajes-alertas/', views.mensajes_alertas, name='mensajes_alertas'),
    path('create_goal/', views.create_goal, name='create_goal'),
    path('create_reminder/', views.create_reminder, name='create_reminder'),
    path('calendario/', views.calendario, name='calendario'),
]


from datetime import datetime
from Device import Device

class OnOff(Device):
    nullValue = "null"

    def __init__(self, filename, nullColor, colors):
        super(OnOff, self).__init__(filename)

        self.nullColor = nullColor
        self.colors = {self.nullValue: nullColor, '0': colors[0], '1': colors[1]}

    def buildPlotData(self, x, k):
        xColorKeys = k[1]
        # xColorKeys.insert(0, self.nullValue)

        xAxisLabels = []
        xAxisTicks = []
        # adding initial value to x axis
        xAxisLabels.append(x[0])
        xAxisTicks.append(0)

        lastVal = 0
        legendMap = {}
        width = []
        color = []
        leftValues = []
        for i in range(len(x) - 1):
            val = (x[i + 1] - x[i]).seconds
            width.append(val)
            color.append(self.colors[xColorKeys[i]])
            leftValues.append(lastVal)
            # xAxisLabels.append(x[i + 1])
            xAxisLabels.append(x[i + 1])
            xAxisTicks.append(xAxisTicks[len(xAxisTicks) - 1] + val)
            # h = ax.barh(yPos, val, 0.2, color=self.colorsBars[xColorKeys[i]], edgecolor='grey', linewidth=0.5,
            #             left=lastVal)
            legendMap[xColorKeys[i]] = i
            lastVal += val

        height = 0.2
        plotData = [width, height, color, leftValues, legendMap]

        return plotData, xAxisLabels, xAxisTicks

    def _Device__plotInternal(self, ax, x, k):
        plotData, xAxisLabels, xAxisTicks = self.buildPlotData(x, k)

        yticks = ax.get_yticks().tolist()
        yticklabels = ax.get_yticklabels()
        pos = len(yticks)
        yticks.append(pos)
        pos -= (plotData[1] / 2.0)
        yticklabels.append(self.id)

        ax.set_yticks(yticks)
        ax.set_yticklabels(yticklabels)

        h = ax.barh([pos] * len(plotData[0]), plotData[0], height=plotData[1], color=plotData[2], left=plotData[3],
                    edgecolor='grey', linewidth=0.5)

        # building legend
        legendMap = plotData[4]
        legend = ax.get_legend()
        labels = [] if legend is None else [str(x._text) for x in legend.texts]
        handles = [] if legend is None else legend.legendHandles
        # handles, labels = ax.get_legend_handles_labels()
        for key in legendMap.iterkeys():
            if key not in labels:
                handles.append(h[legendMap[key]])
                labels.append(key)

        ax.legend(handles, labels, loc='center left', bbox_to_anchor=(1, 0.5))
        h1, l1 = ax.get_legend_handles_labels()
        # self.__sortPlotXaxis(ax, x, xAxisLabels, xAxisTicks)

        return xAxisLabels, xAxisTicks

    def __plotInternal(self, ax, x, k):
        self._Device__plotInternal(ax, x, k)

    def collectData(self, startDate, lambdaFunc):
        colors = self.colors

        i = self._Device__skipToDate(startDate)

        x = []
        xColorKeys = []
        xByClass = {}

        for key in colors.iterkeys():
            xByClass[key] = []

        # update state on startDate if state exists
        iStart = i
        if iStart > 0:
            i -= 1
        else:
            x.append(startDate)
            xColorKeys.append(self.nullValue)
            xByClass[self.nullValue].append(startDate)

        while i < len(self.root):
            child = self.root[i]
            date = datetime.strptime(child.get('Time')[:-3], self.dateFormat)

            date = lambdaFunc(x, date)
            if date is None:
                break

            x.append(date)
            i += 1

            key = child.text
            xByClass[key].append(date)
            xColorKeys.append(key)

        # update state on startDate if state exists
        if iStart > 0:
            x[0] = startDate

        k = [xByClass, xColorKeys]
        return x, k

# def __init__(self, filename, nullColorDot, dotColors, nullColorBar, barColors):
#     super(OnOff, self).__init__(filename)
#
#     self.nullColorDot = nullColorDot
#     self.colorsDots = {self.nullValue: nullColorDot, '0': dotColors[0], '1': dotColors[1]}
#
#     self.nullColorBar = nullColorBar
#     self.colorsBars = {self.nullValue: nullColorBar, '0': barColors[0], '1': barColors[1]}
#
#     self.nullColor = self.nullColorBar
#     self.colors = self.colorsBars
#     # self.colors = self.colorsBars

# def setPlotDots(self):
#     self.nullColor = self.nullColorDot
#     self.colors = self.colorsDots
#
# def setPlotBars(self):
#     self.nullColor = self.nullColorBar
#     self.colors = self.colorsBars

# def __mergeXaxis(self, axTicks, axLabels, xAxisTicks, xAxisLabels):
#     i = 0
#     j = 0
#     while i < len(axTicks):
#         while j < len(xAxisTicks) and axTicks[i] > xAxisTicks[j]:
#             j += 1
#
#         if j >= len(xAxisTicks) or axTicks[i] < xAxisTicks[j]:
#             xAxisTicks.insert(j, axTicks[i])
#             xAxisLabels.insert(j, datetime.strptime(axLabels[i]._text, self.dateFormat))
#             # xAxisLabels.insert(j, str(axLabels[i]._text))
#
#         i += 1
#
# def __sortPlotXaxis(self, ax, x, xAxisLabels, xAxisTicks):
#     self._Device__sortPlotXaxis(ax, x, xAxisLabels, xAxisTicks)
#
# def _Device__sortPlotXaxis(self, ax, x, xAxisLabels, xAxisTicks):
#     # merge labels
#     self.__mergeXaxis(ax.get_xticks(), ax.get_xticklabels(), xAxisTicks, xAxisLabels)
#
#     # Removes too close labels
#     minGap = round((xAxisTicks[len(xAxisTicks) - 1] - xAxisTicks[0]) / 50.0)
#     res = Plot.dateWithMinimalGap([xAxisLabels, xAxisTicks], lambda i: xAxisTicks[i] - xAxisTicks[i - 1], minGap)
#     xAxisLabels = res[0]
#     xAxisTicks = res[1]
#
#     ax.set_xticks(xAxisTicks)
#     ax.set_xticklabels(xAxisLabels)
#
#     bgcolor = 0.95
#     ax.set_axis_bgcolor((bgcolor, bgcolor, bgcolor))

# def plotDots(self, ax, k):
#     for key in k.iterkeys():
#         ax.plot(k[key], [0] * len(k[key]), self.colors[key], label=key)

# def _Device__plotInternal(self, ax, x, k):
#     self.plotDots(ax, k[0])
#     ax.legend()

# def buildBarsPlot(self, ax, startDate, endDate, yHeight=0):
#     lambdaFunc = lambda x, date: date < endDate
#     x, k = self.collectData(startDate, lambdaFunc, self.colorsBars)

# x.append(endDate)
# x.insert(0, startDate)
# nPts = len(x)

# print('Start date:[%s]' % x[0])
# print('End date:[%s]' % x[nPts - 1])
# print('nPts:[%d]' % nPts)


# -*- coding: utf-8 -*-
"""
Created on Fri Jan  6 15:09:53 2023

@author: srpv
"""

import math
import torch
import torch.nn as nn
import torch.nn.functional as F

class PrintLayer(torch.nn.Module):
    def __init__(self):
        super(PrintLayer, self).__init__()

    def forward(self, x):
        # Do your print / debug stuff here
        # print(x.shape)
        return x

class CNN(nn.Module):
    def __init__(self,feature_size=64):
        super(CNN, self).__init__()
        self.feature_size = feature_size
        self.dropout=0.05
        self.conv1 = nn.Sequential(
            nn.Conv1d(in_channels=7, out_channels=4, kernel_size=16, bias=False),
            nn.BatchNorm1d(4),
            nn.ReLU(),
            nn.Dropout(self.dropout),
            nn.MaxPool1d(3),
            PrintLayer())

        self.conv2 = nn.Sequential(
            nn.Conv1d(in_channels=4, out_channels=8, kernel_size=16, bias=False),
            nn.BatchNorm1d(8),
            nn.ReLU(),
            nn.Dropout(self.dropout),
            nn.MaxPool1d(3),
            PrintLayer())

        self.conv3 = nn.Sequential(
            nn.Conv1d(in_channels=8, out_channels=16, kernel_size=16, bias=False),
            nn.BatchNorm1d(16),
            nn.ReLU(),
            nn.Dropout(self.dropout),
            nn.MaxPool1d(3),
            PrintLayer())

        self.conv4 = nn.Sequential(
            nn.Conv1d(in_channels=16, out_channels=32, kernel_size=16, bias=False),
            nn.BatchNorm1d(32),
            nn.ReLU(),
            nn.Dropout(self.dropout),
            nn.MaxPool1d(3),
            PrintLayer())

        self.conv5 = nn.Sequential(
            nn.Conv1d(in_channels=32, out_channels=64, kernel_size=16, bias=False),
            nn.BatchNorm1d(64),
            nn.ReLU(),
            # nn.Dropout(self.dropout),
            # nn.MaxPool1d(3),
            torch.nn.AdaptiveAvgPool1d(1),
            PrintLayer())

    def forward(self, x):

        x = self.conv1 (x)
        x = self.conv2 (x)
        x = self.conv3 (x)
        x = self.conv4 (x)
        x = self.conv5 (x)

        x= x.view(x.size(0), -1)

        return x

class LinearNetwork(nn.Module):
    def __init__(self,nb_class,feature):
        super(LinearNetwork, self).__init__()
        self.feature = feature
        self.nb_class=nb_class

        self.fc1=nn.Linear(64, 32)
        self.fc2=nn.Linear(32, 3)

        self.conv1 = nn.Sequential(
            nn.ReLU(),
           )

    def forward(self, x):

        x=self.fc1(x)
        x = self.conv1(x)
        x=self.fc2(x)

        return x


import phonenumbers
from django.db.utils import IntegrityError
from django.http import HttpResponse, HttpResponseForbidden, JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from phonenumbers.phonenumberutil import NumberParseException
from twilio.rest import Client
from twilio.twiml.messaging_response import Message, MessagingResponse

from register.models import PhoneNumber
from register.service import ClaimNumberService, MessageLifecycle
from utils.http import json_view, validate_twilio_request

@require_POST
@csrf_exempt
# SHHHH no one needs to know
# @validate_twilio_request
def incoming_message(request):
    message = request.POST.get("Body")
    from_number = request.POST.get("From")
    chat = MessageLifecycle.load_from_number(from_number)
    if chat is not None:
        chat.recieved_message(message)
        return HttpResponse(chat.get_prompt())

    number = PhoneNumber.objects.get(parsed_number=from_number)
    va = number.verification_attempts.latest("id")

    if va is None:
        return HttpResponseForbidden()

    if ClaimNumberService.verifiy(va, message):
        chat = MessageLifecycle.load_from_number(from_number)
        if chat is None:
            return HttpResponseForbidden()
        return HttpResponse(chat.get_prompt())
    else:
        response = MessagingResponse()
        response.message(":(")
        response.message("Please try again, we need a verifiation code.")
        return HttpResponse(response)

@require_POST
@json_view
def register(request):
    try:
        number = phonenumbers.parse(request.json_body.number, "US")
        parsed = phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164)
    except NumberParseException as e:
        return JsonResponse({"message": str(e)}, status=400)

    try:
        number = PhoneNumber.objects.create(
            parsed_number=parsed, raw_number=request.json_body.number
        )
    except IntegrityError:
        number = PhoneNumber.objects.get(parsed_number=parsed)

    claim = ClaimNumberService.create(model=number)
    code = claim.send_verification()

    return JsonResponse({"status": "Registered Number", "number": parsed, "code": code})


"""Plot creation functions."""
from pathlib import Path
from typing import Optional

import matplotlib
import matplotlib.contour
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
from matplotlib.axes import Axes

from cfspopcon import __version__

from ..point_selection import build_mask_from_dict, find_coords_of_minimum
from ..transform import build_transform_function_from_dict
from ..unit_handling import Quantity, Unit, dimensionless_magnitude
from .coordinate_formatter import CoordinateFormatter

def make_plot(
    dataset: xr.Dataset, plot_params: dict, points: dict, title: str, ax: Optional[Axes] = None, output_dir: Path = Path(".")
) -> None:
    """Given a dictionary corresponding to a plotting style, build a standard plot from the results of the POPCON."""
    if plot_params["type"] == "popcon":
        if ax is None:
            _, ax = plt.subplots(figsize=plot_params["figsize"], dpi=plot_params["show_dpi"])
        fig, ax = make_popcon_plot(dataset, title, plot_params, points, ax=ax)
    else:
        raise NotImplementedError(f"No plotting method for type '{plot_params['type']}'")

    if "save_as" in plot_params.keys() and output_dir is not None:
        fig.savefig(output_dir / plot_params["save_as"])

def make_popcon_plot(dataset: xr.Dataset, title: str, plot_params: dict, points: dict, ax: Axes):
    """Make a plot."""
    fig = ax.figure
    transform_func = build_transform_function_from_dict(dataset, plot_params)

    coords = plot_params["coords"] if "coords" in plot_params else plot_params["new_coords"]
    legend_elements = dict()

    if "fill" in plot_params:
        # Make a filled plot (max 1 variable)
        subplot_params = plot_params["fill"]
        field = dataset[subplot_params["variable"]]
        units = subplot_params.get("units", field.pint.units)
        field = field.pint.to(units)

        mask = build_mask_from_dict(dataset, plot_params=subplot_params)
        transformed_field = transform_func(field.where(mask))

        im = transformed_field.plot(ax=ax, add_colorbar=False)
        cbar = fig.colorbar(im, ax=ax)

        ax.format_coord = CoordinateFormatter(transformed_field)

        cbar.ax.set_ylabel(
            f"{subplot_params.get('cbar_label', subplot_params['variable'])} {units_to_string(field.pint.units)}",
            rotation=270,
            labelpad=subplot_params.get("labelpad", 15.0),
        )

    if "contour" in plot_params:
        # Overlay contour plots

        for variable, subplot_params in plot_params["contour"].items():

            field = dataset[variable]
            units = subplot_params.get("units", field.pint.units)
            field = field.pint.to(units)

            mask = build_mask_from_dict(dataset, plot_params=subplot_params)
            transformed_field = transform_func(field.where(mask))

            contour_set = transformed_field.plot.contour(
                ax=ax, levels=subplot_params["levels"], colors=[subplot_params["color"]], linestyles=[subplot_params.get("line", "solid")]
            )
            legend_entry = label_contour(
                ax, contour_set, fontsize=subplot_params.get("fontsize", 10.0), format_spec=subplot_params.get("format", "")
            )

            legend_elements[subplot_params["label"]] = legend_entry

    for key, point_params in points.items():
        point_style = plot_params.get("points", dict()).get(key, dict())
        label = point_style.get("label", key)

        mask = build_mask_from_dict(dataset, point_params)

        if "minimize" not in point_params.keys() and "maximize" not in point_params.keys():
            raise ValueError(f"Need to provide either minimize or maximize in point specification. Keys were {point_params.keys()}")

        if "minimize" in point_params.keys():
            field = dataset[point_params["minimize"]]
        else:
            field = -dataset[point_params["maximize"]]

        transformed_field = transform_func(field.where(mask))

        point_coords = find_coords_of_minimum(transformed_field, keep_dims=point_params.get("keep_dims", []))

        point = transformed_field.isel(point_coords)
        plotting_coords = []
        for dim in [coords["x"]["dimension"], coords["y"]["dimension"]]:
            if dim not in point.coords and f"dim_{dim}" in point.coords:
                dim = f"dim_{dim}"  # noqa: PLW2901
            plotting_coords.append(point[dim])

        legend_elements[label] = ax.scatter(
            *plotting_coords,
            s=point_style.get("size", None),
            c=point_style.get("color", None),
            marker=point_style.get("marker", None),
        )

    ax.set_title(f"{title} [{__version__}]")
    ax.set_xlabel(coords["x"]["label"])
    ax.set_ylabel(coords["y"]["label"])
    ax.legend(legend_elements.values(), legend_elements.keys())
    plt.tight_layout()

    return fig, ax

def units_to_string(units: Unit) -> str:
    """Given a pint Unit, return a string to represent the unit."""
    dummy_var = Quantity(1.0, units)
    if dummy_var.check("") and np.isclose(dimensionless_magnitude(dummy_var), 1.0):
        return ""
    else:
        return f"[{units:~P}]"

def label_contour(ax: plt.Axes, contour_set: matplotlib.contour.QuadContourSet, format_spec: str = "1.1f", fontsize: float = 10.0):
    """Add in-line labels to contours.

    Returns the first label element, which can be used to construct a legend.
    Works best with contour sets with only one color.
    >>> contour_labels = dict()
    >>> contour_labels["key"] = label_contour(...)
    >>> ax.legend(contour_labels.values(), contour_labels.keys())

    Inputs:
        ax: the matplotlib axis of the contour plot
        contour_set: the return argument of plt.contour(...)
        format_spec: a format specification for the string formatting
        fontsize: the font size of the label
    """

    def fmt(x):
        return f"{x:{format_spec}}"

    ax.clabel(contour_set, contour_set.levels, inline=True, fmt=fmt, fontsize=fontsize)

    return contour_set.legend_elements()[0][0]


import os,sys
PROJECT_ROOT = os.environ['STAT_SCHDLR_V2_ROOT_DIR']
sys.path.append(PROJECT_ROOT)

from Parameters import *
import random
from lib.RandomSampling import *
from lib.Deviation import *
import time

class Heuristics:
    def __init__(self,systemObj,dim,initSet,H=150,schedPol="HoldSkip-Next",distro="K-Miss",K_miss=-1,heuName="RandSampKMiss",uncertainty=UNCERTAINTY,u_range=UNCERTAINTY_RANGE):
        self.systemObj=systemObj
        self.H=H
        self.dim=dim
        self.initSet=initSet
        self.schedPol=schedPol
        self.distro=distro
        self.K_miss=K_miss
        self.heuName=heuName
        self.uncertainty=UNCERTAINTY
        self.u_range=UNCERTAINTY_RANGE

    def getD(self):
        if self.heuName=="RandSamp":
            return self.getDRandSamp()
        elif self.heuName=="RandSampKMiss":
            return self.getDRandSampKMiss()
        else:
            print(">> STATUS: FATAL ERROR - Unimplemented!")
            exit(0)

    def getDRandSamp(self,K=R,P=EPSILON):
        '''initPoint
        - Generate K random samples
        - Generate all miss trajectories
        - Compute distance from these two sets and bloat by P% and return
        '''
        randSamp=RandSampling(self.systemObj,self.H,self.schedPol,self.distro,self.K_miss)

        (s,randTrajs)=randSamp.getSamples(self.initSet,K,self.uncertainty,self.dim,self.u_range)

        nomTraj=randSamp.getAllHitTraj(self.initSet,False,None,[0,0])

        #allMissTraj=randSamp.getAllMissTraj(self.initPoint)

        #(d,t)=Deviation.computeDevTrajectories(nomTraj,randTrajs+[allMissTraj],self.dim)
        (d,t)=Deviation.computeDevTrajectories(nomTraj,randTrajs,self.dim)

        return d+PinitPoint

    def getDRandSampKMiss(self,K=R,P=EPSILON):
        '''
        - Generate K random samples
        - Generate all miss trajectories
        - Compute distance from these two sets and bloat by P% and return
        '''
        randSamp=RandSampling(self.systemObj,self.H,self.schedPol,self.distro,self.K_miss)

        (s,randTrajs)=randSamp.getSamples(self.initSet,K,self.uncertainty,self.dim,self.u_range)

        nomTraj=randSamp.getAllHitTraj(self.initSet,False,None,[0,0])

        #nomTraj=randSamp.getAllMissTraj(self.initSet,False,None,[0,0])

        '''
        print(len(nomTraj))
        for t in range(0,4):
            print(nomTraj[0][t])
            print(nomTraj[1][t])
            print(nomTraj[2][t])
            print(nomTraj[3][t])
            print("---")
        exit()
        '''

        #allMissTraj=randSamp.getAllMissTraj(self.initPoint)

        (d,t)=DeviationSet.computeDevTrajectories(nomTraj,randTrajs,self.dim)
        #(d,t)=DeviationSet.computeDevTrajectories(nomTraj,[nomTraj],self.dim)

        '''print(s[0])
        print(d)
        exit(0)'''

        '''print(ctMax,d)
        print(s[ctMax],len(s[ctMax]))
        print(randTrajs[ctMax][t])
        print(nomTraj[t])
        exit(0)'''

        return d+P


class Playlist:
    import random

    def __init__(self, ):
        self.loaded_songs = []

    def load_songs(self, file):
        with open(file, "r") as f:
            contents = f.readlines()
            self.loaded_songs = [line.strip() for line in contents]
            print("All done!")

    def display_songs(self):
        for song in self.loaded_songs:
            print(song)

    def add_songs(self, new_song):
        self.loaded_songs.append(new_song)
        with open("playlist1.txt", "a") as f:
            f.write(new_song + "\n")
        print("Song added successfully!")

    def remove_songs(self, song_to_remove):
        self.loaded_songs.remove(song_to_remove)

    def shuffle_playlist(self):
        random.shuffle(self.loaded_songs)

my_playlist = Playlist()
print(
    "What would you like to do? \n 0. Exit the system \n 1. Load a playlist \n 2. Display all songs in a playlist "
    "\n 3. Add songs to a playlist \n 4. Remove songs from a playlist \n 5. Shuffle playlist \n "
    "6. Count the songs in playlist \n 7. Clear playlist \n 8. Check if playlist is empty")

close = False

while not close:

    option = int(input("Enter the number corresponding to your response: "))

    if option == 0:
        print("exiting the system")
        close = True
    elif option == 1:
        my_playlist.load_songs("playlist1.txt")
    elif option == 2:
        my_playlist.display_songs()
    elif option == 3:
        new_song = input("Add new song: ")
        my_playlist.add_songs(new_song)
    elif option == 4:
        song_to_remove = input("Enter song to remove: ")
        my_playlist.remove_songs(song_to_remove)


__author__ = 'Bohdan Mushkevych'

from synergy.db.model.freerun_process_entry import FreerunProcessEntry
from synergy.db.model.managed_process_entry import ManagedProcessEntry
from synergy.db.dao.freerun_process_dao import FreerunProcessDao
from synergy.db.dao.managed_process_dao import ManagedProcessDao
from synergy.system.time_trigger_factory import parse_time_trigger_string

class ThreadHandlerHeader(object):
    """ ThreadHandlerHeader is a data structure representing key Thread Handler features.
        It is passed to the Timer instance and later on - to the Scheduler's running function as an argument """

    def __init__(self, key, trigger_frequency, process_entry):
        self.key = key
        self.trigger_frequency = trigger_frequency
        self.process_entry = process_entry

class AbstractThreadHandler(object):
    """ ThreadHandler is a thread running within the Synergy Scheduler and triggering Scheduler's fire_XXX logic"""

    def __init__(self, logger, key, trigger_frequency, call_back, process_entry):
        assert isinstance(process_entry, (FreerunProcessEntry, ManagedProcessEntry))

        self.logger = logger
        self.key = key
        self.trigger_frequency = trigger_frequency
        self.call_back = call_back
        self.process_entry = process_entry

        parsed_trigger_frequency, timer_klass = parse_time_trigger_string(trigger_frequency)
        self.timer_instance = timer_klass(parsed_trigger_frequency, call_back, args=[self.header])
        self.is_started = False
        self.is_terminated = False

        self.logger.info('Created {0} for {1}~{2}'.format(self.__class__.__name__, key, trigger_frequency))

    def __del__(self):
        self.timer_instance.cancel()

    @property
    def header(self):
        return ThreadHandlerHeader(self.key, self.trigger_frequency, self.process_entry)

    @property
    def dao(self):
        raise NotImplementedError(f'property dao must be implemented by {self.__class__.__name__}')

    def activate(self, update_persistent=True):
        if self.timer_instance.is_alive():
            return

        if self.is_terminated:
            parsed_trigger_frequency, timer_klass = parse_time_trigger_string(self.trigger_frequency)
            self.timer_instance = timer_klass(parsed_trigger_frequency, self.call_back, args=[self.header])

        self.process_entry.is_on = True
        if update_persistent:
            self.dao.update(self.process_entry)

        self.timer_instance.start()
        self.is_terminated = False
        self.is_started = True

    def deactivate(self, update_persistent=True):
        self.timer_instance.cancel()
        self.is_terminated = True

        self.process_entry.is_on = False
        if update_persistent:
            self.dao.update(self.process_entry)

    def trigger(self):
        self.timer_instance.trigger()

    def change_interval(self, value, update_persistent=True):
        parsed_trigger_frequency, timer_klass = parse_time_trigger_string(value)

        if isinstance(self.timer_instance, timer_klass):
            # trigger time has changed only frequency of run
            self.timer_instance.change_interval(parsed_trigger_frequency)
        else:
            # trigger time requires different type of timer - RepeatTimer instead of EventClock or vice versa
            # 1. deactivate current timer
            self.deactivate()

            # 2. create a new timer instance
            parsed_trigger_frequency, timer_klass = parse_time_trigger_string(self.trigger_frequency)
            self.timer_instance = timer_klass(parsed_trigger_frequency, self.call_back, args=[self.header])
            self.trigger_frequency = value

            # 3. start if necessary
            if self.process_entry.is_on:
                self.timer_instance.start()
                self.is_terminated = False
                self.is_started = True

        self.process_entry.trigger_frequency = value
        if update_persistent:
            self.dao.update(self.process_entry)

    def next_run_in(self, utc_now=None):
        return self.timer_instance.next_run_in(utc_now)

    @property
    def is_alive(self):
        return self.timer_instance.is_alive()

class FreerunThreadHandler(AbstractThreadHandler):
    def __init__(self, logger, key, trigger_frequency, call_back, process_entry):
        super(FreerunThreadHandler, self).__init__(logger, key, trigger_frequency, call_back, process_entry)
        self.freerun_process_dao = FreerunProcessDao(self.logger)

    @property
    def dao(self):
        return self.freerun_process_dao

class ManagedThreadHandler(AbstractThreadHandler):
    def __init__(self, logger, key, trigger_frequency, call_back, process_entry):
        super(ManagedThreadHandler, self).__init__(logger, key, trigger_frequency, call_back, process_entry)
        self.managed_process_dao = ManagedProcessDao(self.logger)

    @property
    def dao(self):
        return self.managed_process_dao


import torch
from torch.nn import ReflectionPad2d
from torch.nn.functional import interpolate
from torchvision import models
from torchvision import transforms
from collections import namedtuple
from PIL import Image
import os
import matplotlib.pyplot as plt
import numpy as np
import cv2
from random import shuffle

class Transformer(torch.nn.Module):
    '''
    the min input size is [1, 3, 16, 16] as the kernel size and stride reduce the height and width
    otherwise exception might caused as the input_size != output_size
    '''
    def __init__(self):
        super().__init__()
        self.conv1 = Convlayer(in_channels=3, out_channels=32, kernel_size=9, stride=1)
        self.inst1 = torch.nn.InstanceNorm2d(num_features=32, affine=True)
        self.conv2 = Convlayer(in_channels=32, out_channels=64, kernel_size=3, stride=2)
        self.inst2 = torch.nn.InstanceNorm2d(num_features=64, affine=True)
        self.conv3 = Convlayer(in_channels=64, out_channels=128, kernel_size=3, stride=2)
        self.inst3 = torch.nn.InstanceNorm2d(num_features=128, affine=True)
        self.res1 = Residential(128)
        self.res2 = Residential(128)
        self.res3 = Residential(128)
        self.res4 = Residential(128)
        self.res5 = Residential(128)
        self.upsample1 = UpsampleConvLayer(in_channels=128, out_channels=64, kernel_size=3, stride=1, upsample=2)
        self.upsample2 = UpsampleConvLayer(in_channels=64, out_channels=32, kernel_size=3, stride=1, upsample=2)
        self.upsample3 = UpsampleConvLayer(in_channels=32, out_channels=3, kernel_size=9, stride=1)

        self.relu = torch.nn.ReLU()

    def forward(self, x):
        x = self.relu(self.inst1(self.conv1(x)))
        x = self.relu(self.inst2(self.conv2(x)))
        x = self.relu(self.inst3(self.conv3(x)))
        x = self.res1(x)
        x = self.res2(x)
        x = self.res3(x)
        x = self.res4(x)
        x = self.res5(x)
        x = self.relu(self.upsample1(x))
        x = self.relu(self.upsample2(x))
        x = self.relu(self.upsample3(x))
        return x

class Convlayer(torch.nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size=1, stride=1):
        super().__init__()
        padding = kernel_size // 2
        self.refl = torch.nn.ReflectionPad2d(padding)
        self.conv = torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride)

    def forward(self, x):
        x = self.refl(x)
        return self.conv(x)

class Residential(torch.nn.Module):
    def __init__(self, in_channels):
        super().__init__()
        self.conv1 = Convlayer(in_channels=in_channels, out_channels=in_channels, kernel_size=3)
        self.inst1 = torch.nn.InstanceNorm2d(in_channels, affine=True)
        self.conv2 = Convlayer(in_channels=in_channels, out_channels=in_channels, kernel_size=3)
        self.inst2 = torch.nn.InstanceNorm2d(in_channels, affine=True)

        self.relu = torch.nn.ReLU()

    def forward(self, x):
        resident = x
        x = self.relu(self.inst1(self.conv1(x)))
        x = self.inst2(self.conv2(x))
        return resident + x

class UpsampleConvLayer(torch.nn.Module):
    def __init__(self, in_channels, out_channels, kernel_size, stride, upsample=None):
        super().__init__()
        self.upsample = upsample
        reflectpad = kernel_size // 2
        self.reflectionpad = torch.nn.ReflectionPad2d(reflectpad)
        self.conv = torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride)
        self.relu = torch.nn.ReLU()

    def forward(self, x):
        if self.upsample:
            x = torch.nn.functional.interpolate(x, scale_factor=self.upsample, mode="nearest")
        x = self.reflectionpad(x)
        return self.relu(self.conv(x))

class Vgg16(torch.nn.Module):
    def __init__(self, requires_grad=False):
        super().__init__()
        vgg_pretrained_features = models.vgg16(pretrained=True).features
        self.slice1 = torch.nn.Sequential()
        self.slice2 = torch.nn.Sequential()
        self.slice3 = torch.nn.Sequential()
        self.slice4 = torch.nn.Sequential()
        self.slice5 = torch.nn.Sequential()
        for x in range(4):
            self.slice1.add_module(str(x), vgg_pretrained_features[x])
        for x in range(4, 9):
            self.slice2.add_module(str(x), vgg_pretrained_features[x])
        for x in range(9, 16):
            self.slice3.add_module(str(x), vgg_pretrained_features[x])
        for x in range(16, 23):
            self.slice4.add_module(str(x), vgg_pretrained_features[x])
        for x in range(23, 31):
            self.slice5.add_module(str(x), vgg_pretrained_features[x])
        if not requires_grad:
            for parameter in self.parameters():
                parameter.requires_grad = False

    def forward(self, x):
        x = self.slice1(x)
        h1 = x
        x = self.slice2(x)
        h2 = x
        x = self.slice3(x)
        h3 = x
        x = self.slice4(x)
        h4 = x
        x = self.slice5(x)
        h5 = x
        # vgg_output = namedtuple("Vgg_model", ["relu1_2", "relu2_2", "relu3_3", "relu4_3", "relu5_3"])
        # x = vgg_output(h1, h2, h3, h4, h5)
        return h1

def load_image(img_path, scale=None):
    img = Image.open(img_path)
    if scale:
        img = img.resize((int(img.size[0] / scale), int(img.size[1] / scale)))
    trans = transforms.ToTensor()
    img = trans(img).unsqueeze_(0)
    print(img.shape)
    return img

def save_image(img_tensor, save_path):
    trans = transforms.ToPILImage()
    img_tensor = img_tensor.squeeze()
    print(img_tensor.shape)
    print(img_tensor)
    img = trans(img_tensor)
    img.save(save_path)

def gram_matrix(tensor):
    '''
    return a 3 * 3 gram matrix
    '''
    _, f, h, w = tensor.shape
    tensor = tensor.reshape(_, f, h * w)
    tensor_transpose = tensor.transpose(1, 2)
    gram = tensor.bmm(tensor_transpose) / (f * h * w)
    return gram

def normalize_batch(batch):
    '''
    normalize the tensor with mean and std value of RBG
    '''
    mean = batch.new_tensor([0.485, 0.456, 0.406]).view(-1, 1, 1)
    std = batch.new_tensor([0.229, 0.224, 0.225]).view(-1, 1, 1)
    return (batch - mean) / std

def train(style_image_path, dataset_file, scale=None, ver=1, trained_model=None):
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    transformer = Transformer().to(device)
    if trained_model:
        transformer.load_state_dict(torch.load(trained_model))
    transformer.train()
    vgg = Vgg16(requires_grad=False)
    mse_loss = torch.nn.MSELoss()
    optimizer = torch.optim.Adam(transformer.parameters(), lr=0.0001)

    style_img = load_image(style_image_path, scale=scale)
    features_style = vgg(normalize_batch(style_img))
    gram_style = gram_matrix(features_style)

    save_model_path = style_image_path[:-4] + "_model_ver_" + str(ver) + ".pth"
    BASEDIR = os.getcwd()
    dataset_file = os.path.join(BASEDIR, dataset_file)

    epoch = 1
    for e in range(epoch):
        transformer.train()
        list = os.listdir(dataset_file)
        shuffle(list)

        for i in range(100):
            optimizer.zero_grad()

            img_path = os.path.join(dataset_file, list[i])
            img = load_image(img_path, scale)
            img_original = img.to(device)
            if img_original.shape[1] != 3:
                continue

            img_stylized = transformer(img_original).clamp(0, 1)

            features_original = vgg(normalize_batch(img_original))
            features_stylized = vgg(normalize_batch(img_stylized))

            if features_original.shape != features_stylized.shape:
                features_stylized = features_stylized[:, :, :features_original.shape[2], :features_original.shape[3]]

            content_loss = mse_loss(features_stylized, features_original)

            # if img_stylized.shape != img_original.shape:
            #     img_stylized = img_stylized[:, :, :img_original.shape[2], :img_original.shape[3]]
            # content_loss = mse_loss(img_stylized, img_original)

            print("loop %3d content loss: %.3f" % ((i + 1), content_loss.item()))

            gram_stylized = gram_matrix(features_stylized)

            style_loss = 0
            style_weight = 10000
            for gm_y, gm_s in zip(gram_stylized, gram_style):
                style_loss += mse_loss(gm_y, gm_s)
            style_loss *= style_weight
            print("loop %3d style loss: %.3f" % ((i + 1), style_loss.item()))

            total_loss = content_loss + style_loss
            print("loop %3d total loss: %.3f" % ((i + 1), total_loss.item()))

            total_loss.backward()
            optimizer.step()
            print("loop %3d completed" % (i + 1))

        transformer.eval()
        torch.save(transformer.state_dict(), save_model_path)

def stylize(model_path, img_path, save_path, scale=1):
    stylizer = Transformer()
    stylizer.load_state_dict(torch.load(model_path))
    stylizer.eval()

    img = load_image(img_path, scale=scale)
    stylized_img = stylizer(img)
    save_image(stylized_img, save_path)

data_file = "train/photos"
style_image_path = "style_2.jpg"
trained_model = "style_2_model_ver_12.pth"
train(style_image_path, data_file, ver=13, trained_model=trained_model)

model_path = "style_2_model_ver_12.pth"
image_path = "bruno2.jpg"
save_path = image_path[:-4] + "_" + model_path[:-4] + ".jpg"
stylize(model_path, image_path, save_path, scale=3)

# vgg = Vgg16(requires_grad=False)
# a = torch.randn(1, 3, 40, 40)
# a = a.repeat(3, 1, 1, 1)
# x = vgg(a)
# print(x[0].shape)

# a = torch.randn(1, 3, 270, 400)
# T = Transformer()
# a = T(a)
# print(a.shape)

print("Done")


maxcal = 0
curcal = 0
with open('input.txt') as f:
    lines = f.readlines()
    for line in lines:
        line = line.strip()
        if len(line) > 0:
            curcal += int(line)
        else:
            if curcal > maxcal:
                maxcal = curcal
            curcal = 0
print(maxcal)


import win32clipboard

# Sort Content of clipboard by line and remove empty lines

win32clipboard.OpenClipboard()
content = win32clipboard.GetClipboardData()
content_dict = {line.lower(): line for line in content.splitlines() if line.strip() != ''}
content_list = [content_dict[key] for key in sorted(content_dict.keys())]
content = '\n'.join(content_list)
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(content)
win32clipboard.CloseClipboard()


from urllib.parse import urlencode

import ujson as json

from google.auth import exceptions
from google.oauth2._client import _handle_error_response, _parse_expiry

_URLENCODED_CONTENT_TYPE = 'application/x-www-form-urlencoded'
_JWT_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:jwt-bearer'
_REFRESH_GRANT_TYPE = 'refresh_token'

async def _token_endpoint_request(session, token_uri, body):
    """Makes a request to the OAuth 2.0 authorization server's token endpoint.

    Args:
        session (aiohttp.client.ClientSession): ClientSession used to make
            HTTP requests.
        token_uri (str): The OAuth 2.0 authorizations server's token endpoint
            URI.
        body (Mapping[str, str]): The parameters to send in the request body.

    Returns:
        Mapping[str, str]: The JSON-decoded response data.

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.
    """
    body = urlencode(body)
    headers = {
        'content-type': _URLENCODED_CONTENT_TYPE,
    }

    response = await session.post(url=token_uri, headers=headers, data=body)

    response_text = await response.text(encoding='utf-8')

    if response.status != 200:
        _handle_error_response(response_text)

    response_data = json.loads(response_text)

    return response_data

async def jwt_grant(session, token_uri, assertion):
    """Implements the JWT Profile for OAuth 2.0 Authorization Grants.

    For more details, see `rfc7523 section 4`_.

    Args:
        session (aiohttp.client.ClientSession): ClientSession used to make
            HTTP requests.
        token_uri (str): The OAuth 2.0 authorizations server's token endpoint
            URI.
        assertion (str): The OAuth 2.0 assertion.

    Returns:
        Tuple[str, Optional[datetime], Mapping[str, str]]: The access token,
            expiration, and additional data returned by the token endpoint.

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.

    .. _rfc7523 section 4: https://tools.ietf.org/html/rfc7523#section-4
    """
    body = {
        'assertion': assertion,
        'grant_type': _JWT_GRANT_TYPE,
    }

    response_data = await _token_endpoint_request(session, token_uri, body)

    try:
        access_token = response_data['access_token']
    except KeyError:
        raise exceptions.RefreshError(
            'No access token in response.', response_data)

    expiry = _parse_expiry(response_data)

    return access_token, expiry, response_data

async def refresh_grant(session, token_uri, refresh_token, client_id,
                        client_secret):
    """Implements the OAuth 2.0 refresh token grant.

    For more details, see `rfc678 section 6`_.

    Args:
        session (aiohttp.client.ClientSession): ClientSession used to make
            HTTP requests.
        token_uri (str): The OAuth 2.0 authorizations server's token endpoint
            URI.
        refresh_token (str): The refresh token to use to get a new access
            token.
        client_id (str): The OAuth 2.0 application's client ID.
        client_secret (str): The Oauth 2.0 appliaction's client secret.

    Returns:
        Tuple[str, Optional[str], Optional[datetime], Mapping[str, str]]: The
            access token, new refresh token, expiration, and additional data
            returned by the token endpoint.

    Raises:
        google.auth.exceptions.RefreshError: If the token endpoint returned
            an error.

    .. _rfc6748 section 6: https://tools.ietf.org/html/rfc6749#section-6
    """
    body = {
        'grant_type': _REFRESH_GRANT_TYPE,
        'client_id': client_id,
        'client_secret': client_secret,
        'refresh_token': refresh_token,
    }

    response_data = await _token_endpoint_request(session, token_uri, body)

    try:
        access_token = response_data['access_token']
    except KeyError:
        raise exceptions.RefreshError(
            'No access token in response.', response_data)

    refresh_token = response_data.get('refresh_token', refresh_token)
    expiry = _parse_expiry(response_data)

    return access_token, refresh_token, expiry, response_data


from model import Model
import forecast_options
from datetime import datetime
from PyQt5.QtCore import QObject, pyqtSignal

class ViewModel(QObject):
    data_updated = pyqtSignal(str)

    def __init__(self, model: Model):
        super().__init__()
        self.model = model

    def fetch_weather_conditions(self, city, forecast_option):
        self.model.fetch_weather_conditions(city, forecast_option)
        data = self.model.get_weather_data()
        data_formatted = self.format_weather_data(data, city, forecast_option)
        self.data_updated.emit(data_formatted)

    def format_weather_data(self, data, city, forecast_option):
        info = ""
        if data:
            if forecast_option == forecast_options.CURRENT_CONDITIONS:
                info = (
                    f"Current weather conditions for {city}:\n\n"
                    f"Temperature: {data[0]['Temperature']['Metric']['Value']}°C\n"
                    f"Real Feel: {data[0]['RealFeelTemperature']['Metric']['Value']}°C\n"
                    f"Condition: {data[0]['WeatherText']}\n"
                    f"Wind: {data[0]['Wind']['Speed']['Metric']['Value']} km/h, {data[0]['Wind']['Direction']['Localized']}\n"
                )
            elif forecast_option == forecast_options.HOURLY_FORECAST:
                info = f"Weather forecast for the next 12 hours for {city}:\n\n"
                for hourly_forecast in data:
                    info += (
                        f"Time: {datetime.fromisoformat(hourly_forecast['DateTime'][:-6]).strftime('%H:%M')}\n"
                        f"Temperature: {hourly_forecast['Temperature']['Value']}°C\n"
                        f"Condition: {hourly_forecast['IconPhrase']}\n"
                        f"Wind: {hourly_forecast['Wind']['Speed']['Value']} km/h, {hourly_forecast['Wind']['Direction']['Localized']}\n"
                        f"Rain Probability: {hourly_forecast['RainProbability']}%\n\n"
                    )
            elif forecast_option == forecast_options.ONE_DAY_FORECAST:
                info = (
                    f"Weather forecast for tomorrow for {city}:\n\n"
                    f"Minimum Temperature: {data['DailyForecasts'][0]['Temperature']['Minimum']['Value']}°C\n"
                    f"Maximum Temperature: {data['DailyForecasts'][0]['Temperature']['Maximum']['Value']}°C\n"
                    f"Day: {data['DailyForecasts'][0]['Day']['IconPhrase']}\n"
                    f"Night: {data['DailyForecasts'][0]['Night']['IconPhrase']}"
                )
            elif forecast_option == forecast_options.FIVE_DAY_FORECAST:
                info = f"Weather forecast for the next 5 days for {city}:\n\n"
                for day_forecast in data["DailyForecasts"]:
                    info += (
                        f"Day: {datetime.strptime(day_forecast['Date'][:10], '%Y-%m-%d').strftime('%A')}\n"
                        f"Minimum Temperature: {day_forecast['Temperature']['Minimum']['Value']}°C\n"
                        f"Maximum Temperature: {day_forecast['Temperature']['Maximum']['Value']}°C\n"
                        f"Day: {day_forecast['Day']['IconPhrase']}\n"
                        f"Night: {day_forecast['Night']['IconPhrase']}\n\n"
                    )
            else:
                raise ValueError("Invalid forecast option.")
        return info


a=5
print(type(a))

class Laptop:
    def __init__(self,name,processor):
        self.name="Asus"
        self.processor="i9"

    def printOutput(self):
        print("My laptop name is :" ,self.name, "and the processor is : ", self.processor)

laptop1=Laptop("antara","i9")
laptop2=Laptop("arpita","i7")
# print(id(laptop1))
# print(id(laptop2))
laptop1.printOutput()

#laptop1.config()
#laptop2.config()


from django.db import models

class SocialMedia(models.Model):
    redes = {
        ('FB', 'Facebook'),
        ('PI', 'Pinterest'),
        ('WA', 'Whatsapp'),
        ('IG', 'Instagram'),
        ('LI', 'Linkedin'),
        ('BH', 'Behance'),
        ('DA', 'Devian Art')
    }

    nombre = models.CharField(max_length=2, choices=redes, verbose_name='Nombre')
    enlace = models.CharField(max_length=100, verbose_name='URL de la Red Social')
    imagen = models.ImageField(upload_to='medios_sociales', default='', null=True, blank=True, verbose_name='Imágen')

    class Meta:
        db_table = "apps_socialmedia"
        verbose_name = 'Red Social'
        verbose_name_plural = 'Redes Sociales'

    def __str__(self):
        return self.nombre


import logging

import pytest

from onetl.file.format import CSV

def test_csv_options_default():
    csv = CSV()
    assert csv.delimiter == ","
    assert csv.encoding == "utf-8"
    assert csv.quote == '"'
    assert csv.escape == "\\"
    assert csv.header is False
    assert csv.lineSep == "\n"

def test_csv_options_default_override():
    csv = CSV(
        delimiter="value",
        encoding="value",
        quote="value",
        escape="value",
        header=True,
        lineSep="value",
    )
    assert csv.delimiter == "value"
    assert csv.encoding == "value"
    assert csv.quote == "value"
    assert csv.escape == "value"
    assert csv.header is True
    assert csv.lineSep == "value"

def test_csv_options_delimiter_alias():
    csv = CSV(sep="value")
    assert csv.delimiter == "value"

@pytest.mark.parametrize(
    "known_option",
    [
        "charToEscapeQuoteEscaping",
        "dateFormat",
        "emptyValue",
        "ignoreLeadingWhiteSpace",
        "ignoreTrailingWhiteSpace",
        "nullValue",
        "timestampFormat",
        "timestampNTZFormat",
        "columnNameOfCorruptRecord",
        "comment",
        "enableDateTimeParsingFallback",
        "enforceSchema",
        "inferSchema",
        "locale",
        "maxCharsPerColumn",
        "maxColumns",
        "mode",
        "multiLine",
        "nanValue",
        "negativeInf",
        "positiveInf",
        "preferDate",
        "samplingRatio",
        "unescapedQuoteHandling",
        "compression",
        "escapeQuotes",
        "quoteAll",
    ],
)
def test_csv_options_known(known_option):
    csv = CSV.parse({known_option: "value"})
    assert getattr(csv, known_option) == "value"

def test_csv_options_unknown(caplog):
    with caplog.at_level(logging.WARNING):
        csv = CSV(unknown="abc")
        assert csv.unknown == "abc"

    assert ("Options ['unknown'] are not known by CSV, are you sure they are valid?") in caplog.text


import numpy as np
import pandas as pd
from astropy import units as u
from astroquery.simbad import Simbad
import astropy.coordinates as coord
from astropy.coordinates import SkyCoord

Simbad.add_votable_fields('otype')

df = pd.read_csv('Hcat.csv') #Catalog of High/Low Mass Binaries

ra = df['ra']
dec = df['dec']
df['Actual_Name'] = np.zeros(len(ra))
df['Object Type'] = np.zeros(len(ra))

for i in range(len(ra)): #Find Source Name and Type for the Nearest Source within 2 arcmin
    result_table = Simbad.query_region(coord.SkyCoord(ra[i], dec[i], unit=(u.deg, u.deg), frame='icrs'), radius='0d2m0s')
    if result_table:
        print(result_table['MAIN_ID'][0])
        df['Actual_Name'][i] = result_table['MAIN_ID'][0].decode("utf-8")
        df['Object Type'][i] = result_table['OTYPE'][0].decode("utf-8")

print(df.head())
df.to_csv('Hcat.csv', index=None)


import tcod
from globs import globs

class Rectangle:
    def __init__(self, x, y, w, h):
        self.top_x = x
        self.top_y = y
        self.bottom_x = x+w
        self.bottom_y = y+h

    def centering(self):
        center_x = (self.top_x + self.bottom_x) / 2
        center_y = (self.top_y + self.bottom_y) / 2
        return(center_x, center_y)

    def check_intersection(self, other):
        return(self.top_x <= other.bottom_x and self.bottom_x >= other.top_x and self.top_y <= other.bottom_y and self.bottom_y >= other.top_y)

class Tile:
    def __init__(self, blocked, block_sight= None):
        self.blocked = blocked
        self.explored = False
        #if a tile is blocked it also blocks sight
        if block_sight is None: block_sight = blocked
        self.block_sight = block_sight

class Character:
    global map
    map = globs['map']

    '''generic object represented by ascii char on the screen
    '''

    def __init__(self, axis_X, axis_Y, character, color, blocks=False):
        self.axis_X = axis_X
        self.axis_Y = axis_Y
        self.character = character
        self.color = color
        self.blocks = blocks

    def move(self, dx, dy):
        if not map[self.axis_X + dx][self.axis_Y + dy].blocked:
            self.axis_X += dx
            self.axis_Y += dy

    def draw(self, fov_map, char_con):
        if tcod.map_is_in_fov(fov_map, int(self.axis_X), int(self.axis_Y)):
            tcod.console_set_default_foreground(char_con, self.color)
            tcod.console_put_char(char_con, int(self.axis_X), int(self.axis_Y), self.character, tcod.BKGND_NONE)


import requests
import argparse
import os
from pathlib import Path
from downloader import download_image
from extension import get_extension

def fetch_spacex_last_launch(id):
    url_api_spacex = f'https://api.spacexdata.com/v5/launches/{id}'
    response = requests.get(url_api_spacex)
    response.raise_for_status()
    links_pics = response.json()['links']['flickr']['original']
    for links_number, url in enumerate(links_pics):
        path = os.path.join('image', f'spacex{links_number}{get_extension(url)}')
        download_image(url, path)

def createParser ():
    parser = argparse.ArgumentParser(description='Downloader SpaceX launch')
    parser.add_argument ('-i', '--id', default='latest', help='"id" from https://api.spacexdata.com/v5/launches. Default download last launch')
    return parser

def main():
    parser = createParser()
    namespace = parser.parse_args()
    Path("image").mkdir(parents=True, exist_ok=True)
    fetch_spacex_last_launch(namespace.id)

if __name__ == '__main__':
    main()


# Gnu General Public License - see LICENSE.TXT

import os

import xbmc
import xbmcgui
import xbmcvfs

from .jsonrpc import JsonRpc, get_value, set_value
from .simple_logging import SimpleLogging

log = SimpleLogging(__name__)
ver = xbmc.getInfoLabel('System.BuildVersion')[:2]

def check_skin_installed():

    params = {
        'addonid': "skin.estuary_embycon",
        'properties': ['version', 'enabled']
    }
    result = JsonRpc('Addons.GetAddonDetails').execute(params)
    log.debug("EmbyCon Skin Details: {0}", result)

    installed = result.get("result") is not None
    version = 'na'
    if installed:
        version = result.get("result").get("addon").get("version")

    if not installed:
        clone_default_skin()

def clone_default_skin():
    xbmc.executebuiltin("Dialog.Close(all,true)")
    xbmc.executebuiltin("ActivateWindow(Home)")

    message = []
    message.append("This will clone the default Estuary Kodi skin and add EmbyCon functionality to it.")
    message.append("Once cloned you can switch between skins in the Kodi interface settings.")
    message.append("Do you want to continue?")
    response = xbmcgui.Dialog().yesno("EmbyCon, Clone Estuary Skin?", "\n".join(message))

    if not response:
        return

    clone_skin()
    set_skin_settings()
    update_kodi_settings()

    # xbmc.executebuiltin("ReloadSkin()")
    # xbmc.executebuiltin("ActivateWindow(Home)")

def walk_path(root_path, relative_path, all_files):
    files = xbmcvfs.listdir(root_path)
    found_paths = files[0]
    found_files = files[1]

    for item in found_files:
        rel_path = os.path.join(relative_path, item)
        all_files.append(rel_path)

    for item in found_paths:
        new_path = os.path.join(root_path, item)
        rel_path = os.path.join(relative_path, item)
        all_files.append(rel_path)
        walk_path(new_path, rel_path, all_files)

def clone_skin():
    log.debug("Cloning Estuary Skin")

    kodi_path = xbmcvfs.translatePath("special://xbmc")
    kodi_skin_source = os.path.join(kodi_path, "addons", "skin.estuary")
    log.debug("Kodi Skin Source: {0}", kodi_skin_source)

    pdialog = xbmcgui.DialogProgress()
    pdialog.create("EmbyCon Skin Cloner", "")

    all_files = []
    walk_path(kodi_skin_source, "", all_files)
    for found in all_files:
        log.debug("Found Path: {0}", found)

    kodi_home_path = xbmcvfs.translatePath("special://home")
    kodi_skin_destination = os.path.join(kodi_home_path, "addons", "skin.estuary_embycon")
    log.debug("Kodi Skin Destination: {0}", kodi_skin_destination)

    # copy all skin files (clone)
    count = 0
    total = len(all_files)
    for skin_file in all_files:
        percentage_done = int(float(count) / float(total) * 100.0)
        pdialog.update(percentage_done, "%s" % skin_file)

        source = os.path.join(kodi_skin_source, skin_file)
        destination = os.path.join(kodi_skin_destination, skin_file)
        xbmcvfs.copy(source, destination)

        count += 1

    # alter skin addon.xml
    addon_xml_path = os.path.join(kodi_skin_destination, "addon.xml")
    log.debug("Addon XML file path : {0}", addon_xml_path)
    with open(addon_xml_path, "r", encoding="utf-8") as addon_file:
        addon_xml_data = addon_file.read()

    addon_xml_data = addon_xml_data.replace("id=\"skin.estuary\"", "id=\"skin.estuary_embycon\"")
    addon_xml_data = addon_xml_data.replace("name=\"Estuary\"", "name=\"Estuary EmbyCon\"")

    # log.debug("{0}", addon_xml_data)

    # update the addon.xml
    with open(addon_xml_path, "w", encoding="utf-8") as addon_file:
        addon_file.write(addon_xml_data)

    # get embycon path
    embycon_path = os.path.join(kodi_home_path, "addons", "plugin.video.embycon")

    log.debug("Major Version: {0}", ver)

    file_list = ["Home.xml",
                 "Includes_Home.xml",
                 "DialogVideoInfo.xml",
                 "DialogSeekBar.xml",
                 "VideoOSD.xml"]

    for file_name in file_list:
        source = os.path.join(embycon_path, "resources", "skins", "skin.estuary", ver, "xml", file_name)
        if xbmcvfs.exists(source):
            destination = os.path.join(kodi_skin_destination, "xml", file_name)
            log.debug("Copying modified skin files : source:{0} destination:{1}", source, destination)
            xbmcvfs.copy(source, destination)
        else:
            log.debug("Copying modified skin files : source:{0} destination:{1} !Skipping, source not available!", source, destination)

    xbmc.executebuiltin("UpdateLocalAddons")

    pdialog.close()
    del pdialog

    response = xbmcgui.Dialog().yesno("EmbyCon Skin Cloner", "Do you want to switch to the new cloned skin?")
    if not response:
        return

    params = {
        'addonid': "skin.estuary_embycon",
        'enabled': True
    }
    result = JsonRpc('Addons.SetAddonEnabled').execute(params)
    log.debug("Addons.SetAddonEnabled : {0}", result)

    log.debug("SkinCloner : Current Skin : " + get_value("lookandfeel.skin"))
    set_result = set_value("lookandfeel.skin", "skin.estuary_embycon")
    log.debug("Save Setting : lookandfeel.skin : {0}", set_result)
    log.debug("SkinCloner : Current Skin : " + get_value("lookandfeel.skin"))

def update_kodi_settings():
    log.debug("Settings Kodi Settings")

    # set_value("screensaver.mode", "script.screensaver.logoff")
    set_value("videoplayer.seekdelay", 0)
    set_value("filelists.showparentdiritems", False)
    set_value("filelists.showaddsourcebuttons", False)
    set_value("myvideos.extractchapterthumbs", False)
    set_value("myvideos.extractflags", False)
    set_value("myvideos.selectaction", 3)
    set_value("myvideos.extractthumb", False)

def set_skin_settings():
    log.debug("Settings Skin Settings")

    xbmc.executebuiltin("Skin.SetBool(HomeMenuNoPicturesButton)")
    xbmc.executebuiltin("Skin.SetBool(HomeMenuNoMusicButton)")
    xbmc.executebuiltin("Skin.SetBool(HomeMenuNoVideosButton)")
    xbmc.executebuiltin("Skin.SetBool(HomeMenuNoFavButton)")
    xbmc.executebuiltin("Skin.SetBool(HomeMenuNoTVButton)")
    xbmc.executebuiltin("Skin.SetBool(HomeMenuNoWeatherButton)")
    xbmc.executebuiltin("Skin.SetBool(HomeMenuNoMusicVideoButton)")
    xbmc.executebuiltin("Skin.SetBool(HomeMenuNoRadioButton)")
    xbmc.executebuiltin("Skin.SetBool(no_slide_animations)")
    xbmc.executebuiltin("Skin.SetBool(HomeMenuNoMovieButton)")
    xbmc.executebuiltin("Skin.SetBool(HomeMenuNoTVShowButton)")
    xbmc.executebuiltin("Skin.SetBool(HomeMenuNoGamesButton)")
    xbmc.executebuiltin("Skin.Reset(HomeMenuNoProgramsButton)")


def f(n=1, show=False):
    '''
    Esta rotina permite
    :param n: Digite o valor a se calcular o fatorial.
    :param show: Ativando esta função será detalhado as contas matemáticas.
    :return: Será o retorno na tela do usuário de acordo com os parâmetros de entrada.
    Desenvolvido por Lucas Andrade
    '''
    f=1
    for c in range(n, 0, -1):
        f *= c
        if show == True:
            if c > 1:
                print(f'{c} x', end=' ')
            else:
                print(f'1 = {f}')
    return f'O fatoria de {n} é igual a {f}.'

#help(f)
a = int(input('Digite um número: '))
b = str(input('Gostaria de ver as contas [S/N]: ')).upper().strip()[0]
if b == 'S':
    b = True
print(f(a, b))


import subprocess
import os

from . import config

def platform_ssh(target, args=None, execlp=False):
    if target == 'aws':
        master_params = config.get_master_ssh_params(target)
        hostname = master_params.pop('HostName')
        opts = make_ssh_opts(master_params)
        cmd = ['ssh'] + opts + [hostname]
    elif target == 'vagrant':
        # We could just use ssh and its options...
        cmd = ['vagrant', 'ssh', '--']
    else:
        print('crazy stuff')
        return
    if args:
        cmd.extend(args)
    if execlp:
        cmd.insert(0, cmd[0])
        os.execlp(*cmd)
    else:
        subprocess.check_call(cmd)

def make_ssh_opts(params):

    def yo():
        for key, val in params.items():
            yield '-o'
            yield u'{}={}'.format(key, val)

    return list(yo())

def platform_scp(target, local, remote, direction):
    if direction not in ('up', 'down'):
        raise ValueError('bad direction')
    master_params = config.get_master_ssh_params(target)
    opts = make_ssh_opts(master_params)
    items = [local, u'{}://{}'.format(master_params['HostName'], remote)]
    if direction == 'down':
        items.reverse()
    subprocess.check_call(['scp', '-q'] + opts + items)

def platform_rsync(target, local, remote, direction):
    if direction not in ('up', 'down'):
        raise ValueError('bad direction')
    master_params = config.get_master_ssh_params(target)
    ssh_opts = make_ssh_opts(master_params)
    items = [local, u'{}://{}'.format(master_params['HostName'], remote)]
    if direction == 'down':
        items.reverse()
    subprocess.check_call(
        ['rsync', '-avz', '-e', 'ssh {}'.format(' '.join(ssh_opts))]
        + items
    )


from sqlalchemy import create_engine
import model
import server
from model import Industry

with open("industry_codes.csv", 'r', encoding='ISO-8859-1') as f:
    engine = create_engine('postgresql:///donations')
    conn = engine.raw_connection()
    Industry.__table__.drop(engine)
    model.connect_to_db(server.app)
    model.db.create_all()
    cursor = conn.cursor()
    cmd = "COPY industries(catcode, catname, catorder, industry, sector, sector_long) FROM STDIN WITH (FORMAT CSV, HEADER FALSE, DELIMITER E'\t');"
    cursor.copy_expert(cmd, f)
    conn.commit()


from algorithms import algorithms

def apply_algorithm_to_dataset(algorithm: str, dataset_fname: str, output_fname: str):
    try:
        A = [a for a in algorithms if a["name"] == algorithm][0]
    except:
        raise Exception(f'Algorithm not found: {algorithm}')
    F = A['function']
    F(dataset_fname, output_fname)