import argparse
import logging
import os.path
import sys

# check that requirements are installed here
try:
    # pylint: disable=unused-import
    import pyparsing
    import jinja2
except ModuleNotFoundError as exc:
    print("Cannot import `%s`, you probably need to install it. See `generator/requirements.txt` or `README.md`." % exc.name, file=sys.stderr)
    sys.exit(2)

from flatdata.generator.engine import Engine
from flatdata.generator.tree.errors import FlatdataSyntaxError

def _parse_command_line():
    parser = argparse.ArgumentParser(
        description="Generates code for a given flatdata schema file.")
    parser.add_argument("-s", "--schema", type=str, required=True,
                        help="Path to the flatdata schema file")
    parser.add_argument("-g", "--gen", type=str, required=True,
                        help="Language to generate bindings for. Supported values: %s" %
                        (', '.join(Engine.available_generators())))
    parser.add_argument("-O", "--output-file", type=str, required=True,
                        default=None,
                        help="Destination file. Forces all output to be stored in one file")
    parser.add_argument("-v", "--verbose", action="store_true",
                        help="Enable verbose mode")
    parser.add_argument("--debug", action="store_true",
                        help="Enable debug output")
    return parser.parse_args()

def _setup_logging(args):
    level = logging.WARNING
    if args.debug:
        level = logging.DEBUG
    elif args.verbose:
        level = logging.INFO

    logging.basicConfig(
        format="%(asctime)s - %(levelname)s - %(module)s:%(lineno)d - %(message)s",
        datefmt="%H:%M:%S",
        level=level)

def _check_args(args):
    if not os.path.isfile(args.schema):
        logging.fatal("Cannot find schema file at %s", args.schema)
        sys.exit(1)

def _run(args):
    _setup_logging(args)
    _check_args(args)

    with open(args.schema, 'r') as input_file:
        schema = input_file.read()
        try:
            engine = Engine(schema)
            logging.debug("Tree: %s", engine.tree)
        except FlatdataSyntaxError as ex:
            logging.fatal("Error reading schema: %s ", ex)
            sys.exit(1)

    try:
        logging.info("Generating %s...", args.gen)
        output_content = engine.render(args.gen)
    except ValueError as ex:
        logging.fatal("%s", ex)
        sys.exit(1)

    dirname = os.path.dirname(os.path.abspath(args.output_file))
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    with open(args.output_file, "w") as output:
        output.write(output_content)
        logging.info("Code for %s is written to %s", args.gen, args.output_file)

def main():
    """Entrypoint"""
    _run(_parse_command_line())


from django.core.management.base import BaseCommand
from pta.models import TeamMember

class OurTeam:
    member = (
        ('Chen Chen','Chen Chen is a Senior in Computer Science at Kennesaw State University.  He enjoys many MOBA games like League of Legends, Overwatch, and Heroes of the Storm.','ChenChen.jpg'),
        ('Jeremy Sloan','I am a senior majoring in computer science from Ga. I graduate in the spring of 2018. I hope True Detective season 3 is better than season 2.','jeremysloan.png'),
        ('Ross Taylor','Ross Taylor is a Senior at KSU graduating in December with a degree in Computer Science.','RossTaylor.jpg'),
        ('Suat Iskender','Suat Iskender is a Senior in Computer Science at Kennesaw State University.  He joined the Collaborate! team in July.  When he is not coding, he enjoys long walks in the park and playing Heroes of the Storm.','SuatIskender.jpg'),
    )

class Command(BaseCommand):
    help = "add in team member information"

    def handle(self, *args, **options):
        for person in OurTeam.member:
            per = TeamMember(
                fullname=person[0],
                description=person[1],
                imagename=person[2]
            )
            per.save()


from odoo import api, fields, models, _
from odoo.exceptions import UserError

class StockMove(models.Model):
    _inherit = 'stock.move'

    branch_id = fields.Many2one('res.branch')

    def _assign_picking(self):
        """ Try to assign the moves to an existing picking that has not been
        reserved yet and has the same procurement group, locations and picking
        type (moves should already have them identical). Otherwise, create a new
        picking to assign them to. """
        Picking = self.env['stock.picking']
        for move in self:
            move.branch_id = self.group_id.sale_id.branch_id.id
            recompute = False
            picking = move._search_picking_for_assignation()
            if picking:
                if picking.partner_id.id != move.partner_id.id or picking.origin != move.origin:
                    # If a picking is found, we'll append `move` to its move list and thus its
                    # `partner_id` and `ref` field will refer to multiple records. In this
                    # case, we chose to  wipe them.
                    picking.write({
                        'partner_id': False,
                        'origin': False,
                    })
            else:
                recompute = True
                picking = Picking.create(move._get_new_picking_values())
            move.write({'picking_id': picking.id})
            move._assign_picking_post_process(new=recompute)
            # If this method is called in batch by a write on a one2many and
            # at some point had to create a picking, some next iterations could
            # try to find back the created picking. As we look for it by searching
            # on some computed fields, we have to force a recompute, else the
            # record won't be found.
            if recompute:
                move.recompute()
        return True

    def _get_new_picking_values(self):
        vals = super(StockMove, self)._get_new_picking_values()
        vals['branch_id'] = self.group_id.sale_id.branch_id.id
        return vals

    def _create_account_move_line(self, credit_account_id, debit_account_id, journal_id):
        self.ensure_one()
        AccountMove = self.env['account.move']
        quantity = self.env.context.get('forced_quantity', self.product_qty)
        quantity = quantity if self._is_in() else -1 * quantity

        # Make an informative `ref` on the created account move to differentiate between classic
        # movements, vacuum and edition of past moves.
        ref = self.picking_id.name
        if self.env.context.get('force_valuation_amount'):
            if self.env.context.get('forced_quantity') == 0:
                ref = 'Revaluation of %s (negative inventory)' % ref
            elif self.env.context.get('forced_quantity') is not None:
                ref = 'Correction of %s (modification of past move)' % ref

        move_lines = self.with_context(forced_ref=ref)._prepare_account_move_line(quantity, abs(self.value), credit_account_id, debit_account_id)
        if move_lines:
            date = self._context.get('force_period_date', fields.Date.context_today(self))
            new_account_move = AccountMove.sudo().create({
                'journal_id': journal_id,
                'line_ids': move_lines,
                'date': date,
                'ref': ref,
                'stock_move_id': self.id,
                'branch_id': self.picking_id.branch_id.id
            })
            new_account_move.post()

    def _generate_valuation_lines_data(self, partner_id, qty, debit_value, credit_value, debit_account_id, credit_account_id):
        # This method returns a dictonary to provide an easy extension hook to modify the valuation lines (see purchase for an example)
        self.ensure_one()
        if self._context.get('forced_ref'):
            ref = self._context['forced_ref']
        else:
            ref = self.picking_id.name

        debit_line_vals = {
            'name': self.name,
            'product_id': self.product_id.id,
            'quantity': qty,
            'product_uom_id': self.product_id.uom_id.id,
            'ref': ref,
            'partner_id': partner_id,
            'debit': debit_value if debit_value > 0 else 0,
            'credit': -debit_value if debit_value < 0 else 0,
            'account_id': debit_account_id,
            'branch_id':self.picking_id.branch_id.id
        }

        credit_line_vals = {
            'name': self.name,
            'product_id': self.product_id.id,
            'quantity': qty,
            'product_uom_id': self.product_id.uom_id.id,
            'ref': ref,
            'partner_id': partner_id,
            'credit': credit_value if credit_value > 0 else 0,
            'debit': -credit_value if credit_value < 0 else 0,
            'account_id': credit_account_id,
            'branch_id': self.picking_id.branch_id.id
        }

        rslt = {'credit_line_vals': credit_line_vals, 'debit_line_vals': debit_line_vals}
        if credit_value != debit_value:
            # for supplier returns of product in average costing method, in anglo saxon mode
            diff_amount = debit_value - credit_value
            price_diff_account = self.product_id.property_account_creditor_price_difference
            if not price_diff_account:
                price_diff_account = self.product_id.categ_id.property_account_creditor_price_difference_categ
            if not price_diff_account:
                raise UserError(_('Configuration error. Please configure the price difference account on the product or its category to process this operation.'))

            rslt['price_diff_line_vals'] = {
                'name': self.name,
                'product_id': self.product_id.id,
                'quantity': qty,
                'product_uom_id': self.product_id.uom_id.id,
                'ref': ref,
                'partner_id': partner_id,
                'credit': diff_amount > 0 and diff_amount or 0,
                'debit': diff_amount < 0 and -diff_amount or 0,
                'account_id': price_diff_account.id,
                'branch_id': self.picking_id.branch_id.id
            }
        return rslt


import code
import brackets
import sys
import argparse
import brackets.importer
from brackets.helpers import eval, exec, compile
from brackets import exception_handler

USAGE = "%(prog)s [-h | -c cmd | file | -] [arg] ..."
VERSION = "%(prog)s " + brackets.__version__
EPILOG = """  file         program read from script
  -            program read from stdin
  [arg] ...    arguments passed to program in sys.argv[1:]
"""
BANNER = "Brackets %s\nRunning Python %s on %s\n" % (brackets.__version__, sys.version, sys.platform)

class Console(code.InteractiveConsole):
    def __init__(self, spy=False, source='', *args, **kwargs):
        self.spy = spy
        super().__init__(*args, **kwargs)
        self.runsource('from brackets import *')
        if source:
            self.runsource(source)

    def runsource(self, source, filename="<input>", symbol="single"):
        try:
            code, debug, original = brackets.translate(source)
        except:
            if source.endswith('\n'):
                # Case 1
                self.showsyntaxerror(filename)
                return False
            else:
                return True

        if code is None:
            # Case 2
            return True

        # Case 3
        if self.spy:
            print(('-'*80)+'\n{0}'.format(code)+('-'*80))
        self.runcode(code)
        return False

def shell(scriptname, argv):
    parser = argparse.ArgumentParser(
        prog="brackets",
        usage=USAGE,
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=EPILOG)

    parser.add_argument("-c", dest="command",
                        help="program passed in as a string")

    parser.add_argument("--spy", action="store_true",
                        help="print equivalent Python code before executing")

    parser.add_argument("-v", "--version", action="version", version=VERSION)

    # this will contain the script/program name and any arguments for it.
    parser.add_argument('args', nargs=argparse.REMAINDER,
                        help=argparse.SUPPRESS)

    # stash the brackets executable in case we need it later
    # mimics Python sys.executable
    brackets.executable = argv[0]

    options = parser.parse_args(argv[1:])

    # reset sys.argv like Python
    sys.argv = options.args

    if options.command:
        # User did "brackets -c ..."
        return run_command(options.command)

    if options.args:
        if options.args[0] == "-":
            # Read the program from stdin
            return run_command(sys.stdin.read())

        else:
            # User did "brackets <filename>"
            return run_file(options.args[0])

    # User did NOTHING!
    return run_repl(spy=options.spy)

def run_repl(spy):
    sys.exit(Console(spy).interact(banner=BANNER))

def run_command(command):
    code, debug, original = brackets.translate(command)
    try:
        sys.exit(Console().runcode(code))
    except Exception as e:
        exception_handler(e, debug, original)

