#    Coding Challenge:    Parentheses
#    By:                  Lyman McBride
#    Date:                5/3/2021

#    Purpose:             Write a function that takes a string of parentheses,
#                         and determines if the order of the parentheses is valid.
#                         The function should return true if the string is valid,
#                         and false if it's invalid.

#   Runtime:              O(N)

def parentheses(string):
    print(string)
    one = "("
    close = ")"
    stack = []
    for paren in string:
        if paren == one:
            stack.append(paren)
        elif paren == close:
            if len(stack) > 0:
                stack.pop()
            else:
                return False

    return True if len(stack) == 0 else False

print(parentheses("  ("))


from google.cloud import language

from google.cloud.language import enums
from google.cloud.language import types
import csv
# Instantiates a client
client = language.LanguageServiceClient()
# export GOOGLE_APPLICATION_CREDENTIALS="/Users/rustamquliyev/Documents/Optify/Optify_App/Django-backend/optify/optify-a768f9fd8bc9.json"

with open('schedule_data.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    for row in csv_reader:
        text = row[0]
        document = types.Document(
        content=text,
        language="en",
        type=enums.Document.Type.PLAIN_TEXT)
        response = client.analyze_syntax(
            document=document
        )
        print(response)

    # Get the language of the text, which will be the same as
    # the language specified in the request or, if not specified,
    # the automatically-detected language.

#Entity Analyss

# Detects the sentiment of the text
# sentiment = client.analyze_sentiment(document=document).document_sentiment

# print('Text: {}'.format(text))
# print('Sentiment: {}, {}'.format(sentiment.score, sentiment.magnitude))


import re

N = int(input().strip())
l=[]
for i in range(N):
    firstName,emailID = input().strip().split(' ')
    firstName,emailID = [str(firstName),str(emailID)]
    if re.search('@gmail\.com$',emailID):
        l.append(firstName)
print(*sorted(l),sep='\n')


__author__ = 'bhushan'

import threading
import time

class AsyncWrite(threading.Thread):
    def __init__(self, text, out):
        threading.Thread.__init__(self)
        self.text = text
        self.out = out

    def run(self):
        f = open(self.out, "a")
        f.write(self.text + '\n')
        f.close()
        time.sleep(2)
        print("Finished writing to " + self.out)

def Main():
    message = raw_input("Enter message")
    background = AsyncWrite(message, 'out.txt')
    background.start()
    print("100 + 400 = ", 100+400 )
    background.join()
    print("waited for thread to complete")

if __name__ == '__main__':
    Main()


class DispatchException(Exception):
    def __init__(self, message, *, process, event, proc_errors):
        self.message = message
        self.process = process
        self.event = event
        self.proc_errors = proc_errors
        super().__init__(message)

    @property
    def formatted_errors(self):
        return [{
            'id': str(pe.id),
            'func': str(pe.func),
            'message': str(pe.message)
        } for pe, _ in self.proc_errors]


# Method 1 : OEIS A063990

l = [220, 284, 1184, 1210, 2620, 2924, 5020, 5564, 6232, 6368]

print(sum(l))

# Method 2

from math import isqrt

def divisor_sum(n):
    total = 0
    sqrt_n = isqrt(n)
    for i in range(1, sqrt_n + 1):
        if n % i == 0:
            total += (i + n // i)

    if n == sqrt_n * sqrt_n:
        total -= sqrt_n

    return total - n

sums = {0: 0}
amicable = []

for n in range(1, 10000 + 1):
    div_sum = divisor_sum(n)
    sums[n] = div_sum
    if div_sum < n and sums[div_sum] == n:
        amicable.append(n)
        amicable.append(div_sum)

print(sum(amicable))


from rest_framework.response import Response
from rest_framework.decorators import api_view
from .serializers import TaskSerializer
from .models import Task

# testing without db connection
person = {"p1":"tamim"}

@api_view(["GET","POST"])
def getData(request):
    global person
    if request.method == "GET":
        # person = {"name":'Tamim'}
        return Response(person)
    if request.method == "POST":
        data = request.data
        person = data
        return Response(f"person : {person}")

# testing with db connection
@api_view(["GET","POST",'DELETE'])
def taskList(request):
    if request.method == "GET":
        tasks = Task.objects.all()
        serializers = TaskSerializer(tasks,many = True)
        return Response(serializers.data)
    if request.method == "POST":
        serializers = TaskSerializer(data=request.data)
        if serializers.is_valid():
            serializers.save()
            return Response("Successfully Added")
        return Response("Product Add Failed")
    if request.method == "DELETE":
        task = Task.objects.get(id=request.data.id)
        task.delete()
        return Response("Item successfully deleted")
    # print(serializers)
    # return Response("hello world")


import happybase
connection = happybase.Connection('192.168.30.130')
connection.open()

print(connection.tables())
# table.put(b'name', {b'family:qual1': b'value1',
#                        b'family:qual2': b'value2'})
#
# # prints 'value1'
# row = table.row(b'name')
# print(row[b'family:qual1'])
#
# for key, data in table.rows([b'row-key-1', b'row-key-2']):
#     print(key, data)  # prints row key and data for each row
#
# for key, data in table.scan(row_prefix=b'row'):
#     print(key, data)  # prints 'value1' and 'value2'
#
# # row = table.delete(b'row-key')


import re

patterns = ["textA", "textB"]
text = "this contain textB as an example contained"

#iterating in patterns to find a match
for pattern in patterns:
    print("Searching for: " + pattern)

    if re.search(pattern,text):
        print("Found")
    else:
        print("Not Found")

#returning the position of
find_position = re.search("textB",text)
print(str(type(find_position)) + " " + str(find_position.start()))

#searches for term many times, returns a list of all matches  re.findall
print(str(len(re.findall("on", text))) + "  " + str(re.findall("on", text)))

#reg expression
def multi_re_find(patterns, phrase):

    for pat in pattern:
        print("Searching fo pattern {}".format(pat))
        print(re.findall(pat, phrase))
        print("\n")

new_text1 = "sddsddd ... sdddd....sddd...ssssddd...sssd"

#pattern = ["sd*"] #0 or more times
#pattern = ["sd?"] #0 or more than once d
#pattern = ["sd{3}"] #followed by 3 d.
pattern = ["s[sd]+"] #an s followed by one more s or d

multi_re_find(pattern,new_text1)


from setuptools import setup

with open("README.md", "r", encoding="utf-8") as fh:
    long_description = fh.read()

setup(
    name='guancodes',
    version='0.0.3',
    author="Tomasz Rybotycki",
    author_email="rybotycki.tomasz+guancodes@gmail.com",
    long_description=long_description,
    long_description_content_type='text/markdown',
    description="Package for generating Guan Codes",
    packages=['guancodes'],
    install_requires=[
        'requests',
        'importlib-metadata; python_version == "3.8"',
    ],
    classifiers=[
        "Intended Audience :: Developers",
        "License :: OSI Approved :: Apache Software License",
        "Natural Language :: English",
    ],
    license="Apache License 2.0.",
)


# Event Types
SENSOR_UPDATE_COMPLETE = 'SENSOR_UPDATE_COMPLETE'
SENSOR_UPDATE = 'SENSOR_UPDATE'

INSIDE_TENT = 'insideTent'
OUTSIDE_TENT = 'outsideTent'
FLOATER_BOTTOM = 'floaterBottom'
FLOATER_TOP = 'floaterTop'
RESERVOIR = 'reservoir'
PH = 'pH'
EMERGENCY_SHUTOFF = 'emergencyShutoff'

TEMPERATURE = 'temperature'
HUMIDITY = 'humidity'
STATE = 'state'
UPDATED_AT = 'updatedAt'
VALUE = 'value'
SENSOR = 'sensor'
PROPERTY = 'property'
TRIGGERED_RECENTLY = 'triggeredRecently'
TIME = 'time'
DEPTH = 'depth'

sensorsInitialState = {
  INSIDE_TENT: {
    TEMPERATURE: None,
    HUMIDITY: None,
    UPDATED_AT: None,
  },
  OUTSIDE_TENT: {
    TEMPERATURE: None,
    HUMIDITY: None,
    UPDATED_AT: None,
  },
  FLOATER_BOTTOM: {
    STATE: None,
    UPDATED_AT: None,
    TRIGGERED_RECENTLY: True,
  },
  FLOATER_TOP: {
    STATE: None,
    UPDATED_AT: None,
    TRIGGERED_RECENTLY: True,
  },
  EMERGENCY_SHUTOFF: {
    STATE: None,
    UPDATED_AT: None,
    TRIGGERED_RECENTLY: True,
  },
  RESERVOIR: {
    TEMPERATURE: None,
    UPDATED_AT: None,
    DEPTH: None,
  },
  PH: {
    VALUE: None,
    UPDATED_AT: None,
  },
}

class Sensors:
  def __call__(self, state=sensorsInitialState, action={}):
    state = state.copy() # Ensure we're returning a new object
    sensor = action.get(SENSOR)
    prop = action.get(PROPERTY)

    if action.get('type') == SENSOR_UPDATE:
      state[sensor] = state[sensor].copy() # Ensure we're updating a new obj

      if state[sensor][prop] != action[VALUE]:
        state[sensor][prop] = action[VALUE]
        state[sensor][UPDATED_AT] = int(action[TIME])

    return state


#!venv/bin/python

import src.parameters
import src.io
import src.ions
import src.aggregates
import src.peptides
import numpy as np
import pandas as pd
import scipy.sparse
from matplotlib import pyplot as plt
import matplotlib
import seaborn as sns
# from sklearn import linear_model
import os

# Initializing
extension = "tenzer"
# extension = "udmse"
# extension = "swim"
if extension == "tenzer":
    parameter_file_name = "projects/tenzer/parameters.json"
    conditions = {
        "A": slice(0, None, 2),
        "B": slice(1, None, 2),
        "QC": slice(0, None, 1)
    }
elif extension == "udmse":
    parameter_file_name = "projects/udmse/parameters.json"
    conditions = {
        "A": slice(0, 9, 1),
        "B": slice(9, 18, 1),
        "QC": slice(18, None, 1)
    }
elif extension == "swim":
    parameter_file_name = "projects/swim/parameters.json"
    conditions = {
        "A": slice(0, 9, 1),
        "B": slice(9, 18, 1),
        "QC": slice(18, None, 1)
    }

parameters = src.parameters.importParameterDictFromJSON(parameter_file_name)
log = src.io.Log(parameters["LOG_FILE_NAME"][:-4] + "_" + extension + "_lfq.txt")
parameters["PLOTS_PATH"] = parameters["OUTPUT_PATH"] + "figures/"
if not os.path.exists(parameters["PLOTS_PATH"]):
    os.makedirs(parameters["PLOTS_PATH"])

# Loading data
with log.newSection("Loading data"):
    anchors = src.io.loadArray("ANCHORS_FILE_NAME", parameters)
    anchor_ions = src.io.loadMatrix(
        "ANCHOR_IONS_FILE_NAME",
        parameters,
    )
    ions = src.io.loadArray("IONS_FILE_NAME", parameters)
    ion_alignment_parameters = src.io.loadJSON(
        "ION_ALIGNMENT_PARAMETERS_FILE_NAME",
        parameters,
    )
    anchor_alignment_parameters = src.io.loadJSON(
        "ANCHOR_ALIGNMENT_PARAMETERS_FILE_NAME",
        parameters,
    )
    neighbors = src.io.loadMatrix(
        "ANCHOR_NEIGHBORS_FILE_NAME",
        parameters,
    )
    neighbors += neighbors.T
    database = src.peptides.loadDatabase(parameters["DATABASE_FILE_NAME"])
    base_mass_dict = database["base_mass_dict"]
    proteins = database["proteins"]
    total_protein_sequence = database["total_protein_sequence"]
    # ptms = database["ptms"]
    # ptm_matrix = database["ptm_matrix"]
    peptides = database["peptides"]
    peptide_index_matrix = database["peptide_index_matrix"]
    # digestion_matrix = database["digestion_matrix"]
    peptide_masses = database["peptide_masses"]
    fragments = database["fragments"]
    anchor_peptide_scores = src.io.loadMatrix(
        "ANCHOR_PEPTIDE_SCORES_FILE_NAME",
        parameters,
    )
    anchor_peptide_match_counts = src.io.loadMatrix(
        "ANCHOR_PEPTIDE_MATCH_COUNTS_FILE_NAME",
        parameters,
    )
    peptide_masses, fragments = src.peptides.calculateMasses(
        peptides,
        peptide_index_matrix,
        base_mass_dict,
        total_protein_sequence,
        parameters,
        log,
    )
    anchor_boundaries, fragment_peptide_indices, fragment_indices = src.aggregates.matchAnchorsToFragments(
        fragments,
        anchors,
        base_mass_dict,
        parameters,
        log
    )

# # Plot calibration
# with log.newSection("Plotting calibration results"):
#     estimation_anchors = src.io.loadArray(
#         "PSEUDO_AGGREGATE_IONS_FILE_NAME",
#         parameters,
#         log
#     )[1::2]
#     fig, ax = plt.subplots(3, 2, sharex=True, sharey="row")
#     tmp = plt.subplots_adjust(hspace=0.1, wspace=0.1)
#     quick_anchors = np.empty(
#         len(estimation_anchors),
#         dtype=estimation_anchors.dtype
#     )
#     for attribute in quick_anchors.dtype.names:
#         quick_anchors[attribute] = np.average(estimation_anchors[attribute], axis=1)
#     for attribute, x_loc, y_loc in [
#         ("MZ", 0, 0),
#         ("CALIBRATED_MZ", 1, 0),
#         ("DT", 0, 1),
#         ("CALIBRATED_DT", 1, 1),
#         ("RT", 0, 2),
#         ("CALIBRATED_RT", 1, 2),
#     ]:
#         average_attribute = quick_anchors[attribute].reshape((-1, 1))
#         data = estimation_anchors[attribute] - average_attribute
#         if attribute in parameters["RELATIVE_ATTRIBUTES"]:
#             data *= 1000000 / average_attribute
#             label = "{} PPM".format(attribute)
#         else:
#             label = attribute
#         tmp = sns.violinplot(
#             x='variable',
#             y='value',
#             data=pd.melt(
#                 pd.DataFrame(
#                     data
#                 ),
#             ),
#             ax=ax[y_loc, x_loc],
#             inner=None
#         )
#         tmp = ax[y_loc, x_loc].axes.get_xaxis().set_visible(False)
#         tmp = ax[y_loc, x_loc].axes.get_yaxis().set_visible(False)
#         tmp = ax[y_loc, x_loc].set_xlabel("")
#         tmp = ax[y_loc, x_loc].set_ylabel("")
#     tmp = ax[0, 0].set_ylabel(u"Δ MZ (ppm)")
#     tmp = ax[1, 0].set_ylabel(u"Δ DT")
#     tmp = ax[2, 0].set_ylabel(u"Δ RT")
#     tmp = ax[0, 0].axes.get_yaxis().set_visible(True)
#     tmp = ax[1, 0].axes.get_yaxis().set_visible(True)
#     tmp = ax[2, 0].axes.get_yaxis().set_visible(True)
#     tmp = ax[0, 0].set_title("Uncalibrated")
#     tmp = ax[0, 1].set_title("Calibrated")
#     tmp = ax[2, 0].axes.get_xaxis().set_visible(True)
#     tmp = ax[2, 1].axes.get_xaxis().set_visible(True)
#     # tmp = fig.text(0.5, 0.04, 'Sample', ha='center')
#     tmp = ax[2, 0].get_xaxis().set_ticklabels(
#         [
#             "Sample {}".format(x.split("_")[-2]) for x in parameters["APEX_FILE_NAMES"]
#         ]
#     )
#     tmp = ax[2, 1].get_xaxis().set_ticklabels(
#         [
#             "Sample {}".format(x.split("_")[-2]) for x in parameters["APEX_FILE_NAMES"]
#         ]
#     )
#     tmp = plt.setp(ax[2, 0].get_xticklabels(), rotation=45, ha="right")
#     tmp = plt.setp(ax[2, 1].get_xticklabels(), rotation=45, ha="right")
#     # plt.show()
#     tmp = plt.savefig(parameters["PLOTS_PATH"] + extension + "_lfq_calibration.pdf", bbox_inches='tight')
#     tmp = plt.close()

# Plot calibration
with log.newSection("Plotting calibration results"):
    estimation_anchors = src.io.loadArray(
        "PSEUDO_AGGREGATE_IONS_FILE_NAME",
        parameters,
        log
    )[1::2]
    fig, ax = plt.subplots(2, 3, sharex="col", sharey=True)
    tmp = plt.subplots_adjust(hspace=0.1, wspace=0.1)
    quick_anchors = np.empty(
        len(estimation_anchors),
        dtype=estimation_anchors.dtype
    )
    for attribute in quick_anchors.dtype.names:
        quick_anchors[attribute] = np.average(estimation_anchors[attribute], axis=1)
    for attribute, x_loc, y_loc in [
        ("MZ", 0, 0),
        ("CALIBRATED_MZ", 0, 1),
        ("DT", 1, 0),
        ("CALIBRATED_DT", 1, 1),
        ("RT", 2, 0),
        ("CALIBRATED_RT", 2, 1),
    ]:
        average_attribute = quick_anchors[attribute].reshape((-1, 1))
        data = estimation_anchors[attribute] - average_attribute
        if attribute in ["MZ", "CALIBRATED_MZ"]:
            data *= 1000000 / average_attribute
            label = "{} PPM".format(attribute)
        else:
            label = attribute
        tmp = sns.violinplot(
            x='value',
            y='variable',
            data=pd.melt(
                pd.DataFrame(
                    data
                ),
            ),
            ax=ax[y_loc, x_loc],
            inner=None,
            orient="h"
        )
        tmp = ax[y_loc, x_loc].axes.get_xaxis().set_visible(False)
        tmp = ax[y_loc, x_loc].axes.get_yaxis().set_visible(False)
        tmp = ax[y_loc, x_loc].set_xlabel("")
        tmp = ax[y_loc, x_loc].set_ylabel("")
    tmp = ax[0, 0].set_title(r'$\Delta m/z$ (ppm)')
    tmp = ax[0, 1].set_title(r'$\Delta t_D$')
    tmp = ax[0, 2].set_title(r'$\Delta t_R$')
    tmp = ax[1, 0].axes.get_xaxis().set_visible(True)
    tmp = ax[1, 1].axes.get_xaxis().set_visible(True)
    tmp = ax[1, 2].axes.get_xaxis().set_visible(True)
    tmp = ax[0, 2].yaxis.set_label_position("right")
    tmp = ax[1, 2].yaxis.set_label_position("right")
    tmp = ax[0, 2].set_ylabel("Uncalibrated")
    tmp = ax[1, 2].set_ylabel("Calibrated")
    tmp = ax[0, 2].axes.get_yaxis().set_visible(True)
    tmp = ax[1, 2].axes.get_yaxis().set_visible(True)
    tmp = ax[0, 2].tick_params(axis='y', which='both', left=False)
    tmp = ax[1, 2].tick_params(axis='y', which='both', left=False)
    tmp = ax[0, 0].get_yaxis().set_ticklabels(
        [
            os.path.splitext(
                os.path.basename(x)
            )[0] for x in parameters["APEX_FILE_NAMES"]
        ]
    )
    tmp = ax[1, 0].get_yaxis().set_ticklabels(
        [
            os.path.splitext(
                os.path.basename(x)
            )[0] for x in parameters["APEX_FILE_NAMES"]
        ]
    )
    tmp = ax[0, 0].axes.get_yaxis().set_visible(True)
    tmp = ax[1, 0].axes.get_yaxis().set_visible(True)
    # plt.show()
    tmp = plt.savefig(parameters["PLOTS_PATH"] + extension + "_lfq_calibration.pdf", bbox_inches='tight')
    tmp = plt.close()

# Unfiltered LFQ calculations
with log.newSection("Calculating unfiltered aggregate LFQ"):
    unfiltered_ions = src.io.loadArray("IONS_UNFILTERED_FILE_NAME", parameters)
    unfiltered_anchors, unfiltered_anchor_ions, unfiltered_ions = src.aggregates.defineFromIons(
        unfiltered_ions,
        parameters,
        log,
        save=False,
        remove_noise=False,
        order_anchors=False
    )
    log.printMessage("Calculating aggregate properties per condition")
    anchors_per_condition = {}
    anchor_ions_per_condition = {}
    sample_ions = unfiltered_anchor_ions.T.tocsr()
    sample_ions.data += 1
    for condition, condition_slice in conditions.items():
        condition_anchors = np.empty(
            len(unfiltered_anchors),
            dtype=[
                ("INTENSITY", np.float),
                ("CV", np.float),
                ("ION_COUNT", np.int),
            ]
        )
        condition_anchor_ions = sample_ions[condition_slice].T.tocsr()
        condition_anchor_ions.data -= 1
        anchor_sizes = np.diff(condition_anchor_ions.indptr)
        intensities = np.zeros(len(unfiltered_anchors), dtype=np.float)
        cvs = np.zeros(len(unfiltered_anchors), dtype=np.float)
        for size in range(1, np.max(anchor_sizes) + 1):
            anchor_subset = np.flatnonzero(anchor_sizes == size)
            anchor_subset_matrix = np.concatenate(
                [
                    condition_anchor_ions.data[
                        condition_anchor_ions.indptr[anchor_index]: condition_anchor_ions.indptr[anchor_index + 1]
                    ] for anchor_index in anchor_subset
                ]
            ).reshape(-1, size)
            intensity_matrix = unfiltered_ions["CALIBRATED_INTENSITY"][anchor_subset_matrix]
            cvs[anchor_subset] = scipy.stats.variation(intensity_matrix, axis=1)
            intensities[anchor_subset] = np.average(intensity_matrix, axis=1)
        condition_anchors["ION_COUNT"] = anchor_sizes
        condition_anchors["CV"] = cvs
        condition_anchors["INTENSITY"] = intensities
        anchors_per_condition[condition] = condition_anchors
        anchor_ions_per_condition[condition] = condition_anchor_ions

# Plotting unfiltered aggregate intensities and counts
with log.newSection("Plotting unfiltered aggregate intensities and counts"):
    fig, ax = plt.subplots(3, 1, sharex=True)
    tmp = plt.subplots_adjust(hspace=0.1)
    sample_totals = []
    for sample in range(parameters["SAMPLE_COUNT"]):
        sample_anchors = unfiltered_ions["AGGREGATE_INDEX"][unfiltered_ions["SAMPLE"] == sample]
        frequencies = np.bincount(unfiltered_anchors["ION_COUNT"][sample_anchors])
        start = np.flatnonzero(frequencies > 0)[0]
        tmp = ax[0].plot(
            np.arange(start, len(frequencies)),
            frequencies[start:],
            marker="."
        )
        sample_totals.append(np.sum(frequencies))
    ax[0].get_yaxis().set_major_formatter(
        matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))
    )
    tmp = ax[0].legend(
        [
            "{} ({} ions)".format(
                os.path.splitext(os.path.basename(name))[0],
                format(count, ",")
            ) for name, count in zip(
                parameters["APEX_FILE_NAMES"],
                sample_totals
            )
        ],
        # bbox_to_anchor=(0., 1.02, 1., .102),
        # loc=5,
        fontsize="x-small",
        ncol=2,
        # mode="expand",
        # borderaxespad=0.
    )
    tmp = ax[0].set_ylabel("Ion Frequency")
    aggregate_frequencies = np.bincount(unfiltered_anchors["ION_COUNT"])
    aggregate_start = np.flatnonzero(aggregate_frequencies > 0)[0]
    tmp = ax[1].plot(
        np.arange(aggregate_start, len(aggregate_frequencies)),
        np.log2(aggregate_frequencies[aggregate_start:]),
        marker="."
    )
    tmp = ax[1].yaxis.set_label_position("right")
    tmp = ax[1].set_ylabel(
        "Log2(Aggregate Frequency)",
        # rotation=270,
        # ha="left",
        # va="center",
    )
    x = [
        np.log2(
            anchors_per_condition["QC"]["INTENSITY"][
                unfiltered_anchors["ION_COUNT"] == i
            ]
        ) for i in range(
            1,
            parameters["SAMPLE_COUNT"] + 1
        )
    ]
    # z = np.array([np.percentile(i, [0, 25, 50, 75, 100]) for i in x])
    # # plt.plot(z ,marker=".")
    # tmp = ax[2].fill_between(range(len(z)), z[:, 0], z[:, 4], alpha=0.5)
    # tmp = ax[2].fill_between(range(len(z)), z[:, 1], z[:, 3], alpha=0.5)
    # tmp = [ax[2].plot(i, c="grey", linestyle=":") for i in z.T]
    # x[0][0]=0 # inf present
    # d = pd.DataFrame(
    #     np.stack(
    #         [
    #             np.concatenate(x),
    #             np.repeat(np.arange(parameters["SAMPLE_COUNT"]) + 1, [len(i) for i in x]),
    #         ]
    #     ).T,
    #     columns=["QC_INTENSITY", "ION_COUNT"]
    # )
    # tmp = sns.violinplot(
    #     x='ION_COUNT',
    #     y='QC_INTENSITY',
    #     data=d,
    #     inner="quartile",
    #     # gridsize=1000,
    # )
    tmp = ax[2].boxplot(x, whis="range")
    # tmp = plt.plot(range(1,11), z[:,2], c="grey",linestyle=":")
    tmp = ax[2].set_ylabel("Log2(Aggregate Intensity)")
    tmp = ax[2].set_xlabel("Reproducibility")
    # tmp = ax[2].yaxis.grid(which="major", linestyle=":", color='lightgrey', alpha=0.5)
    # tmp = ax[2].set_axisbelow(True)
    # tmp = plt.show()
    tmp = plt.savefig(parameters["PLOTS_PATH"] + extension + "_lfq_aggregate_counts_and_intensities.pdf", bbox_inches='tight')
    tmp = plt.close()

