import os
import re
import sys
import copy
import json
import spacy
import string
import logging
import argparse

import numpy as np
from nltk.corpus import stopwords

MODIFIERS_POS_SET = ['NOUN', 'VERB', 'ADJ', 'ADV', 'ADP']
COMPOUND_POS_LIST = ['NOUN', 'PROPN']
# See:
# https://spacy.io/api/annotation#dependency-parsing
# https://github.com/clir/clearnlp-guidelines/blob/master/md/specifications/dependency_labels.md
SRC_TAG_SET = ['agent', 'attr', 'dative', 'dobj', 'nsubj', 'nsubjpass', 'obj', 'oprd']
CONTRACTIONS = \
    ['t', 've', 'd', 'ye', 'e', 'er', 's', 'g', 'n', 'll', 're', 'm', 'a', 'o', 're', 'y', 'gon', 'wan', 'na']

def _process_strings(line,
                     lang_nlp,
                     get_lemmas,
                     get_pos,
                     remove_stopwords,
                     replace_stopwords,
                     get_maps):

    """ Helper function for obtaining various word representations """

    # strip, replace special tokens
    orig_line = line
    line = line.strip()
    line = re.sub(r''', '\'', line.strip())
    line = re.sub(r'"', '\"', line.strip())
    # Tokenize etc.
    line_nlp = lang_nlp(line)
    spacy_tokens = [elem.text for elem in line_nlp]
    spacy_tokens_lower = [elem.text.lower() for elem in line_nlp]
    spacy_lemmas = None
    spacy_pos = None
    if get_lemmas:
        spacy_lemmas = list()
        for elem in line_nlp:
            if elem.lemma_ == '-PRON-' or elem.lemma_.isdigit():
                spacy_lemmas.append(elem.lower_)
            else:
                spacy_lemmas.append(elem.lemma_.lower().strip())
    if get_pos:
        spacy_pos = [elem.pos_ for elem in line_nlp]

    # Generate a mapping between whitespace tokens and SpaCy tokens
    ws_tokens = orig_line.strip().split()
    ws_tokens_lower = orig_line.strip().lower().split()
    ws_to_spacy_map = dict()
    spacy_to_ws_map = dict()
    if get_maps:
        ws_loc = 0
        ws_tok = ws_tokens[ws_loc]

        for spacy_loc, spacy_tok in enumerate(spacy_tokens):
            while True:
                # Map whitespace tokens to be identical to spacy tokens
                ws_tok = re.sub(r''', '\'', ws_tok)
                ws_tok = re.sub(r'"', '\"', ws_tok)

                if spacy_tok == ws_tok or spacy_tok in ws_tok:
                    # Terminate
                    if ws_loc >= len(ws_tokens):
                        break

                    # Extend maps
                    if not ws_to_spacy_map.get(ws_loc, None):
                        ws_to_spacy_map[ws_loc] = list()
                    ws_to_spacy_map[ws_loc].append(spacy_loc)
                    if not spacy_to_ws_map.get(spacy_loc, None):
                        spacy_to_ws_map[spacy_loc] = list()
                    spacy_to_ws_map[spacy_loc].append(ws_loc)

                    # Move pointer
                    if spacy_tok == ws_tok:
                        ws_loc += 1
                        if ws_loc < len(ws_tokens):
                            ws_tok = ws_tokens[ws_loc]
                    else:
                        ws_tok = ws_tok[len(spacy_tok):]
                    break
                else:
                    ws_loc += 1

        # Assert full coverage of whitespace and SpaCy token sequences by the mapping
        ws_covered = sorted(list(ws_to_spacy_map.keys()))
        spacy_covered = sorted(list(set(list([val for val_list in ws_to_spacy_map.values() for val in val_list]))))
        assert ws_covered == [n for n in range(len(ws_tokens))], \
            'WS-SpaCy mapping does not cover all whitespace tokens: {}; number of tokens: {}'\
            .format(ws_covered, len(ws_tokens))
        assert spacy_covered == [n for n in range(len(spacy_tokens))], \
            'WS-SpaCy mapping does not cover all SpaCy tokens: {}; number of tokens: {}' \
            .format(spacy_covered, len(spacy_tokens))

    if remove_stopwords:
        # Filter out stopwords
        nsw_spacy_tokens_lower = list()
        nsw_spacy_lemmas = list()
        for tok_id, tok in enumerate(spacy_tokens_lower):
            if tok not in STOP_WORDS:
                nsw_spacy_tokens_lower.append(tok)
                if get_lemmas:
                    nsw_spacy_lemmas.append(spacy_lemmas[tok_id])
            else:
                if replace_stopwords:
                    nsw_spacy_tokens_lower.append('<STPWRD>')
                    if get_lemmas:
                        nsw_spacy_lemmas.append('<STPWRD>')

        spacy_tokens_lower = nsw_spacy_tokens_lower
        if get_lemmas:
            spacy_lemmas = nsw_spacy_lemmas

    return line_nlp, spacy_tokens_lower, spacy_lemmas, spacy_pos, ws_tokens, ws_tokens_lower, ws_to_spacy_map, \
        spacy_to_ws_map

def _extract_modifiers(line, pos_to_keep):

    """ Parses a single line taken from a text corpus, identifying nouns and elements modifying them /
    being modified by them """

    spacy_sent_rep, _, _, _, _, _, _, _ = \
        _process_strings(line,
                         nlp,
                         get_lemmas=False,
                         get_pos=False,
                         remove_stopwords=False,
                         replace_stopwords=False,
                         get_maps=False)

    sentence_modifiers = dict()
    noun_tokens = dict()

    # Find modifiers
    for rep_id, rep in enumerate(spacy_sent_rep):
        if rep.pos_ == 'NOUN':

            # Ignore compounds
            if rep_id < len(spacy_sent_rep) - 1:
                if spacy_sent_rep[rep_id + 1].pos_ in COMPOUND_POS_LIST:
                    continue

            noun_lemma = \
                rep.lower_ if rep.lemma_ == '-PRON-' or rep.lemma_.isdigit() else rep.lemma_.lower()
            noun_lemma = noun_lemma.strip(punctuation_plus_space)
            if len(noun_lemma) == 0 or noun_lemma in CONTRACTIONS:
                continue
            noun_modifiers = dict()
            if not noun_tokens.get(noun_lemma, None):
                noun_tokens[noun_lemma] = list()
            noun_tokens[noun_lemma].append(rep.text.lower())

            # Find modifiers
            children = [child for child in rep.children]
            for child in children:
                # Obtain lemmas
                child_lemma = \
                    child.lower_ if child.lemma_ == '-PRON-' or child.lemma_.isdigit() else child.lemma_.lower()
                child_lemma = child_lemma.strip(punctuation_plus_space)
                child_token = child.text.lower().strip(punctuation_plus_space)
                # Filter by pos
                if child.pos_ in pos_to_keep and child_lemma != noun_lemma and \
                        child_token not in CONTRACTIONS and len(child_lemma) > 1:
                    # Extend modifier table
                    if not noun_modifiers.get(child_lemma, None):
                        noun_modifiers[child_lemma] = {'[TOKENS]': list(),
                                                       '[POS]': list(),
                                                       '[DEP TAGS]': list(),
                                                       '[ROLE]': list(),
                                                       '[COUNTS]': 0}
                    noun_modifiers[child_lemma]['[TOKENS]'].append(child_token)
                    noun_modifiers[child_lemma]['[POS]'].append(child.pos_)
                    noun_modifiers[child_lemma]['[DEP TAGS]'].append(child.dep_)
                    noun_modifiers[child_lemma]['[ROLE]'].append('child')
                    noun_modifiers[child_lemma]['[COUNTS]'] += 1
            # Evaluate head
            head = rep.head
            head_lemma = head.lower_ if head.lemma_ == '-PRON-' or head.lemma_.isdigit() else head.lemma_.lower()
            head_lemma = head_lemma.strip(punctuation_plus_space)
            head_token = head.text.lower().strip(punctuation_plus_space)
            # Filter by pos
            if head.pos_ in pos_to_keep and head_lemma != noun_lemma and \
                    head_token not in CONTRACTIONS and len(head_lemma) > 1:
                if not noun_modifiers.get(head_lemma, None):
                    noun_modifiers[head_lemma] = {'[TOKENS]': list(),
                                                  '[POS]': list(),
                                                  '[DEP TAGS]': list(),
                                                  '[ROLE]': list(),
                                                  '[COUNTS]': 0}
                noun_modifiers[head_lemma]['[TOKENS]'].append(head_token)
                noun_modifiers[head_lemma]['[POS]'].append(head.pos_)
                noun_modifiers[head_lemma]['[DEP TAGS]'].append(head.dep_)
                noun_modifiers[head_lemma]['[ROLE]'].append('head')
                noun_modifiers[head_lemma]['[COUNTS]'] += 1

            # Consolidate sentence-level information
            if len(noun_modifiers.keys()) > 0:
                if sentence_modifiers.get(noun_lemma, None) is None:
                    sentence_modifiers[noun_lemma] = noun_modifiers
                else:
                    for mod_lemma in noun_modifiers.keys():
                        if sentence_modifiers[noun_lemma].get(mod_lemma, None) is None:
                            sentence_modifiers[noun_lemma][mod_lemma] = noun_modifiers[mod_lemma]
                        else:
                            for key in sentence_modifiers[noun_lemma][mod_lemma].keys():
                                sentence_modifiers[noun_lemma][mod_lemma][key] += noun_modifiers[mod_lemma][key]
    return sentence_modifiers, noun_tokens