def run_file(file):
    brackets.importer.BracketsLoader('__brackets_main__', file).load_module('__brackets_main__')

def main():
    sys.exit(shell("brackets", sys.argv))

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function
from io import TextIOWrapper
import csv
import re
import six
from mogi.models.models_isa import StudySample, StudyFactor, SampleType, OrganismPart, Organism, Study, Investigation
from mogi.utils.ontology_utils import check_and_create_ontology

def check_and_create_model(name, model_to_check, db_alias=''):
    # check if we have the organism
    # if we do return the pk

    qs = model_to_check.objects.filter(ontologyterm__name=name)

    if qs:
        return qs[0]

    # if we do not have the organism name, check ontology
    # if we do have an ontology create the organism with the ontology and return the pk
    ont_ids = check_and_create_ontology(name, db_alias=db_alias)

    ob = model_to_check(ontologyterm_id=ont_ids[0])
    ob.name = ob.ontologyterm.name
    ob.public = True
    if db_alias:
        ob.save(using=db_alias)
    else:
        ob.save()

    return ob

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

def check_and_create_study_factor(study_factor_type, study_factor_value, study_factor_unit=''):
    # Check if we have the study factor type already. If not, check ontology and add.
    study_factor_type_ont_id = check_and_create_ontology(study_factor_type)[0]

    # Check if we have the study factor unit, if not check ontology and add
    if study_factor_unit:
        study_factor_unit_id = check_and_create_ontology(study_factor_unit)[0]
    else:
        study_factor_unit_id = None

    # Check if we have the study factor value, if not check ontology and add
    if is_number(study_factor_value):
        value = study_factor_value
        study_factor_value_ont_id = None
    else:
        value = None
        study_factor_value_ont_id = check_and_create_ontology(study_factor_value)[0]

    sf_qs = StudyFactor.objects.filter(ontologyterm_type_id=study_factor_type_ont_id,
                                       value=value,
                                       ontologyterm_unit_id=study_factor_unit_id,
                                       ontologyterm_value_id=study_factor_value_ont_id)
    if sf_qs:
        return sf_qs[0]
    else:
        # if not create a new study factor
        studyfactor = StudyFactor(ontologyterm_type_id=study_factor_type_ont_id,
                                           value=value,
                                           ontologyterm_unit_id=study_factor_unit_id,
                                           ontologyterm_value_id=study_factor_value_ont_id)

        studyfactor.save()
        return studyfactor

def sample_batch_create(sample_list, study_default='', replace_duplicates=False, delimiter='\t'):
    reader = csv.reader(TextIOWrapper(sample_list, encoding='ascii', errors='replace'), delimiter=delimiter)

    # Get indexes of column. Can use either ISA style study file or simplified version
    cols = next(reader)
    idxs = {'study_factors': {}}
    fc = 0
    for i, col in enumerate(cols):
        if col.lower() == 'investigation':
            idxs['investigation'] = i
        elif col.lower() == 'study':
            idxs['study'] = i
        if col == 'Characteristics[Organism]' or col == 'organism':
            idxs['organism'] = i
        elif col == 'Characteristics[Organism part]' or col == 'organism_part':
            idxs['organism_part'] = i
        elif col == 'Source Name' or col == 'source_name':
            idxs['source_name'] = i
        elif col == 'Sample Name' or col == 'sample_name':
            idxs['sample_name'] = i
        elif col == 'sample_type':
            idxs['sample_type'] = i
        else:
            match_type = re.match('^(?:Factor Value|factor_)\[(.*)\]$', col)
            if match_type:
                fc += 1
                fc_type = match_type.group(1)

                idxs['study_factors'][fc] = {
                    'value': i,
                    'unit': '',
                    'type': fc_type
                }

            if fc:
                match_unit = re.match('(?:Unit|factor_\[.*\]_unit)$', col)
                if match_unit:
                    idxs['study_factors'][fc]['unit'] = i

    for row in reader:

        # get organism and check if we have relevant ontology (if not add best match)
        organism = check_and_create_model(row[idxs['organism']], Organism)
        # same for organism type
        organism_part = check_and_create_model(row[idxs['organism_part']], OrganismPart)

        # get sample type (if not defined will either be blank or animal depending on sample name)
        if 'sample_type' in idxs.keys():
            st_qs = SampleType.objects.filter(type=row[idxs['sample_type']])
            if st_qs:
                sampletype = st_qs[0]
        else:
            if re.match('.*blank.*', row[idxs['sample_name']], re.IGNORECASE):
                sampletype = SampleType.objects.get(type='BLANK')  # defaults to animal if no sampletype giv
            else:
                sampletype = SampleType.objects.get(type='ANIMAL')  # defaults to animal if no sampletype giv

        # get study factors
        studyfactors = []
        for k, v in six.iteritems(idxs['study_factors']):

            sf = check_and_create_study_factor(v['type'],
                                                              row[v['value']],
                                                              row[v['unit']] if v['unit'] else '')
            studyfactors.append(sf)

        if not study_default and 'study' in idxs and 'investigation' in idxs:
            investigation = Investigation.objects.filter(name=row[idxs['investigation']]).first()
            study = Study.objects.filter(name=row[idxs['study']], investigation=investigation).first()

        else:
            study = study_default

        if not study:
            print('missing study')
            continue

        # # Create (or replace) Study samples with details
        study_samples_present = StudySample.objects.filter(study=study, sample_name=row[idxs['sample_name']])

        if not study_samples_present:
            create_ss(study, organism, organism_part, row[idxs['sample_name']], row[idxs['source_name']],
                      sampletype, studyfactors)
        elif study_samples_present and replace_duplicates:
            study_samples_present[0].delete()
            create_ss(study, organism, organism_part, row[idxs['sample_name']], row[idxs['source_name']],
                      sampletype, studyfactors)

def create_ss(study, organism, organism_part, sample_name, source_name, sampletype, studyfactors):
    studysample = StudySample(study=study,
                              sample_name=sample_name,
                              source_name=source_name,
                              organism=organism,
                              organism_part=organism_part,
                              sampletype=sampletype)

    studysample.save()
    studysample.studyfactor.add(*studyfactors)


import requests
from bs4 import BeautifulSoup
import xmltodict

def law_search(text):
    # textは'法令'でもらう
    text_set = text.split()
    command = text_set[0]
    if command == '#法令':
        lawname = text_set[1]
        article = text_set[2]
        RequestURL = 'http://elaws.e-gov.go.jp/api/1/articles;lawNum=' + lawname + ';article=' +article
        xml = requests.get(RequestURL)
        resdata = xmltodict.parse(xml.content.decode('utf-8', 'replace'))
        if resdata['DataRoot']['Result']['Code'] != '0':
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='取得できませんでした\n' + lawname + '\n' + article)
                )
            return 'OK'
        data = resdata['DataRoot']['ApplData']
        ReturnText = []
        ReturnText.append(data['LawNum'])

        ReturnText.append(data['LawContents']['Article']['ArticleTitle'])
        ReturnText.append(data['LawContents']['Article']['ArticleCaption'])
        for para in data['LawContents']['Article']['Paragraph']:
            te = para['@Num'] + ' ' + para['ParagraphSentence']['Sentence']['#text']
            ReturnText.append(te)
        return '\n'.join(ReturnText)

    elif command == '#法令番号':
        lawname = text_set[1]
        RequestURL = 'http://elaws.e-gov.go.jp/search/elawsSearch/elaws_search/lsg0100/search?searchType=2&searchLawName=' +lawname+'&abbreviationFlg=true'
        html = requests.get(RequestURL)
        soup = BeautifulSoup(html.content, "html.parser")
        items = soup.find_all('table', class_='table table-striped table-condensed table-bordered')

        ReturnText = ''
        count = 0
        for item in items:
            item_res = item.find_all('td')
            del item_res[:3]
            for item_one in item_res:
                if count % 3 == 0:
                    pass
                elif count % 3 == 1:
                    ReturnText = ReturnText + item_one.text
                elif count % 3 == 2:
                    ReturnText = ReturnText +': '+ item_one.text + '\n'
                count += 1
        return ReturnText