# Plotting edge COUNTS
with log.newSection("Plotting aggregate consistent coelution counts"):
    a, b = np.unique(np.diff(neighbors.indptr), return_counts=True)
    fig, ax = plt.subplots(2, 1, sharex=True, gridspec_kw={'height_ratios': [5, 1]})
    tmp = plt.subplots_adjust(hspace=0.1)
    tmp = ax[0].scatter(a, np.log2(b), marker=".")
    tmp = ax[0].set_ylabel("Log2(Aggregate Frequency)")
    tmp = ax[1].boxplot(np.diff(neighbors.indptr), whis="range", vert=False, widths=0.5)
    tmp = ax[1].set_yticks([])
    ax[1].get_xaxis().set_major_formatter(
        matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ','))
    )
    tmp = ax[1].set_xlabel("# Consistently Co-eluting Aggregates")
    # tmp = plt.show()
    tmp = plt.savefig(parameters["PLOTS_PATH"] + extension + "_lfq_aggregate_edge_counts.pdf", bbox_inches='tight')
    tmp = plt.close()

# # Plotting edge COUNTS single sample
# with log.newSection("Plotting aggregate single sample coelution counts"):
#     original_rt_errors = ions["RT_ERROR"].copy()
#     original_dt_errors = ions["DT_ERROR"].copy()
#     ions["RT_ERROR"] = 0.1
#     ions["DT_ERROR"] = 1
#     sample_rt_indices, low_rt_indices, high_rt_indices = src.aggregates.__indexIonRT(
#         anchor_ions,
#         ions,
#         parameters,
#         log
#     )
#     for ion_index in anchor_ions[anchor_index].data:
#         ion = ions[ion_index]
#         ion_rt = ion["RT"]
#         ion_dt = ion["DT"]
#         ion_sample = ion["SAMPLE"]
#         low_index = low_rt_indices[ion_index]
#         high_index = high_rt_indices[ion_index]
#         ion_neighbors = sample_rt_indices[ion_sample][low_index: high_index]
#         ion_neighbors = ion_neighbors[
#             np.abs(
#                 ions["DT"][ion_neighbors] - ion_dt
#             ) < np.sqrt(
#                 ion["DT_ERROR"]**2 + ions["DT_ERROR"][ion_neighbors]**2
#             ) * parameters["ANCHOR_ALIGNMENT_DEVIATION_FACTOR"]
#         ]
#         ion_neighbors = ion_neighbors[
#             ions["AGGREGATE_INDEX"][ion_neighbors] < anchor_index
#         ]
#     fig, ax = plt.subplots(2, 1, sharex=True, gridspec_kw={'height_ratios': [5, 1]})
#     tmp = plt.subplots_adjust(hspace=0.1)
#     a, b = np.unique(np.diff(neighbors.indptr), return_counts=True)
#     tmp = ax[0].scatter(a, np.log2(b), marker=".")
#     tmp = ax[0].set_ylabel("Log(Aggregate frequency)")
#     tmp = ax[1].boxplot(np.diff(neighbors.indptr), whis="range", vert=False, widths=0.5)
#     tmp = ax[1].set_yticks([])
#     tmp = ax[1].set_xlabel("Edge count")
#     # tmp = plt.show()
#     tmp = plt.savefig(parameters["PLOTS_PATH"] + extension + "_lfq_aggregate_edge_counts.pdf", bbox_inches='tight')
#     tmp = plt.close()
#     ions["RT_ERROR"] = original_rt_errors
#     ions["DT_ERROR"] = original_dt_errors