def extract_all_modifiers(corpus_path, out_path):

    """ Extracts certain classes of words that modify ambiguous terms of interest from parallel sentence pairs. """

    def _score_modifiers(entry,
                         modifier_counts_global,
                         modifier_frequencies_global,
                         noun_entry_sizes_global,
                         nouns_total,
                         curr_noun):
        """ Helper function for calculation various modifier relevance metrics at cluster level """
        # Add smoothing for PMI computation
        smoothed_modifier_counts_global = dict()
        smoothed_noun_entry_sizes_global = {n: 0 for n in noun_entry_sizes_global.keys()}
        for mod in modifier_counts_global.keys():
            smoothed_modifier_counts_global[mod] = dict()
            for n in modifier_counts_global[mod].keys():
                n_count = modifier_counts_global[mod].get(n, 0)
                smoothed_n_count = n_count + 100  # smoothing factor
                smoothed_modifier_counts_global[mod][n] = smoothed_n_count
                smoothed_noun_entry_sizes_global[n] += smoothed_n_count
        # Compute smoothed counts total
        smoothed_modifier_total = 0
        for mod in smoothed_modifier_counts_global:
            smoothed_modifier_total += sum(smoothed_modifier_counts_global[mod].values())

        modifiers_with_freq = list()
        modifiers_with_ratio_within = list()
        modifiers_with_ratio_across = list()
        modifiers_with_mim = list()
        modifiers_with_pmi = list()
        for mod in entry.keys():
            # FREQ
            modifiers_with_freq.append((mod, entry[mod]['[COUNTS]']))
            # RATIO WITHIN
            modifier_ratio_within = modifier_frequencies_global[mod][curr_noun]
            modifiers_with_ratio_within.append((mod, modifier_ratio_within))
            # RATIO ACROSS
            total_modifiers_across_clusters = sum(modifier_counts_global[mod].values())
            modifier_ratio_across = modifier_counts_global[mod][curr_noun] / total_modifiers_across_clusters
            modifiers_with_ratio_across.append((mod, modifier_ratio_across / noun_entry_sizes_global[curr_noun]))
            # Compute inverse noun frequency
            inverse_noun_frequency = np.log(nouns_total / sum(list(modifier_frequencies_global[mod].values())))
            # MIM
            modifier_mim = modifier_frequencies_global[mod][curr_noun] * inverse_noun_frequency
            modifiers_with_mim.append((mod, modifier_mim))
            # PMI
            joined_prob = smoothed_modifier_counts_global[mod][curr_noun] / smoothed_modifier_total
            marginal_prob_mod = sum(smoothed_modifier_counts_global[modifier].values()) / smoothed_modifier_total
            marginal_prob_noun = smoothed_noun_entry_sizes_global[curr_noun] / smoothed_modifier_total
            modifier_sense_pmi = np.log2(joined_prob / (marginal_prob_mod * marginal_prob_noun))
            modifiers_with_pmi.append((modifier, modifier_sense_pmi))
        # Integrate
        updated_entry = dict()
        updated_entry['[MODIFIERS]'] = {m: v for m, v in entry.items()}

        updated_entry['[MODIFIERS WITH FREQ]'] = dict()
        for mwf, score in modifiers_with_freq:
            updated_entry['[MODIFIERS WITH FREQ]'][mwf] = score

        updated_entry['[MODIFIERS WITH RATIO WITHIN]'] = dict()
        for mrw, score in modifiers_with_ratio_within:
            updated_entry['[MODIFIERS WITH RATIO WITHIN]'][mrw] = score

        updated_entry['[MODIFIERS WITH RATIO ACROSS]'] = dict()
        for mra, score in modifiers_with_ratio_across:
            updated_entry['[MODIFIERS WITH RATIO ACROSS]'][mra] = score

        updated_entry['[MODIFIERS WITH MIM]'] = dict()
        for mwm, score in modifiers_with_mim:
            updated_entry['[MODIFIERS WITH MIM]'][mwm] = score

        updated_entry['[MODIFIERS WITH PMI]'] = dict()
        for mwp, score in modifiers_with_pmi:
            updated_entry['[MODIFIERS WITH PMI]'][mwp] = score
        return updated_entry

    # Initialize the output table
    modifiers_table = dict()
    noun_tokens_table = dict()

    # Track counts
    line_count = 0
    noun_count = 0
    mod_count = 0

    # Iterate
    with open(corpus_path, 'r', encoding='utf8') as out_file:
        for line_id, line in enumerate(out_file):
            line_modifiers, noun_tokens = _extract_modifiers(line.strip(), MODIFIERS_POS_SET)
            if len(line_modifiers.keys()) <= 0:
                continue
            # Extend modifiers table
            for noun in line_modifiers.keys():
                if modifiers_table.get(noun, None) is None:
                    modifiers_table[noun] = line_modifiers[noun]
                    noun_tokens_table[noun] = noun_tokens[noun]
                    noun_count += 1
                    mod_count += len(line_modifiers[noun].keys())
                else:
                    noun_tokens_table[noun] += noun_tokens[noun]
                    for modifier in line_modifiers[noun].keys():
                        if modifiers_table[noun].get(modifier, None) is None:
                            modifiers_table[noun][modifier] = line_modifiers[noun][modifier]
                            mod_count += 1
                        else:
                            for key in modifiers_table[noun][modifier].keys():
                                modifiers_table[noun][modifier][key] += line_modifiers[noun][modifier][key]
            line_count += 1

            # Report occasionally
            if line_count > 0 and line_count % 10000 == 0:
                logging.info('Parsed {:d} lines successfully'.format(line_id))
                logging.info('Found a total of {:d} modifiers for {:d} unique noun lemmas'
                             .format(mod_count, noun_count))

            # Checkpoint
            if line_count > 0 and line_count % 100000 == 0:
                checkpoint_table = copy.deepcopy(modifiers_table)
                modifier_frequencies = dict()
                modifier_counts = dict()
                noun_entry_sizes = dict()
                num_nouns = 0
                for noun in modifiers_table.keys():
                    num_nouns += 1
                    # Compute modifier total
                    noun_entry_sizes[noun] = \
                        sum([modifiers_table[noun][modifier]['[COUNTS]'] for modifier in modifiers_table[noun].keys()])
                    for modifier in modifiers_table[noun].keys():
                        if not modifier_frequencies.get(modifier, None):
                            modifier_counts[modifier] = dict()
                            modifier_frequencies[modifier] = dict()
                        modifier_counts[modifier][noun] = modifiers_table[noun][modifier]['[COUNTS]']
                        modifier_frequencies[modifier][noun] = \
                            modifiers_table[noun][modifier]['[COUNTS]'] / noun_entry_sizes[noun]

                for noun in modifiers_table.keys():
                    checkpoint_table[noun] = _score_modifiers(modifiers_table[noun], modifier_counts,
                                                              modifier_frequencies, noun_entry_sizes, num_nouns, noun)

                logging.info('Scoring of modifiers completed!')
                logging.info('Checkpointing extracted modifiers ...')
                modifiers_path = '{:s}.json'.format(out_path)
                tokens_path = '{:s}_noun_tokens.json'.format(out_path)
                with open(modifiers_path, 'w', encoding='utf8') as mof:
                    json.dump(checkpoint_table, mof, indent=3, sort_keys=True, ensure_ascii=False)
                logging.info('Saved the modifiers table to {:s}'.format(modifiers_path))
                with open(tokens_path, 'w', encoding='utf8') as tof:
                    json.dump(noun_tokens_table, tof, indent=3, sort_keys=True, ensure_ascii=False)
                logging.info('Saved noun tokens to {:s}'.format(tokens_path))

    # Score modifiers
    # Compute modifier frequency for each noun
    modifier_frequencies = dict()
    modifier_counts = dict()
    noun_entry_sizes = dict()
    num_nouns = 0
    for noun in modifiers_table.keys():
        num_nouns += 1
        # Compute modifier total
        noun_entry_sizes[noun] = \
            sum([modifiers_table[noun][modifier]['[COUNTS]'] for modifier in modifiers_table[noun].keys()])
        for modifier in modifiers_table[noun].keys():
            if not modifier_frequencies.get(modifier, None):
                modifier_counts[modifier] = dict()
                modifier_frequencies[modifier] = dict()
            modifier_counts[modifier][noun] = modifiers_table[noun][modifier]['[COUNTS]']
            modifier_frequencies[modifier][noun] = \
                modifiers_table[noun][modifier]['[COUNTS]'] / noun_entry_sizes[noun]

    for noun in modifiers_table.keys():
        modifiers_table[noun] = _score_modifiers(modifiers_table[noun], modifier_counts,
                                                 modifier_frequencies, noun_entry_sizes, num_nouns, noun)
    logging.info('Scoring of modifiers completed!')

    # Final report
    logging.info('FINAL REPORT')
    logging.info('Found a total of {:d} modifiers for {:d} unique noun lemmas'.format(mod_count, noun_count))

    logging.info('Saving extracted modifiers ...')
    modifiers_path = '{:s}.json'.format(out_path)
    tokens_path = '{:s}_noun_tokens.json'.format(out_path)
    with open(modifiers_path, 'w', encoding='utf8') as mof:
        json.dump(modifiers_table, mof, indent=3, sort_keys=True, ensure_ascii=False)
    logging.info('Saved the modifiers table to {:s}'.format(modifiers_path))
    with open(tokens_path, 'w', encoding='utf8') as tof:
        json.dump(noun_tokens_table, tof, indent=3, sort_keys=True, ensure_ascii=False)
    logging.info('Saved noun tokens to {:s}'.format(tokens_path))

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--corpus_path', type=str, required=True,
                        help='path to the text corpus')
    parser.add_argument('--output_path', type=str, required=True,
                        help='path to which the modifiers should be saved')
    parser.add_argument('--src_lang', type=str, default=None,
                        help='denotes the language ID of the source sentences, e.g. \'en\'')
    args = parser.parse_args()

    # Logging to file
    base_dir = '/'.join(args.output_path.split('/')[:-1])
    file_name = args.output_path.split('/')[-1]
    file_name = '.'.join(file_name.split('.')[:-1])
    log_dir = '{:s}/logs/'.format(base_dir)
    if not os.path.exists(log_dir):
        os.mkdir(log_dir)
    log_path = '{:s}{:s}.log'.format(log_dir, file_name)
    logging.basicConfig(filename=log_path, filemode='w', level=logging.INFO, format='%(levelname)s: %(message)s')
    # Logging to console
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    logging.getLogger('').addHandler(console)

    # Instantiate processing pipeline
    spacy_map = {'en': 'en_core_web_sm', 'de': 'de_core_news_sm'}
    try:
        nlp = spacy.load(spacy_map[args.src_lang], disable=['ner', 'textcat'])
    except KeyError:
        logging.info('SpaCy does not support the language {:s}. Exiting.'.format(args.src_lang))
        sys.exit(0)
    pct_stripper = str.maketrans(string.punctuation, ' ' * len(string.punctuation))
    punctuation_plus_space = string.punctuation + ' ' + '\t' + '\n'
    # Import stopword list
    if args.src_lang == 'en':
        STOP_WORDS = stopwords.words('english')
    else:
        STOP_WORDS = []

    extract_all_modifiers(args.corpus_path, args.output_path)


import discord
from discord import Game
from discord.ext.commands import Bot
import asyncio
import os

BOT_PREFIX = "e!"
BOT_TOKEN = os.environ.get('EMBA_BOT_TOKEN')

current_announcement = {} # current announcement sent | Key: server id, Value: embedded object
announcement_channel = {} # channel to send announcements to | Key: server id, Value: channel

client = Bot(command_prefix=BOT_PREFIX)
client.remove_command('help')

@client.event
async def on_ready():
    """This function runs when the bot is started"""
    await client.change_presence(game = Game(name = 'the trumpet'))
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

@client.command(name='help', pass_context=True)
async def help(ctx):
    """help command"""
    # Only allowed to use commands if they have administrative permissions
    if ctx.message.author.server_permissions.administrator:
        # obtain the argument (remove the command and the leading and trailing whitespaces)
        argument = ctx.message.content[7:].strip()

        #check if user specified create module
        if argument == 'create':
            await helpcreate(ctx)
            return
        embed = discord.Embed(color = discord.Color.orange())
        embed.set_author(name='Help', icon_url='https://cdn.discordapp.com/attachments/561393414571294752/563071668533067901/announcement_icon.jpg')
        embed.add_field(
            name='Commands',
            value='*e!create [text]* - Creates an an embedded post, to learn more about create try e!help create\n*e!preview* - Sends a preview of the announcement to the requesting channel\n*e!channel [#channel]* - Sets the announcement channel\n*e!post* - post the announcement to the set channel',
            inline=True
        )
        await client.say(embed=embed)

async def helpcreate(ctx):
    embed = discord.Embed(color=discord.Color.orange())
    embed.set_author(name='Help | Create', icon_url='https://cdn.discordapp.com/attachments/561393414571294752/563071668533067901/announcement_icon.jpg')
    embed.add_field(
        name='Title',
        value='The first part of your input is the title of the announcement, | should be put at the end of the title and any field.\nIn the input: `e!create Contest | Details<This is a test` The title is `Contest`',
        inline=True
    )
    embed.add_field(
        name='Sections',
        value='Separate sections with |',
        inline=True
    )
    embed.add_field(
        name='Section Headers',
        value='^This is a section header, section headers are the first few words after a | before a < in inputed\nIn the input: `e!create Contest | Other Details<The event will take place...` Other Details would be the header',
        inline=True
    )
    await client.send_message(ctx.message.channel, embed=embed)