class MinStack(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []
        self.flag = False
        self.min = 0

    def push(self, x):
        """
        :type x: int
        :rtype: void
        """
        if not self.stack:
            self.flag = True
            self.stack.append(0)
            self.min = x
        else:
            self.stack.append(x - self.min)
            if x - self.min < 0:
                self.min = x

    def pop(self):
        """
        :rtype: void
        """
        temp  = self.stack.pop()
        if temp < 0:
            self.min -= temp

    def top(self):
        """
        :rtype: int
        """
        temp = self.stack[-1]
        if temp >= 0:
            return self.min + temp
        else:
            return self.min

    def getMin(self):
        """
        :rtype: int
        """
        if self.flag:
            return self.min
        else:
            raise Exception

        # Your MinStack object will be instantiated and called as such:
        # obj = MinStack()
        # obj.push(x)
        # obj.pop()
        # param_3 = obj.top()
        # param_4 = obj.getMin()


from datetime import datetime
import time
import threading

class LatencyTracker:
  def __init__(self, network_handler):
    self.last_mesuraments = []
    self.network_handler = network_handler

  def is_latency_packet(self, output):
    splited_output = output.split("\n")
    if len(output) <= 1: return False
    header = output[0].split()
    if len(header) <= 1: return False
    if header[0] != "PINL" or header[0] != "200": return False
    return True

  def start_tracking(self):
    thread = threading.Thread(self.send_latency_packets)
    thread.start()

  def send_latency_packets(self):
    while True:
      self.network_handler.send_message("PINL")
      initial_time = datetime.now().timestamp()
      self.last_initial_time = initial_time
      time.sleep(20)

  def send_latency_response(self, connection_socket):
    arrival_time = datetime.now().timestamp()
    connection_socket.sendall(f"PINL 200\n{arrival_time}")

  def store_mesurament(self, latency_packet):
    arrival_time = latency_packet.split('\n')[1]
    new_mesurament = self.Latency(self.last_initial_time, arrival_time)
    self.last_mesuraments.append(new_mesurament)

  def __str__(self):
    mesuraments = len(self.last_mesuraments)
    if mesuraments == 0:
      return "No latency mesurament done yet."
    final_srt = ""
    for mesurament in self.last_mesuraments:
      final_srt = final_srt + str(mesurament)

  class Latency:
    def __init__(self, initial_time, arrival_time):
      self.initial_time = initial_time
      self.arrival_time = arrival_time
      self.interval = round((arrival_time - initial_time) * 1000, 2)

    def __str__(self):
      datetime_obj = datetime.utcfromtimestamp(int(self.initial_time))
      datetime_str = datetime_obj.strftime("%H:%M:%S - %d:%m:%y")
      return f"Latency(ms): {self.interval}\nTime of Mesurament: {datetime_str}\n"


import string
from collections import Counter  # for counting elms and n-grams
import docx  # docx
import fitz  # pdf
import nltk  # language processing
import pandas as pd  # csv and xls
import pymorphy2  # lemmatization
from tkinter import filedialog  # interface
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tkinter.ttk import Checkbutton
from tkinter.ttk import Combobox
from tkinter import scrolledtext
from matplotlib import pyplot as plt  # graphics
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from nltk import ngrams  # ngrams
from nltk import word_tokenize  # tokenization
from nltk.corpus import stopwords  # deleting spam
from nltk.probability import FreqDist  # distribution

def open_source_file(file_name):  # открывает исходный файл
	if file_name.endswith('txt'):
		with open(f'{file_name}', "r", encoding='UTF-8') as source_file_data:
			raw_source_text = source_file_data.read()
			return raw_source_text
	elif file_name.endswith('pdf'):
		doc = fitz.open(file_name)
		text = [page.get_text("text") for page in doc]
		raw_source_text = "\n".join(text)
		return raw_source_text
	elif file_name.endswith('docx'):
		source_file_data = docx.Document(file_name)
		text = [paragraph.text for paragraph in source_file_data.paragraphs]
		raw_source_text = "\n".join(text)
		return raw_source_text

def raw_text_processing(raw_source_text):  # избавляет текст от пунктуации
	raw_text_length = len(raw_source_text)
	raw_source_text = raw_source_text.lower()
	spec_char = string.punctuation + '\n\xa0«»\t—–-…“„'  # добавляем нужные символы
	raw_source_text = "".join([char for char in raw_source_text if char not in spec_char])  # нет пунктуации
	cleared_text = "".join([char for char in raw_source_text if char not in string.digits])  # нет чисел
	return cleared_text, raw_text_length

def tokenization(cleared_text):  # выделяет слова из очищенной "массы"
	text_tokens = word_tokenize(cleared_text)
	tokenized_text = nltk.Text(text_tokens)
	return tokenized_text, text_tokens

def spam_words_delete(text_tokens):  # удаляет стоп-слова, слова паразиты и все бесполезное
	russian_stopwords = stopwords.words("russian")
	russian_stopwords.extend(['это', 'нею', 'б', 'ах'])  # добавляем в список стопслов свои
	no_spam_tokens = []
	for token in text_tokens:
		if token not in russian_stopwords:
			no_spam_tokens.append(token)
	return no_spam_tokens

def lemmatization(no_spam_tokens):  # приводит слова к нормальной, "словарной" форме
	lemmatized_tokens = []
	single_lemmatized_tokens = []
	morph = pymorphy2.MorphAnalyzer()
	for word in no_spam_tokens:  # запускаем проверку слов
		parsed_word = morph.parse(word)[0]
		lemmatized_tokens.append(parsed_word.normal_form)
	for word in lemmatized_tokens:
		if word not in single_lemmatized_tokens:
			single_lemmatized_tokens.append(word)
	return lemmatized_tokens, single_lemmatized_tokens

def storing_to_dataframe(lemmatized_tokens, single_lemmatized_tokens,
                         saved_file_name):  # записываем результаты в таблицу
	lemmatized_data = dict(col1=lemmatized_tokens)
	single_lemmatized_data = dict(col1=single_lemmatized_tokens)
	single_lemmatized_dataframe = pd.DataFrame(single_lemmatized_data)
	single_lemmatized_dataframe.to_excel(f'{saved_file_name}\\Список слов без повторений.xlsx', index=False)
	lemmatized_dataframe = pd.DataFrame(lemmatized_data)
	lemmatized_dataframe.to_excel(f'{saved_file_name}\\Список слов.xlsx', index=False)

def get_most_common_words(text):
	freq_of_dist = FreqDist(text)
	most_common_word = (freq_of_dist.most_common(1))[0]
	return most_common_word, freq_of_dist

def frequency_plotter(freq_of_dist, saved_file_name, graph_name):
	freq_of_dist = dict(freq_of_dist)  # создаем таблицу со всеми словами и частотой употребления
	sorted_freq_of_dist = {}
	sorted_keys = sorted(freq_of_dist, key=freq_of_dist.get, reverse=True)
	for w in sorted_keys:
		sorted_freq_of_dist[w] = freq_of_dist[w]
	f = list(sorted_freq_of_dist.items())[:30]
	first30words = []
	for pair in f:
		first30words.append(pair[0])
		first30words.append(pair[1])
	x = [v for k, v in enumerate(first30words) if not k % 2]
	y = [v for k, v in enumerate(first30words) if k % 2]
	plt.xlabel("Слова")
	plt.ylabel("Количество употреблений")
	plt.grid()
	plt.plot(x, y)
	plt.xticks(rotation=90)
	plt.tight_layout()
	plt.autoscale()
	plt.savefig(f'{saved_file_name}\\{graph_name}')
	plt.clf()

def main(file_name, saved_file_name):
	def data_to_docx():
		data_out = docx.Document()
		data_out.add_paragraph("Характеристики текста:")
		data_out.add_paragraph(f'Символов до обработки: {len(raw_source_text)}')
		data_out.add_paragraph(f'Символов после удаления пунктуации: {len(cleared_text)}')
		data_out.add_paragraph(f'Знаков пунктуации: {len(raw_source_text) - len(cleared_text)}')
		data_out.add_paragraph(f'Текст содержит слов: {len(text_tokens)}')
		data_out.add_paragraph(f'Самое частое слово до уборки стоп-слов:'
		                       f' "{most_common_word[0]}" в количестве {most_common_word[1]}')
		data_out.add_paragraph(f'Самое частое слово после уборки стоп-слов:'
		                       f'"{cleared_most_common_word[0]}" в количестве {cleared_most_common_word[1]}')
		data_out.add_paragraph(f'Слов после удаления стоп-слов: {len(no_spam_tokens)}')
		data_out.add_paragraph(f'Удалено стоп-слов: {len(text_tokens) - len(no_spam_tokens)}')
		data_out.add_paragraph(
			f'При лемматизации удалено слов: {len(no_spam_tokens) - len(single_lemmatized_tokens)}')
		data_out.add_paragraph(f'Уникальных слов: {len(single_lemmatized_tokens)}')
		data_out.add_paragraph("Графики:")
		data_out.add_paragraph("График 1. Слова до уборки стоп-слов")
		frequency_plotter(freq_of_dist,saved_file_name, 'График 1. Слова до уборки стоп-слов.png')
		data_out.add_picture(f'{saved_file_name}\\График 1. Слова до уборки стоп-слов.png')
		frequency_plotter(cleared_freq_of_dist, saved_file_name, 'График 2. Слова после уборки стоп-слов.png')
		data_out.add_paragraph("График 2. Слова после уборки стоп-слов")
		data_out.add_picture(f'{saved_file_name}\\График 2. Слова после уборки стоп-слов.png')
		data_out.save(f'{saved_file_name}\\Результаты анализа.docx')

	raw_source_text = open_source_file(file_name)
	cleared_text = raw_text_processing(raw_source_text)[0]
	tokenized_text, text_tokens = tokenization(cleared_text)
	no_spam_tokens = spam_words_delete(text_tokens)
	lemmatized_tokens, single_lemmatized_tokens = lemmatization(no_spam_tokens)
	storing_to_dataframe(lemmatized_tokens, single_lemmatized_tokens, saved_file_name)
	most_common_word, freq_of_dist = get_most_common_words(tokenized_text)
	cleared_most_common_word, cleared_freq_of_dist = get_most_common_words(no_spam_tokens)
	return data_to_docx, raw_source_text, tokenized_text, no_spam_tokens, lemmatized_tokens

def ngrams_cal(save_file_name, text_input, ngram_count, word_or_symbol):
	if word_or_symbol == 'Анализ символов':
		united_text = ''.join(text_input)
		raw_grams = ngrams(united_text, ngram_count)
		counted_ngrams = Counter(raw_grams)
		df = pd.DataFrame(counted_ngrams.keys())
		df["Количество употреблений"] = counted_ngrams.values()
		df.to_excel(f'{save_file_name}\\Результат подсчета n-грамм.xlsx')
	elif word_or_symbol == 'Анализ слов':
		raw_grams = ngrams(text_input, ngram_count)
		counted_ngrams = Counter(raw_grams)
		df = pd.DataFrame(counted_ngrams.keys())
		df["Количество употреблений"] = counted_ngrams.values()
		df.to_excel(f'{save_file_name}\\Результат подсчета n-грамм.xlsx')

def interface():
	def start():
		def ngramm_window_show():
			def choice():
				which_ngram = analysis_type.get()
				ngram_count = int(how_many_ngram.get())
				word_or_symbol = word_or_symbol_choice.get()
				pass_ngram_param(saved_file_name, which_ngram, ngram_count, word_or_symbol)
				messagebox.showinfo('Уведомление', 'Этап подсчета n-грамм выполнен')
				messagebox.showinfo('Уведомление', 'Работа завершена \nМожно выходить')
				ngram_window.destroy()
				if res == 'yes':
					show_results(saved_file_name)

			def pass_ngram_param(saved_file_name, which_ngram, ngram_count, word_or_symbol):
				if which_ngram == 'Оригинальный текст':
					ngrams_cal(saved_file_name, program[1], ngram_count, word_or_symbol)
				elif which_ngram == 'Без пунктуации и цифр':
					ngrams_cal(saved_file_name, program[2], ngram_count, word_or_symbol)
				elif which_ngram == 'Без стоп-слов':
					ngrams_cal(saved_file_name, program[3], ngram_count, word_or_symbol)
				elif which_ngram == 'Лемматизованный текст':
					ngrams_cal(saved_file_name, program[4], ngram_count, word_or_symbol)
				else:
					ngram_window.destroy()
					messagebox.showinfo('Уведомление', 'Неверно указаны вводные данные')
					ngramm_window_show()

			ngram_window = Tk()
			ngram_window.title("Анализ n-грамм")
			ngram_label = Label(ngram_window, text='Выберите параметры анализа\n и степень n-граммы',
			                    font=("Arial Bold", 14))
			analysis_type = Combobox(ngram_window)
			analysis_type['values'] = ['Оригинальный текст', 'Без пунктуации и цифр',
			                           'Без стоп-слов', 'Лемматизованный текст']
			analysis_type.current(0)
			word_or_symbol_choice = Combobox(ngram_window)
			word_or_symbol_choice['values'] = ['Анализ символов', 'Анализ слов']
			word_or_symbol_choice.current(0)
			choice_button = Button(ngram_window, text="Запустить анализ n-грамм", command=choice, padx=5, pady=5, bd=0,
			                       fg='#fff',
			                       bg='#08f', underline=0, activebackground='#fff', activeforeground='#fff',
			                       cursor='hand2')
			how_many_ngram = Combobox(ngram_window)
			how_many_ngram['values'] = [i for i in range(2, 11)]
			how_many_ngram.current(0)
			ngram_label.grid(column=1, row=0, padx=10, pady=10)
			analysis_type.grid(column=0, row=1, padx=10, pady=10)
			word_or_symbol_choice.grid(column=1, row=1, padx=10, pady=10)
			how_many_ngram.grid(column=2, row=1, padx=10, pady=10)
			choice_button.grid(column=1, row=2, padx=10, pady=10)

			def btn_focus_in(e=None):
				choice_button.configure(fg='#08f')
				choice_button.configure(bg='#fff')

			def btn_focus_out(e=None):
				choice_button.configure(bg='#08f')
				choice_button.configure(fg='#fff')

			choice_button.bind('<Enter>', btn_focus_in)
			choice_button.bind('<Leave>', btn_focus_out)

			ngram_window.mainloop()

		try:
			res = messagebox.askquestion('', 'Нужно ли выводить результаты на экран?')
			file_name = "{}".format(file_name_entry.get())
			saved_file_name = "{}".format(save_directory_entry.get())
			check1 = chk_state1.get()
			check2 = chk_state2.get()
			if check1 == 1 or check2 == 1:
				program = main(file_name, saved_file_name)
				if check1 == 1:
					program[0]()
					messagebox.showinfo('Уведомление', 'Этап базового анализа выполнен')
					if check2 != 1:
						messagebox.showinfo('Уведомление', 'Работа завершена \nМожно выходить')
						if res == 'yes':
							show_results(saved_file_name)
				if check2 == 1:
					ngramm_window_show()
			elif check1 != 1 and not check2 != 1:
				messagebox.showinfo('Уведомление', 'Вы не выбрали ни одного параметра')
		except TypeError:
			messagebox.showinfo('Ошибка', 'Не указано имя файла для анализа')

	def load_results():
		messagebox.showinfo('Уведомление', 'Выберите папку для загрузки результатов')
		loading_directory = filedialog.askdirectory()
		show_results(loading_directory)

	def show_guide():
		guide_text_source = open('D:\\PITON\\guide_text.txt', "r", encoding='UTF-8')
		guide_text = guide_text_source.read()
		guide_window = Tk()
		guide_window.title('Инструкция по применению')
		guide_window_label = Label(guide_window, text=guide_text, justify='left')
		guide_window_label.grid(column=0, row=0)

	def get_file_name():
		messagebox.showinfo('Уведомление', 'Выберите файл для анализа')
		file_name = filedialog.askopenfilename()
		file_name_result = "{}".format(file_name)
		file_name_entry.delete(0, END)
		file_name_entry.insert(0, file_name_result)
		return file_name

	def get_save_directory():
		messagebox.showinfo('Уведомление', 'Выберите или создайте папку для сохранения результатов')
		saved_file_name = filedialog.askdirectory()
		res = "{}".format(saved_file_name)
		save_directory_entry.delete(0, END)
		save_directory_entry.insert(0, res)
		return saved_file_name

	def show_results(saved_file_name):
		result_window = Tk()
		result_window.title("Результаты анализа")
		tab_control = ttk.Notebook(result_window)
		tab1 = ttk.Frame(tab_control)
		tab2 = ttk.Frame(tab_control)
		tab3 = ttk.Frame(tab_control)
		tab_control.add(tab1, text='Результаты базового анализа')
		tab_control.add(tab2, text='Результаты анализа n-грамм')
		tab_control.add(tab3, text='Графики')
		tab_control.pack(expand=1, fill='both')
		base_analysis_scroll = scrolledtext.ScrolledText(tab1)
		ngram_analysis_scroll = scrolledtext.ScrolledText(tab2)
		try:
			base_analysis_file = docx.Document(f'{saved_file_name}\\Результаты анализа.docx')
			base_analysis_text = [paragraph.text for paragraph in base_analysis_file.paragraphs]
			base_analysis_text = "\n".join(base_analysis_text).partition('Г')[0]
			base_analysis_scroll.insert(INSERT, base_analysis_text)
		except FileNotFoundError:
			base_analysis_scroll.insert(INSERT, 'Анализ не выполнялся, либо файл был удален.\nПоказывать нечего')
		pd.set_option('display.max_rows', None)
		pd.set_option('display.max_columns', None)
		pd.set_option('display.max_colwidth', None)
		try:
			ngram_analysis_text = pd.read_excel(f'{saved_file_name}\\Результат подсчета n-грамм.xlsx')
			ngram_analysis_text = pd.DataFrame(ngram_analysis_text).astype(str)
			ngram_analysis_text = ngram_analysis_text.astype(str)
			ngram_analysis_scroll.insert(INSERT, ngram_analysis_text)
		except FileNotFoundError:
			ngram_analysis_scroll.insert(INSERT, 'Анализ n-грамм не выполнялся, либо файл был удален.\nПоказывать нечего')
		base_analysis_scroll.pack(expand=1, fill=Y)
		ngram_analysis_scroll.pack(expand=1, fill=Y)
		fig1 = plt.figure(figsize=(6.4, 4.8))
		plt.imshow(plt.imread(f'{saved_file_name}\\График 1. Слова до уборки стоп-слов.png'))
		plt.axis('off')
		canvas1 = FigureCanvasTkAgg(fig1, master=tab3)
		canvas1.get_tk_widget().pack(side=TOP)
		fig2 = plt.figure(figsize=(6.4, 4.8))
		plt.imshow(plt.imread(f'{saved_file_name}\\График 2. Слова после уборки стоп-слов.png'))
		plt.axis('off')
		canvas2 = FigureCanvasTkAgg(fig2, master=tab3)
		canvas2.get_tk_widget().pack(side=BOTTOM)
		result_window.mainloop()

	global window
	window = Tk()
	f_top = Frame(window)
	f_bot = Frame(window)
	f_left = Frame(window)
	f_right = Frame(window)
	window.title("Анализатор ЕЯ")
	window.resizable = True
	label = Label(f_top, text="Анализатор естественного языка", font=("Arial Bold", 14), justify='right')
	guide_button = Button(f_top, text='Инструкция по применению', command=show_guide, padx=5, pady=5, bd=0, fg='#fff',
	                      bg='#08f', underline=0, activebackground='#fff', activeforeground='#fff', cursor='hand2')
	load_button = Button(f_top, text="Загрузить прошлые результаты", command=load_results, padx=5, pady=5, bd=0, fg='#fff',
	                      bg='#08f', underline=0, activebackground='#fff', activeforeground='#fff', cursor='hand2')
	description1 = Label(f_left, text="Выберите составляющие анализа:", font=("Arial Bold", 14))
	description2 = Label(f_right, text="Выберите или введите путь к файлу", font=("Arial Bold", 14))
	description3 = Label(f_right, text="Выберите или введите путь\nдля сохранения результатов", font=("Arial Bold", 14))
	start_button = Button(f_left, text="ПУСК", command=start, padx=5, pady=5, bd=0, fg='#fff', bg='#08f',
	                      underline=0, activebackground='#fff', activeforeground='#fff', cursor='hand2')
	file_name_entry = Entry(f_right, width=50)
	file_name_entry.insert(INSERT, 'D:\\1.txt')
	save_directory_entry = Entry(f_right, width=50)
	save_directory_entry.insert(INSERT, 'D:\\результаты')
	file_name_button = Button(f_right, text="Загрузить", command=get_file_name, padx=5, pady=5, bd=0, fg='#fff',
	                          bg='#08f',
	                          underline=0, activebackground='#fff', activeforeground='#fff', cursor='hand2')
	save_directory_button = Button(f_right, text="Загрузить", command=get_save_directory, padx=5, pady=5, bd=0,
	                               fg='#fff', bg='#08f',
	                               underline=0, activebackground='#fff', activeforeground='#fff', cursor='hand2')
	chk_state1 = IntVar()
	chk_state1.set(1)
	chk1 = Checkbutton(f_left, text='Базовый анализ', var=chk_state1, cursor='hand2')
	chk_state2 = IntVar()
	chk_state2.set(1)
	chk2 = Checkbutton(f_left, text='Анализ n-грамм', var=chk_state2, cursor='hand2')

	f_top.pack(side=TOP)
	f_left.pack(side=LEFT)
	f_right.pack(side=RIGHT)
	f_bot.pack(side=BOTTOM, pady=10, padx=10)
	label.pack(side=TOP, padx=5, pady=5)
	load_button.pack(side=LEFT, padx=5, pady=5)
	guide_button.pack(side=TOP, padx=5, pady=15)
	description1.grid(column=0, row=0, padx=5, pady=5)
	chk1.grid(column=0, row=1, padx=5, pady=5)
	chk2.grid(column=0, row=2, padx=5, pady=5)
	description2.grid(column=0, row=0, padx=5, pady=5)
	file_name_entry.grid(column=0, row=1, padx=5, pady=5)
	file_name_button.grid(column=1, row=1, padx=5, pady=5)
	description3.grid(column=0, row=2, padx=5, pady=5)
	save_directory_entry.grid(column=0, row=3, padx=5, pady=5)
	save_directory_button.grid(column=1, row=3, padx=10, pady=10)
	start_button.grid(column=0, row=3, pady=20)

	def load_focus_in(e=None):
		load_button.configure(fg='#08f')
		load_button.configure(bg='#fff')

	def guide_focus_in(e=None):
		guide_button.configure(fg='#08f')
		guide_button.configure(bg='#fff')

	def start_focus_in(e=None):
		start_button.configure(fg='#08f')
		start_button.configure(bg='#fff')

	def file_focus_in(e=None):
		file_name_button.configure(fg='#08f')
		file_name_button.configure(bg='#fff')

	def save_focus_in(e=None):
		save_directory_button.configure(fg='#08f')
		save_directory_button.configure(bg='#fff')

	def load_focus_out(e=None):
		load_button.configure(bg='#08f')
		load_button.configure(fg='#fff')

	def guide_focus_out(e=None):
		guide_button.configure(bg='#08f')
		guide_button.configure(fg='#fff')

	def start_focus_out(e=None):
		start_button.configure(bg='#08f')
		start_button.configure(fg='#fff')

	def file_focus_out(e=None):
		file_name_button.configure(bg='#08f')
		file_name_button.configure(fg='#fff')

	def save_focus_out(e=None):
		save_directory_button.configure(bg='#08f')
		save_directory_button.configure(fg='#fff')

	load_button.bind('<Enter>', load_focus_in)
	load_button.bind('<Leave>', load_focus_out)
	guide_button.bind('<Enter>', guide_focus_in)
	guide_button.bind('<Leave>', guide_focus_out)
	start_button.bind('<Enter>', start_focus_in)
	start_button.bind('<Leave>', start_focus_out)
	file_name_button.bind('<Enter>', file_focus_in)
	file_name_button.bind('<Leave>', file_focus_out)
	save_directory_button.bind('<Enter>', save_focus_in)
	save_directory_button.bind('<Leave>', save_focus_out)

	window.mainloop()

interface()


#Input
import math
print('This program uses modular arithmetic with the Gregorian Calender to predict the day of the week given the date. In the format, if the date is say January 1st, 2020, write 1/1/2020.')
input_date = input("Enter Date in MM/DD/YYYY format: ")
#Processing Input
string_list = input_date.split("/")
date_list = list(map(int, string_list))
#Logic
month = date_list[0]
date_code = date_list[1]
year = date_list[2]
#Leap Year Check
if (year/4)==round(year/4):
	if (year/100)!=round(year/100):
		leap = 1
	else:
		if (year/400)==round(year/400):
			leap = 1
		else:
			leap = 0
else:
	leap = 0
#Month Code
if month == 1:
	if leap == 1:
		month_code = 5
	else:
		month_code = 6
elif month == 2:
	if leap == 1:
		month_code = 1
	else:
		month_code = 2
elif month == 3:
	month_code = 2
elif month == 4:
	month_code = 5
elif month == 5:
	month_code = 0
elif month == 6:
	month_code = 3
elif month == 7:
	month_code = 5
elif month == 8:
	month_code = 1
elif month == 9:
	month_code = 4
elif month == 10:
	month_code = 6
elif month == 11:
	month_code = 2
elif month == 12:
	month_code = 4
else:
	print('Error: Month is not defined correctly.')
#Year Code
year_var=year
while 2000<=year_var<=2050:
	if year_var<2000:
		year_var=year_var+28
	else:
		year_var=year_var-28
#Year Code Calculation
start=year_var-2000
addition=int(math.floor(start/4))
start=start+addition
division=int(math.floor(start/7))
year_code = start - int(division*7)
#Final Modular Aritmetic Calculation
total = year_code+month_code+date_code
modulo = total%7
#Final Output and Processing
if modulo==1:
	str='Monday.'
elif modulo==2:
	str='Tuesday.'
elif modulo==3:
	str='Wednesday.'
elif modulo==4:
	str='Thursday.'
elif modulo==5:
	str='Friday.'
elif modulo==6:
	str='Saturday.'
else:
	str='Sunday.'

#Final Output
print(f'The date {input_date} will fall on a {str}')


#!/usr/bin/env python3
"""
    manual_update.py

    Part of Argostimè

    Standalone script to manually update the price of a product offer by product_offer_id.
"""

import sys
import logging

from argostime.models import ProductOffer
from argostime import create_app

app = create_app()
app.app_context().push()

try:
    product_offer_id: int = int(sys.argv[1])
except:
    print("No number given")
    sys.exit(-1)

offer: ProductOffer = ProductOffer.query.get(product_offer_id)

logging.debug("Found offer %s", product_offer_id)
logging.debug("Manually updating ProductOffer %s", offer)

try:
    offer.crawl_new_price()
except Exception as exception:
    logging.error("Received %s while updating price of %s, continuing...", exception, offer)


from turtle import *
from random import randint
import random
penup()
left(180)
forward(375)
#Draw the A
pendown()
right(180)
right(45)
right(45)
right(45)
right(45)
right(45)
right(45)
right(45)
forward(75)
stamp()
forward(75)
forward(75)
stamp()
shape('turtle')
color("BLUE")
stamp()
forward(20)
forward(30)
color("green")
stamp()
forward(40)
color('purple')
stamp()
right(45)
right(45)
color("black")
forward(20)
stamp()
forward(30)
color('pink')
stamp()
forward(40)
color("yellow")
stamp()
forward(50)
shape()
shape("classic")
color('black')
left(45)
stamp()
right(45)
left(90)
right(90)
right(45)
color("blue")
right(45)
right(45)
right(45)
forward(20)
forward(30)
forward(20)
left(45)
forward(100)

right(180)
forward(200)
left(90)
forward(100)

#Draw the L
pendown()
pencolor("purple")
right(180)
forward(150)
left(90)
forward(75)

forward(50)

#Draw the E
pencolor("blue")
pendown()
left(90)
forward(150)
right(90)
forward(75)
right(180)
forward(75)
left(90)
forward(75)
left(90)
forward(75)
right(180)
forward(75)
left(90)
forward(75)
left(90)
forward(75)

forward(150)
left(90)
forward(175)
number=random.randint(1, 2)
if number == 1:
    color="pink"
else:
    color="red"
#Draw the C
pencolor(color)
right(90)
pendown()
left(180)
circle(90, 180)

import Tkinter as t
from subprocess import call
window = t.Tk()
def callback():
    call("./shutdown")
b = t.Button(window, text="Shutdown", command=callback)
b.pack()
t.mainloop()


def sortList(list1):
	for i in range(0,len(list1)):
		for j in range(i+1,len(list1)):
			if list1[i] > list1[j]:
				temp = list1[i]
				list1[i] = list1[j]
				list1[j] = temp
	return list1

def mergeSortedLists(l1,l2):
	i=0
	j=0
	l3=[]
	while i < len(l1) and j < len(l2):
		if l1[i] < l2[j]:
			l3.append(l1[i])
			i+=1
		else:
			l3.append(l2[j])
			j+=1
	if i < len(l1):
		l3.extend(l1[i:])
	if j < len(l2):
		l3.extend(l2[j:])
	return l3

def main():
	l1=input("Enter list :")
	l2=input("Enter list :")

	l1=sortList(l1)
	l2=sortList(l2)

	l3=mergeSortedLists(l1,l2)
	print(l3)

if __name__=="__main__":
	main()


import hashlib

import tweepy
from flask import jsonify, redirect, session, request

from main import api
from settings import SETTINGS

from database import tweet_db_session, user_db_session
from models.eroiine import Tweet
from models.user import User

from exception import cannotAuthTwitterException

@api.route('/')
def page_top():
    eroiine_dict = get_eroiines_from_db()
    return jsonify(eroiine_dict)

@api.route('/auth/twitter', methods=['GET'])
def page_auth_twitter():
    auth = get_auth_twitter()
    redirect_url = auth.get_authorization_url()
    session['request_token'] = auth.request_token
    return redirect(redirect_url)

@api.route('/auth/twitter/save_data', methods=['GET'])
def page_save_tokens():
    hashed_id = save_token_twitter()
    save_eroiines_to_db(hashed_id)
    return redirect('/')

def get_eroiines_from_db() -> dict:
    """get all-eroiines from database.
    Returns:
        dict: ero-iine with tweet-id as key.
    """
    response = {}
    for t in tweet_db_session.query(Tweet).all():
        response[t.tweet_id] = {
            'user_id': t.user_id,
            'text': t.tweet_text,
            'image_url1': t.image_url_1,
            'image_url2': t.image_url_2,
            'image_url3': t.image_url_3,
            'image_url4': t.image_url_4,
        }

    return response

def get_auth_twitter() -> tweepy.OAuthHandler:
    """auth twitter with saved tokens.
    Returns:
        tweepy.OAuthHandler:
    """
    return tweepy.OAuthHandler(SETTINGS['TWITTER_API_KEY'], SETTINGS['TWITTER_API_SECRET_KEY'])

def get_auth_twitter_consumer(hashed_twitter_id: str) -> tweepy.OAuthHandler:
    """auth twitter with saved tokens.
    Args:
        hashed_twitter_id(str):
    Returns:
        tweepy.OAuthHandler:
    """
    user = user_db_session.query(User.token, User.token_secret).filter(User.hashed_user_id == hashed_twitter_id).one()
    auth = get_auth_twitter()
    auth.set_access_token(user.token, user.token_secret)
    twitter_api = tweepy.API(auth)
    return twitter_api

def get_eroiines_from_twitter():
    pass

def save_eroiines_to_db(hashed_twitter_id: str):
    """save eroiines from user-twitter-favolites.
    """
    twitter_api = get_auth_twitter_consumer(hashed_twitter_id)
    exist_keys = [key[0] for key in tweet_db_session.query(Tweet.tweet_id).all()]

    fav_list = []
    for fav in twitter_api.favorites():
        t = fav._json
        if is_img_tweet(t):
            media = t['entities']['media']
            image_urls = [media[i]['media_url'] if len(media) > i else None for i in range(4)]
            if t['id'] not in exist_keys:
                tweet = Tweet(t['id'], t['user']['id'], t['text'], image_urls)
                fav_list.append(tweet)

    if len(fav_list) > 0:
        tweet_db_session.add_all(fav_list)
        tweet_db_session.commit()

def is_img_tweet(tweet: dict):
    """determine img tweet.
    Returns:
        bool:
    """
    try:
        media = tweet['entities']['media']
        if len(media) > 0:
            if media[0]['type'] == 'photo':
                return True
    except Exception:
        pass
    return False

def hash_twitter_id(twitter_id: int):
    """for cookie injection(wip)
    Returns:
        str: sha256-hex-hashed twitter_id
    """
    return hashlib.sha256(str(twitter_id).encode()).hexdigest()

def save_token_twitter():
    """save auth-tokens
    Returns:
        str: hashed twitter id
    """
    token = session.pop('request_token', None)
    verifier = request.args.get('oauth_verifier')
    if token is None or verifier is None:
        return False

    auth = get_auth_twitter()
    auth.request_token = token
    auth.get_access_token(verifier)

    consumer_key = auth.access_token
    consumer_key_secret = auth.access_token_secret

    try:
        auth = get_auth_twitter()
        auth.set_access_token(consumer_key, consumer_key_secret)
        twitter_api = tweepy.API(auth)

        user = twitter_api.me()

        hashed_id = hash_twitter_id(user.id)

        exist_users = [user[0] for user in user_db_session.query(User.hashed_user_id).all()]

        if hashed_id not in exist_users:
            user_db_session.add(User(hashed_id, consumer_key, consumer_key_secret))
            user_db_session.commit()

        return hashed_id

    except Exception:
        raise cannotAuthTwitterException


import requests
import re
import socket

def get_lan_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("1.1.1.1",80))
    ipaddr=s.getsockname()[0]
    s.close()

    return ipaddr