# LFQ calculations
with log.newSection("Calculating aggregate LFQ"):
    anchors_per_condition = {}
    anchor_ions_per_condition = {}
    sample_ions = anchor_ions.T.tocsr()
    sample_ions.data += 1
    for condition, condition_slice in conditions.items():
        condition_anchors = np.empty(
            len(anchors),
            dtype=[
                ("INTENSITY", np.float),
                ("CV", np.float),
                ("ION_COUNT", np.int),
            ]
        )
        condition_anchor_ions = sample_ions[condition_slice].T.tocsr()
        condition_anchor_ions.data -= 1
        anchor_sizes = np.diff(condition_anchor_ions.indptr)
        intensities = np.zeros(len(anchors), dtype=np.float)
        cvs = np.zeros(len(anchors), dtype=np.float)
        for size in range(np.min(parameters["MINIMUM_OVERLAP"]), np.max(anchor_sizes) + 1):
            anchor_subset = np.flatnonzero(anchor_sizes == size)
            anchor_subset_matrix = np.concatenate(
                [
                    condition_anchor_ions.data[
                        condition_anchor_ions.indptr[anchor_index]: condition_anchor_ions.indptr[anchor_index + 1]
                    ] for anchor_index in anchor_subset
                ]
            ).reshape(-1, size)
            intensity_matrix = ions["CALIBRATED_INTENSITY"][anchor_subset_matrix]
            cvs[anchor_subset] = scipy.stats.variation(intensity_matrix, axis=1)
            intensities[anchor_subset] = np.average(intensity_matrix, axis=1)
        condition_anchors["ION_COUNT"] = anchor_sizes
        condition_anchors["CV"] = cvs
        condition_anchors["INTENSITY"] = intensities
        anchors_per_condition[condition] = condition_anchors
        anchor_ions_per_condition[condition] = condition_anchor_ions
    logfcs = np.log2(anchors_per_condition["A"]["INTENSITY"] / anchors_per_condition["B"]["INTENSITY"])

# Calculating edge accuracy
with log.newSection("Calculating consistent coeluton accuracy"):
    classes = np.round(logfcs)
    a_indices, b_indices = neighbors.nonzero()
    overlap = neighbors.data
    a_classes = classes[a_indices]
    b_classes = classes[b_indices]
    c = np.in1d(a_classes, [-2, 0, 1])
    c &= np.in1d(b_classes, [-2, 0, 1])
    a_classes = a_classes[c]
    b_classes = b_classes[c]
    a_indices = a_indices[c]
    b_indices = b_indices[c]
    overlap = neighbors.data[c]
    eco1 = np.zeros(parameters["SAMPLE_COUNT"] + 1)
    yea1 = np.zeros(parameters["SAMPLE_COUNT"] + 1)
    hum1 = np.zeros(parameters["SAMPLE_COUNT"] + 1)
    eco2 = np.zeros(parameters["SAMPLE_COUNT"] + 1)
    yea2 = np.zeros(parameters["SAMPLE_COUNT"] + 1)
    hum2 = np.zeros(parameters["SAMPLE_COUNT"] + 1)
    for i in range(2, parameters["SAMPLE_COUNT"] + 1):
        full_overlap = overlap == i
        a_full = a_classes[full_overlap]
        b_full = b_classes[full_overlap]
        ecoli, human, yeast = np.unique(np.concatenate([a_full, b_full]), return_counts=True)[1]
        total = ecoli + human + yeast
        ecoli_ratio = ecoli / total
        human_ratio = human / total
        yeast_ratio = yeast / total
        ecoli_expected = ecoli_ratio * ecoli_ratio
        human_expected = human_ratio * human_ratio
        yeast_expected = yeast_ratio * yeast_ratio
        equal = a_full == b_full
        ecoli_hits = equal[(a_full == -2) | (a_full == -2)]
        human_hits = equal[(a_full == 0) | (a_full == 0)]
        yeast_hits = equal[(a_full == 1) | (a_full == 1)]
        ecoli_hit_ratio = 2 * np.sum(ecoli_hits) / total
        yeast_hit_ratio = 2 * np.sum(yeast_hits) / total
        human_hit_ratio = 2 * np.sum(human_hits) / total
        eco1[i] = ecoli_hit_ratio / ecoli_ratio
        yea1[i] = yeast_hit_ratio / yeast_ratio
        hum1[i] = human_hit_ratio / human_ratio
        eco2[i] = ecoli_expected / ecoli_ratio
        yea2[i] = yeast_expected / yeast_ratio
        hum2[i] = human_expected / human_ratio

# Plotting edge accuracy
with log.newSection("Plotting consitent coelution accuracy"):
    e_ex, = plt.plot(100 * eco1[2:], marker="o", linestyle="-", c="blue")
    h_ex, = plt.plot(100 * hum1[2:], marker="o", linestyle="-", c="red")
    y_ex, = plt.plot(100 * yea1[2:], marker="o", linestyle="-", c="green")
    e_th, = plt.plot(100 * eco2[2:], marker=".", linestyle=":", c="blue")
    h_th, = plt.plot(100 * hum2[2:], marker=".", linestyle=":", c="red")
    y_th, = plt.plot(100 * yea2[2:], marker=".", linestyle=":", c="green")
    tmp = plt.legend(
        (
            e_ex,
            h_ex,
            y_ex,
            e_th,
            h_th,
            y_th
        ), (
            "LogFC = -2 Experimental (ECOLI)",
            "LogFC = 0 Experimental (HUMAN)",
            "LogFC = 1 Experimental (YEAST)",
            "LogFC = -2 Expected (ECOLI)",
            "LogFC = 0 Expected (HUMAN)",
            "LogFC = 1 Expected (YEAST)"
        ),
        loc="upper left"
    )
    tmp = plt.xlabel("Consistently Co-eluting Runs")
    tmp = plt.xticks(
        np.arange(parameters["SAMPLE_COUNT"] - 1),
        np.arange(2, parameters["SAMPLE_COUNT"] + 1)
    )
    tmp = plt.ylabel("% Consistent Co-eluting Aggregates With Equal LogFC")
    # tmp = plt.show()
    tmp = plt.savefig(parameters["PLOTS_PATH"] + extension + "_lfq_edge_accuracy.pdf", bbox_inches='tight')
    tmp = plt.close()

# Annotation accuracy
with log.newSection("Calculating aggregate annotation accuracy"):
    percolated_pims = pd.read_csv(
        parameters["PERCOLATOR_TARGET_PIMS"],
        delimiter="\t"
    )
    percolated_pim_fdrs = percolated_pims.values[:, 2]
    anchor_pims, peptide_pims = anchor_peptide_match_counts.nonzero()
    pim_fdr = 0.01
    significant_percolated_pims = percolated_pims.values[
        percolated_pim_fdrs <= pim_fdr,
        0
    ].astype(int)
    significant_anchors = anchor_pims[significant_percolated_pims]
    significant_peptides = peptide_pims[significant_percolated_pims]
    significant_peptide_sequences = src.peptides.getPeptideSequences(
        significant_peptides,
        peptides,
        peptide_index_matrix,
        total_protein_sequence
    )
    significant_proteins = src.peptides.getProteinAccessions(
        significant_peptides,
        peptides,
        proteins
    )
    significant_organisms = np.array(
        [
            prot.split("_")[-1] for prot in significant_proteins
        ]
    )