@client.command(name='create', pass_context=True)
async def create(ctx):
    """The bot creates an announcement and saves it for the server.  The user can then preview or post the announcement

    Args:
        - ctx: context of the command
    """
    # Only allowed to use commands if they have administrative permissions
    if ctx.message.author.server_permissions.administrator:
        # get the input (strip the command syntax)
        message = ctx.message.content[9:]

        # split message based on '|'
        input = message.split('|')

        if len(input) is 0:
            await client.send_message(ctx.message.channel, embed=discord.Embed(description='No contents specified!', color=discord.Color.red()))
            return

        # create embed with teal color
        announcement = discord.Embed(color=discord.Color.teal())

        # set author based on the first part of the users message
        announcement.set_author(name=input[0], icon_url='https://cdn.discordapp.com/attachments/561393414571294752/563071668533067901/announcement_icon.jpg')
        input = input[1:]
        for segment in input:
            # use the first word as the field name
            field_name = segment.split('<', 1)[0]

            # use the rest as the value
            field_text = segment.split('<', 1)[1]

            #add the field
            announcement.add_field(
                name=field_name,
                value=field_text,
                inline=True
            )
        # set announcement
        current_announcement[ctx.message.server.id] = announcement
        await client.send_message(ctx.message.channel, embed=discord.Embed(description='Announcement set! Preview with with e!preview', color=discord.Color.green()))

@client.command(name='channel', pass_context=True)
async def set_announcement_channel(ctx):
    """The bot sets the announcement channel specified by the user for the current server

    Args:
        - ctx: context of the command
    """
    # Only allowed to use commands if they have administrative permissions
    if ctx.message.author.server_permissions.administrator:
        # gets the channel id from form: <#0000000000> to 00000000000
        channel_id = ctx.message.content[10:].replace(" ", "").replace("<", "").replace("#", "").replace(">", "")

        # get the selected channel
        channel = client.get_channel(channel_id)
        if channel is None:
            await client.send_message(ctx.message.channel, embed=discord.Embed(description="Invalid channel", color=discord.Color.red()))
        else:
            #set announcement channel for current server
            announcement_channel[ctx.message.server.id] = channel
            await client.send_message(ctx.message.channel, embed=discord.Embed(description="Set announcements channel as " + channel.mention, color=discord.Color.green()))

@client.command(name='preview', pass_context=True)
async def preview(ctx):
    """The bot outputs a preview of the embedded announcement

    Args:
        - ctx: context of the command (used for getting the server id)
    """
    # Only allowed to use commands if they have administrative permissions
    if ctx.message.author.server_permissions.administrator:
        # get the servers announcement
        announcement = current_announcement.get(ctx.message.server.id)
        if announcement is None:
            await client.send_message(ctx.message.channel, embed=discord.Embed(description="No announcement message set! Set an announcement with e!create", color=discord.Color.red()))
        else:
            await client.send_message(ctx.message.channel, embed=announcement)

@client.command(name='post', pass_context=True)
async def post(ctx):
    """The bot posts the servers announcement to the specified announcement channel

    Args:
        - ctx: context of the command (used for getting the server id)
    """
    # Only allowed to use commands if they have administrative permissions
    if ctx.message.author.server_permissions.administrator:
        # get server announcement
        announcement = current_announcement.get(ctx.message.server.id)
        if announcement is None: # if no announcement set
            await client.send_message(ctx.message.channel, embed=discord.Embed(description="No announcement message set! Set an announcement with e!create", color=discord.Color.red()))
            return
        # get announcement channel
        channel = announcement_channel.get(ctx.message.server.id)
        if channel is None: # if no announcement channel set
            await client.send_message(ctx.message.channel, embed=discord.Embed(description="No announcement channel set! Set an announcement channel with e!channel", color=discord.Color.red()))
        else:
            everyone = ctx.message.server.roles[0]
            await client.send_message(channel, everyone)
            await client.send_message(channel, embed=announcement)

client.run(BOT_TOKEN)


from audioop import avg
from tabnanny import check
from tkinter import Y

# x = 2 + 3

# y = 8

# z = x * y

#name = "onyebuchi"
#print(z)
#print(name)
#print(type(name))
#print(type(x))

#print(type([5, 6]))

#print(type({'a':'john', 'b':20}))

#def square(x):
    #x = 5
    #print(x * x)
#square(x)

#def exponet(x, y):

    #print(x ** y)
#exponet(2, 3)
#print(name[:])
#print(len(name))

#scors = [1, 2, 3, 4, 5, 6, 7]
#print(scors[::1])

# #x = 1
# while x <= 10:
#     print(x)
#     x = x + 1

# for x in range(8):
#     print(x)

# def my_sum(x, y):
#     print(x+y)
# my_sum(1012, 10012)

# def my_sum(x, y):
#     return x+y
# x = my_sum(3, 5)
# print(x)

# def is_even(x):
#     if x % 2 == 0:
#         return True

#     else:
#         return False
# print(is_even(9))

# def is_old(y):
#     if y % 2 == 1:
#         return True
#     else:
#         return False
# print(is_old(9))

# def is_prime(x):
#     if x / 2 == 0:

# def add_list(x):
#     ans = 0

#     for i in x:
#         ans = ans + i

#     return ans

# print(add_list([11, 12, 30, 44]))

# def avg(x):
#     return add_list(x) / len(x)
# print(avg([11, 12, 30, 44]))

# file_name = input("Enter name for the file.\n")
# if file_name: # means same thing as 'if file_name != "" '
#     new_text = input(f"Enter text to be stored in {file_name} and press enter when done:\n")

#     file_open = open(file_name, "a")
#     file_open.write(new_text)
#     file_open.close()

#     with open(file_name) as new_file:
#         text = new_file.read()

#         print(f"\nThe text in {file_name} has {len(text)} \
#             characters in it.\nHere is the text itself:\n{text}\n")
# else:
#     print("Come, Oga! Just enter a valid file name next time. Mtschew!!!")

# ls = [["a","z", "d"], ["b", "c", "d"], ["e", "f", "g"] ]

# print(ls[0][0])
# print(ls[0][2])
# print(ls[1][1])
# print(ls[2][0])
# print(ls[2][2])

customer_info = {
    1240676:{
        "name": "onyebuchi",
        "age" : 20,
        "gender": "male",
        "balance": 0,
        "deposit": [8000000, 300000],
        "withdraw":[40000, 300000]
        },
    1234567:{
        "name": "MOD MAN",
        "age": 19,
        "balance": 20000000,
        "withdraw" : [3000, 500000]
        }
}

# print(customer_info[1240676])
total_deposit = sum(customer_info[1240676]['deposit'])
total_withdrawal = sum(customer_info[1240676]['withdraw'])
balance = total_deposit - total_withdrawal
print(f"Total deposit is: {total_deposit:,}")
print(f"Total withdrawal is: {total_withdrawal:,}")
print(f"current balance is: {customer_info[1240676]['balance']:,}")

customer_info[1240676]['balance'] = balance
print(f"\nNew balance is: {customer_info[1240676]['balance']:,}")


from datetime import date

# UmlClass translates plaintext UML file into .hpp and .cpp files
class UmlClass:

    # Initialize with these values to return to default .hpp/.cpp in loop
    def __init__(self, className):
        self.name = className

        # List of private and public members
        self.hppPrivate = ["private:"]
        self.hppPublic = ["public:"]

        # Starting .cpp template
        self.cpp = [
            "// Copyright (C) 2016. All rights reserved.",
            "// Created: " + str(date.today()),
            "",
            "#include \"" + self.name + ".hpp\""
        ]

        # Starting .hpp template
        self.hpp = [
            "// Copyright (C) 2016. All rights reserved.",
            "// Created: " + str(date.today()),
            "",
            "#ifndef " + self.name + "_hpp",
            "#define " + self.name + "_hpp",
            "",
            "class " + self.name,
            "{",
            "};",
            "#endif"
        ]

    # Soft tab size 4
    indent = "    "

    # Adds a given string to public member list
    def addToPublic(self, pubMember):
        self.hppPublic.append(pubMember)

    # Adds a given string to private member list
    def addToPrivate(self, privMember):
        self.hppPrivate.append(privMember)

    # Checks if given string is a member function
    def isFunction(self, line):
        if "(" in line and ")" in line and "(C)" not in line:
            return True

    # Searches and includes libraries for data types that need them
    # Requires namespace to be assigned before this function is called
    def includeLibs(self):

        # Data types being searched
        stringFound = False
        vectorFound = False

        for line in self.hpp:
            if "std::string" in line:
                stringFound = True
            if "std::vector" in line:
                vectorFound = True

        # Include libraries, along with extra space if found
        if stringFound:
            self.hpp[self.hpp.index("class " + self.name):1] = ["#include <string>"]
        if vectorFound:
            self.hpp[self.hpp.index("class " + self.name):1] = ["#include <vector>"]
        if stringFound or vectorFound:
            self.hpp[self.hpp.index("class " + self.name):1] = [""]

    # Builds hpp using public and private member lists
    def buildHpp(self):
        # Insert public members after {, where class begins
        self.hpp[self.hpp.index("{")+1:1] = self.hppPublic
        # Insert private members after last public member
        self.hpp[self.hpp.index(self.hppPublic[-1])+1:1] = self.hppPrivate

    # Formats hpp list into proper .hpp syntax
    def formatHpp(self):
        self.moveReturnType()
        self.addNamespace()
        self.includeLibs()
        self.indentAndSemiColon()

    # Build and format hpp and cpp lists
    def build(self):
        self.buildHpp()
        self.formatHpp()
        self.buildCpp()
        self.formatCpp()

    # Adds std:: prefix to data types that require it
    def addNamespace(self):
        for line in self.hpp:
            i = self.hpp.index(line)
            if "string" in line:
                line = line.replace("string", "std::string", 1)
                self.hpp[i] = line
            if "vector" in line:
                line = line.replace("vector", "std::vector", 1)
                self.hpp[i] = line

    # Swaps location of returned data type
    def moveReturnType(self):
        for line in self.hpp:
            i = self.hpp.index(line)
            if self.isMember(line):
                if " : " in line:
                    line = line[line.index(":")+1:].strip() + " " + line[:line.index(":")].strip()
                else:
                    line = "void " + line
            self.hpp[i] = line

    # Checks if given string is a member function of data member
    # This determines if a line needs to be formatted or not
    def isMember(self, line):
        notMember = ["/", "#", "class ", "{", "}", "public:", "private:", "protected:", "return"]
        if any(notM in line for notM in notMember) or line == "":
            return False
        else:
            return True

    # Indents a member and adds semicolon at the end
    def indentAndSemiColon(self):
        for line in self.hpp:
            i = self.hpp.index(line)
            if self.isMember(line):
                line = self.indent + line + ";"
                self.hpp[i] = line

    # Builds cpp list using members in hpp list
    # Copies member without indent and semicolon
    def buildCpp(self):
        for line in self.hpp:
            if (self.isFunction(line)):
                self.cpp.append(line[len(self.indent):-1]) # remove indent and ;

    # Adds class namespace and function body along with return statement (if needed)
    def formatCpp(self):
        for line in self.cpp:
            i = self.cpp.index(line)
            if self.isMember(line):
                line = self.insertClassName(line)
                # Add function body
                line = "\n" + line + "\n{\n" + self.indent + self.insertReturnType(line) + "\n}"
                self.cpp[i] = line

    # Returns the return statement (if needed)
    def insertReturnType(self, line):
        line = line[:line.index("(")]

        # If return type exists, construct a return statement
        if len(line.split()) > 1:
            if line[:line.index(self.name)].strip() == "void":
                return ""
            else:
                return "\n" + self.indent + "return " + self.findReturnDefault(line) + ";"
        else:
            return ""

    # If there is a return type, inserts a default return value
    # This will prevent compilation errors from the outset
    def findReturnDefault(self, line):
        line = line[:line.index(self.name)].strip()

        # Check for data types and return some default zero value
        if line == "int" or line == "char" or line == "double" or line == "float" or line == "short":
            return "0"
        elif line == "std::string":
            return "\"\""
        elif line == "bool":
            return "false"
        elif line == "void":
            return ""
        else:
            return ""

    # Returns the class namespace used in the .cpp file
    def insertClassName(self, line):
        # Search and insert className::
        splitLine = line.split()
        for bit in splitLine:
            j = splitLine.index(bit)
            if "(" in bit:
                bit = self.name + "::" + bit
                splitLine[j] = bit
        if len(splitLine) > 1:
            line = " ".join(splitLine)
        else:
            line = "".join(splitLine)
        return line

    # Builds hpp and cpp lists and creates all relevant files
    def createFiles(self):
        self.build()

        # Create .hpp
        self.hppFile = open(self.name + ".hpp", "w")
        for line in self.hpp:
            self.hppFile.write(line + "\n")
        self.hppFile.close()

        # Create .cpp
        self.cppFile = open(self.name + ".cpp", "w")
        for line in self.cpp:
            self.cppFile.write(line + "\n")
        self.cppFile.close()