class Getmyip:
    def getip(self):
        try:
            myip = self.visit("http://www.ip.cn/")
        except:
            try:
                myip = self.visit("http://dir.twseo.org/ip-check.php")
            except:
                try:
                    myip = self.visit("http://ip111.cn/")
                    # if you want to add more,use the format "except try"
                    # make sure the most useful link be the first
                except:
                    print("Fail to get the Network ip.")
                    print("Get the LAN ip.")
                    myip = get_lan_ip()
        return myip

    def visit(self,url):
        opener = requests.get(url)
        # print(opener.url)
        if url == opener.url:
            str = opener.text
            print("IP information from",url)
        return re.search('\d+\.\d+\.\d+\.\d+',str).group(0)

def get_network_ip():
    getmyip = Getmyip()
    localip = getmyip.getip()
    print(localip)
    return localip

get_network_ip()
# opener = requests.get("http://www.ip.cn/",timeout=20)
# str = opener.text
# print(str)


import sys
import time
from paho.mqtt import client as mqtt_client

broker = 'test.mosquitto.org'
port = 1883
topic = "edbotv1_ufu2022/position/set"
topic_test = "edbotv1_ufu2022/position/test_connection"
client_id = f'python-mqtt'

def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT Broker!")
    else:
        print("Failed to connect, return code %d\n", rc)