# Plot annotation accuracies
with log.newSection("Plotting aggreggate annotation accuracy"):
    organism_coloring = np.repeat("grey", len(significant_organisms)).astype(np.object)
    organism_coloring[significant_organisms == "HUMAN"] = "red"
    organism_coloring[significant_organisms == "ECOLI"] = "blue"
    organism_coloring[significant_organisms == "YEAST"] = "green"
    significant_organisms[organism_coloring == "grey"] = "OTHER"
    unique_organisms = ["OTHER", "ECOLI", "YEAST", "HUMAN"]
    for i, c in enumerate(unique_organisms):
        s = np.flatnonzero(significant_organisms == c)
        scatter = plt.scatter(
            np.log2(anchors_per_condition["QC"]["INTENSITY"][significant_anchors[s]]),
            logfcs[significant_anchors][s],
            c=organism_coloring[s],
            s=1
        )
    tmp = plt.legend(unique_organisms)
    tmp = plt.xlabel("Log2(QC)")
    tmp = plt.ylabel("Log2(B/A)")
    # tmp = plt.show()
    tmp = plt.savefig(parameters["PLOTS_PATH"] + extension + "_lfq_annotation_accuracy.pdf", bbox_inches='tight')
    tmp = plt.close()

# # Plot annotation accuracies
# with log.newSection("Plotting aggreggate annotation accuracy"):
#     unique_organisms = ["ECOLI", "YEAST", "HUMAN"]
#     fig, ax = plt.subplots(1, len(unique_organisms), sharex=True, sharey=True)
#     for i, c in enumerate(unique_organisms):
#         scatter = ax[i].scatter(
#             np.log2(anchors_per_condition["QC"]["INTENSITY"][significant_anchors]),
#             logfcs[significant_anchors],
#             c="grey",
#             s=1
#         )
#         s = np.flatnonzero(significant_organisms == c)
#         scatter = ax[i].scatter(
#             np.log2(anchors_per_condition["QC"]["INTENSITY"][significant_anchors[s]]),
#             logfcs[significant_anchors][s],
#             c="red",
#             s=1
#         )
#         tmp = ax[i].set_title(c)
#     tmp = ax[1].set_xlabel("Log(A+B)")
#     tmp = ax[0].set_ylabel("Log(A/B)")
#     # tmp = plt.show()
#     tmp = plt.savefig(parameters["PLOTS_PATH"] + extension + "_lfq_annotation_accuracy.pdf", bbox_inches='tight')
#     tmp = plt.close()

# Plot significant aggreggate ion count enrichment
with log.newSection("Plotting significant aggreggate ion count enrichment"):
    annotated_frequencies = np.bincount(anchors["ION_COUNT"][significant_anchors])
    all_frequencies = np.bincount(anchors["ION_COUNT"])
    fig, ax = plt.subplots(1, 1)
    tmp = ax.set_xlabel("Reproducibility")
    tmp = ax.set_ylabel("Log2(Frequency)")
    # ax2 = ax.twinx()
    plt_annotated, = ax.plot(
        np.arange(2, parameters["SAMPLE_COUNT"] + 1),
        np.log2(annotated_frequencies[2:]),
        c="green",
        marker=".",
        label="Annotated",
    )
    plt_all, = ax.plot(
        np.arange(2, parameters["SAMPLE_COUNT"] + 1),
        np.log2(all_frequencies[2:]),
        c="red",
        marker=".",
        label="All",
    )
    # plt_percentage, = ax2.plot(
    #     np.arange(2, parameters["SAMPLE_COUNT"] + 1),
    #     annotated_frequencies[2:] / all_frequencies[2:],
    #     c="blue",
    #     marker=".",
    #     # label="All aggregates",
    # )
    tmp = ax.legend(
        [plt_annotated, plt_all],
        ["Annotated Aggregates", "All Aggregates"],
        # loc='upper center'
    )
    # tmp = ax2.legend(
    #     [plt_percentage],
    #     ["Annotation percentage"],
    # )
    # tmp = plt.show()
    tmp = plt.savefig(parameters["PLOTS_PATH"] + extension + "_lfq_annotated_aggregate_enrichment.pdf", bbox_inches='tight')
    tmp = plt.close()

# # Plot annotation example
# with log.newSection("Plotting significant aggreggate ion annotation example"):
#     top_score_index = np.argmax(anchor_peptide_scores.data)
#     anchor_index = np.searchsorted(
#         anchor_peptide_scores.indptr,
#         top_score_index,
#         "right"
#     ) - 1
#     anchor_candidates = fragment_peptide_indices[
#         slice(*anchor_boundaries[anchor_index])
#     ]
#     anchor_neighbors = neighbors.indices[
#         neighbors.indptr[anchor_index]: neighbors.indptr[anchor_index + 1]
#     ]
#     raw_neighbor_candidates = np.concatenate(
#         [
#             fragment_peptide_indices[
#                 slice(*anchor_boundaries[n])
#             ] for n in anchor_neighbors
#         ]
#     )
#     neighbor_candidates = raw_neighbor_candidates[
#         np.isin(
#             raw_neighbor_candidates,
#             anchor_candidates
#         )
#     ]
#     candidates, candidate_counts = np.unique(
#         neighbor_candidates,
#         return_counts=True
#     )
#     counts, frequencies = np.unique(
#         candidate_counts,
#         return_counts=True
#     )
#     counts = np.concatenate([[0], counts])
#     frequency = np.concatenate(
#         [
#             [len(anchor_candidates)],
#             np.cumsum(frequencies[::-1])[::-1]
#         ]
#     )
#     ransac = linear_model.RANSACRegressor()
#     tmp = ransac.fit(
#         counts.reshape(-1, 1)[:-1],
#         np.log2(frequency).reshape(-1, 1)[:-1]
#     )
#     score = -ransac.predict(counts[-1])[0][0]
#     # plt.bar(counts, frequency)
#     # plt.scatter(counts, frequency, marker=".")
#     # plt.xlabel("#Peptides with fragment count")
#     # plt.ylabel("Frequency")
#     # plt.show()
#     tmp = plt.scatter(counts, np.log2(frequency), marker=".")
#     tmp = plt.plot(
#         [
#             0,
#             counts[-1]
#         ],
#         [
#             ransac.predict(counts[0])[0][0],
#             ransac.predict(counts[-1])[0][0]
#         ]
#     )
#     tmp = plt.plot(
#         [counts[-1], counts[-1]],
#         [-score, np.log2(frequencies[-1])],
#         linestyle="--",
#         c="grey"
#     )
#     tmp = plt.xlabel("#Peptides with fragment count")
#     tmp = plt.ylabel("Log frequency")
#     tmp = plt.title("Score={}".format(score))
#     # plt.show()
#     tmp = plt.savefig(parameters["PLOTS_PATH"] + extension + "_lfq_annotation_example.pdf", bbox_inches='tight')
#     tmp = plt.close()

# # Plot browser example
# from matplotlib import pyplot as plt
# import src.gui
#
# class DummyGUI(object):
#     def __init__(self):
#         self.minimum_replicates = 10
#         self.maximum_replicates = 10
#         self.label_type = "None"
#         self.view_type = -1
#         self.fdr_threshold = 0.01
#         self.axis_type = "Log intensity"
#         self.show_edges = True
#         self.aggregate_fig = plt.Figure()
#         self.aggregate_ax = self.aggregate_fig.add_subplot(111)
#         self.ion_fig = plt.Figure()
#         self.ion_ax = self.ion_fig.add_subplot(111)
#     def getMinimumReplicateCount(self):
#         return self.minimum_replicates
#     def getMaximumReplicateCount(self):
#         return self.maximum_replicates
#     def getLabelType(self):
#         return self.label_type
#     def getViewType(self):
#         return self.view_type
#     def getFDRThreshold(self):
#         return self.fdr_threshold
#     def getAxisType(self):
#         return self.axis_type
#     def getShowEdges(self):
#         return self.show_edges
#     def getVisibleBoundaries(self):
#         dt_low, dt_high = self.aggregate_ax.get_ylim()
#         rt_low, rt_high = self.aggregate_ax.get_xlim()
#         return rt_low, rt_high, dt_low, dt_high
#
# dataset = src.gui.Dataset("data/tenzer/parameters.json")
# g = DummyGUI()
# dataset.updateVisibleNodes(g)
# dataset.plotVisibleNodes(g)
# dataset.plotAnnotatedNodes(g)
# dataset.plotSelectedNodes(g)
# dataset.plotEdges(g)
# g.aggregate_fig.show()
#
# # g.refreshAggregateCanvas()
# # dataset.plotIons(g)
# # g.refreshIonCanvas()

#
#
# # a, b = np.unique(np.diff(neighbors[significant_anchors].indptr), return_counts=True)
# # plt.scatter(a, b / np.sum(b))
# from pyteomics import mgf
# spectra = [s for s in mgf.read('.tmp/lfq_qc_dda.mgf')]
# # spectrum_sizes = np.array([len(i['m/z array']) for i in spectra)
# # spectrum_sizes = np.repeat(spectrum_sizes, spectrum_sizes)
# # aa, bb = np.unique(spectrum_sizes, return_counts=True)
# # plt.scatter(aa, bb / np.sum(bb))
# # plt.show()
#
# x = np.diff(neighbors[significant_anchors].indptr)
# # x = np.diff(neighbors.indptr)
# y = np.array([len(i['m/z array']) for i in spectra])
# d = pd.DataFrame(
#     np.stack(
#         [
#             np.concatenate([x, y]),
#             np.repeat(["Ion-network", "MGF"], [len(x), len(y)]),
#         ]
#     ).T,
#     columns=["value", "Data format"],
# )
# d["Y"] = 1
# d["value"] = d["value"].astype(np.int)
# tmp = sns.violinplot(
#     x='value',
#     y='Y',
#     hue='Data format',
#     split=True,
#     data=d,
#     inner="quartile",
#     gridsize=1000,
#     orient="h"
# )
# tmp = plt.ylabel("Distribution")
# tmp = plt.xlabel("Number of peaks / Consistently co-eluting aggregates")
# tmp = plt.yticks([])
# tmp = plt.xlim([0, 500])
# plt.show()


# 백줕 13164번 행복 유치원

import sys
sys.stdin = open('input.txt')
sys.setrecursionlimit(300000)

def group(total, rest, s):
    global ans

    if rest <= 1:
        ans = min(total + (h[N - 1] - h[s]), ans)
        return
    for e in range(s, N - rest + 1):
        group(h[e] - h[s] + total, rest - 1, e + 1)

N, K = map(int, input().split())
h = list(map(int, input().split()))
ans = (10 ** 9) * K
if K == 1:
    ans = h[N - 1] - h[0]
else:
    for e in range(N - K + 1):
        group(h[e] - h[0], K - 1, e + 1)
print(ans)


from flask import render_template, request
from . import main
from .. import db
from ..models import Message
import json
import re

@main.route('/', methods=['GET'])
def index():
    return render_template('index.html')

@main.route('/messages', methods=['GET'])
def get_messages():
    result = dict()
    code = None

    messages = Message.query.all()
    if len(messages) > 0:
        message_results = list()
        for message in messages:
            if is_base64(message.content):
                message_to_add = {'id': message.id, 'content': message.content }
                message_results.append(message_to_add)
        result.update({ 'messages': message_results })
        result.update({ 'success': True })
        code = 200
    else:
        result.update({ 'success': False })
        result.update({ 'message': 'not found' })
        code = 404
    return json.dumps(result), code

@main.route('/messages', methods=['POST'])
def add_message():
    result = dict()
    code = None

    content = request.form['content']
    if content is None:
        result.update({ 'success': False })
        result.update({ 'message': 'missing content' })
        code = 500
    elif is_base64(content) is False:
        result.update({ 'success': False })
        result.update({ 'message': 'content is not base64 encoded' })
        code = 500
    else:
        message = Message(content=request.form['content'])
        db.session.add(message)
        result.update({ 'success': True })
        code = 200
    return json.dumps(result), code