# Main function
print("[ UML to CPP ] Create .hpp and .cpp files from UML.txt")
print("> Attempting to create files...")
umlFile = open("UML.txt", 'r')

uml = umlFile.read().splitlines() # pull UML into memory, 1 line per element
umlFile.close()
filesCreated = 0

for line in uml:
    if line[:5] == "class" and line[-1:] == "{":
        obj = UmlClass(line[6:-2])
    elif line[:1] == "+":
        obj.addToPublic(line[1:])
    elif line[:1] == "-":
        obj.addToPrivate(line[1:])
    elif line == "}":
        obj.createFiles()
        filesCreated += 2
    elif line == "":
        continue
    else:
        print("> Syntax error in UML file")

print("> " + str(filesCreated) + " files created")


l=[]
n=int(input("Enter the number of terms:"))
for i in range(n):
    a=int(input("Enter number "+str(i+1)+":"))
    l.append(a)
for j in range(len(l)):
    count=0
    for k in range(len(l)):
        if l[j]==l[k]:
            count+=1

    print(l[j],"occurs",count,"time(s)")

Class XI- Python Programs/5th November Program List/3rd November 2022- Occurance Checker list.py


"""atlas URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
import logging

import djangosaml2
from django.conf import settings as django_settings
from django.http import HttpResponse
from django.urls import include, path, re_path

logger = logging.getLogger(__name__)

urlpatterns = [
    path("", include("index.urls")),
    path("saml2/", include("djangosaml2.urls")),
    path("test/", djangosaml2.views.EchoAttributesView.as_view()),
    path("mail/", include("mail.urls")),
    path("analytics/", include("analytics.urls")),
    path("reports/", include("report.urls")),
    path("initiatives/", include("initiative.urls")),
    path("terms/", include("term.urls")),
    path("users/", include("user.urls")),
    path("search/", include("search.urls")),
    path("collections/", include("collection.urls")),
    path("etl/", include("etl.urls")),
]

# if in dev or test use local auth
if (
    hasattr(django_settings, "DEBUG")
    and getattr(django_settings, "DEBUG")
    or hasattr(django_settings, "TESTING")
    and getattr(django_settings, "TESTING")
    or hasattr(django_settings, "DEMO")
    and getattr(django_settings, "DEMO")
):
    urlpatterns.append(path("accounts/", include("django.contrib.auth.urls")))

if hasattr(django_settings, "DEBUG") and getattr(django_settings, "DEBUG"):
    import debug_toolbar

    urlpatterns += (path("__debug__/", include(debug_toolbar.urls)),)

import sys
import traceback

def full_stack():
    """Return full stack trace of an exception.

    :returns: full stack trace of an exception.
    """
    exc = sys.exc_info()[0]
    if exc is not None:
        frame = sys.exc_info()[-1].tb_frame.f_back
        stack = traceback.extract_stack(frame)
    else:
        stack = traceback.extract_stack()[:-1]  # last one would be full_stack()
    trc = "Traceback (most recent call last):\n"
    stackstr = trc + "".join(traceback.format_list(stack))
    if exc is not None:
        # pylint: disable=bad-str-strip-call
        stackstr += "  " + traceback.format_exc().lstrip(trc)
    return stackstr

def custom_error_view(request, exception=None):
    """Log 500 errors."""
    logger.error(full_stack())
    logger.warning(exception)
    return HttpResponse(
        "Ops, there was an error. Please try again in a few minutes.", status=500
    )

def custom_warning_view(request, exception=None):
    """Log 400 errors."""
    logger.warning(full_stack())
    logger.warning(exception)
    return HttpResponse("Ops, that page doesn't exist!", status=404)

handler500 = custom_error_view
handler404 = custom_warning_view


import tkinter as tk  # Importar antes de usar Tkinter

import tkinter.messagebox

import pickle

# Paso 1, crea una instancia del objeto y crea una ventana

window = tk.Tk()

# Paso 2, nombre la visualización de la ventana

window.title('VENTANA PRINCIPAL')

# Paso 3, establezca el tamaño de la ventana (largo * ancho)

window.geometry('400x300')  # Aquí la multiplicación es pequeña x

# Paso 5, información del usuario

tk.Label(window, text='HOLAAAA', font=('Arial', 14)).place(x=10, y=170)

ventana_grabar = tk.Toplevel(window)

ventana_grabar.geometry('300x200')

ventana_grabar.title('Grabar')

window.mainloop()


import unittest
from unittest import mock

import pandas as pd
from sqlalchemy import MetaData

from pytar_calc.calc.og import OgCalc
from pytar_calc.calc.plwm import WmCalc, PlCalc
from pytar_calc.calc.pr import PrCalc
from pytar_calc.calc.start import QuerySm
from pytar_calc.models.daneb import engine_tmp
from pytar_calc.calc.osd import FkSzcz
from pytar_calc.calc.osd import SmCalc
from pytar_calc.shared.data_descriptions import wb17
from pytar_calc.tests.external_data import fk_df
from pytar_calc.tests.set_up_db import TestDB
import random

class FkMock:
    pass

class TestTariffNaPacjenta(TestDB):
    """Test of main workflow.
    """
    DEBUG = True
    options = {'case_group': ['kod_prod', 'kod_sw', 'nr_ks'],
               'path': r'T:\organizacyjne_robocze\tmp\pytar_test',
               'schema': 'wb17',
               'price_priority': 'cena_z_pliku'
               }
    wb17.update(options)
    data_description = wb17
    uid = '%s' % random.randint(0,9999999)
    query_sm_sql_query = f"""
        create table %s as
        select t1.nr_ks, t1.kod_sw, t1.kod_prod, '1' as kod_dod
        from {options['schema']}.sm t1 inner join {options['schema']}.og t2 on t1.kod_sw=t2.kod_sw and t1.nr_ks=t2.nr_ks
        where kod_prod like "5.51.01.0005047"