client = mqtt_client.Client(client_id)
client.on_connect = on_connect
client.connect(broker, port)

def mqtt_publish(motor_id, position):
    msg = "{\"motor\":" + str(motor_id) + ", \"pos\":" + str(position) + "}"
    result = client.publish(topic, msg)
    status = result[0]
    return status

def mqtt_init():
    client.loop_start()
    time.sleep(1)

def mqtt_get_status_conenction():
    client.publish(topic_test, "conencting")
    return client.is_connected()


import os
import argparse
from pathlib import Path
from numpy.fft import rfft, rfftfreq
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import soundfile as sf
import scipy.signal as signal
import numpy as np

def figures(outs, ID, pltdir):
    fig, ax = plt.subplots(3, 2)
    for idx, out in enumerate(outs):
        i = idx // 2
        j = idx % 2
        getattr(ax[i, j], out[-2])(*out[0:-2])
        ax[i, j].set_title(out[-1])
    fig.tight_layout()
    plt.savefig(os.path.join(pltdir, ID + ".png"))
    plt.clf()

def plot(ID, wavdir, pltdir, sr=16000, ext=""):
    x_orig = sf.read(os.path.join(wavdir, ID + "-orig.wav"))[0]
    x_adv = sf.read(os.path.join(wavdir, ID + "-" + ext + "-adv.wav"))[0]
    X_F_orig = abs(rfft(x_orig))
    X_F_adv = abs(rfft(x_adv))
    freq = rfftfreq(len(x_orig), d=1 / sr)
    freq_a = rfftfreq(len(x_adv), d=1 / sr)
    f_orig, t_orig, Zxx_orig = signal.stft(x_orig, fs=sr)
    f_adv, t_adv, Zxx_adv = signal.stft(x_adv, fs=sr)

    outs = [
        (range(len(x_orig)), x_orig, "plot", "orig"),
        (range(len(x_adv)), x_adv, "plot", "adv"),
        (freq, X_F_orig, "plot", "orig FFT"),
        (freq_a, X_F_adv, "plot", "adv FFT"),
        (t_orig, f_orig, np.abs(Zxx_orig), "pcolormesh", "orig STFT"),
        (t_adv, f_adv, np.abs(Zxx_adv), "pcolormesh", "adv STFT"),
    ]

    figures(outs, ID, pltdir)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--i")
    parser.add_argument("--w")
    parser.add_argument("--p")
    parser.add_argument("--sr", type=int)
    args = parser.parse_args()
    plot(args.i, args.w, args.p, args.sr)