def is_base64(string):
    if len(string) % 4 == 0 and re.match('^[A-Za-z0-9+\/=]+\Z', string):
        return(True)
    else:
        return(False)


"""
Created on 5 févr. 2014

@author: inso
"""

import datetime
import logging
import asyncio
from ..tools.decorators import asyncify, once_at_a_time, cancel_once_task
from PyQt5.QtCore import QAbstractTableModel, Qt, QVariant, QSortFilterProxyModel, \
    QDateTime, QLocale, QModelIndex

from PyQt5.QtGui import QFont, QColor

class CertsFilterProxyModel(QSortFilterProxyModel):
    def __init__(self, ts_from, ts_to, parent=None):
        super().__init__(parent)
        self.app = None
        self.ts_from = ts_from
        self.ts_to = ts_to

    @property
    def account(self):
        return self.app.current_account

    def set_period(self, ts_from, ts_to):
        """
        Filter table by given timestamps
        """
        logging.debug("Filtering from {0} to {1}".format(
            datetime.datetime.fromtimestamp(ts_from).isoformat(' '),
            datetime.datetime.fromtimestamp(ts_to).isoformat(' '))
        )
        self.ts_from = ts_from
        self.ts_to = ts_to
        self.modelReset.emit()

    def filterAcceptsRow(self, sourceRow, sourceParent):
        def in_period(date_ts):
            return date_ts in range(self.ts_from, self.ts_to)

        source_model = self.sourceModel()
        date_col = source_model.columns_types.index('date')
        source_index = source_model.index(sourceRow, date_col)
        date = source_model.data(source_index, Qt.DisplayRole)
        return in_period(date)

    @property
    def community(self):
        return self.sourceModel().community

    def columnCount(self, parent):
        return self.sourceModel().columnCount(None) - 5

    def setSourceModel(self, sourceModel):
        self.app = sourceModel.app
        super().setSourceModel(sourceModel)

    def lessThan(self, left, right):
        """
        Sort table by given column number.
        """
        source_model = self.sourceModel()
        left_data = source_model.data(left, Qt.DisplayRole)
        right_data = source_model.data(right, Qt.DisplayRole)
        if left_data == "":
            return self.sortOrder() == Qt.DescendingOrder
        elif right_data == "":
            return self.sortOrder() == Qt.AscendingOrder
        return (left_data < right_data)

    def data(self, index, role):
        source_index = self.mapToSource(index)
        model = self.sourceModel()
        source_data = model.data(source_index, role)
        state_col = model.columns_types.index('state')
        state_index = model.index(source_index.row(), state_col)
        state_data = model.data(state_index, Qt.DisplayRole)
        if role == Qt.DisplayRole:
            if source_index.column() == model.columns_types.index('uid'):
                return source_data
            if source_index.column() == model.columns_types.index('date'):
                return QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(source_data).date(),
                    QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                )
            if source_index.column() == model.columns_types.index('payment') or \
                    source_index.column() == model.columns_types.index('deposit'):
                return source_data

        if role == Qt.FontRole:
            font = QFont()
            return font

        if role == Qt.ForegroundRole:
            if state_data == TransferState.REFUSED:
                return QColor(Qt.red)
            elif state_data == TransferState.TO_SEND:
                return QColor(Qt.blue)

        if role == Qt.TextAlignmentRole:
            if source_index.column() == self.sourceModel().columns_types.index('date'):
                return Qt.AlignCenter

        if role == Qt.ToolTipRole:
            if source_index.column() == self.sourceModel().columns_types.index('date'):
                return QDateTime.fromTime_t(source_data).toString(Qt.SystemLocaleLongDate)
            return None

        return source_data

class HistoryTableModel(QAbstractTableModel):
    """
    A Qt abstract item model to display communities in a tree
    """

    def __init__(self, app, account, community, parent=None):
        """
        Constructor
        """
        super().__init__(parent)
        self.app = app
        self.account = account
        self.community = community
        self.transfers_data = []
        self.refresh_certs()
        self._max_confirmations = 0

        self.columns_types = (
            'date',
            'uid',
            'state',
            'pubkey',
            'block_number'
        )

        self.column_headers = (
            self.tr('Date'),
            self.tr('UID/Public key'),
            'State',
            'Pubkey',
            'Block Number'
        )

    def change_account(self, account):
        cancel_once_task(self, self.refresh_certs)
        self.account = account

    def change_community(self, community):
        cancel_once_task(self, self.refresh_certs)
        self.community = community

    def certifications(self):
        if self.account:
            return self.account.certifications(self.community)
        else:
            return []

    @once_at_a_time
    @asyncify
    async def refresh_certs(self):
        self.beginResetModel()
        self.transfers_data = []
        self.endResetModel()

    def max_confirmations(self):
        return self._max_confirmations

    def rowCount(self, parent):
        return len(self.transfers_data)

    def columnCount(self, parent):
        return len(self.columns_types)

    def headerData(self, section, orientation, role):
        if self.account and self.community:
            if role == Qt.DisplayRole:
                return self.column_headers[section]

    def data(self, index, role):
        row = index.row()
        col = index.column()

        if not index.isValid():
            return QVariant()

        if role == Qt.DisplayRole:
            return self.transfers_data[row][col]

        if role == Qt.ToolTipRole:
            return self.transfers_data[row][col]

    def flags(self, index):
        return Qt.ItemIsSelectable | Qt.ItemIsEnabled


cor = {'amarelo':'\033[1;33m', 'limp':'\033[m', 'red':'\033[1;31m'}

extenso = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'treze',
     'quatorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove', 'vinte')

n = int(input('Diga um número entre 0 e 20: '))
while n < 0 or n >20:
    print(cor['red'], 'Número inválido', cor['limp'], end='')
    n = int(input('Tente novamente com nº entre 0 e 20: '))

print('\nVc digitou o número {0}{1}{2}'.format(cor['amarelo'], extenso[n], cor['limp']))

from datetime import date
print(f'\nProcessado em {date.today()}')

#Para obter a posição e o nome ocupado nesta posição:
#for posicao, nome in enumerate(extenso):
#    print(f'posição {posicao} = {nome}')

#para obter a posição
#for c in range(0, len(extenso)):
#    print(c)


import sys
import json
from django.db import models
from collections import defaultdict
from naivebayes import util
from naivebayes import naivebayes

SPAM_FOLDER = "naivebayes/data/wellham"
HAM_FOLDER = "naivebayes/data/wellspam"

LOG_HALF = "-0.69314718055994529"
EMPTY_DICT = "{}"
DEFAULT_LOG_PRIORS = '[%d, %d]' % (LOG_HALF, LOG_HALF)
EMPTY_DEFAULT_PROBABILITIES = '(0,0)'

class Distribution(models.Model):
    num_spam              = models.IntegerField(default=0)
    num_ham               = models.IntegerField(default=0)
    log_priors            = models.TextField(default=DEFAULT_LOG_PRIORS)
    log_probabilities     = models.TextField(default=EMPTY_DICT)
    default_probabilities = models.TextField(default=EMPTY_DEFAULT_PROBABILITIES) # Stored as (default_prob_for_spam, default_prob_for_ham)

    def learn(self):

        print >>sys.stderr, "Training..."
        file_lists = []
        for folder in (SPAM_FOLDER, HAM_FOLDER):
            file_lists.append(util.get_files_in_folder(folder))

        (log_probabilities_by_category, log_priors_by_category) = naivebayes.learn_distributions(file_lists)

        (self.log_probabilities, self.log_priors) = \
            (json.dumps(log_probabilities_by_category, encoding='latin-1'),\
             json.dumps(log_priors_by_category))

        # Store default probabilities, as these are lost when we serialize the dicts
        self.default_probabilities = json.dumps([log_probabilities_by_category[0][-1], log_probabilities_by_category[1][-1]])

        self.num_spam = len(file_lists[0])
        self.num_ham = len(file_lists[1])


import os
import nltk
import numpy as np
import math
import pickle as pkl
from tqdm import tqdm

root = "./pa1-data/"
documents = {}
tokens = {}
tokenizer = nltk.tokenize.RegexpTokenizer(r'\w+')
stop_words = nltk.corpus.stopwords.words('english')
lematizer = nltk.stem.WordNetLemmatizer()
steamer = nltk.stem.PorterStemmer()

break_point = 0
for folder in os.listdir(root):

    path = root + folder
    for name in tqdm(os.listdir(path)):
        break_point = break_point + 1

        file_name = path + "/" + name
        file = open(file_name, 'r')

        for line in file:

            documents[name] = line
            tokens[name] = tokenizer.tokenize(line)

            text_no_stop_words = []
            for word in tokens[name]:
                if word not in stop_words:
                    text_no_stop_words.append(word)

            text_no_stop_words = [lematizer.lemmatize(word) for word in text_no_stop_words]
            text_no_stop_words = [steamer.stem(word) for word in text_no_stop_words]
            tokens[name] = text_no_stop_words

def get_vocabulary(collection):
    """
        Get the vocabulary from the collection
    """
    vocabulary = []

    for key in tqdm(collection):
        for word in collection[key]:
            if word not in vocabulary:
                vocabulary.append(word)

    return vocabulary

"""
    Here we extract the vocabulary from the collection!
"""
Vocabulary = get_vocabulary(tokens)

print(len(documents))
print(len(Vocabulary))

pkl.dump(Vocabulary, open("Vocabulary.pkl", "wb"))


# 从文件中获取UA以List返回,默认返回前20个
import sqlite3

def Enca_get_proxyUA(start_num=0, end_number=20):
    db = sqlite3.connect("./useragents.db")
    cursor = db.cursor().execute(f'select * from uas limit {start_num},{end_number}').fetchall()
    for ua in cursor:
        result_ualist = []
        for this_ua in ua[1:]:
            result_ualist.append(this_ua)
        # print('/'.join(result_ualist))
        return result_ualist

print(140 * 0.3)


import sys
try:  # Literal 3.8
    from typing import Literal
except ImportError:
    input("requires Python 3.9 or higher... press enter to quit")
    exit(1)
import argparse
import time

from subversion_rando.game import CypherItems, GameOptions
from subversion_rando.logic_presets import casual, expert, medium
from subversion_rando.main_generation import generate, write_rom, write_spoiler_file

def commandLineArgs(sys_args: list[str]) -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', '--casual', action="store_true",
                        help='Casual logic, easy setting matching the vanilla Subversion experience, Default')
    parser.add_argument('-u', '--logicmedium', action="store_true",
                        help='Medium logic, medium setting between casual and expert')
    parser.add_argument('-e', '--expert', action="store_true",
                        help='Expert logic, hard setting comparable to Varia.run Expert difficulty')
    parser.add_argument('-q', '--logiccustom', action="store_true",
                        help='use the gui to customize logic')

    parser.add_argument('-s', '--speedrun', action="store_true",
                        help='Speedrun fill, fast setting comparable to Varia.run Speedrun fill algorithm')
    parser.add_argument('-d', '--assumedfill', action="store_true",
                        help='Assumed fill, standard slower progression fill algorithm, Default')
    parser.add_argument(
        '-m', '--medium', action="store_true",
        help='Medium fill, medium speed setting that places low-power items first for increased exploration'
    )
    parser.add_argument('-mm', '--majorminor', action="store_true",
                        help='Major-Minor fill, using unique majors and locations')
    parser.add_argument('-b', '--majorminorbias', action="store_true",
                        help='unique items have high probability to be in unique item locations')

    parser.add_argument('-a', '--area', action="store_true",
                        help='Area rando shuffles major areas of the game, expert logic only')

    parser.add_argument('-o', '--smallspaceport', action="store_true",
                        help='cuts out some parts of the space port to make it smaller')

    parser.add_argument('-r', '--escapeshortcuts', action="store_true",
                        help='shortens the escape paths - (final escape shortened only if not area rando)')

    parser.add_argument('--daphne_gate', action="store_true",
                        help='???')

    parser.add_argument('--goals', default=0, type=int,
                        help='number of randomized objectives (0 for disabled)')

    parser.add_argument(
        '--skipcrashspaceport', action="store_true",
        help='A second GFS Daphne starts crashed in Lomyr Valley, removing the requirement to crash the Space Port'
    )
    args = parser.parse_args(sys_args)
    # print(args)
    return args