"""

    fk = FkMock()
    fk.fk_szcz = fk_df
    fk.fk = fk_df

    @classmethod
    def setUpClass(cls):
        query_sm = QuerySm(cls.query_sm_sql_query, cls.uid, **cls.data_description)
        og = OgCalc('og', query_sm, cls.uid, **cls.data_description)
        og.create_tar()
        cls.query_sm = query_sm
        cls.og = og
        if cls.options['schema'] == 'wb17':
            cls.fk = FkSzcz(**cls.data_description, query_sm=cls.query_sm)

    @classmethod
    def tearDownClass(cls):
        if not cls.DEBUG:
            metadata = MetaData(engine_tmp)
            metadata.reflect(engine_tmp)
            tables_to_drop = [i for i in metadata.tables if cls.uid.casefold() in i]
            for i in tables_to_drop:
                metadata.tables[i].drop()

    def test_wm(self):
        wm = WmCalc('wm', self.query_sm, self.uid, og=self.og.og, fk=self.fk, **self.data_description)
        wm.create_tar()
        wm.calc_from_pricelist()
        wm.calc_from_unit_price()
        wm.create_tar_sr_il()
        sr_il_nobs = wm.tar_sr_il.shape[0]
        wm.add_pricelist()
        self.assertEqual(sr_il_nobs, wm.tar_sr_il.shape[0])
        wm.add_unit_price()
        self.assertEqual(sr_il_nobs, wm.tar_sr_il.shape[0])
        # dwie funkcje, które maja wplyw po zmianie wspolczynnikow
        wm.generate_event_cost()
        self.assertEqual(sr_il_nobs, wm.tar_sr_il.shape[0])
        wm.calc_tariff()
        if self.options['schema'] == 'test_daneb':
            self.assertEqual(wm.tariff.at[0, 'suma_wm'], 4.5, 'WM prices diffrent')
        del wm
        wm = WmCalc('wm', self.query_sm, self.uid, og=self.og.og, fk=self.fk, **self.data_description)
        dispatchers_commands_wm = ['create_tar', 'calc_from_pricelist', 'calc_from_unit_price', 'create_tar_sr_il',
                                   'add_pricelist', 'add_unit_price', 'generate_event_cost', 'calc_tariff', ]
        for i in dispatchers_commands_wm:
            _method = getattr(wm, i, None)
            _method()
        if self.options['schema'] == 'test_daneb':
            self.assertEqual(wm.tariff.at[0, 'suma_wm'], 4.5, 'WM prices diffrent')

    def test_pl(self):
        pl = PlCalc('pl', self.query_sm, self.uid, og=self.og.og, fk=self.fk, **self.data_description)
        pl.create_tar()
        pl.create_tar_sr_il()
        sr_il_nobs = pl.tar_sr_il.shape[0]
        pl.calc_from_pricelist()
        self.assertEqual(sr_il_nobs, pl.tar_sr_il.shape[0])
        pl.add_pricelist()
        self.assertEqual(sr_il_nobs, pl.tar_sr_il.shape[0])
        pl.calc_from_unit_price()
        self.assertEqual(sr_il_nobs, pl.tar_sr_il.shape[0])
        pl.add_unit_price()
        self.assertEqual(sr_il_nobs, pl.tar_sr_il.shape[0])
        pl.generate_event_cost()
        self.assertEqual(sr_il_nobs, pl.tar_sr_il.shape[0])
        pl.calc_tariff()

    def test_pr(self):
        pr = PrCalc('pr', self.query_sm, self.uid, og=self.og.og, fk=self.fk, **self.data_description)
        pr.create_tar()
        pr.create_tar_sr_il_abc()
        sr_il_nobs = pr.tar_sr_il.shape[0]
        pr.calc_from_pricelist()
        pr.add_cp_prices()
        self.assertEqual(sr_il_nobs, pr.tar_sr_il.shape[0])
        # PR_HR
        pr.create_tar_pr_hr()
        pr.create_pers_infrast_wagi_czas()
        pr.calc_pr_hr_costs()
        self.assertEqual(sr_il_nobs, pr.tar_sr_il.shape[0])
        pr.add_pr_a_prices()
        self.assertEqual(sr_il_nobs, pr.tar_sr_il.shape[0])
        pr.assign_prices_to_abc()
        self.assertEqual(sr_il_nobs, pr.tar_sr_il.shape[0])
        pr.generate_event_cost()
        self.assertEqual(sr_il_nobs, pr.tar_sr_il.shape[0])
        pr.tar_sr_il.to_excel(r'T:\organizacyjne_robocze\012_Taryfikator\test\pr.xlsx')

    def test_if_osd_calculates_without_exceptions(self):
        sm = SmCalc('sm', self.query_sm, self.uid, og=self.og.og, fk=self.fk, **self.data_description)
        sm.create_tar()
        sm.filter_opks()
        sm.osd_with_intra_hosp_migrations()
        print('')

    @mock.patch('pytar_calc.shared.helper.Freezer._freeze_df')
    def test_freeze(self, patch):
        wm = WmCalc('wm', self.query_sm, self.uid, og=self.og.og, fk=self.fk, **self.data_description)
        wm.create_tar()
        wm.create_tar_sr_il()
        wm.freeze('tar_sr_il')
        self.assertEqual(patch.call_count, 1)
        wm.freeze(['tar_sr_il', 'tar_sr_il'])
        self.assertEqual(patch.call_count, 3)

    def test_freeze_history(self):
        wm = WmCalc('wm', self.query_sm, self.uid, og=self.og.og, fk=self.fk, **self.data_description)
        num_of_files = len(list((wm.path / 'arch').glob('*')))
        data = {'var': [10, 1, 100, 1],
                'weights': [9, 100, 1, 9],
                'groups': ['g1', 'g1', 'g1', 'g2']
                }
        df = pd.DataFrame(data)
        wm.df = df
        wm.freeze('df')
        data = {'var': [101, 1, 100, 1],
                'weights': [9, 100, 1, 9],
                'groups': ['g1', 'g1', 'g1', 'g2']
                }
        df = pd.DataFrame(data)
        # in spite of two Freezer.freeze calls freezes one file instead of two because second call overrides first file
        wm.freeze('df')
        num_of_files_add_1 = len(list((wm.path / 'arch').glob('*')))
        self.assertEqual(num_of_files + 1, num_of_files_add_1)

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


# 바로 왼쪽의 숫자보다 큰 숫자의 개수는?
# N개의 정수를 입력받아 정수로 리스트에 저장
N = int(input())
arr = list(map(int, input().split()))

cnt = 0
# 탐색구간
for i in range(1, N):
    if(arr[i-1]<arr[i]):
       cnt = cnt + 1
print(cnt)

0814_추가/바로왼쪽보다 큰경우.py

바로왼쪽보다 큰경우.py


import random

# Color dictionary, in r-g-b format.
# Color ranges from 0x0 - 0x7f. The MSB is always enabled.
color_dict = {
    'y': '0xff, 0xc4, 0x80, ',  # Yellow
    'o': '0xfc, 0x8c, 0x80, ',  # Orange
    'r': '0xff, 0x80, 0x80, ',  # Red
    'g': '0x80, 0xff, 0x80, '  # Green
}

acceptable_colors = ['r', 'r', 'y', 'y', 'o', 'o', 'g']

# Transforms a simple txt file to a c-readable array.
# Contains colors for PLD8806 RGB LED strip.
result = '{\n'
for y in range(30):
    result += '\t{ '
    for x in range(32):
        result += color_dict[random.choice(acceptable_colors)]
    result = result[:-2] + ' } ,\n'
result = result[:-3] + '\n};'

print(result)


from tkinter import *
from random import randrange

root = Tk()
root.title("Mon fenêtre avec curseur personnaliser")
cnv =Canvas(root, width=400, height=400)
cnv.pack()

old=None

def rayon(r):
    global old
    r = int(r)
    cnv.delete(old)
    old = cnv.create_oval(200-r,200-r,200+r,200+r)

r = randrange(0,200)
rayon(r)

curseur = Scale(root, orient="horizontal", command=rayon, from_=0, to=200)
curseur.set(r )
curseur.pack()

root.mainloop()

Tkinter/II - Quelques widgets/11 - Gestion de curseur/index.py


#呼叫GPU
import tensorflow as tf
import pandas as pd
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from keras import datasets
from keras.models import Sequential
from keras.layers import Dense, SimpleRNN, LSTM, Dropout, GRU, Attention
#from tensorflow.keras.utils import to_categorical
from keras.utils.np_utils import to_categorical
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.preprocessing import MinMaxScaler
import plotly.express as px
from sklearn.metrics import accuracy_score
import seaborn  as sns
from  matplotlib.ticker import FuncFormatter

import tensorflow.compat.v1.keras.backend as K
import tensorflow as tf
tf.compat.v1.disable_eager_execution()

# from numba import jit, cuda
print("Num GPUs Available: ", len(tf.config.list_physical_devices('GPU')))
def predict(place, output_hr):
    # place = '港濱軸帶'#赤崁園區,港濱軸帶,安平老街,國華海安商圈,孔廟文化園區
    # output_hr = 5
    print(type(output_hr))
    output_hr = int(0 if output_hr is None else output_hr)
    print(type(output_hr))

    min_df = pd.read_excel("D:/crowd-dashboard/data/台南_智發中心_成大產學合作_遊客分時.xlsx", sheet_name = "data sample")
    min_df = min_df[min_df['attraction'] == place]
    min_df['dt_date'] = pd.to_datetime(min_df['dt_date'])
    min_df.sort_values(by = ['dt_date', 'dt_hour'], inplace = True)
    min_df.reset_index(drop = True, inplace = True)
    #display(min_df)
    num_arr = min_df['num']
    num_arr = num_arr.to_list()

    ### 1.2 取得天氣（溫度、降雨）資料
    w_df = pd.read_csv("D:/crowd-dashboard/data/2022_Jun-Sep_溫度(C)_分景點.csv")
    w_df = w_df[place]
    w_df = w_df.to_list()

    r_df = pd.read_csv("D:/crowd-dashboard/data/2022_Jun-Sep_降雨量(mm)_分景點_小雨1,大雨2,強雨3.csv",encoding= 'big5')
    r_df = r_df[place]
    r_df = r_df.to_list()

    ### 1.3 取得票券資料

    t_df = pd.read_csv("D:/crowd-dashboard/data/票證/赤崁樓_票券轉換7_8.csv")
    t_df = t_df['tickets']
    t_df = t_df.to_list()

    ### 1.4 取得假日資料

    h_df = pd.read_csv("D:/crowd-dashboard/data/2022holiday(hour).csv")
    h_df = h_df.drop("Unnamed: 0", axis=1)
    h_df['Sum']= h_df[['Weekend','New year','Spring festival','228 peace memorial day','Childrens’ day','Tomb sweeping day','May day','Dragon boat festival','Moon festival','National day','Highschool winter vacation','Highschool summer vacation','College winter vacation','College summer vacation','Huayuan night market opening day','long weekend','1st day of long weekend','Last day of long weekend','Last day of long weekend']].sum(1)
    h_df = h_df['Sum']
    h_df = h_df.to_list()

    ### 1.5 取得停車資料

    p_df = pd.read_csv("D:/crowd-dashboard/data/停車/停車逐時資料_" + place + ".csv",encoding= 'utf-8')
    p_df = p_df['Parking']
    p_df = p_df.to_list()

    input_hr = 48
    input_dim = 6
    output_hr = 5
    last_hr = input_hr + output_hr

    X=np.empty([len(num_arr) - last_hr, input_dim, input_hr], dtype = float)
    y=np.empty([len(num_arr) - last_hr, output_hr], dtype = float)
    for i in range(len(num_arr) - last_hr):
        #X[i][:][:] = [num_arr[i:i + input_hr], r_df[i:i + input_hr]] #, r_df[i:i + input_hr], w_df[i:i + input_hr], h_df[i:i + input_hr], t_df[i:i + input_hr], p_df[i:i + input_hr]
        X[i][:][:] = [num_arr[i:i + input_hr], r_df[i:i + input_hr], w_df[i:i + input_hr], h_df[i:i + input_hr], t_df[i:i + input_hr], p_df[i:i + input_hr]]#All variables
        #X[i][:][:] = [num_arr[i:i + input_hr], r_df[i:i + input_hr], w_df[i:i + input_hr], h_df[i:i + input_hr],  p_df[i:i + input_hr]]#No Ticket
        y[i][:] = num_arr[i + input_hr:i + last_hr]

    X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 0, test_size = 0.1)

    #if(place == "港濱軸帶" or place == "國華海安商圈"):
    if(place):
        """##### 港濱軸帶"""

        loaded_model = tf.keras.models.load_model("D:/crowd-dashboard/GRU model parameter/" + place + "/" + place + "_人全_200epoch_lr0.1＿best_model.h5".format(place))

        loaded_model.summary()

        y_pred_cmp = loaded_model(X_test)
        y_pred_cmp[0]

        # 引入模組
        #loc = '港濱軸帶'#赤崁園區,港濱軸帶,安平老街,國華海安商圈,孔廟文化園區

        min_df = pd.read_excel("D:/crowd-dashboard/data/台南_智發中心_成大產學合作_遊客分時.xlsx", sheet_name = "data sample")
        min_df = min_df[min_df['attraction'] == place]
        min_df['dt_date'] = pd.to_datetime(min_df['dt_date'])
        min_df.sort_values(by = ['dt_date', 'dt_hour'], inplace = True)
        min_df.reset_index(drop = True, inplace = True)

        num_arr = min_df['num']
        num_arr = num_arr.to_list()

        min_df = pd.concat([min_df,pd.DataFrame(columns=list('a'))])
        transform_dict = {
                        "a":"date_hour"
                        }
        min_df.rename(columns = transform_dict, inplace = True)
        min_df.head()

        from datetime import datetime, timedelta

        initial = np.datetime64('2022-07-01 00:00')

        for i in range(len(min_df)):
            every_hour = (initial + np.timedelta64(i,'h')).copy()
            min_df.loc[i, 'date_hour']= every_hour

        min_df['date_hour']

        n = output_hr
        new_index = pd.RangeIndex(n)
        na_df = pd.DataFrame(np.nan,index=new_index,columns=min_df.columns)
        new_df = pd.concat([min_df,na_df],axis=0)
        new_df.reset_index(drop = True, inplace = True)

        new_df_arr = new_df['num']
        new_df_arr = new_df_arr.to_list()

        # from uncertainties import ufloat
        # import pandas
        # import numpy

        # number_with_uncertainty = ufloat(2,1)

        # df = pandas.DataFrame({'a': [number_with_uncertainty]}) # This line works fine.

        # # create a new column with the correct dtype
        # df.loc[:, 'b'] = numpy.zeros(len(df), dtype=object)

        # df.loc[0,'b'] = ufloat(3,1) # This line now works.

        for m in range(output_hr):
            test = y_pred_cmp[0][m]
            #new_df.loc[:, 'num'] = np.zeros(len(new_df), dtype=object)
            #new_df.loc[len(min_df)+m, 'num'] = test
            new_df.loc[len(min_df)+m]['num'] = test
            #new_df['num'][len(min_df)+m] = test
            new_num_arr = new_df['num']
            new_num_arr = new_num_arr.to_list()

        print(new_df)
        min_df['date_hour']

        for j in range(n):
            future_5hour = (new_df['date_hour'] [len(min_df)+j-1]+ np.timedelta64(1,'h')).copy()
            new_df.loc[len(min_df)+j, 'date_hour']=future_5hour

        new_df

        import seaborn  as sns

        px = 2/plt.rcParams['figure.dpi']
        fig = plt.figure(figsize=(533.2*px, 125*px),constrained_layout =True, dpi = 400)

        ax = sns.pointplot(x="date_hour", y="num", data=new_df[(len(min_df)-input_hr):len(min_df)], color="#294A6E",scale = 0.5)
        g = sns.pointplot(x="date_hour", y="num", data=new_df[(len(min_df)-input_hr):len(new_df)], color="#abd7a7",scale = 0.8)
        plt.setp(g.collections, alpha=.3) #for the markers
        plt.setp(g.lines, alpha=.3)       #for the lines

        bp = sns.barplot(x="date_hour", y="num", data=new_df[(len(min_df)-input_hr):len(new_df)], alpha=0)
            #data=min_df["num"]
        data = new_df[(len(min_df)-input_hr):len(new_df)]
        lst = data["num"].tolist()

        if (len(new_df[(len(min_df)-input_hr):len(new_df)]) < 20):
            labels = ax.bar_label(bp.containers[0])
        print(lst)

    else:
        pass
    #plt.title('Yuguang Island Predicted Crowd Numbers')
    plt.xlabel('Date and Time')
    plt.ylabel('Crowd Numbers')
    plt.xticks(size=6, rotation=60)

    from matplotlib.lines import Line2D
    custom_lines = [Line2D([0], [0], color='#abd7a7', lw=2, alpha = 1),
                    Line2D([0], [0], color='#99b6ac', lw=2)]

    lines = plt.plot()
    output_hr = str(output_hr)
    plt.legend(custom_lines, ['After' + output_hr + 'hours', 'Before 48 hours'])

    plt.savefig('D:/crowd-dashboard/預測資料new/'+ place +'.png', dpi='figure')

    def Average(lst):
        return sum(lst) / len(lst)

    # Driver Code
    #lst = [15, 9, 55, 41, 35, 20, 62, 49]
    #average = Average(lst)
    average = np.nanmean(lst)
    print(average)
    #average = float(average)
    average = int(average)
    print(average)
    return average