x=1
y=0
z=0
a=0

while x or 0:
    x=int(input("Enter a Number (zero to quit): "))
    if x or 0:
        if z==0:
            y=x
        if x>y:
            a+=1
        z+=1
        y=x
print ("Number of Values Greater Than the Previous: ",a)


transmission = []
with open("data.txt") as data:
    transmission = [str(s) for s in data.read()]

HEX_TO_BINARY = {
    '0': '0000',
    '1': '0001',
    '2': '0010',
    '3': '0011',
    '4': '0100',
    '5': '0101',
    '6': '0110',
    '7': '0111',
    '8': '1000',
    '9': '1001',
    'A': '1010',
    'B': '1011',
    'C': '1100',
    'D': '1101',
    'E': '1110',
    'F': '1111'
}

def hexToBinary(s):
    return HEX_TO_BINARY[s]

def getNextBits(binaryTransmission, numBits):
    next = ''
    for i in range(numBits):
        next += binaryTransmission.pop(0)
    return next

def binaryToBaseTen(binary):
    return int(binary, 2)

def decodeLiteralValue(binaryTransmission):
    signalBit = getNextBits(binaryTransmission, 1)
    valueInBinary = getNextBits(binaryTransmission, 4)
    while signalBit == '1':
        signalBit = getNextBits(binaryTransmission, 1)
        valueInBinary += getNextBits(binaryTransmission, 4)
    return binaryToBaseTen(valueInBinary)

def decodeOperatorPacket(binaryTransmission):
    lengthBit = getNextBits(binaryTransmission, 1)
    subpackets = []
    if lengthBit == '0':
        subpacketLength = binaryToBaseTen(getNextBits(binaryTransmission, 15))
        targetTransmissionLength = len(binaryTransmission) - subpacketLength
        while len(binaryTransmission) > targetTransmissionLength:
            subpackets.append(decodeNextPacket(binaryTransmission))
    elif lengthBit == '1':
        numberOfSubpackets = binaryToBaseTen(getNextBits(binaryTransmission, 11))
        for _ in range(numberOfSubpackets):
            subpackets.append(decodeNextPacket(binaryTransmission))
    return subpackets

def decodeNextPacket(binaryTransmission):
    packetVersion = binaryToBaseTen(getNextBits(binaryTransmission, 3))
    typeID = binaryToBaseTen(getNextBits(binaryTransmission, 3))
    packet = {
        'packetVersion': packetVersion,
        'typeID': typeID
    }
    if typeID == 4:
        literalValue = decodeLiteralValue(binaryTransmission)
        packet['value'] = literalValue
    else:
        subpackets = decodeOperatorPacket(binaryTransmission)
        packet['subpackets'] = subpackets
    return packet

binaryTransmission = []
for s in transmission:
    binary = hexToBinary(s)
    for bit in binary:
        binaryTransmission.append(bit)

rootPacket = decodeNextPacket(binaryTransmission)

print("Part 1: ")
packets = [rootPacket]
versionSum = 0
while len(packets) > 0:
    packet = packets.pop()
    versionSum += packet['packetVersion']
    if 'subpackets' in packet:
        for subpacket in packet['subpackets']:
            packets.append(subpacket)
print(versionSum)

print("Part 2")

def calculatePacket(packet):
    typeID = packet['typeID']
    if typeID == 4:
        return packet['value']
    else:
        subPacketValues = []
        for subpacket in packet['subpackets']:
            subPacketValues.append(calculatePacket(subpacket))
        if typeID == 0:
            return sum(subPacketValues)
        if typeID == 1:
            product = 1
            for v in subPacketValues:
                product = product * v
            return product
        if typeID == 2:
            return min(subPacketValues)
        if typeID == 3:
            return max(subPacketValues)
        if typeID == 5:
            if subPacketValues[0] > subPacketValues[1]:
                return 1
            else:
                return 0
        if typeID == 6:
            if subPacketValues[0] < subPacketValues[1]:
                return 1
            else:
                return 0
        if typeID == 7:
            if subPacketValues[0] == subPacketValues[1]:
                return 1
            else:
                return 0

print(calculatePacket(rootPacket))


import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from mpl_toolkits import mplot3d
import pandas as pd
import numpy as np
import seaborn as sns
import copy
import collections
from functools import reduce
from pathlib import Path
from statistical_tests import StatisticalTests
from datetime import datetime, timedelta
from matplotlib import dates as mpl_dates