# main program
def Main(argv: list[str]) -> None:
    """ generate from command line """
    workingArgs = commandLineArgs(argv[1:])

    logic = casual  # default
    if workingArgs.expert:
        logic = expert
    elif workingArgs.logicmedium:
        logic = medium

    fillChoice: Literal["M", "MM", "D", "S", "B"]
    if workingArgs.medium:
        fillChoice = "M"
    elif workingArgs.majorminor:
        fillChoice = "MM"
    elif workingArgs.speedrun:
        fillChoice = "S"
    elif workingArgs.majorminorbias:
        fillChoice = "B"
    else:
        fillChoice = "D"

    area_rando = False
    if workingArgs.area:
        area_rando = True
        # if fillChoice == "MM":
        #     fillChoice = "D"
        #     print("Cannot use Major-Minor in Area rando currently. Using assumed fill instead.")

    small_spaceport = False
    if workingArgs.smallspaceport:
        small_spaceport = True

    escape_shortcuts = False
    if workingArgs.escapeshortcuts:
        escape_shortcuts = True

    daphne_gate = False
    if workingArgs.daphne_gate:
        daphne_gate = True

    skip_crash_space_port = False
    if workingArgs.skipcrashspaceport:
        skip_crash_space_port = True

    options = GameOptions(logic, area_rando, fillChoice, small_spaceport,
                          escape_shortcuts, CypherItems.NotRequired,
                          daphne_gate, workingArgs.goals, skip_crash_space_port)
    game = generate(options)
    rom_name = write_rom(game)
    write_spoiler_file(game, rom_name)

if __name__ == "__main__":
    t0 = time.perf_counter()
    Main(sys.argv)
    t1 = time.perf_counter()
    print(f"time taken: {t1 - t0}")


class OPCLIVersion:
    def __init__(self, version_string: str):
        version_tuple = version_string.split(".")
        parts = []
        for part in version_tuple:
            parts.append(int(part, 0))
        self._parts = parts

    def _normalize(self, other):
        parts_self = list(self._parts)
        parts_other = list(other._parts)

        # be robust about version strings of differing lenghts
        # e.g., 11.3.1 vs 11.3.1.1
        diff_len = len(parts_self) - len(parts_other)

        # if the length difference was negative, _parts_other is longer,
        # and we need to exitend _parts self
        while diff_len < 0:
            parts_self.append(0)
            diff_len += 1
        # if diff was positive, we need to extend _parts other
        while diff_len > 0:
            parts_other.append(0)
            diff_len -= 1

        # now 11.3.1 vs 11.3.1.1 becomes
        # 11.3.1.0 vs 11.3.1.1, and can be compared 1 to 1
        return (parts_self, parts_other)

    def __str__(self):
        _str = ".".join([str(i) for i in self._parts])
        return _str

    def __eq__(self, other):
        equal = id(self) == id(other)

        if not equal:
            if not isinstance(other, OPCLIVersion):
                other = OPCLIVersion(other)

            parts_self, parts_other = self._normalize(other)
            equal = True
            for i, part in enumerate(parts_self):
                if part != parts_other[i]:
                    equal = False
                    break

        return equal

    def __ne__(self, other):
        ne = not self.__eq__(other)
        return ne

    def __lt__(self, other):
        if not isinstance(other, type(self)):
            other = OPCLIVersion(other)

        lt = False
        _parts_self, _parts_other = self._normalize(other)

        for i, part in enumerate(_parts_self):
            if part > _parts_other[i]:
                break
            elif part == _parts_other[i]:
                continue
            elif part < _parts_other[i]:
                lt = True
                break

        return lt

    def __le__(self, other):
        le = self.__lt__(other) or self.__eq__(other)
        return le

MINIMUM_ITEM_CREATION_VERSION = OPCLIVersion('1.12.1')

# versions >= this ceiling are unsupported
UNSUPPORTED_VERSION_CEILING = OPCLIVersion('2.0.0')


import numpy as np
import pandas as pd
from collections import Counter

DATASET_PATH = "./data/UCI HAR Dataset/"

INPUT_SIGNAL_TYPES = [
    "body_acc_x_",
    "body_acc_y_",
    "body_acc_z_",
    "body_gyro_x_",
    "body_gyro_y_",
    "body_gyro_z_",
    "total_acc_x_",
    "total_acc_y_",
    "total_acc_z_"
]

def load_x(X_signals_paths):
    X_signals = []
    for signal_type_path in X_signals_paths:
        with open(signal_type_path, "r") as f:
            X_signals.append([np.array(serie, dtype=np.float32)
                             for serie in [row.replace('  ', ' ').strip().split(' ') for row in f]])
    return np.transpose(X_signals, (1, 2, 0))   # (?, 128, 9)

def load_y(y_path):
    with open(y_path, "r") as f:
        y = np.array([elem for elem in [row.replace('  ', ' ').strip().split(' ') for row in f]],
                     dtype=np.int32)
    y = y.reshape(-1, )
    return y - 1    # (?, 1)

train_x_signals_paths = [
    DATASET_PATH + "train/Inertial Signals/" + signal + "train.txt" for signal in INPUT_SIGNAL_TYPES
]
test_x_signals_paths = [
    DATASET_PATH + "test/Inertial Signals/" + signal + "test.txt" for signal in INPUT_SIGNAL_TYPES
]

train_y_path = DATASET_PATH + "train/y_train.txt"
test_y_path = DATASET_PATH + "test/y_test.txt"

train_x = load_x(train_x_signals_paths)
test_x = load_x(test_x_signals_paths)

train_y = load_y(train_y_path)
test_y = load_y(test_y_path)

train_y_one_hot = np.asarray(pd.get_dummies(train_y), dtype=np.int8)
test_y_one_hot = np.asarray(pd.get_dummies(test_y), dtype=np.int8)

print(train_x.shape, test_x.shape)
print(train_y.shape, Counter(train_y))
print(test_y.shape, Counter(test_y))
print(train_y_one_hot.shape)
print(test_y_one_hot.shape)

np.save("./data/processed/np_train_x.npy", train_x)
np.save("./data/processed/np_train_y.npy", train_y)
np.save("./data/processed/np_train_y_one_hot.npy", train_y_one_hot)
np.save("./data/processed/np_test_x.npy", test_x)
np.save("./data/processed/np_test_y.npy", test_y)
np.save("./data/processed/np_test_y_one_hot.npy", test_y_one_hot)

# (7352, 128, 9) (2947, 128, 9)
# (7352,) Counter({5: 1407, 4: 1374, 3: 1286, 0: 1226, 1: 1073, 2: 986})
# (2947,) Counter({5: 537, 4: 532, 0: 496, 3: 491, 1: 471, 2: 420})
# (7352, 6)
# (2947, 6)


import abc
import typing as tp

class Conversation(abc.ABC):
    """
    Inspired by https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py
    """

    def __init__(self, system_prompt: str, roles: tp.Tuple[str, str]):
        self.system_prompt = system_prompt
        self.roles = roles
        self.messages: tp.List[tp.Tuple[str, str]] = []

    @abc.abstractmethod
    def get_prompt(self) -> str:
        pass

    def update_last_message(self, text: str) -> None:
        self.messages[-1] = (self.messages[-1][0], text)

    def append_message(self, role: str, text: str) -> None:
        self.messages.append([role, text])

class LlamaConversation(Conversation):
    def __init__(self):
        super().__init__(
            system_prompt="",  # faked for compatibility
            roles=("", ""),
        )

    def get_prompt(self) -> str:
        prompt = self.system_prompt
        for role, text in self.messages:
            if text:
                prompt += f" {role} {text}"
            else:
                prompt += f" {role} "
        return prompt

class SaigaConversation(Conversation):
    def __init__(self):
        super().__init__(
            system_prompt="<s> system\n Ты — Сайга, русскоязычный автоматический ассистент. Ты разговариваешь с людьми и помогаешь им.</s>\n",
            roles=("user", "bot"),
        )

    def get_prompt(self) -> str:
        prompt = self.system_prompt
        for role, text in self.messages:
            if text:
                prompt += f"<s> {role}\n {text} </s>\n"
            else:
                prompt += f"<s> {role} "
        return prompt

class VerbalistConversation(Conversation):
    def __init__(self):
        super().__init__(
            system_prompt="<s> system\n Ты — Буквоед, русскоязычный автоматический ассистент. Ты разговариваешь с людьми и помогаешь им. </s>\n",
            roles=("user", "bot"),
        )

    def get_prompt(self) -> str:
        prompt = self.system_prompt
        for role, text in self.messages:
            if text:
                prompt += f"<s> {role}\n {text} </s>\n"
            else:
                prompt += f"<s> {role} "
        return prompt

class MistralOrcaConversation(Conversation):
    def __init__(self):
        super().__init__(
            system_prompt="<|im_start|> system\n You are MistralOrca, a large language model trained by Alignment Lab AI. <|im_end|>\n",
            roles=("user", "assistant"),
        )

    def get_prompt(self) -> str:
        # prompt = self.system_prompt
        prompt = ""
        for role, text in self.messages:
            if text:
                prompt += f"<|im_start|>{role}\n{text}<|im_end|>\n"
            else:
                prompt += f"<|im_start|>{role}\n"
        return prompt

conversation_classes = {
    "saiga": SaigaConversation,
    "verbalist": VerbalistConversation,
    "llama": LlamaConversation,
    "open_orca_mistral": MistralOrcaConversation,
}

if __name__ == "__main__":
    utterances = [
        "А тот второй парень — он тоже терминатор?",
        "Не совсем. Модель T-1000, усовершенствованный прототип.",
        "То есть, он более современная модель?",
        "Да. Мимикрирующий жидкий металл.",
        "И что это значит?",
    ]
    print("-=-=-=- Saiga -=-=-=-")
    conv = SaigaConversation()
    conv.append_message(conv.roles[0], utterances[0])
    conv.append_message(conv.roles[1], utterances[1])
    conv.append_message(conv.roles[0], utterances[2])
    conv.append_message(conv.roles[1], None)
    print(conv.get_prompt())
    print("-=-=-=-=-=-=-=-=-=-=-")


import math
import sys
from typing import Iterator, List, Tuple
import gurobipy as gp
from gurobipy import GRB , Model , Var , tupledict , Constr
from functools import lru_cache
from collections import Counter
import cProfile

def getInitialColumns(lengths, L):
    columns = [[0 for _ in range(len(lengths))] for _ in range(len(lengths))]
    for i in range(len(lengths)):
        columns[i][i] = math.floor(L/lengths[i])
    return columns

def getSolution(model):
    model.optimize()
    if not hasattr(model, 'objVal'):
        return None
    solution = model.objVal
    return solution

def addNewColumn(n, model, lengths, N, L, columns, dual):
    sub = gp.Model("Knapsack")
    x = sub.addVars(1, N, vtype=GRB.INTEGER)
    sub_pi = sub.addVars(1, N)
    # for i in range(L):
    #     sum_yet = 0
    #     for j in range(len(columns)):
    #         sum_yet += n[j, i]
    #     sub_pi[0, i] = sum_yet
    for i in range(len(dual)):
        sub_pi[0, i] = dual[i]

    sub.addConstr((sum(x[0, s]*lengths[s] for s in range(len(lengths))) <= L))
    sub.setObjective(sum(-sub_pi[0, s]*x[0, s] for s in range(len(lengths))), GRB.MINIMIZE )
    sub.write('sub_knapsack.lp')
    sub.optimize()
    new_column = []
    for v in sub.getVars():
        if (abs(v.x) > 1e-6):
            print(v.varName, v.x)
            new_column.append(v.x)
    return new_column