place = '港濱軸帶'#赤崁園區,港濱軸帶,安平老街,國華海安商圈,孔廟文化園區
output_hr = 5
predict(place, output_hr)


import redis
import json
from datetime import datetime
from threading import Thread
import socket

redis_app = redis.Redis(host="red01", port=6379)

def make_decision(conn):
    sub = redis_app.pubsub()
    sub.subscribe('messages')

    last_time = datetime.now()
    decision = 0
    for message in sub.listen():
        if message is None:
            continue
        data = message["data"]
        if not isinstance(data, int):
            d = json.loads(data.decode().replace("'", '"'))
            decision += d["payload"]
            diff = datetime.now() - last_time
            if diff.seconds * 1000000 + diff.microseconds > 5000000:
                last_time = datetime.now()
                last_call_reply = last_time.strftime("%Y-%m-%dT%H:%M:%S")
                reply = {"datetime": last_call_reply, "status": "up" if decision >= 0 else "down"}
                conn.sendall(str(reply).encode())
                redis_app.set(str(last_time.timestamp()), "up" if decision >= 0 else "down")
                decision = 0
                print(reply)

def socket_conn():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("0.0.0.0", 7001))
    s.listen()
    while True:
        try:
            print("Connecting")
            conn, address = s.accept()
            print(address)
            thread1 = Thread(target=make_decision,
                           args=[conn])
            thread1.start()
        except KeyboardInterrupt:
            try:
                conn.close()
            except:
                pass
            finally:
                s.close()

if __name__ == "__main__":
    socket_conn()


#Faça um programa que peça a quantidade de números. Em seguida, lê os números e apresenta a média e mostre também os números digitados#

qtd = int(input("Insira uma quantidade de números: "))

numeros = []
acc = 0

for i in range(qtd):
    numero = float(input("Digite o número: "))
    numeros.append(numero)
    acc += numero

media = acc / qtd

print("Os números digitados são:", numeros)
print("E o valor da média é de:", media)


from django.forms import Form
from django.forms.fields import TypedChoiceField
from django.forms.models import ModelChoiceField
from django.forms.widgets import TextInput
from django.db.models import BLANK_CHOICE_DASH
from django.contrib.sites.models import Site
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from treebeard.forms import MoveNodeForm
try:
    from django.utils.six import text_type
except ImportError:  # pragma: no cover
    text_type = unicode
from .utils import _collect_menus, update_all_urls
from .models import MenuItem

class MenuItemTreeForm(MoveNodeForm):
    def __init__(self, *args, **kwargs):
        super(MenuItemTreeForm, self).__init__(*args, **kwargs)
        if 'site' in self.fields:
            self.fields['site'].initial = settings.SITE_ID

        if 'uri' in self.fields:
            self.fields['uri'].widget = TextInput(
                attrs={'required': 'required', 'class': 'vLargeTextField'})

    def save(self, commit=True):
        has_slug = bool(self.instance.menu_slug)
        slug_in_cleaned_data = self.cleaned_data.get('menu_slug', False)
        if has_slug and not slug_in_cleaned_data:
            self.cleaned_data['menu_slug'] = self.instance.menu_slug
        return super(MenuItemTreeForm, self).save(commit=commit)

    class Meta:
        model = MenuItem
        fields = ['path', 'depth', 'numchild', 'menu_slug', 'site', 'title',
                  'uri', 'is_published', '_position', '_ref_node_id']

class ImportMenusForm(Form):
    site = ModelChoiceField(queryset=Site.objects.none(), required=True,
                            label=_("Site"), help_text=_(
                                "The site to import the selected menu into"))
    klass = TypedChoiceField(choices=(), coerce=text_type, required=True,
                             label=_("Menu"), help_text=_(
                                 "Select a configured menu whose URLs you "
                                 "want to add to the given site."))

    def _collected_menus(self):
        return tuple(_collect_menus())

    def _menu_class_choices(self):
        return ((x.path, x.name) for x in self._collected_menus())

    def __init__(self, *args, **kwargs):
        super(ImportMenusForm, self).__init__(*args, **kwargs)
        if 'site' in self.fields:
            self.fields['site'].queryset = Site.objects.all()
            self.fields['site'].initial = settings.SITE_ID

        if 'klass' in self.fields:
            choices = (BLANK_CHOICE_DASH + list(self._menu_class_choices()))
            self.fields['klass'].choices = choices
            if len(choices) <= 1:
                self.fields['klass'].widget.attrs.update({
                    'disabled': 'disabled',
                    'readonly': 'readonly'})
                self.fields['klass'].help_text = _("No menus have been "
                                                   "configured yet")

    # def clean(self):
    #     super(ImportMenusForm, self).clean()
    #     cd = self.cleaned_data
    #     menu_selected = cd.get('existing_menu', None)
    #     new_menu = cd.get('new_menu', None)
    #     if menu_selected and new_menu:
    #         msg = '{menu_label} and {new_label} may not both be selected'
    #         msg_formatted = msg.format(
    #             menu_label=self.fields['existing_menu'].label,
    #             new_label=self.fields['new_menu'].label)
    #         raise ValidationError(msg_formatted)
    #     return cd

    def _menu_class_instance_from_cleaned_data(self):
        klass = self.cleaned_data['klass']
        for menu in self._collected_menus():
            if klass == menu.path:
                return menu.instance
        raise ValueError("Menu instance went missing.")

    def save(self):
        klass = self._menu_class_instance_from_cleaned_data()
        possibilities = tuple(klass.get_urls())
        results = update_all_urls(MenuItem, possibilities)
        if results is not None:
            return tuple(results)
        return None


number = int(input('Please enter a number to verify if it is prime: '))
aux = 0                             # 'aux' will count how many dividers have 'number'

if number < 0:
    print('Please enter a valid number')
else:
    for i in range(1,number+1):
        if number % i == 0:
            aux += 1                # When found a divisor of 'number', 'aux' will count it

if aux == 2:                        # Since primes only have two divisors, 1 and themselves, when 'aux' is 2, then 'number' is prime
    print(number,'is prime')
else:
    print(number,'is not prime')


import asyncio
import os
import logging
from concurrent.futures import FIRST_COMPLETED
from stress import StressCPU
import json
import sys
import time
import urllib.request
import aiohttp

DNS_NAMESPACE = os.getenv('DNS_NAMESPACE')
# STRESS_SIZE = os.getenv('STRESS_SIZE')
STRESS_SIZE = 10

# QUEUE_HOST = "http://demo." + DNS_NAMESPACE + ".svc.cluster.local:80"
QUEUE_HOST= 'http://127.0.0.1:8080'
QUEUE_URL = QUEUE_HOST+'/pull'

class Tasker:
	def __init__(self, loop, session, queue):
		self.loop = loop
		self.session = session
		self.queue = queue

	async def _fetch(self, url, **kwargs):
		# logging.debug("Calling "+url)
		async with self.session.get(url,**kwargs) as response:
			status = response.status
			assert status == 200
			data = await response.text()
			return data

	def __del__(self):
		self.session.close()

class Consumer(Tasker):
	async def __call__(self):
		logging.debug("Checking tasks in queue")
		tasks_computed=[self.loop.create_task(_compute_new_task(self.queue)) for i in range(self.queue.qsize())]
		# tasks_computed=[self.loop.create_task(_compute_new_task(self.queue)) for i in range(10)]
		await self.queue.join()
		completed_tasks=[await res for res in tasks_computed]
		pending_acks=[
			self.loop.create_task(self._fetch(QUEUE_URL,params={'ack':str(id)} ))
			for id
			in completed_tasks]

class Scheduler(Tasker):
	async def __call__(self):
		logging.info("Checking "+ QUEUE_URL+" for new tasks")
		tasks = [self.loop.create_task(self._fetch(QUEUE_URL)) for i in range(21)]

		for t in tasks:
			resp = await t
			id=json.loads(resp)['id']
			if(id):
				_add_to_queue(id,self.queue)

def _add_to_queue(item,queue):
	logging.info("Added new item to the queue with id "+str(item))
	queue.put_nowait(item)
	return(item)

async def _compute_new_task(queue):
	item = await queue.get()
	if (item != None):
		if(STRESS_SIZE):
			stress=StressCPU(stress_size=int(STRESS_SIZE))
		else:
			stress=StressCPU()
		stress.runTest()
		queue.task_done()
		return item
	return

async def _constant_pooling(loop,session,queue):
	s = Scheduler(queue=queue,loop=loop,session=session)
	while True:
		try:
			await s()
		except:
			logging.info("There was an error when executing the loop. Retrying in 2 seconds...")
			await asyncio.sleep(1, loop=loop)
			pass
			# self.loop.close()
			# sys.exit()
		await asyncio.sleep(0.8, loop=loop)

async def _compute_task(loop,session,queue):
	c = Consumer(loop,session,queue)
	while True:
		empty_queue = c.queue.empty()
		if(empty_queue):
			logging.debug("Waiting for elements in the queue")
			await asyncio.sleep(0.1, loop=loop)
		else:
			await c()
		# await asyncio.sleep(1, loop=loop)

def _init_producer(queue,session,loop):
	logging.info("Creating producer")
	producer = loop.create_task(_constant_pooling(queue=queue,loop=loop,session=session))

def _connection_check(url):
	logging.info("Checking connection with "+url)
	status = 0
	while not(status == 200):
		try:
			# con = urllib.request.urlopen(url)
			with urllib.request.urlopen(url) as resp:
				status = resp.getcode()
		except:
			logging.info("Can't connect to "+url+". Retrying in 1s")
			time.sleep(1)
			pass

	logging.info("Connection with "+url+" established...")

def _init_consumer(queue,session,loop):
	logging.info("Creating consumer")
	consumer = loop.create_task(_compute_task(queue=queue,loop=loop,session=session))