class Plots:

    def __init__(self):
        pass

    def change_to_percents(self, df, label_list, number_columns):
        sum_elements = sum(list(df.values()))
        temp_value = [0 for i in range(number_columns + 1)]
        res_dict = dict(zip(label_list, temp_value))
        for i in label_list:
            res_dict[i] = (df[i] / sum_elements) * 100

        return res_dict

    def calculate_structure_population_age_based_range(self, list_df, save_name):
        x_pos = list()
        y_pos = ['2014a', '2014b', '2015a', '2015b', '2016a', '2016b', '2017a', '2017b', '2018a', '2018b', '2019']
        z_pos = list()
        # label_list = [i + 1 for i in range(6)]
        label_list = ['18-24', "25-34", '35-44', '45-54', '55-64', '65+']
        temp_value = [0 for i in range(6)]
        structure_population_list = list()
        for df, save in zip(list_df, save_name):
            # print('df in calculate')
            # print(df)
            range_birth = (df.iloc[:, 1]).to_list()
            # print('range_birth')
            # print(range_birth)
            structure_population = dict(zip(label_list, temp_value))
            for year in range_birth:
                if year == '18-24':
                    structure_population[label_list[0]] += 1
                elif year == '25-34':
                    structure_population[label_list[1]] += 1
                elif year == '35-44':
                    structure_population[label_list[2]] += 1
                elif year == '45-54':
                    structure_population[label_list[3]] += 1
                elif year == '55-64':
                    structure_population[label_list[4]] += 1
                elif year == '65+':
                    structure_population[label_list[5]] += 1
                else:
                    continue

            structure_population_list.append(structure_population)

            x_pos.append(structure_population.values())
            z_pos.append(structure_population.keys())
            plt.bar(structure_population.keys(), structure_population.values())
            plt.ylim(top=1000)
            plt.ylim(bottom=0)
            plt.xlabel('Grupa wiekowa')
            plt.ylabel('Ilość osób')
            temp_name = save.split('_')
            year = temp_name[0]
            month = temp_name[1]
            plt.title('Histogram struktury wieku uczestników badania - ' + year + ' ' + month, fontsize=10)
            plt.savefig('results/histograms/population_age/hist_' + save + '.png')
            plt.clf()

        plt.savefig('results/histograms/population_age/hist_3d.png')
        plt.clf()
        return structure_population_list

    def calculate_structure_education(self, list_df, save_name):
        legend_list = ["Podstawowe", "Zasadnicze zawodowe", "Średnie ogólnokształcące", "Średnie techniczne",
                       "Pomaturalne", "Studia wyższe niepełne", "Studia wyższe ukończone"]
        temp_value = [0 for i in range(7)]
        label_list = [i + 1 for i in range(7)]
        education_list = list()
        for df, save in zip(list_df, save_name):
            temp = df.iloc[:, 1].to_list()
            education_dict = dict(zip(label_list, temp_value))
            for i in df.iloc[:, 1].to_list():
                if i == 1:
                    education_dict[label_list[0]] += 1
                elif i == 2:
                    education_dict[label_list[1]] += 1
                elif i == 3:
                    education_dict[label_list[2]] += 1
                elif i == 4:
                    education_dict[label_list[3]] += 1
                elif i == 5:
                    education_dict[label_list[4]] += 1
                elif i == 6:
                    education_dict[label_list[5]] += 1
                elif i == 7:
                    education_dict[label_list[6]] += 1

            education_dict_percents = self.change_to_percents(education_dict, label_list, 7)
            education_list.append(education_dict_percents)
            colors = list('rgbkymc')
            handles = list()
            plt.bar(education_dict.keys(), education_dict.values(), color=colors)
            handles = list()
            for name, number, color in zip(legend_list, label_list, colors):
                handles.append(mpatches.Patch(color=color, label=str(number) + ' - ' + name))
            plt.legend(handles=handles)
            plt.xlabel('Poziom wykształcenia')
            plt.ylabel('Ilość osób')
            plt.ylim(top=1200)
            plt.ylim(bottom=0)
            temp_name = save.split('_')
            year = temp_name[0]
            month = temp_name[1]
            plt.title('Histogram poziomu wykształcenia uczestników badania - ' + year + ' ' + month, fontsize=10)
            plt.savefig('results/histograms/education/hist_' + save + '.png')
            plt.clf()

        return education_list

    def calculate_structure_accomodation(self, list_df, save_name):
        legend_list = ["W wysokim bloku (>= 5 pięter)", "W niskim bloku (<= 4 pięter)", "W kamienicy",
                       "W domu w zabudowie szeregowej", "W domu jednorodzinnym"]
        temp_value = [0 for i in range(5)]
        label_list = [i + 1 for i in range(5)]
        accommodation_list = list()
        for df, save in zip(list_df, save_name):
            accommodation_dict = dict(zip(label_list, temp_value))
            for i in df.iloc[:, 1].to_list():
                if i == 1:
                    accommodation_dict[label_list[0]] += 1
                elif i == 2:
                    accommodation_dict[label_list[1]] += 1
                elif i == 3:
                    accommodation_dict[label_list[2]] += 1
                elif i == 4:
                    accommodation_dict[label_list[3]] += 1
                elif i == 5:
                    accommodation_dict[label_list[4]] += 1

            accommodation_dict_percents = self.change_to_percents(accommodation_dict, label_list, 5)
            accommodation_list.append(accommodation_dict_percents)
            colors = list('rgbkymc')
            handles = list()
            plt.bar(accommodation_dict.keys(), accommodation_dict.values(), color=colors)
            for name, number, color in zip(legend_list, label_list, colors):
                handles.append(mpatches.Patch(color=color, label=str(number) + ' - ' + name))
            plt.legend(handles=handles)
            plt.ylim(top=1000)
            plt.ylim(bottom=0)
            plt.xlabel('Miejsce zamieszkania')
            plt.ylabel('Ilość osób')
            temp_name = save.split('_')
            year = temp_name[0]
            month = temp_name[1]
            plt.title('Histogram rozkładu miejsca zamieszkania uczestników badania - ' + year + ' ' + month, fontsize=9)
            plt.savefig('results/histograms/accomodation/hist_' + save + '.png')
            plt.clf()

        return accommodation_list

    def calculate_A2(self, list_df, save_name):
        legend_list = ["Zdecydowanie tak", "Raczej tak", "Ani tak, ani nie",
                       "Raczej nie", "Zdecydowanie nie"]
        temp_value = [0 for i in range(5)]
        label_list = [i + 1 for i in range(5)]

        a2_list = list()
        for df, save in zip(list_df, save_name):
            A2_dict = dict(zip(label_list, temp_value))
            for i in df.iloc[:, 1].to_list():
                if i == 1:
                    A2_dict[label_list[0]] += 1
                elif i == 2:
                    A2_dict[label_list[1]] += 1
                elif i == 3:
                    A2_dict[label_list[2]] += 1
                elif i == 4:
                    A2_dict[label_list[3]] += 1
                elif i == 5:
                    A2_dict[label_list[4]] += 1

            error_dict = dict(zip(label_list, temp_value))
            for i in label_list:
                error_dict[i] = np.sqrt(A2_dict[i])
            a2_list.append(A2_dict)
            colors = list('rgbymc')
            handles = list()
            plt.bar(A2_dict.keys(), A2_dict.values(), color=colors, yerr=error_dict.values(), ecolor='black',
                    capsize=10)
            for name, number, color in zip(legend_list, label_list, colors):
                handles.append(mpatches.Patch(color=color, label=str(number) + ' - ' + name))
            plt.legend(handles=handles)
            plt.xlabel('5-stopniowa skala oceny')
            plt.ylabel('Ilość osób')
            plt.ylim(top=1850)
            plt.ylim(bottom=0)
            temp_name = save.split('_')
            year = temp_name[0]
            month = temp_name[1]
            plt.title('Ocena poczucia bezpieczeństwa w Krakowie - ' + year + ' ' + month, fontsize=10)
            plt.savefig('results/histograms/A2/hist_' + save + '.png')
            plt.clf()

        return a2_list

    def calculate_A2_with_3_cat(self, list_df, save_name):
        legend_list = ["tak", "Ani tak, ani nie", "nie"]
        temp_value = [0 for i in range(3)]
        label_list = [i + 1 for i in range(3)]

        a2_list = list()
        for df, save in zip(list_df, save_name):
            A2_dict = dict(zip(label_list, temp_value))
            for i in df.iloc[:, 1].to_list():
                if i == 1 or i == 2:
                    A2_dict[label_list[0]] += 1
                elif i == 3:
                    A2_dict[label_list[1]] += 1
                elif i == 4 or i == 5:
                    A2_dict[label_list[2]] += 1

            A2_dict_percents = self.change_to_percents(A2_dict, label_list, 3)
            a2_list.append(A2_dict_percents)
            error_dict = dict(zip(label_list, temp_value))
            for i in label_list:
                error_dict[i] = np.sqrt(A2_dict[i])

            colors = list('rgbymc')
            handles = list()
            plt.bar(A2_dict.keys(), A2_dict.values(), color=colors, yerr=error_dict.values(), ecolor='black',
                    capsize=10)
            plt.xticks(range(1, 4))
            plt.ylim(top=1850)
            plt.ylim(bottom=0)
            for name, number, color in zip(legend_list, label_list, colors):
                handles.append(mpatches.Patch(color=color, label=str(number) + ' - ' + name))
            plt.legend(handles=handles)
            plt.xlabel('3-stopniowa skala oceny')
            plt.ylabel('Ilość osób')
            temp_name = save.split('_')
            year = temp_name[0]
            month = temp_name[1]
            plt.title('Ocena poczucia bezpieczeństwa w Krakowie - ' + year + ' ' + month, fontsize=10)
            plt.savefig('results/histograms/A2_ver_2/hist_' + save + '.png')
            plt.clf()

        return a2_list

    def calculate_fear_index_affective_part(self, list_df):
        df_dict = dict()
        for df, number in zip(list_df, range(11)):
            affective_list = list()
            affective_dict = dict()
            for i in range(2):
                temp = list()
                df_list = df.iloc[:, i].to_list()
                for col in df_list:
                    if pd.isna(col):
                        temp.append(0)
                    else:
                        col = int(col)
                    if col == 1 or col == 6 or col == 7 or col == 95 or col == 96 or col == 0:
                        temp.append(0)
                    elif col == 2:
                        temp.append(7.5)
                    elif col == 3:
                        temp.append(15)
                    elif col == 4:
                        temp.append(22.5)
                    elif col == 5:
                        temp.append(30)
                    affective_dict[str(i + 1)] = temp
            for i, j in zip(affective_dict['1'], affective_dict['2']):
                affective_list.append((i + j) / 2)
            df_dict[number] = affective_list

        return df_dict

    def calculate_fear_index_cognitive_part(self, list_df):
        df_dict = dict()
        for df, number in zip(list_df, range(11)):
            list_all = list()
            cognitive_dict = dict()
            for i in range(2, 10):
                temp = list()
                for col in df.iloc[:, i].to_list():
                    if pd.isna(col):
                        temp.append(0)
                    else:
                        col = int(col)
                    if col == 1:
                        temp.append(3.75)
                    elif col == 2:
                        temp.append(2.81)
                    elif col == 3:
                        temp.append(1.88)
                    elif col == 4:
                        temp.append(0.94)
                    elif col == 5 or col == 6 or col == 7 or col == 95 or col == 96 or col == 0:
                        temp.append(0)
                    cognitive_dict[str(i)] = temp
            for i in cognitive_dict.keys():
                list_all.append(cognitive_dict[i])
            list_all = np.array(list_all)
            cognitive_list = np.sum(list_all, axis=0)
            df_dict[number] = cognitive_list
        return df_dict

    def calculate_fear_index_behavioral_part(self, list_df):
        df_dict = dict()
        for df, number in zip(list_df, range(11)):
            list_all = list()
            behavioral_dict = dict()
            for i in range(10, 21):
                temp = list()
                for col in df.iloc[:, i].to_list():
                    if pd.isna(col):
                        temp.append(0)
                    else:
                        col = int(col)
                    if col == 1:
                        temp.append(2.73)
                    elif col == 2:
                        temp.append(2.05)
                    elif col == 3:
                        temp.append(1.36)
                    elif col == 4:
                        temp.append(0.68)
                    elif col == 5 or col == 6 or col == 7 or col == 95 or col == 96 or col == 0:
                        temp.append(0)
                    behavioral_dict[str(i)] = temp
            for i in behavioral_dict.keys():
                list_all.append(behavioral_dict[i])
            list_all = np.array(list_all)
            behavioral_list = np.sum(list_all, axis=0)
            df_dict[number] = behavioral_list
        return df_dict

    def calculate_fear_index(self, list_df, save_name):
        legend_list = ["bardzo niski", "raczej niski", "średni",
                       "raczej wysoki", "bardzo wysoki"]
        legend_list_3_cat = ["niski", "średni", "wysoki"]
        affective_dict = self.calculate_fear_index_affective_part(list_df)
        cognitive_dict = self.calculate_fear_index_cognitive_part(list_df)
        behavioral_dict = self.calculate_fear_index_behavioral_part(list_df)
        list_all = list()
        for i in affective_dict.keys():
            temp = np.array([affective_dict[i], cognitive_dict[i], behavioral_dict[i]])
            list_all.append(np.sum(temp, axis=0))

        label_list = [i + 1 for i in range(5)]
        temp_value = [0 for i in range(5)]
        label_list_3_cat = [i + 1 for i in range(3)]
        temp_value_3_cat = [0 for i in range(3)]
        fear_list_df = list()
        fear_list_df_3_cat = list()
        for element, save in zip(list_all, save_name):
            fear_index_dict = dict(zip(label_list, temp_value))
            fear_index_dict_3_cat = dict(zip(label_list_3_cat, temp_value_3_cat))
            for i in element:
                if 0 <= i < 30:
                    fear_index_dict[label_list[0]] += 1
                    fear_index_dict_3_cat[label_list_3_cat[0]] += 1
                elif 30 <= i < 40:
                    fear_index_dict[label_list[1]] += 1
                    fear_index_dict_3_cat[label_list_3_cat[1]] += 1
                elif 40 <= i < 50:
                    fear_index_dict[label_list[2]] += 1
                    fear_index_dict_3_cat[label_list_3_cat[1]] += 1
                elif 50 <= i < 60:
                    fear_index_dict[label_list[3]] += 1
                    fear_index_dict_3_cat[label_list_3_cat[1]] += 1
                elif 60 <= i <= 90:
                    fear_index_dict[label_list[4]] += 1
                    fear_index_dict_3_cat[label_list_3_cat[2]] += 1

            error_dict = dict(zip(label_list_3_cat, temp_value_3_cat))
            for i in label_list_3_cat:
                error_dict[i] = np.sqrt(fear_index_dict_3_cat[i])
            fear_index_dict_percents = self.change_to_percents(fear_index_dict, label_list, 5)
            fear_list_df.append(fear_index_dict_percents)
            fear_index_dict_percents_3_cat = self.change_to_percents(fear_index_dict_3_cat, label_list_3_cat, 3)
            fear_list_df_3_cat.append(fear_index_dict_percents_3_cat)
            colors = list('rgb')
            handles = list()
            plt.bar(fear_index_dict_3_cat.keys(), fear_index_dict_3_cat.values(), yerr=error_dict.values(),
                    ecolor='black', capsize=10, color=colors)
            plt.ylim(top=1850)
            plt.ylim(bottom=0)
            plt.xticks(range(1, 4))
            for name, number, color in zip(legend_list_3_cat, label_list_3_cat, colors):
                handles.append(mpatches.Patch(color=color, label=str(number) + ' - ' + name))
            plt.legend(handles=handles)
            plt.xlabel('Wartość indeksu strachu')
            plt.ylabel('Ilość osób')
            temp_name = save.split('_')
            year = temp_name[0]
            month = temp_name[1]
            plt.title('Indeks strachu - ' + year + ' ' + month, fontsize=10)
            plt.savefig('results/histograms/fear_index_3_cat/hist_' + save + '.png')
            plt.clf()

        return list_all, fear_list_df, fear_list_df_3_cat, affective_dict, cognitive_dict, behavioral_dict

    def calculate_A3(self, list_df, save_name):
        legend_list = ["Zdecydowanie tak", "Raczej tak", "Ani tak, ani nie",
                       "Raczej nie", "Zdecydowanie nie"]
        legend_list_cat3 = ["tak", "Ani tak, ani nie", "nie"]
        temp_value = [0 for i in range(5)]
        label_list = [i + 1 for i in range(5)]
        temp_value_3_cat = [0 for i in range(3)]
        label_list_3_cat = [i + 1 for i in range(3)]
        a3_list = list()
        a3_list_3_cat = list()
        for df, save in zip(list_df, save_name):
            A3_dict = dict(zip(label_list, temp_value))
            A3_dict_3_cat = dict(zip(label_list_3_cat, temp_value_3_cat))
            for i in df.iloc[:, 1].to_list():
                if i == 1:
                    A3_dict[label_list[0]] += 1
                    A3_dict_3_cat[label_list[0]] += 1
                elif i == 2:
                    A3_dict[label_list[1]] += 1
                    A3_dict_3_cat[label_list[0]] += 1
                elif i == 3:
                    A3_dict[label_list[2]] += 1
                    A3_dict_3_cat[label_list[1]] += 1
                elif i == 4:
                    A3_dict[label_list[3]] += 1
                    A3_dict_3_cat[label_list[2]] += 1
                elif i == 5:
                    A3_dict[label_list[4]] += 1
                    A3_dict_3_cat[label_list[2]] += 1

            colors = list('rgbkymc')
            handles = list()
            A3_dict_percents = self.change_to_percents(A3_dict, label_list, 5)
            A3_dict_percents_3_cat = self.change_to_percents(A3_dict_3_cat, label_list_3_cat, 3)
            a3_list.append(A3_dict_percents)
            a3_list_3_cat.append(A3_dict_percents_3_cat)
            error_dict = dict(zip(label_list, temp_value))
            for i in label_list:
                error_dict[i] = np.sqrt(A3_dict[i])
            plt.bar(A3_dict.keys(), A3_dict.values(), yerr=error_dict.values(), ecolor='black', capsize=10,
                    color=colors)
            for name, number, color in zip(legend_list, label_list, colors):
                handles.append(mpatches.Patch(color=color, label=str(number) + ' - ' + name))
            plt.legend(handles=handles)
            plt.xlabel('5-stopniowa skala oceny')
            plt.ylabel('Ilość osób')
            plt.ylim(top=1850)
            plt.ylim(bottom=0)
            temp_name = save.split('_')
            year = temp_name[0]
            month = temp_name[1]
            plt.title('Ocena poczucia bezpieczeństwa w poszczególnych dzielnicach Krakowa - ' + year + ' ' + month,
                      fontsize='10')
            plt.savefig('results/histograms/A3/hist_' + save + '.png')
            plt.clf()
        return a3_list, a3_list_3_cat

    def create_time_series(self, list_dicts, question, number_of_answers, label_x):
        label_list = [i + 1 for i in range(number_of_answers)]
        data_label = ['2014 III', '2014 IX', '2015 VI', '2015 IX', '2016 III', '2016 IX',
                      '2017 VI', '2017 IX', '2018 VI', '2018 IX', '2019 VIII']

        dates = [
            datetime(2014, 3, 1),
            datetime(2014, 9, 1),
            datetime(2015, 6, 1),
            datetime(2015, 9, 1),
            datetime(2016, 3, 1),
            datetime(2016, 9, 1),
            datetime(2017, 6, 1),
            datetime(2017, 9, 1),
            datetime(2018, 6, 1),
            datetime(2018, 9, 1),
            datetime(2019, 8, 1)]

        temp_dict = collections.defaultdict(list)
        error_dict = collections.defaultdict(list)
        error_value_up_dict = collections.defaultdict(list)
        error_value_down_dict = collections.defaultdict(list)
        for i in list_dicts:
            for label in label_list:
                temp_dict[label].append(i[label])
                error = np.sqrt(i[label])
                error_dict[label].append(error)
                error_value_up_dict[label].append(i[label] + error)
                error_value_down_dict[label].append(i[label] - error)

        for i, label in zip(label_list, label_x):
            plt.xticks(fontsize=7)
            plt.plot_date(dates, temp_dict[i], linestyle='solid', color='black')
            plt.plot_date(dates, error_value_up_dict[i], fmt='--', color='k', linewidth=0.5)
            plt.plot_date(dates, error_value_down_dict[i], fmt='--', color='k', linewidth=0.5)
            plt.ylim(top=100)
            plt.ylim(bottom=0)
            plt.xlabel('Data')
            plt.ylabel('Procent respodentów')
            plt.title("Zmiana odpowiedzi '" + label + "' dla skali subiektywnego ryzyka wiktymizacjii", fontsize='9')

            plt.savefig('results/time_series/' + question + '/' + str(i) + '.png', dpi=300)
            plt.clf()