def solve():
    try:
        m = gp.Model("Cutting stock")
        m.setParam('OutputFlag', 0)
        N = 5 # number of widths
        M = N # max number
        L = 110

        demands = [48, 8, 10, 24, 35]
        lengths = [20, 75, 55, 50, 45]
        columns = getInitialColumns(lengths, L)
        for each in columns:
            print(each)
        # NOTE: to include each rool at most once add vtype=GRB.BINARY
        # x = m.addVars(1, len(columns), name="x", vtype=GRB.BINARY)
        # NOTE: to permit each rool to be included more that once remove the vtype=GRB.BINARY
        x = m.addVars(1, len(columns), name="x")
        n = m.addVars(len(columns), len(demands))

        for c in range(len(columns)):
            for s in range(len(demands)):
                n[c, s] = columns[c][s]

        for c in range(len(columns)):
            for s in range(len(demands)):
                print(n[c, s])
            print('-'*10)

        pro = m.addConstrs((sum(n[c, s]*x[0, c] for c in range(len(columns))) >= demands[s] for s in range(len(demands))))
        m.setObjective(sum(x[0, c] for c in range(len(columns))), GRB.MINIMIZE)
        solution = getSolution(m)

        dual = []
        for p in pro:
            if (abs(pro[p].Pi) > 1e-6):
                print(pro[p].Pi)
                dual.append(pro[p].Pi)
        while addNewColumn(n, m, lengths, N, L, columns, dual):
            solution = getSolution(m)
        print(solution)
        print (f"Optimal Solution : { solution }")

    except gp . GurobiError as e :
        print ('Error code ' + str(e.errno) + ': ' + str(e))
    except AttributeError as e:
        print(e)
        print('Encountered an attribute error')

if __name__ == "__main__":
    solve()
    # cProfile.run('solve()')


import pickle as pkl

class Engine(object):
    def __init__(self):
        self.hooks = {}

    def hook(self, name, state):

        if name in self.hooks:
            self.hooks[name](state)

    def train(self, network, iterator, maxepoch, optimizer, scheduler):
        state = {
            'network': network,
            'iterator': iterator,
            'maxepoch': maxepoch,
            'optimizer': optimizer,
            'scheduler': scheduler,
            'epoch': 0,
            't': 0,
            'train': True,
        }

        # self.hook('debug_state', state)
        # import pdb; pdb.set_trace()

        self.hook('on_start', state)
        while state['epoch'] < state['maxepoch']:
            self.hook('on_start_epoch', state)
            for sample in state['iterator']:
                state['sample'] = sample
                self.hook('on_sample', state)

                def closure():
                    if state['epoch'] < 3:
                        warming = True
                    else:
                        warming = False
                    loss, output, loss_value_dict = state['network'](state['sample'], warming)

                    # print(f"iter {state['t']}, loss: {state['loss_meter'].avg}")
                    # if config.tensorboard:
                    #     writter.add_scalar('Loss/train', loss.item(), state['t'])
                    state['output'] = output
                    state['loss'] = loss
                    state['loss_value_dict'] = loss_value_dict
                    self.hook('tensorboard_writter', state)
                    loss.backward()
                    self.hook('on_forward', state)
                    # to free memory in save_for_backward
                    state['output'] = None
                    state['loss'] = None
                    return loss

                state['optimizer'].zero_grad()
                state['optimizer'].step(closure)
                self.hook('on_update', state)
                state['t'] += 1
            state['epoch'] += 1
            self.hook('on_end_epoch', state)
        self.hook('on_end', state)
        return state

    def test(self, network, iterator, split):
        state = {
            'network': network,
            'iterator': iterator,
            'split': split,
            't': 0,
            'train': False,
        }

        self.hook('on_test_start', state)
        for sample in state['iterator']:
            state['sample'] = sample
            self.hook('on_test_sample', state)

            def closure():
                # loss, output = state['network'](state['sample'])
                loss, output, prediction, proposal = state['network'](state['sample'])
                state['output'] = output
                state['loss'] = loss
                state['prediction'] = prediction,
                state['proposal'] = proposal
                self.hook('on_test_forward', state)
                # to free memory in save_for_backward
                state['output'] = None
                state['loss'] = None

            closure()
            state['t'] += 1
        # pkl.dump(state['save_sample_prediction'], open('baselines/MILNCE-WSTAN/train.pkl', 'wb'))
        # import pdb; pdb.set_trace()
        self.hook('on_test_end', state)
        return state


# platform specific setting here
import platform
import os

if platform.system() == "Linux":
    KEY_BACKSPACE = 263
    CMD = "mplayer -fs -really-quiet -playlist"
else:
    KEY_BACKSPACE = 8

    exec_list = [
        r"C:\Program Files (x86)\VideoLAN\VLC\vlc.exe",
        r"C:\Program Files\VideoLAN\VLC\vlc.exe",
    ]

    vlc_exec = None
    for fpath in exec_list:
        if os.path.exists(fpath):
            vlc_exec = fpath
            break

    if vlc_exec is None:
        raise FileNotFoundError("Cannot find vlc executable")

    CMD = f'"{vlc_exec}" --fullscreen'


from PIL import Image
from collections import Counter
import numpy as np