def main():
	logging.basicConfig(level=logging.INFO)
	logging.getLogger("asyncio").setLevel(logging.DEBUG)

	logging.info("Starting application")
	# loop.set_debug(True)

	queue = asyncio.Queue()
	loop = asyncio.get_event_loop()
	session = aiohttp.ClientSession(loop=loop)

	_connection_check(QUEUE_HOST+"/status")

	_init_producer(queue=queue,loop=loop,session=session)
	_init_consumer(queue=queue,loop=loop,session=session)

	loop.run_forever()

if __name__ == '__main__':
	main()


"""
Created at 2019-12-22 12:52

@author: jinyanliu
"""
import collections
from enum import Enum

class Method(Enum):
    DEAL_INTO_NEW_STACK = "deal into new stack"
    DEAL_WITH_INCREMENT = "deal with increment"
    CUT = "cut"

def get_instructions_list():
    instructions_list = []
    with open("day_22_input") as lines:
        for line in lines:
            instructions_list.append(line)
    # print(instructions_list)
    return instructions_list

class ShuffleComputer:
    def __init__(self, start_deck):
        self._current_deck = start_deck

    @property
    def current_deck(self):
        return self._current_deck

    @current_deck.setter
    def current_deck(self, value):
        self._current_deck = value

    def deal_with_increment(self, step):
        deck_len = len(self.current_deck)
        new_deck = {}
        new_deck[0] = self.current_deck[0]
        current_old_deck_position = 0
        current_new_deck_position = 0

        while len(new_deck) < len(self.current_deck):
            if current_new_deck_position + step < deck_len:
                new_deck[current_new_deck_position + step] = self.current_deck[current_old_deck_position + 1]
                current_old_deck_position = current_old_deck_position + 1
                current_new_deck_position = current_new_deck_position + step
            else:
                new_deck[current_new_deck_position + step - (deck_len - 1) - 1] = self.current_deck[
                    current_old_deck_position + 1]
                current_old_deck_position = current_old_deck_position + 1
                current_new_deck_position = current_new_deck_position + step - (deck_len - 1) - 1

        # print(self.current_deck)
        # print(new_deck)
        new_deck = collections.OrderedDict(sorted(new_deck.items()))
        self.current_deck = new_deck

    def deal_into_new_stack(self):
        target_list = []
        new_deck = {}
        for value in self.current_deck.values():
            target_list.append(value)
        target_list.reverse()
        i = 0
        for value in target_list:
            new_deck[i] = value
            i += 1

        # print(new_deck)
        self.current_deck = new_deck

    def cut(self, size):
        target_list = []
        new_deck = {}
        for value in self.current_deck.values():
            target_list.append(value)

        if size >= 0:
            new_list = target_list[size:]
            new_list = new_list + target_list[:size]
        else:
            size = abs(size)
            new_list = target_list[:(len(target_list) - size)]
            new_list = target_list[(len(target_list) - size):] + new_list
        i = 0
        for value in new_list:
            new_deck[i] = value
            i += 1

        # print(new_deck)
        self.current_deck = new_deck

    def get_position_of_card(self, card_number):
        for key, value in self.current_deck.items():
            if card_number == value:
                return key

    def get_instructions_and_actions(self):
        return {
            Method.DEAL_WITH_INCREMENT.value: self.deal_with_increment,
            Method.DEAL_INTO_NEW_STACK.value: self.deal_into_new_stack,
            Method.CUT.value: self.cut
        }

def get_solution_1():
    map_dict = {}
    for i in range(0, 10007):
        map_dict[i] = i

    computer = ShuffleComputer(map_dict)

    for instruction in get_instructions_list():
        if Method.DEAL_WITH_INCREMENT.value in instruction:
            input = [int(s) for s in str.split(instruction) if s.isdigit()][0]
            computer.get_instructions_and_actions()[Method.DEAL_WITH_INCREMENT.value](input)
        elif Method.DEAL_INTO_NEW_STACK.value in instruction:
            computer.get_instructions_and_actions()[Method.DEAL_INTO_NEW_STACK.value]()
        elif Method.CUT.value in instruction:
            input = int(instruction.split(" ")[1])
            computer.get_instructions_and_actions()[Method.CUT.value](input)

    print(computer.current_deck)

    return computer.get_position_of_card(2019)

if __name__ == "__main__":
    print(get_solution_1())


# Author: Olga Sotiriadi
# Lab:8
# Date:03.04.2022
# Purpose: Time Calculator
import pathlib
import tkinter as tk
import tkinter.ttk as ttk
import pygubu
import tkinter.messagebox as mb

PROJECT_PATH = pathlib.Path(__file__).parent
PROJECT_UI = PROJECT_PATH / "TimeCalc.ui"

class TimecalcApp:
    SEC_PER_DAY = 86400
    SEC_PER_HOUR = 3600
    SEC_PER_MIN = 60

    def __init__(self, master=None):
        # Boilerplate to build the tkinter interface based on TimeCalc.ui
        self.__builder = builder = pygubu.Builder()
        builder.add_resource_path(PROJECT_PATH)
        builder.add_from_file(PROJECT_UI)
        self.__mainwindow = builder.get_object('top_level', master)
        builder.connect_callbacks(self)

        # Save these UI elements as properties so that we can access them when
        # the user clicks on the calculate button.
        self.__days_entry = builder.get_object('days_entry', master)
        self.__hours_entry = builder.get_object('hours_entry', master)
        self.__minutes_entry = builder.get_object('minutes_entry', master)
        self.__seconds_entry = builder.get_object('seconds_entry', master)
        self.__result_entry_variable = builder.get_variable('result_entry_variable')

    def calculate(self):
        # Convert days, hours, minutes and seconds to seconds. If there's an error, display an error message.
        try:
            days = float(self.__days_entry.get())
            hours = float(self.__hours_entry.get())
            minutes = float(self.__minutes_entry.get())
            seconds = float(self.__seconds_entry.get())
            total_seconds = self.SEC_PER_DAY * days + self.SEC_PER_HOUR * hours + self.SEC_PER_MIN * minutes + seconds
            self.__result_entry_variable.set("{:.2f} seconds".format(total_seconds))
        except ValueError:
            mb.showerror(title="Error Calculating!", message="Please try again.")

    def run(self):
        self.__mainwindow.mainloop()

    def get_top_frame(self):
        # Return the top frame for the app so that it can be displayed in a tabbed notebook.
        return self.__mainwindow

    def clear(self):
        self.__days_entry.delete(0, tk.END)
        self.__hours_entry.delete(0, tk.END)
        self.__minutes_entry.delete(0, tk.END)
        self.__seconds_entry.delete(0, tk.END)

if __name__ == '__main__':
    root = tk.Tk()
    root.title("Time Calculator")
    app = TimecalcApp(root)
    app.run()


from Superarray import Superarray

class Supermatriz(Superarray):
    def __init__(self, numero_de_linhas, numero_de_colunas):
        super().__init__(1, numero_de_linhas) #chamando os atributos da classe Superarray

        #definindo o num de col, linhas e matriz padrao
        self.__liminf_col = 1
        self.__limsup_col = numero_de_colunas
        self.__matriz = [[None]*numero_de_colunas for _ in range(numero_de_linhas)]

    def atribuir(self, linha, coluna, valor):
        # verifico se os valores informados para linha e coluna estao fora dos limites do construtor
        # para verificar linha, pego os limites do superarray
        # dispara exceção se tiver fora dos limites
        if (linha > self.limsup or linha < self.liminf or
            coluna > self.__limsup_col or coluna < self.__liminf_col
        ):
            raise ValueError('Posição informada esta fora dos limites da matriz')

        else:
            # subtrai os liminf para obter o indice correto matematico de uma matriz
            self.__matriz[linha - self.liminf][coluna - self.__liminf_col] = valor

    def acessar(self,linha, coluna):
        if (linha > self.limsup or linha < self.liminf or
            coluna > self.__limsup_col or coluna < self.__liminf_col
        ):
            raise ValueError('Posição informada esta fora dos limites da matriz')

        else:
            return self.__matriz[linha-self.liminf][coluna-self.__liminf_col]

    def imprimir(self):
        for linha in self.__matriz:
            print(linha)


import os

import yaml
import numpy as np
import pandas as pd
from tqdm import tqdm
from numba import jit

import indicators

def get_config(config_path):
	with open(config_path) as f:
		config = yaml.load(f, Loader = yaml.FullLoader)
	return config

def get_fx_file_paths(fx_pair, agg_level, agg_magnitude, tech_indicators, data_dir, is_test = False,
    train_end = '2019-02-01'):
    input_path = os.path.join(data_dir, 'csv')
    output_path = os.path.join(data_dir, 'npy')
    train_end = np.datetime64(train_end)
    phases = ['train', 'test']
    file_paths = {phase :
        os.path.join(output_path,
            f"""{fx_pair.upper()}_{str(agg_magnitude)}_{agg_level}_{phase}_{'_'.join([str(y)
                for x in list(tech_indicators.items())
                for y in x]).replace(', ', '_')}.npy""")
        for phase in phases}
    # Return if data exists
    if os.path.exists(file_paths['train']):
        return file_paths['train']
    # Otherwise create it
    print(f'Creating data {file_paths}')
    file_list = [x for x in os.listdir(input_path) if fx_pair in x]
    fx_npy = {x : None for x in phases}
    for file_name in tqdm(file_list, total = len(file_list)):
        # Read file and setup
        df = pd.read_csv(os.path.join(input_path, file_name), header = None,
            names = ['fx_pair', 'timestamp', 'bid', 'ask'])
        df = df.drop('fx_pair', axis = 1)
        df['timestamp'] = pd.to_datetime(df['timestamp'],
            format = '%Y%m%d %H:%M:%S.%f')
        df = df.dropna()
        df = df[['timestamp', 'bid', 'ask']]
        df['price'] = df[['bid', 'ask']].mean(axis = 1)
        df = df.drop(['bid', 'ask'], axis = 1)
        # Set phase
        if df['timestamp'].max() < train_end:
            phase = 'train'
        else:
            phase = 'test'
        # Aggregate data at level and magnitude
        df = df.set_index('timestamp')
        df = df.resample(f'{agg_magnitude}{agg_level}',
            label = 'right').ohlc()['price'].reset_index()
        df['timestamp'] = df['timestamp'].astype(int)
        # Calc technical indicators
        for indicator,params in tech_indicators.items():
            if indicator == 'macd':
                df = indicators.macd(df, *params)
            elif indicator == 'rsi':
                df = indicators.rsi(df, *params)
            elif indicator == 'adx':
                df = indicators.adx(df, *params)
            else:
                raise Exception(f'Unrecognized technical indicator {indicator}')
        # Add to phase numpy array
        df_np = df.dropna().to_numpy()
        assert np.sum(np.isnan(df_np)) == 0
        if fx_npy[phase] is None:
            fx_npy[phase] = df_np
        else:
            fx_npy[phase] = np.vstack([fx_npy[phase], df_np])

    for phase in fx_npy.keys():
        np.save(file_paths[phase], fx_npy[phase])
    file_path = file_paths['test'] if is_test else file_paths['train']
    return file_path