from collections import deque

class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if not root: return root

        q = deque()
        q.append(root)

        while q:
            n = len(q)
            level = []

            for _ in range(n):
                node = q.popleft()
                level.append(node)

                if node.left:
                    q.append(node.left)
                if node.right:
                    q.append(node.right)

            for i in range(len(level) - 1):
                level[i].next = level[i + 1]

        return root

class Solution2:
    def connect(self, root: 'Node') -> 'Node':
        if not root:
            return root

        # Start with the root node. There are no next pointers
        # that need to be set up on the first level
        leftmost = root

        # Once we reach the final level, we are done
        while leftmost.left:

            # Iterate the "linked list" starting from the head
            # node and using the next pointers, establish the
            # corresponding links for the next level
            head = leftmost
            while head:

                # CONNECTION 1
                head.left.next = head.right

                # CONNECTION 2
                if head.next:
                    head.right.next = head.next.left

                # Progress along the list (nodes on the current level)
                head = head.next

            # Move onto the next level
            leftmost = leftmost.left

        return root


import SloppyCell.Collections as Collections

expt = Collections.Experiment('Rap1YorkNGF')

expt.longname = 'NGF Stimulation 50 ng/ml - York 1998'
expt.comments = """REF: R. D. York et. al., Nature vol. 392, 622 (1998)
CELLTYPE: PC12
MEAS: GTP binding by Rap1 in response to NGF at 50 ng/ml
UNITS: Rap1.GTP/(Rap1.GTP + Rap1.GDP) X 10 (percent total / 10)
NOTES: Division by 10 is just to put data on a better scale for
NOTES:    plotting
NOTES: Rap1(0) = 0.48 subtracted from this data set so that Rap1(0) = 0
NOTES: No error bars were provided with the original data"""

expt.SetFixedScaleFactors({'Rap1Active': 1.0/(0.2*600000*0.1)})

expt.SetData({'NGFstim50': {
                            'Rap1Active': {
                                           #   0.0:(Rap1Active    0.48   0.048
                                           10.0:(1.09, 0.314),
                                           30.0:(1.11, 0.318),
                                           40.0:(1.59, 0.414),
                                           }
                            }
              }
             )


#Read the file line by line, delete the line break. As files can only contain strings, the number must now be converted into an integer.
#Add the number into a list. When all numbers are in the list, sort the list. Then print out the biggest numbers.

number_list = []
with open('numbers.txt', 'r') as file:
    for line in file:
        line = line.strip()
        line = int(line)
        number_list.append(line)

number_list.sort(reverse=True)
print(number_list[0])
print(number_list[1])
print(number_list[2])


from Bridgelabz.pythonprograms.DataStructure.prac import primeanagram2D
anagramarr = primeanagram2D()  # returns the 2D Anagram Array in which prime number
for x in range(2):             # which are Anagram or Non- Anagram are Store
    if x == 0:
        print("Prime Numbers which are Anagram:")
    else:
        print("Prime Numbers which are not Anagram:")
    for y in range(500):
        if anagramarr[x][y] == 0:
            continue
        print(int(anagramarr[x][y]), end=" ")
    print()


import wx

class RadioButtonGrid(wx.Panel):
    CtrlType = wx.RadioButton
    firstCtrlStyle = wx.RB_GROUP

    def __init__(
        self,
        parent,
        id = wx.ID_ANY,
        pos = wx.DefaultPosition,
        size = wx.DefaultSize,
        rows = None,
        columns = None
    ):
        wx.Panel.__init__(self, parent, id, pos, size)
        biggestWidth = 0
        sizer = wx.FlexGridSizer(len(rows) + 2, len(columns) + 1)
        sizer.Add((0, 0))
        for column in columns:
            staticText = wx.StaticText(self, -1, column)
            width = staticText.GetBestSize()[0]
            if width > biggestWidth:
                biggestWidth = width
            sizer.Add(staticText, 0, wx.ALIGN_CENTER_HORIZONTAL)

        self.ctrlTable = ctrlTable = []
        for column in columns:
            ctrl = self.CtrlType(self, style=self.firstCtrlStyle)
            ctrlColumn = [ctrl]
            for row in rows[1:]:
                ctrl = self.CtrlType(self)
                ctrlColumn.append(ctrl)
            ctrlTable.append(ctrlColumn)

        biggestWidth += 3
        width = ctrl.GetBestSize()[0]
        if width > biggestWidth:
            biggestWidth = width

        for y, row in enumerate(rows):
            staticText = wx.StaticText(self, -1, row)
            sizer.Add(staticText, 0, wx.ALIGN_CENTER_VERTICAL)
            for x, column in enumerate(columns):
                ctrl = ctrlTable[x][y]
                sizer.Add(ctrl, 0, wx.ALIGN_CENTER_HORIZONTAL)

        sizer.Add((0, 0))
        for column in columns:
            sizer.Add((biggestWidth, 0))

        self.SetSizer(sizer)
        self.SetAutoLayout(True)
        sizer.Fit(self)
        self.Layout()
        self.SetMinSize(self.GetSize())
        self.Bind(wx.EVT_SIZE, self.OnSize)

    def GetValue(self):
        result = []
        for column in self.ctrlTable:
            for i, ctrl in enumerate(column):
                if ctrl.GetValue():
                    break
            result.append(i)
        return result

    def OnSize(self, event):
        if self.GetAutoLayout():
            self.Layout()

    def SetValue(self, value):
        for column, val in enumerate(value):
            self.ctrlTable[column][val].SetValue(True)


import imp
from multiprocessing import context
from django.shortcuts import render
import requests

# Create your views here.

def home(request):

    city = request.GET.get('city', "Lucknow")
    url = f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid=22093d6a3f26e74036ac481b4eed0935'
    data = requests.get(url).json()
    #print(data)

    payload = {
    'city' : data['name'],
    'weather': data['weather'][0]['main'],
    'icon' : data['weather'][0]['icon'],
    'kelvin_temprature' : data['main']['temp'],
    'celcius_temprature' : int(data['main']['temp']-273),
    'pressure' : data['main']['pressure'],
    'humidity' : data['main']['humidity'],
    'description' : data['weather'][0]['description']
    }

    context = {'data' : payload}
    print(data)

    return render(request,'home.html',context)