def crop(pilimage, height, width):
    allbrightresults = []
    imgw, imgh = pilimage.size
    adjusth = (imgh // height) * height
    adjustw = (imgw // width) * width
    for i in range(0, adjusth, height):
        for j in range(0, adjustw, width):
            box = (j, i, j + width, i + height)
            a = pilimage.crop(box)
            single_brightness_val = calc_brightness(a)
            allbrightresults.append(single_brightness_val)

    theCounter = Counter(allbrightresults)
    if theCounter['Not Bright'] > 1:
        return 'Invalid'
    else:
        return 'Valid'

def calc_brightness(image):
    gray = image.convert('L')
    hist = gray.histogram()
    pixels = sum(hist)
    brightness = scale = len(hist)

    for i in range(0, scale):
        ratio = hist[i] / pixels
        brightness += ratio * (-scale + i)
    if brightness == 255:
        return "Bright"
    else:
        if brightness / scale > 0.5:
            return "Bright"
        return "Not Bright"

# if __name__ == "__main__":
#     filename = sys.argv[1]
#     image = Image.open(filename)
#     resultbright, resultblur = crop(image, 200, 200, 20)
#     counterbright = Counter(resultbright)
#     counterblur = Counter(resultblur)
#     print(counterbright)
#     print(counterblur)


import sys

from . import CPyExtTestCase, CPyExtFunction, unhandled_error_compare

test_frame = sys._getframe(0)
test_frame_no_back = test_frame
while test_frame_no_back.f_back:
    test_frame_no_back = test_frame_no_back.f_back

class TestMisc(CPyExtTestCase):

    def compile_module(self, name):
        type(self).mro()[1].__dict__["test_%s" % name].create_module(name)
        super().compile_module(name)

    test_PyFrame_GetCode = CPyExtFunction(
        lambda args: args[0].f_code,
        lambda: (
            (test_frame,),
        ),
        code='''PyObject* wrap_PyFrame_GetCode(PyObject* frame) {
            return (PyObject*)PyFrame_GetCode((PyFrameObject*)frame);
        }
        ''',
        resultspec="O",
        argspec="O",
        arguments=["PyObject* frame"],
        callfunction="wrap_PyFrame_GetCode",
        cmpfunc=unhandled_error_compare,
    )

    test_PyFrame_GetLineNumber = CPyExtFunction(
        lambda args: args[0].f_lineno,
        lambda: (
            (test_frame,),
        ),
        code='''int wrap_PyFrame_GetLineNumber(PyObject* frame) {
            return PyFrame_GetLineNumber((PyFrameObject*)frame);
        }
        ''',
        resultspec="i",
        argspec="O",
        arguments=["PyObject* frame"],
        callfunction="wrap_PyFrame_GetLineNumber",
        cmpfunc=unhandled_error_compare,
    )

    # GR-46546 These APIs are backported from 3.11
    if sys.version_info >= (3, 11) or sys.implementation.name == 'graalpy':
        test_PyFrame_GetLasti = CPyExtFunction(
            lambda args: args[0].f_lasti,
            lambda: (
                (test_frame,),
            ),
            code='''int wrap_PyFrame_GetLasti(PyObject* frame) {
                return PyFrame_GetLasti((PyFrameObject*)frame);
            }
            ''',
            resultspec="i",
            argspec="O",
            arguments=["PyObject* frame"],
            callfunction="wrap_PyFrame_GetLasti",
            cmpfunc=unhandled_error_compare,
        )

        test_PyFrame_GetBack = CPyExtFunction(
            lambda args: args[0].f_back or "NULL",
            lambda: (
                (test_frame,),
                (test_frame_no_back,),
            ),
            code='''PyObject* wrap_PyFrame_GetBack(PyObject* frame) {
                PyObject* back = (PyObject*)PyFrame_GetBack((PyFrameObject*)frame);
                if (!back)
                    return PyUnicode_FromString("NULL");
                return back;
            }
            ''',
            resultspec="O",
            argspec="O",
            arguments=["PyObject* frame"],
            callfunction="wrap_PyFrame_GetBack",
            cmpfunc=unhandled_error_compare,
        )

        test_PyFrame_GetLocals = CPyExtFunction(
            lambda args: args[0].f_locals,
            lambda: (
                (test_frame,),
            ),
            code='''PyObject* wrap_PyFrame_GetLocals(PyObject* frame) {
                return PyFrame_GetLocals((PyFrameObject*)frame);
            }
            ''',
            resultspec="O",
            argspec="O",
            arguments=["PyObject* frame"],
            callfunction="wrap_PyFrame_GetLocals",
            cmpfunc=unhandled_error_compare,
        )

        test_PyFrame_GetGlobals = CPyExtFunction(
            lambda args: args[0].f_globals,
            lambda: (
                (test_frame,),
            ),
            code='''PyObject* wrap_PyFrame_GetGlobals(PyObject* frame) {
                return PyFrame_GetGlobals((PyFrameObject*)frame);
            }
            ''',
            resultspec="O",
            argspec="O",
            arguments=["PyObject* frame"],
            callfunction="wrap_PyFrame_GetGlobals",
            cmpfunc=unhandled_error_compare,
        )

        test_PyFrame_GetBuiltins = CPyExtFunction(
            lambda args: args[0].f_builtins,
            lambda: (
                (test_frame,),
            ),
            code='''PyObject* wrap_PyFrame_GetBuiltins(PyObject* frame) {
                return PyFrame_GetBuiltins((PyFrameObject*)frame);
            }
            ''',
            resultspec="O",
            argspec="O",
            arguments=["PyObject* frame"],
            callfunction="wrap_PyFrame_GetBuiltins",
            cmpfunc=unhandled_error_compare,
        )


#로봇 청소기
def solve(ci, cj, d):
    global result
    if adj[ci][cj] == 0:
        adj[ci][cj] = 2
        result += 1
    if adj[ci-1][cj] != 0 and adj[ci+1][cj] != 0 and adj[ci][cj-1] != 0 and adj[ci][cj+1] != 0:
        if adj[ci+move[d][0]*(-1)][cj+move[d][1]*(-1)] != 1:
            solve(ci+move[d][0]*(-1), cj+move[d][1]*(-1), d)
        else:
            return result
    else:
        if d == 0:
            d = 3
        else:
            d -= 1
        if adj[ci+move[d][0]][cj+move[d][1]] == 0:
            ni, nj = ci+move[d][0], cj+move[d][1]
            solve(ni, nj, d)
        else:
            solve(ci, cj, d)

N, M = map(int, input().split())
si, sj, d = map(int, input().split())
move = [(-1, 0), (0, 1), (1, 0), (0, -1)]
result = 0
adj = list(list(map(int, input().split())) for _ in range(N))
solve(si, sj, d)
print(result)


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        results=[]
        aList=[root]
        while aList:
            b=[]
            c=[]
            for node in aList:
                if node:
                    c.append(node.val)
                    b.append(node.left)
                    b.append(node.right)
            if len(c)>0:
                results.append(c)
            aList=b
        return results


#!/usr/bin/env python
"""
This module contains the variables used to run barotropic_spectral.py
"""
import os

# Integration options
dt = 900.                  # Timestep (seconds)
ntimes = 960               # Number of time steps to integrate
plot_freq = 6              # Frequency of output plots in hours (if 0, no plots are made)
M = None                   # Truncation (if None, defaults to # latitudes)
r = 0.2                    # Coefficient for Robert Filter

# I/O parameters
figdir = os.path.join(os.getcwd(), 'figures')  # Figure directory

# Diffusion parameters
diff_opt = 1               # Hyperdiffusion option (0 = none, 1 = del^4, 2 = DES)
k = 2.338e16               # Diffusion coefficient for del^4 hyperdiffusion (diff_opt=1)
nu = 1E-4                  # Dampening coefficient for DES hyperdiffusion (diff_opt=2)
fourier_inc = 1            # Fourier increment for computing dampening eddy sponge (diff_opt=2)

# Constants
Re = 6378100.              # Radius of earth (m)
omega = 7.292E-5           # Earth's angular momentum (s^-1)
g = 9.81                   # Gravitational acceleration (m s^-2)


import xbmc
import xbmcgui
from ..Utils import *
from ..TheMovieDB import *
from ..WindowManager import wm
from ..OnClickHandler import OnClickHandler
from .. import VideoPlayer
PLAYER = VideoPlayer.VideoPlayer()
ch = OnClickHandler()

class DialogBaseInfo(object):
    ACTION_PREVIOUS_MENU = [92, 9]
    ACTION_EXIT_SCRIPT = [13, 10]

    def __init__(self, *args, **kwargs):
        super(DialogBaseInfo, self).__init__(*args, **kwargs)
        self.logged_in = check_login()
        self.dbid = kwargs.get('dbid')
        self.bouncing = False
        self.data = None
        self.yt_listitems = []
        self.info = {}

    def onInit(self, *args, **kwargs):
        super(DialogBaseInfo, self).onInit()
        HOME.setProperty("ImageColor", self.info.get('ImageColor', ""))
        self.window = xbmcgui.Window(self.window_id)
        self.window.setProperty("type", self.type)
        self.window.setProperty("tmdb_logged_in", self.logged_in)
        # present for jurialmunkey
        HOME.setProperty("ExtendedInfo_fanart", self.info.get("fanart", ""))

    def onAction(self, action):
        ch.serve_action(action, self.getFocusId(), self)

    def onClick(self, control_id):
        ch.serve(control_id, self)

    def onFocus(self, control_id):
        if control_id == 20000:
            if not self.bouncing:
                self.bounce("up")
            self.setFocusId(self.last_focus)
            self.last_focus = control_id
        elif control_id == 20001:
            if not self.bouncing:
                self.bounce("down")
            self.setFocusId(self.last_focus)
            self.last_focus = control_id
        else:
            self.last_focus = control_id

    @run_async
    def bounce(self, identifier):
        self.bouncing = True
        self.window.setProperty("Bounce.%s" % identifier, "true")
        xbmc.sleep(200)
        self.window.clearProperty("Bounce.%s" % identifier)
        self.bouncing = False

    def fill_lists(self):
        for container_id, listitems in self.listitems:
            try:
                self.getControl(container_id).reset()
                self.getControl(container_id).addItems(create_listitems(listitems))
            except:
                log("Notice: No container with id %i available" % container_id)

        @ch.action("contextmenu", 150)
        @ch.action("contextmenu", 250)
        def right_click_sets_and_similar(self):
            item_id = self.listitem.getProperty("id")
            dbid = self.listitem.getProperty("dbid")
            if self.type == "TVShow":
                tmdbids = get_tvshow_ids(item_id)
                tvdb = tmdbids['tvdb_id']
                if dbid: listitems = [LANG(208)]
                else: listitems = [LANG(13401) % LANG(36902)]
            else:
                imdb = get_imdb_id_from_movie_id(item_id)
                listitems = [LANG(208)]
            if dbid: listitems += [LANG(32233)]
            else: listitems += [LANG(32232)]
            if self.logged_in:
                listitems += [LANG(14076)]
                listitems += [LANG(32107)]
            selection = xbmcgui.Dialog().select(heading=LANG(32151), list=listitems)
            if selection == 0:
                if self.type == "TVShow":
                    if dbid:
                        show_playlist = xbmc.translatePath("special://profile/playlists/video/%s.xsp" % tvdb)
                        if os.path.exists(show_playlist):
                            xbmc.executebuiltin("PlayMedia("+show_playlist+")")
                            self.close()
                        else:
                            xbmc.executebuiltin("ActivateWindow(videos,videodb://tvshows/titles/%s/)" % dbid)
                            self.close()
                    else:
                        xbmc.executebuiltin("ActivateWindow(10025,plugin://plugin.video.metalliq-forqed/tv/tvdb/%s,return)" % tvdb)
                        self.close()
                else:
                    if dbid: url = "temp"
                    else:
                        dbid = 0
                        url = "plugin://plugin.video.metalliq-forqed/movies/play/tmdb/%s/%s" % (item_id, SETTING("player_main_movie"))
                    PLAYER.qlickplay(url, listitem=None, window=self, dbid=dbid)
            if selection == 1:
                if self.type == "TVShow":
                    if dbid:
                        show_path = xbmc.translatePath("special://profile/addon_data/plugin.video.metalliq-forqed/TVShows/%s" % tvdb)
                        if os.path.exists(show_path):
                            try:
                                shutil.rmtree(show_path)
                                xbmc.executebuiltin("RunScript(script.extendedinfo,info=afteradd)")
                                xbmc.executebuiltin("CleanLibrary(video)")
                            except: pass
                    else:
                        xbmc.executebuiltin("RunPlugin(plugin://plugin.video.metalliq-forqed/movies/add_to_library/tmdb/%s)" % item_id)
                        xbmc.executebuiltin("RunScript(script.extendedinfo,info=afteradd)")
                else:
                    if dbid:
                        movie_path = xbmc.translatePath("special://profile/addon_data/plugin.video.metalliq-forqed/Movies/%s" % imdb)
                        if os.path.exists(movie_path):
                            try:
                                shutil.rmtree(movie_path)
                                xbmc.executebuiltin("RunScript(script.extendedinfo,info=afteradd)")
                                xbmc.executebuiltin("CleanLibrary(video)")
                            except: pass
                    else:
                        xbmc.executebuiltin("RunPlugin(plugin://plugin.video.metalliq-forqed/movies/add_to_library/tmdb/%s)" % item_id)
                        xbmc.executebuiltin("RunScript(script.extendedinfo,info=afteradd)")
            if selection == 2:
                change_fav_status(media_id=item_id, media_type="movie", status=str(not bool(self.account_states["favorite"])).lower())
                self.update_states()
            if selection == 3:
                xbmc.executebuiltin("ActivateWindow(busydialog)")
                account_lists = get_account_lists()
                listitems = ["%s (%i)" % (i["name"], i["item_count"]) for i in account_lists]
                listitems.insert(0, LANG(32139))
                listitems.append(LANG(32138))
                xbmc.executebuiltin("Dialog.Close(busydialog)")
                index = xbmcgui.Dialog().select(heading=LANG(32136), list=listitems)
                if index == 0:
                    listname = xbmcgui.Dialog().input(heading=LANG(32137), type=xbmcgui.INPUT_ALPHANUM)
                    if not listname:
                        return None
                    list_id = create_list(listname)
                    xbmc.sleep(1000)
                    change_list_status(list_id=list_id, movie_id=item_id, status=True)
                elif index == len(listitems) - 1:
                    self.remove_list_dialog(account_lists)
                elif index > 0:
                    change_list_status(account_lists[index - 1]["id"], item_id, True)
                    self.update_states()

    @ch.click(1250)
    @ch.click(1350)
    def open_image(self):
        listitems = next((v for (i, v) in self.listitems if i == self.control_id), None)
        index = self.control.getSelectedPosition()
        pos = wm.open_slideshow(listitems=listitems, index=index)
        self.control.selectItem(pos)

    @ch.action("contextmenu", 1250)
    def thumbnail_options(self):
        if not self.info.get("dbid"):
            return None
        selection = xbmcgui.Dialog().select(heading=LANG(22080),
                                            list=[LANG(32006)])
        if selection == 0:
            path = self.listitem.getProperty("original")
            media_type = self.window.getProperty("type")
            params = '"art": {"poster": "%s"}' % path
            get_kodi_json(method="VideoLibrary.Set%sDetails" % media_type,
                          params='{ %s, "%sid":%s }' % (params, media_type.lower(), self.info['dbid']))

    @ch.action("contextmenu", 1350)
    def fanart_options(self):
        if not self.info.get("dbid"):
            return None
        selection = xbmcgui.Dialog().select(heading=LANG(22080),
                                            list=[LANG(32007)])
        if selection == 0:
            path = self.listitem.getProperty("original")
            media_type = self.window.getProperty("type")
            params = '"art": {"fanart": "%s"}' % path
            get_kodi_json(method="VideoLibrary.Set%sDetails" % media_type,
                          params='{ %s, "%sid":%s }' % (params, media_type.lower(), self.info['dbid']))

    @ch.action("contextmenu", 1150)
    @ch.action("contextmenu", 350)
    def download_video(self):
        selection = xbmcgui.Dialog().select(heading=LANG(22080),
                                            list=[LANG(33003)])
        if selection == 0:
            youtube_id = self.listitem.getProperty("youtube_id")
            import YDStreamExtractor
            vid = YDStreamExtractor.getVideoInfo(youtube_id,
                                                 quality=1)
            YDStreamExtractor.handleDownload(vid)

    @ch.action("parentdir", "*")
    @ch.action("parentfolder", "*")
    def previous_menu(self):
        onback = self.window.getProperty("%i_onback" % self.control_id)
        if onback:
            xbmc.executebuiltin(onback)
        else:
            self.close()
            wm.pop_stack()

    @ch.action("previousmenu", "*")
    def exit_script(self):
        self.close()

    @run_async
    def get_youtube_vids(self, search_str):
        try:
            youtube_list = self.getControl(350)
        except:
            return None
        result = search_youtube(search_str, limit=15)
        if not self.yt_listitems:
            self.yt_listitems = result.get("listitems", [])
            if "videos" in self.data:
                vid_ids = [item["key"] for item in self.data["videos"]]
                self.yt_listitems = [i for i in self.yt_listitems if i["youtube_id"] not in vid_ids]
        youtube_list.reset()
        youtube_list.addItems(create_listitems(self.yt_listitems))

    def open_credit_dialog(self, credit_id):
        info = get_credit_info(credit_id)
        listitems = []
        if "seasons" in info["media"]:
            listitems += handle_tmdb_seasons(info["media"]["seasons"])
        if "episodes" in info["media"]:
            listitems += handle_tmdb_episodes(info["media"]["episodes"])
        if not listitems:
            listitems += [{"label": LANG(19055)}]
        listitem, index = wm.open_selectdialog(listitems=listitems)
        if listitem["media_type"] == "episode":
            wm.open_episode_info(prev_window=self,
                                 season=listitems[index]["season"],
                                 episode=listitems[index]["episode"],
                                 tvshow_id=info["media"]["id"])
        elif listitem["media_type"] == "season":
            wm.open_season_info(prev_window=self,
                                season=listitems[index]["season"],
                                tvshow_id=info["media"]["id"])

    def update_states(self):
        if not self.account_states:
            return None
        pass_dict_to_skin(data=get_account_props(self.account_states),
                          prefix="movie.",
                          window_id=self.window_id)


import tensorflow as tf
import numpy as np
from tensorflow.contrib.slim import fully_connected as fc

def locally_connected_1d(input,scope,stride,filter_count,activation_function):
    connector_list = []
    starts = np.arange(0,input.shape[1]-scope,stride)
    for i in starts[:-1]:
        connector_list.append( fc(input[:,i:i+scope], filter_count,activation_fn=activation_function ) )
    connector_list.append(fc(input[:,starts[-1]:input.shape[1]],filter_count,activation_fn=activation_function))
    result = connector_list[0]
    for i in range(1,len(connector_list)):
        result = tf.concat(1,connector_list[i])
    return result

def reverse_locally_connected_1d(input,output_size,scope,stride,filter_count,activation_function):
    connector_list = []
    strides_per_scope = scope//stride
    last_stride = (output_size-scope)//stride

    for i in range(last_stride):
        connector_list.append( fc( input[:,max(0,i-strides_per_scope+1)*filter_count:(i+1)*filter_count] , stride,activation_fn=activation_function ) )
    for i in range(1,strides_per_scope):
        connector_list.append(  fc( input[:,(last_stride-strides_per_scope+i)*filter_count:(last_stride+1)*filter_count],stride,activation_fn=activation_function ) )
    connector_list.append( fc( input[:,last_stride*filter_count:(last_stride+1)*filter_count],stride+(output_size%stride), activation_fn=activation_function ))

    result = connector_list[0]
    for i in range(1,len(connector_list)):
        result = tf.concat(1,connector_list[i])
    return result