@jit(nopython = True)
def calc_exit_price(tick_data, start_index, position, stop_loss, pip_size, enter_price):
    stop_loss_amount = stop_loss * pip_size
    if position == 'long':
        max_price = enter_price
        for i in range(start_index,tick_data.shape[0]):
            _, bid, ask = tick_data[i,:]
            stop_loss_price = max_price - stop_loss_amount
            if max_price < bid:
                max_price = bid
                continue
            elif bid <= stop_loss_price:
                return stop_loss_price
            elif i == (tick_data.shape[0] - 1):
                return bid
    elif position == 'short':
        min_price = enter_price
        for i in range(start_index,tick_data.shape[0]):
            _, bid, ask = tick_data[i,:]
            stop_loss_price = min_price + stop_loss_amount
            if min_price > ask:
                min_price = ask
                continue
            elif ask >= stop_loss_price:
                return stop_loss_price
            elif i == (tick_data.shape[0] - 1):
                return ask
    else:
        return np.nan


from keras import backend as K
from keras import optimizers
from keras.callbacks import ModelCheckpoint, CSVLogger, ReduceLROnPlateau
from keras.engine import InputSpec
from keras.engine.topology import Layer
from keras.layers import Bidirectional, Concatenate, Dense, Dropout, Embedding, Input, LSTM
from keras.models import Model
import numpy as np

__author__ = 'avijitv'

class TemporalMaxPooling(Layer):
    def __init__(self, **kwargs):
        super(TemporalMaxPooling, self).__init__(**kwargs)
        self.supports_masking = True
        self.input_spec = InputSpec(ndim=3)

    def compute_output_shape(self, input_shape):
        return input_shape[0], input_shape[2]

    def call(self, x, mask=None):
        if mask is None:
            mask = K.sum(K.ones_like(x), axis=-1)

        # if masked, set to large negative value so we ignore it when taking max of the sequence
        # K.switch with tensorflow backend is less useful than Theano's
        if K._BACKEND == 'tensorflow':
            mask = K.expand_dims(mask, axis=-1)
            mask = K.tile(mask, (1, 1, K.int_shape(x)[2]))
            masked_data = K.tf.where(K.equal(mask, K.zeros_like(mask)),
                K.ones_like(x)*-np.inf, x)  # if masked assume value is -inf
            return K.max(masked_data, axis=1)
        else:  # theano backend
            mask = mask.dimshuffle(0, 1, "x")
            masked_data = K.switch(K.eq(mask, 0), -np.inf, x)
            return masked_data.max(axis=1)

    def compute_mask(self, input, mask):
        # do not pass the mask to the next layers
        return None

class MaxPoolBiLSTM:
    def __init__(self, config, vocab_size, embedding_matrix, max_seq_len, name='encoder'):
        self.embedding_dim = config['word_embedding_dim']
        self.vocab_size = vocab_size
        self.embedding_matrix = embedding_matrix
        self.max_seq_len = max_seq_len
        self.lstm_unit_dim = config['BiLSTM-Max']['lstm_unit_dim']
        self.encoding_dropout = config['encoding_dropout']
        self.name = name

    def get_model(self):
        seq_input = Input(shape=(self.max_seq_len,), dtype='int32', name=self.name + '_input')

        word_embedding = Embedding(output_dim=self.embedding_dim,
                                   input_dim=self.vocab_size,
                                   weights=[self.embedding_matrix],
                                   mask_zero=True,
                                   input_length=self.max_seq_len,
                                   trainable=False)(seq_input)
        bilstm = Bidirectional(LSTM(units=self.lstm_unit_dim,
                                    return_sequences=True))(word_embedding)

        encoding = TemporalMaxPooling()(bilstm)
        encoding = Dropout(self.encoding_dropout, name=self.name)(encoding)
        return encoding, seq_input

# TODO: DEBUG !!! Val Loss not decreasing
# TODO: Add support for other encoder architectures (LSTM, GRU, BiGRU, BiLSTM-Mean, Self-Attentive, Hier-Conv)
# TODO: Add support for non-linear final classification and multi-hidden layers post encoding
class NLIClassifier:
    def __init__(self, config, vocab_size, embedding_matrix, max_seq_len):
        if config['encoder']['type'] == 'BiLSTM-Max':
            self.premise_encoder, self.premise_input = MaxPoolBiLSTM(config=config['encoder'],
                                                                     vocab_size=vocab_size,
                                                                     embedding_matrix=embedding_matrix,
                                                                     max_seq_len=max_seq_len,
                                                                     name='premise_encoder').get_model()
            self.hypothesis_encoder, self.hypothesis_input = MaxPoolBiLSTM(config=config['encoder'],
                                                                           vocab_size=vocab_size,
                                                                           embedding_matrix=embedding_matrix,
                                                                           max_seq_len=max_seq_len,
                                                                           name='hypothesis_encoder').get_model()
        else:
            raise ValueError('Encoder not implemented')

        self.encoder_type = config['encoder']['type']
        self.path = config['path']
        self.classification_hidden_units = config['classification']['hidden_units']
        self.classification_dropout = config['classification']['dropout']
        self.n_classes = 3

        self.optimizer_type = config['training']['optimizer']
        self.init_lr = config['training']['init_lr']
        self.clipnorm = config['training']['clipnorm']
        self.batch_size = config['training']['batch_size']
        self.epochs = config['training']['epochs']
        self.model = None
        self.encoder_model = None
        self.optimizer = None
        self.get_model()

    def get_model(self):
        merged = Concatenate()([self.premise_encoder, self.hypothesis_encoder])
        classification_hidden = Dense(units=self.classification_hidden_units, activation='linear')(merged)
        classification_hidden = Dropout(self.classification_dropout)(classification_hidden)
        final = Dense(units=self.n_classes, activation='softmax')(classification_hidden)

        self.model = Model(inputs=[self.premise_input, self.hypothesis_input], output=final)
        print('NLI Classifier model -')
        print()
        print(self.model.summary())
        if self.optimizer_type == 'rmsprop':
            self.optimizer = optimizers.RMSprop(lr=self.init_lr, clipnorm=self.clipnorm)
        elif self.optimizer_type == 'adam':
            self.optimizer = optimizers.Adam(lr=self.init_lr, clipnorm=self.clipnorm)
        elif self.optimizer_type == 'sgd':
            self.optimizer = optimizers.SGD(lr=self.init_lr, clipnorm=self.clipnorm)
        else:
            raise ValueError('Optimizer not implemented')

        self.model.compile(optimizer=self.optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
        self.encoder_model = K.function([self.model.get_layer('premise_encoder_input').input],
                                        [self.model.get_layer('premise_encoder').output])

    def fit(self, s1_train_x, s2_train_x, train_y,
            s1_dev_x, s2_dev_x, dev_y):
        lr_plateau = ReduceLROnPlateau(monitor='val_acc', factor=0.2, mode='max',
                                       patience=1, verbose=1, min_lr=0.0001)

        csv_logger = CSVLogger('{0}/{1}_training.log'.format(self.path,
                                                             self.encoder_type))

        checkpointer = ModelCheckpoint(filepath='{0}/{1}.hdf5'.format(self.path,
                                                                      self.encoder_type),
                                       monitor='val_acc', verbose=1, save_best_only=True)

        history = self.model.fit(x=[s1_train_x, s2_train_x],
                                 y=train_y,
                                 batch_size=self.batch_size,
                                 epochs=self.epochs,
                                 validation_data=([s1_dev_x, s2_dev_x], dev_y),
                                 callbacks=[lr_plateau, csv_logger, checkpointer])
        return history

    def predict(self, s1_x, s2_x):
        return self.model.predict(x=[s1_x, s2_x])

    def encode(self, s1_x):
        return self.encoder_model([s1_x])[0]


from tkinter import *

root=Tk()

root.title('Rizzeria')

root.maxsize(800,1000)
root.minsize(800,1000)

logo_img = PhotoImage(file='C:\\Users\\Admin\\Desktop\\Rizzeria\\logo.png')

logo_label = Label(root,image=logo_img, borderwidth=0, highlightthickness=0)
logo_label.pack(pady=10)

root.configure(background='#1C1C1C')

nav_frame = Frame(root, bg="#1C1C1C")
nav_frame.pack(side=TOP, fill=X)

home_button = Button(nav_frame, text="Home", fg="white", bg="#1C1C1C", font=("Arial", 12, "bold"), padx=60)
home_button.pack(side=LEFT, padx=10)

menu_button = Button(nav_frame, text="Menu", fg="white", bg="#1C1C1C", font=("Arial", 12, "bold"), padx=60)
menu_button.pack(side=LEFT, padx=10)

about_button = Button(nav_frame, text="About", fg="white", bg="#1C1C1C", font=("Arial", 12, "bold"), padx=60)
about_button.pack(side=LEFT, padx=10)

contact_button = Button(nav_frame, text="Contact", fg="white", bg="#1C1C1C", font=("Arial", 12, "bold"), padx=60)
contact_button.pack(side=LEFT, padx=10)

hero_frame = Frame(root, bg="#1C1C1C")
hero_frame.pack(fill=X)

hero_text = Label(hero_frame, text="Rizz-ify your taste buds with our signature pizzas", fg="white", bg="#1C1C1C", font=("Arial", 24, "bold"), pady=30)
hero_text.pack()

search_frame = Frame(root, bg="#1C1C1C")
search_frame.pack(pady=20)

search_label = Label(search_frame, text="Search:", fg="white", bg="#1C1C1C", font=("Arial", 16, "bold"))
search_label.pack(side=LEFT, padx=10)

search_entry = Entry(search_frame, width=50, font=("Arial", 14))
search_entry.pack(side=LEFT)

menu_frame = Frame(root, bg="#1C1C1C")
menu_frame.pack(pady=20)

menu_label = Label(menu_frame, text="Menu:", fg="white", bg="#1C1C1C", font=("Arial", 20, "bold"))
menu_label.pack()

menu_list = Listbox(menu_frame, width=50,height=5, font=("Arial", 20),bg="Crimson",fg="white", justify=CENTER)
menu_list.pack(pady=10)

menu_items = ['Rizz-tastic Pizza', 'Rizzi-licious Pizza', 'Rizz-otto Pizza', 'Rizz-oni Pizza', 'Rizz and Cheese', 'Rizz-a-lotta']
for item in menu_items:
    menu_list.insert(END, item)

cta_frame = Frame(root, bg="#1C1C1C")
cta_frame.pack(fill=X, pady=30)

order_button = Button(cta_frame, text="Order Now", fg="white", bg="crimson", font=("Arial", 16, "bold"), padx=20, pady=10)
order_button.pack(side=LEFT, padx=50)

coupon_button = Button(cta_frame, text="Get Coupons", fg="white", bg="crimson", font=("Arial", 16, "bold"), padx=20, pady=10)
coupon_button.pack(side=LEFT, padx=50)

gift_button = Button(cta_frame, text="Gift Cards", fg="white", bg="crimson", font=("Arial", 16, "bold"), padx=20, pady=10)
gift_button.pack(side=LEFT, padx=50)

root.mainloop()


"""empty message

Revision ID: 76fdf3992bab
Revises: 1e480ccc916b
Create Date: 2022-01-27 12:05:33.967430

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '76fdf3992bab'
down_revision = '1e480ccc916b'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    system_settings = op.create_table('system_settings',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('mail', sa.JSON(), nullable=False),
    sa.Column('calendar', sa.JSON(), nullable=False),
    sa.PrimaryKeyConstraint('id', name=op.f('pk_system_settings'))
    )
    # ### end Alembic commands ###

    op.execute(
        system_settings.insert().values(
            mail={'MAIL_SERVER': None, 'MAIL_PORT': 587, 'MAIL_USE_TLS': True, 'MAIL_USE_SSL': True, 'MAIL_SENDER': None},
            calendar={'CALENDAR_LINK': None, 'CALENDAR_CATEGORIES': [], 'CALENDAR_SYNC_INTERVALL': 5}
        )
    )

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('system_settings')
    # ### end Alembic commands ###