from copy import deepcopy

with open('input') as f:
    _input = list(map(lambda x: list(x), f.read().splitlines()))

def op(elements):
    if elements["|"] >= 3:
        return "|"
    else:
        return "."

def tr(elements):
    if elements["#"] >= 3:
        return "#"
    else:
        return "|"

def lu(elements):
    if elements["#"] >= 1 and elements["|"] >= 1:
        return "#"
    else:
        return "."

actions = {".": op, "|": tr, "#": lu}
around = (0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (1, 1), (-1, 1), (1, -1)
size = 50

def calculate_resource(minutes):
    lumber_area = deepcopy(_input)
    seen = list()
    first = 0
    second = False
    countdown = False
    count = 1

    for i in range(minutes):
        new_lumber_area = deepcopy(lumber_area)
        for x in range(size):
            for y in range(size):
                elements_around = {".": 0, "|": 0, "#": 0}
                for a in around:
                    x2, y2 = a
                    if x + x2 < 0 or x + x2 > size - 1 or y + y2 < 0 or y + y2 > size - 1:
                        continue
                    elements_around[lumber_area[x + x2][y + y2]] += 1

                action = actions[lumber_area[x][y]]
                new_lumber_area[x][y] = action(elements_around)
        lumber_area = new_lumber_area

        if new_lumber_area in seen:
            seen = list()
            seen.append(new_lumber_area)
            if second:
                count = (minutes - first) % (i - first)
                countdown = True

            first = i
            second = True
        else:
            seen.append(new_lumber_area)

        if countdown:
            count -= 1

        if count == 0:
            break

    wood = 0
    lumberyards = 0
    for x in range(size):
        for y in range(size):
            if lumber_area[x][y] == "|":
                wood += 1
            if lumber_area[x][y] == "#":
                lumberyards += 1

    print(wood * lumberyards)

calculate_resource(10)
calculate_resource(1000000000)


# -*- coding: utf-8 -*-
from pymongo import Connection

connection = Connection()
db = connection.urfu
students = db.interest.find()
interest = []
for st in students:
    for data in st['interests']:
        groups = db.groups.find()
        for gr in groups:
            for i in gr['interests']:
                if i == data:
                    if gr['group'] not in interest:
                        interest.append(gr['group'])
    db.new_groups.save({'interests': interest[:], 'vk_id': st['vk_id']})
    interest = []


from operator import index
from flask import Flask, request, render_template
from model import predict_housing_price
import joblib

app = Flask(__name__)
app.config['SECRET_KEY'] = 'cc69aeb9e22f352180710480ab0b0c78953d15d16ead0af369141356108fcbb9'

@app.route('/',methods=["GET","POST"])
def home():
    message = "Welcome to my first flask based web application ... !!!"
    return render_template("home.html", message = message)

@app.route('/getResponseModel',methods=["GET","POST"])
def getResponseModel():
    d = request.form.to_dict()

    model = joblib.load("my_model.pkl")

    try:
        y_pred = predict_housing_price(d, model)
        return y_pred

    except:
        return "[Please enter appropriate values]"

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


from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^', include('board.urls')),
    url(r'^board/', include('board.urls')),
    url(r'^login/', views.login, {'template_name': 'board/login_form.html'}, name='login'),
    url(r'^logout/', views.logout, {'next_page': '/login'}, name='logout'),
    url(r'^oauth/', include('social.apps.django_app.urls', namespace='social')),

]


import re
import sys
import traceback

import sublime
import sublime_plugin

# hack to ensure relative package imports work
__package__ = 'LaTeXTools'

from .latextools_plugin import (
    get_plugins_by_type, _classname_to_internal_name
)
from .latextools_utils import get_setting
from .latextools_utils.internal_types import FillAllHelper
from .latextools_utils.input_quickpanel import show_input_quick_panel

from .deprecated_command import deprecate

def reraise(tp, value, tb=None):
    if value is None:
        value = tp()
    if value.__traceback__ is not tb:
        raise value.with_traceback(tb)
    raise value

class LatexFillHelper(object):
    '''
    Base class for some LaTeXTools TextCommands. Implements several methods
    helpful for inserting text into the view and updating the cursor posiiton.
    '''

    # This is necessarily incomplete, but is intended to cover a number of
    # cases and could be extended as needed. I'm unsure that this is the best
    # design; it's done this way to emulate STs default definition of
    # word_separators
    #
    # defines non-word characters; see get_current_word
    NON_WORD_CHARACTERS = u'/\\()"\':,.;<>~!@#$%^&*|+=\\[\\]{}`~?\\s'

    WORD_SEPARATOR_RX = re.compile(
        r'([^' + NON_WORD_CHARACTERS + r']*)',
        re.UNICODE
    )

    # define fancy match prefix to support, e.g., \cite_prefix
    FANCY_PREFIX_RX = re.compile(
        r'([^_' + NON_WORD_CHARACTERS + r']*)_',
        re.UNICODE
    )

    # defines which characters need a matching bracket and their match
    MATCH_CHARS = {
        '{': '}',
        '[': ']',
        '(': ')'
    }

    def complete_auto_match(self, view, edit, insert_char):
        '''
        Completes brackets if auto_match is enabled; also implements the
        "smart_bracket_auto_trigger" logic, which tries to complete the nearest
        open bracket intelligently.

        :param view:
            the current view

        :param edit:
            the current edit

        :param insert_char:
            the character to try to automatch
        '''
        if sublime.load_settings('Preferences.sublime-settings').get(
            'auto_match_enabled', True
        ):
            # simple case: we have an insert char, insert closing char,
            # if its defined
            if insert_char:
                self.insert_at_end(
                    view, edit, self.get_match_char(insert_char)
                )

                # if the insert_char is a bracket, move cursor to middle of
                # bracket and return
                if insert_char in self.MATCH_CHARS:
                    new_regions = []
                    for sel in view.sel():
                        if not sel.empty():
                            new_regions.append(sel)
                        else:
                            new_point = sel.end() - 1
                            new_regions.append(
                                sublime.Region(new_point, new_point))

                    self.update_selections(view, new_regions)
                    return
            elif get_setting('smart_bracket_auto_trigger', True):
                # more complex: if we do not have an insert_char, try to close
                # the nearest bracket that occurs before each selection
                new_regions = []

                for sel in view.sel():
                    word_region = self.get_current_word(view, sel)
                    close_bracket = self.get_closing_bracket(view, word_region)
                    # we should close the bracket
                    if close_bracket:
                        # insert the closing bracket
                        view.insert(edit, word_region.end(), close_bracket)

                        if sel.empty():
                            if word_region.empty():
                                new_regions.append(
                                    sublime.Region(
                                        word_region.end(), word_region.end()))
                            else:
                                new_point = word_region.end() + len(
                                    close_bracket)
                                new_regions.append(
                                    sublime.Region(new_point, new_point))
                        else:
                            new_regions.append(
                                sublime.Region(
                                    sel.begin(),
                                    word_region.end() + len(close_bracket)))
                    else:
                        new_regions.append(sel)

                self.update_selections(view, new_regions)

    def complete_brackets(self, view, edit, insert_char='', remove_regions=[]):
        '''
        Intended to be called from a TextCommand to insert a specified
        insert_char, close the nearest bracket, and remove any regions
        specified

        :param view:
            the current view

        :param edit:
            the current edit

        :param insert_char:
            the character to insert and possibly automatch

        :param remove_regions:
            any regions to be removed from the current view
        '''
        self.insert_at_end(view, edit, insert_char)
        self.complete_auto_match(view, edit, insert_char)
        self.remove_regions(view, edit, remove_regions)
        self.clear_bracket_cache()

    def get_closing_bracket(self, view, sel):
        '''
        Determines if the nearest bracket that occurs before the given
        selection is closed. If the bracket should be closed, returns the
        closing bracket to use.

        Note that this will not work if the arguments to the command span
        multiple lines, but we generally don't support that anyway.

        :param view:
            the current view

        :param sel:
            a sublime.Region indicating the selected area
        '''
        # candidates stores matched bracket-pairs so that we only have
        # to find all matches once per bracket type
        # if the view has changed, we reset the candidates
        candidates = None

        if not hasattr(self, 'last_view') or self.last_view != view.id():
            self.last_view = view.id()
            self.use_full_scan = get_setting(
                'smart_bracket_scan_full_document', False)
            candidates = self.candidates = {}

        if not self.use_full_scan:
            # always clear the candidates when not using a full scan
            candidates = {}
            # when not using a full scan, get the number of lines to
            # look-behind
            try:
                look_around = int(get_setting('smart_bracket_look_around', 5))
            except ValueError:
                look_around = 5

        if candidates is None:
            try:
                candidates = self.candidates
            except:
                candidates = self.candidates = {}

        # first, find the nearest bracket
        if type(sel) is sublime.Region:
            start, end = sel.begin(), sel.end()
        else:
            start = end = sel

        if self.use_full_scan:
            prefix = view.substr(sublime.Region(0, start))
            prefix_start = 0
            suffix_end = view.size()
        else:
            prefix_lines = view.lines(sublime.Region(0, start))
            if len(prefix_lines) >= look_around:
                prefix_start = prefix_lines[-look_around].begin()
            else:
                prefix_start = prefix_lines[0].begin()

            suffix_lines = view.lines(sublime.Region(end, view.size()))
            if len(suffix_lines) >= look_around:
                suffix_end = suffix_lines[look_around - 1].end()
            else:
                suffix_end = suffix_lines[-1].end()

            prefix = view.substr(sublime.Region(prefix_start, start))

        open_bracket, last_index = None, -1
        for char in self.MATCH_CHARS:
            index = prefix.rfind(char)
            if index > last_index:
                open_bracket, last_index = char, index

        if last_index == -1:
            # can't determine bracket to match
            return None

        close_bracket = self.MATCH_CHARS[open_bracket]
        open_brackets = []
        # this is used to throw-away as many matches as possible
        # so subsequent requests don't need to consider every match
        closed_brackets = []

        if open_bracket not in candidates:
            # find all open / close brackets in the current buffer,
            # removing all comments
            candidates[open_bracket] = results = []

            start = prefix_start
            re_str = re.escape(open_bracket) + '|' + re.escape(close_bracket)
            while True:
                if start >= suffix_end:
                    break

                c = view.find(re_str, start)
                if c is None or c.begin() == -1:
                    break

                if c.end() > suffix_end:
                    break

                if view.score_selector(c.begin(), 'comment') != 0:
                    start = c.end()
                    continue

                results.append(c)

                start = c.end()

        for candidate in candidates[open_bracket]:
            if view.substr(candidate) == open_bracket:
                if len(open_brackets) == 0 and candidate.begin() > end:
                    break

                open_brackets.append(candidate)
            else:
                try:
                    removed = open_brackets.pop()
                    if candidate.end() < start:
                        closed_brackets.append(removed)
                        closed_brackets.append(candidate)
                except IndexError:
                    # unbalanced close before open
                    if candidate.end() > end:
                        break

        if len(closed_brackets) > 0:
            candidates[open_bracket] = [
                c for c in candidates[open_bracket]
                if c not in closed_brackets
            ]

        # if we have an open bracket left, then the current bracket needs to
        # be closed
        return close_bracket if len(open_brackets) > 0 else None

    def clear_bracket_cache(self):
        '''
        Clears the cache of brackets stored by get_closing_bracket

        If get_closing_bracket is used, this method must be called at the end
        or else subsequent calls to get_closing_brackets will not be updated
        with a fresh view of the current buffer
        '''
        try:
            del self.candidates
        except:
            pass

        try:
            del self.last_view
        except:
            pass

        try:
            del self.use_full_scan
        except:
            pass

    def get_common_prefix(self, view, locations):
        '''
        gets the common prefix (if any) from a list of locations

        :param view:
            the current view

        :param locations:
            either a list of points or a list of sublime.Regions
        '''
        if type(locations[0]) is int or type(locations[0]) is int:
            locations = [sublime.Region(l, l) for l in locations]

        old_prefix = None
        for location in locations:
            if location.empty():
                word_region = sublime.Region(
                    self.get_current_word(view, location).begin(),
                    location.b
                )
                prefix = view.substr(word_region)
            else:
                prefix = view.substr(location)

            if old_prefix is None:
                old_prefix = prefix
            elif old_prefix != prefix:
                prefix = ''
                break

        return prefix

    def get_common_fancy_prefix(self, view, locations):
        '''
        get the common fancy prefix (if any) from a list of locations

        see get_fancy_prefix for the definition of a fancy prefix

        :param view:
            the current view

        :param locations:
            either a list of points or a list of sublime.Regions
        '''
        remove_regions = []
        old_prefix = None
        new_prefix = ''

        for location in locations:
            prefix_region = self.get_fancy_prefix(view, location)
            if prefix_region.empty():
                continue

            new_prefix = view.substr(
                sublime.Region(prefix_region.begin() + 1, prefix_region.end())
            )

            remove_regions.append(prefix_region)

            if old_prefix is None:
                old_prefix = new_prefix
            elif old_prefix != new_prefix:
                # dummy value that is not None and will never match the
                # prefix
                old_prefix = True
                new_prefix = ''

        return new_prefix, remove_regions

    def get_current_word(self, view, location):
        '''
        Gets the region containing the current word which contains the caret
        or the given selection.

        The current word is defined between the nearest non-word characters to
        the left and to the right of the current selected location.

        Non-word characters are defined by the WORD_SEPARATOR_RX.

        :param view:
            the current view

        :param location:
            either a point or a sublime.Region that defines the caret position
            or current selection
        '''
        if isinstance(location, sublime.Region):
            start, end = location.begin(), location.end()
        else:
            start = end = location

        start_line = view.line(start)
        end_line = view.line(end)
        # inverse prefix so we search from the right-hand side
        line_prefix = view.substr(sublime.Region(start_line.begin(), start))[::-1]
        line_suffix = view.substr(sublime.Region(end, end_line.end()))

        # prefix is the characters before caret
        m = self.WORD_SEPARATOR_RX.search(line_prefix)
        prefix = m.group(1) if m else ''

        m = self.WORD_SEPARATOR_RX.search(line_suffix)
        suffix = m.group(1) if m else ''

        return sublime.Region(start - len(prefix), end + len(suffix))

    def get_match_char(self, insert_char):
        return self.MATCH_CHARS.get(insert_char, '')

    def get_fancy_prefix(self, view, location):
        '''
        Gets the prefix for the command assuming it takes a form like:
            \cite_prefix
            \ref_prefix

        These are also supported:
            \cite_prefix{
            \ref_prefix{

        The prefix is defined by everything *after* the underscore

        :param view:
            the current view

        :param location:
            either a point or a sublime.Region that defines the caret position
            or current selection
        '''
        if isinstance(location, sublime.Region):
            start = location.begin()
        else:
            start = location

        start_line = view.line(start)
        # inverse prefix so we search from the right-hand side
        line_prefix = view.substr(
            sublime.Region(start_line.begin(), start))[::-1]

        m = self.FANCY_PREFIX_RX.match(line_prefix)
        if not m:
            return sublime.Region(start, start)

        return sublime.Region(start - len(m.group(0)), start - m.start())

    def insert_at_end(self, view, edit, value):
        '''
        Inserts a string at the end of every current selection

        :param view:
            the current view

        :param edit:
            the current edit

        :param value:
            the string to insert
        '''
        if value:
            new_regions = []
            for sel in view.sel():
                view.insert(edit, sel.end(), value)
                if sel.empty():
                    new_start = new_end = sel.end() + len(value)
                else:
                    new_start = sel.begin()
                    new_end = sel.end() + len(value)

                new_regions.append(sublime.Region(new_start, new_end))
            self.update_selections(view, new_regions)

    def replace_word(self, view, edit, value):
        '''
        Replaces the current word with the provided string in each selection

        For the definition of word, see get_current_word()

        :param view:
            the current view

        :param edit:
            the current edit

        :param value:
            the string to replace the current word with
        '''
        new_regions = []
        for sel in view.sel():
            if sel.empty():
                word_region = self.get_current_word(view, sel.end())
                start_point = word_region.begin()
                end_point = word_region.end()
            else:
                word_region = self.get_current_word(view, sel)
                start_point = word_region.begin()
                end_point = word_region.end()

            view.replace(edit, sublime.Region(start_point, end_point), value)

            if sel.empty():
                start_point = end_point = start_point + len(value)
            else:
                end_point = start_point + len(value)
            new_regions.append(sublime.Region(start_point, end_point))

        self.update_selections(view, new_regions)

    def remove_regions(self, view, edit, regions):
        view = self.view
        for region in regions:
            view.erase(edit, region)

    def update_selections(self, view, new_regions):
        '''
        Removes all current selections and adds the specified selections

        NB When calling this method, it is important that all current
        selections be either replaced or simply included as-is. Otherwise,
        these selections will be lost

        :param view:
            the current view

        :param new_regions:
            a list of sublime.Regions that should be selected
        '''
        sel = view.sel()
        sel.clear()
        # we could use ST3's add_all, but this way has less branching...
        for region in new_regions:
            sel.add(region)

    def regions_to_tuples(self, regions):
        '''
        Converts a list of regions to a list of two-element tuples containing
        the corresponding points

        This is necessary to properly serialize a set of regions as an argument
        to a Sublime command, since arguments MUST be serializable as JSON
        objects

        :param regions:
            an iterable of sublime.Regions to convert to tuples
        '''
        # a and b are used instead of begin() / end() so that the caret
        # position (b) is preserved
        if type(regions) == sublime.Region:
            return [(regions.a, regions.b)]

        return [
            [r.a, r.b]
            for r in regions
        ]

    def tuples_to_regions(self, tuples):
        '''
        Converts a list of 2-tuples to a list of corresponding regions

        This is the opposite of regions_to_tuples and is intended to
        deserialize regions serialized using that method

        :param tuples:
            an iterable of two-element tuples to convert to sublime.Regions
        '''
        if type(tuples) == tuple:
            return [sublime.Region(tuples[0], tuples[1])]

        return [
            sublime.Region(start, end)
            for start, end in tuples
        ]

    def score_selector(self, view, selector):
        '''
        Scores a selector on a view, returns True if the selectors is
        scored for each selection.

        :param view:
            the current view

        :param selector:
            the selector, which should be scored
        '''
        return all(view.score_selector(sel.b, selector) for sel in view.sel())

class LatexFillAllPluginConsumer(object):
    '''
    Base class for classes which use FillAllHelper plugins
    '''
    COMPLETION_TYPE_NAMES = []
    COMPLETION_TYPES = None

    def _load_plugins(self):
        '''
        Loads the FillAllHelper plugins
        '''
        self.COMPLETION_TYPES = {}
        for plugin in get_plugins_by_type(FillAllHelper):
            name = _classname_to_internal_name(plugin.__name__)
            if name.endswith('_fill_all_helper'):
                name = name[:-16]
                self.COMPLETION_TYPES[name] = plugin()

        self.COMPLETION_TYPE_NAMES = list(self.COMPLETION_TYPES.keys())

    def get_completion_types(self):
        '''
        Gets the list of plugin names
        '''
        if self.COMPLETION_TYPES is None:
            self._load_plugins()
        return self.COMPLETION_TYPE_NAMES

    def get_completion_type(self, name):
        if self.COMPLETION_TYPES is None:
            self._load_plugins()
        return self.COMPLETION_TYPES.get(name)

class LatexFillAllEventListener(
    sublime_plugin.EventListener, LatexFillHelper, LatexFillAllPluginConsumer
):
    '''
    Implements the query completions and query context functionality for some
    completions and the logic to insert brackets as necessary
    '''

    # keys supported by on_query_context
    SUPPORTED_KEYS = None

    SUPPORTED_INSERT_CHARS = {
        'open_curly': '{',
        'open_square': '[',
        'comma': ',',
        'equal_sign': '='
    }

    def on_query_context(self, view, key, operator, operand, match_all):
        '''
        supports query_context for all completion types
        key is "lt_fill_all_{name}" where name is the short name of the
        completion type, e.g. "lt_fill_all_cite", etc.
        '''
        # quick exit conditions
        if not key.startswith("lt_fill_all_"):
            return None
        for sel in view.sel():
            point = sel.b
            if not view.score_selector(point, "text.tex.latex"):
                return None

        # load the plugins
        if self.SUPPORTED_KEYS is None:
            self.SUPPORTED_KEYS = dict(
                ("lt_fill_all_{0}".format(name), name)
                for name in self.get_completion_types()
            )

        try:
            key, insert_char = key.split('.')
        except:
            insert_char = ''

        # not handled here
        if key not in self.SUPPORTED_KEYS:
            return None
        # unsupported bracket
        elif insert_char and insert_char not in self.SUPPORTED_INSERT_CHARS:
            return False
        # unsupported operators
        elif operator not in [sublime.OP_EQUAL, sublime.OP_NOT_EQUAL]:
            return False

        insert_char = self.SUPPORTED_INSERT_CHARS.get(insert_char, '')

        completion_type = self.get_completion_type(
            self.SUPPORTED_KEYS.get(key)
        )

        if not(completion_type and completion_type.is_enabled()):
            return False

        selector = completion_type.get_supported_scope_selector()
        if not self.score_selector(view, selector):
            return False

        lines = [
            insert_char + view.substr(
                sublime.Region(view.line(sel).begin(), sel.b)
            )[::-1]
            for sel in view.sel()
        ]

        func = all if match_all else any
        result = func((
            completion_type.matches_line(line)
            for line in lines
        ))

        return result if operator == sublime.OP_EQUAL else not result

    def on_query_completions(self, view, prefix, locations):
        for location in locations:
            if not view.score_selector(location, "text.tex.latex"):
                return

        completion_types = self.get_completion_types()

        orig_prefix = prefix

        # tracks any regions to be removed
        fancy_prefix, remove_regions = self.get_common_fancy_prefix(
            view, locations
        )
        # although a prefix is passed in, our redefinition of "word" boundaries
        # mean we should recalculate this
        prefix = self.get_common_prefix(view, locations)

        fancy_prefixed_line = None
        if remove_regions:
            if remove_regions:
                fancy_prefixed_line = view.substr(
                    sublime.Region(view.line(locations[0]).begin(), locations[0])
                )[::-1]

        line = view.substr(
            sublime.Region(view.line(locations[0]).begin(), locations[0])
        )[::-1]

        completion_type = None
        for name in completion_types:
            ct = self.get_completion_type(name)
            if (
                fancy_prefixed_line is not None and
                hasattr(ct, 'matches_fancy_prefix')
            ):
                if ct.matches_fancy_prefix(fancy_prefixed_line):
                    line = fancy_prefixed_line
                    prefix = fancy_prefix
                    completion_type = ct
                    break
                elif ct.matches_line(line):
                    completion_type = ct
                    remove_regions = []
                    break
            elif ct.matches_line(line):
                completion_type = ct
                # reset fancy prefix
                remove_regions = []
                break

        if completion_type is None:
            self.clear_bracket_cache()
            return []
        elif not self.score_selector(
                view, completion_type.get_supported_scope_selector()):
            self.clear_bracket_cache()
            return []
        # completions could be unpredictable if we've changed the prefix
        elif orig_prefix and not prefix:
            self.clear_bracket_cache()
            return []

        try:
            completions = completion_type.get_auto_completions(
                view, prefix, line[::-1]
            )
        except:
            traceback.print_exc()
            self.clear_bracket_cache()
            return []

        if len(completions) == 0:
            self.clear_bracket_cache()
            return []
        elif type(completions) is tuple and len(completions) == 2:
            completions, insert_char = completions
            if len(completions) == 0:
                self.clear_bracket_cache()
                return []
        else:
            # this assumes that all regions have a similar current word
            # not ideal, but reasonably safe see:
            # http://docs.sublimetext.info/en/latest/extensibility/completions.html#completions-with-multiple-cursors
            insert_char = view.substr(
                self.get_current_word(view, locations[0])
            )

        # we found a _<prefix> entry, so clear it and remove the prefix
        # and close the brackets
        if remove_regions:
            view.run_command(
                'latex_tools_fill_all_complete_bracket',
                {
                    'insert_char': insert_char,
                    'remove_regions': self.regions_to_tuples(remove_regions)
                }
            )

        if type(completions[0]) is tuple:
            show, completions = zip(*completions)
        else:
            show = completions[:]

        # we did not find a fancy prefix, so append the closing bracket,
        # if needed, to the completions
        if not remove_regions:
            closing_bracket = None
            for sel in view.sel():
                new_bracket = self.get_closing_bracket(view, sel)
                if closing_bracket is None:
                    closing_bracket = new_bracket
                elif new_bracket != closing_bracket:
                    closing_bracket = None
                    break

            if closing_bracket:
                completions = [
                    c + closing_bracket
                    for c in completions
                ]

        self.clear_bracket_cache()

        return (
            zip(show, completions),
            sublime.INHIBIT_WORD_COMPLETIONS |
            sublime.INHIBIT_EXPLICIT_COMPLETIONS
        )

class LatextoolsFillAllCommand(
    sublime_plugin.TextCommand, LatexFillHelper, LatexFillAllPluginConsumer
):
    '''
    Implements the quick panel for auto-triggered completions and the
    logic to insert brackets as necessary

    :param edit:
        the current edit

    :param completion_type:
        the completion plugin to use (optional)
        may be:
            * a string indicating the specific completion type, e.g. "cite"
            * a list of such strings
            * None, in which case all available completion types are searched

    :param insert_char:
        the character to insert before the completion; also determines the
        matching brace if any

    :param overwrite:
        boolean indicating whether or not to overwrite the current field;
        if false, text within the current selection or to the left of the
        cursor is treated as the prefix, which usually restricts the
        displayed results;
        if true, the current word will be replaced by the selected entry

    :param force:
        boolean indicating whether or not to match the context or simply
        insert an entry; if force is true, completion_type must be a string;
        if force is true, the bracket matching and word overwriting behaviour
        is disabled
    '''

    def is_visible(self, *args):
        return bool(self.view.score_selector(0, "text.tex.latex"))

    def run(
        self, edit, completion_type=None, insert_char="", overwrite=False,
        force=False
    ):
        view = self.view

        for sel in view.sel():
            point = sel.b
            if not view.score_selector(point, "text.tex.latex"):
                self.complete_brackets(view, edit, insert_char)
                return

        # if completion_type is a simple string, try to load it
        if isinstance(completion_type, str):
            completion_type = self.get_completion_type(completion_type)
            if completion_type is None:
                if not force:
                    self.complete_brackets(view, edit, insert_char)
                return
        elif force:
            print('Cannot set `force` if completion type is not specified')
            return

        if force:
            insert_char = ''
            overwrite = False

        # tracks any regions to be removed
        remove_regions = []
        prefix = ''

        # handle the _ prefix, if necessary
        if (
            not isinstance(completion_type, FillAllHelper) or
            hasattr(completion_type, 'matches_fancy_prefix')
        ):
            fancy_prefix, remove_regions = self.get_common_fancy_prefix(
                view, view.sel()
            )

        # if we found a _ prefix, we use the raw line, so \ref_eq
        fancy_prefixed_line = None
        if remove_regions:
            fancy_prefixed_line = view.substr(
                sublime.Region(view.line(point).begin(), point)
            )[::-1]

        # normal line calculation
        line = (view.substr(
            sublime.Region(view.line(point).begin(), point)
        ) + insert_char)[::-1]

        # handle a list of completion types
        if type(completion_type) is list:
            for name in completion_type:
                try:
                    ct = self.get_completion_type(name)
                    if (
                        fancy_prefixed_line is not None and
                        hasattr(ct, 'matches_fancy_prefix')
                    ):
                        if ct.matches_fancy_prefix(fancy_prefixed_line):
                            completion_type = ct
                            prefix = fancy_prefix
                            break
                        elif ct.matches_line(line):
                            completion_type = ct
                            remove_regions = []
                            break
                    elif ct.matches_line(line):
                        completion_type = ct
                        remove_regions = []
                        break
                except:
                    pass

            if type(completion_type) is list:
                message = "No valid completions found"
                print(message)
                sublime.status_message(message)
                self.complete_brackets(view, edit, insert_char)
                return
        # unknown completion type
        elif (
            completion_type is None or
            not isinstance(completion_type, FillAllHelper)
        ):
            for name in self.get_completion_types():
                ct = self.get_completion_type(name)
                if ct is None:
                    continue

                if (
                    fancy_prefixed_line is not None and
                    hasattr(ct, 'matches_fancy_prefix')
                ):
                    if ct.matches_fancy_prefix(fancy_prefixed_line):
                        completion_type = ct
                        prefix = fancy_prefix
                        break
                    elif ct.matches_line(line):
                        completion_type = ct
                        remove_regions = []
                        break
                elif ct.matches_line(line):
                    completion_type = ct
                    remove_regions = []
                    break

            if (
                completion_type is None or
                isinstance(completion_type, str)
            ):
                message = \
                    'Cannot determine completion type for current selection'
                print(message)
                sublime.status_message(message)

                self.complete_brackets(view, edit, insert_char)
                return
        # assume only a single completion type to use
        else:
            # if force is set, we do no matching
            if not force:
                if (
                    fancy_prefixed_line is not None and
                    hasattr(completion_type, 'matches_fancy_prefix')
                ):
                    if completion_type.matches_fancy_prefix(
                        fancy_prefixed_line
                    ):
                        prefix = fancy_prefix
                    elif completion_type.matches_line(line):
                        remove_regions = []
                elif completion_type.matches_line(line):
                    remove_regions = []

        # we only check if the completion type is enabled if we're also
        # inserting a comma or bracket; otherwise, it must've been a keypress
        if insert_char and not completion_type.is_enabled():
            self.complete_brackets(view, edit, insert_char)
            return

        # we are not adding a bracket or comma, we do not have a fancy prefix
        # and the overwrite and force options were not set, so calculate the
        # prefix as the previous word
        if insert_char == '' and not prefix and not overwrite and not force:
            prefix = self.get_common_prefix(view, view.sel())

        # reset the _ completions if we are not using them
        if (
            insert_char and
            "fancy_prefix" in locals() and
            prefix != fancy_prefix
        ):
            remove_regions = []
            prefix = ''

        try:
            completions = completion_type.get_completions(
                view, prefix, line[::-1]
            )
        except:
            self.complete_brackets(
                view, edit, insert_char, remove_regions=remove_regions
            )
            reraise(*sys.exc_info())

        if completions is None:
            self.complete_brackets(
                view, edit, insert_char, remove_regions=remove_regions
            )
            return
        elif type(completions) is tuple:
            formatted_completions, completions = completions
        else:
            formatted_completions = completions

        if len(completions) == 0:
            self.complete_brackets(
                view, edit, insert_char, remove_regions=remove_regions
            )
        elif len(completions) == 1:
            # if there is only one completion and it already matches the
            # current text
            if force:
                view.insert(edit, completions[0])
                return
            else:
                if completions[0] == prefix:
                    return

                if insert_char:
                    insert_text = (
                        insert_char + completions[0]
                        if completions[0] else insert_char
                    )
                    self.insert_at_end(view, edit, insert_text)
                elif completions[0]:
                    self.replace_word(view, edit, completions[0])

                self.complete_auto_match(view, edit, insert_char)
                self.remove_regions(view, edit, remove_regions)
            self.clear_bracket_cache()
        else:
            def on_done(i, text=''):
                if i is None:
                    insert_text = text
                elif i < 0:
                    view.run_command(
                        'latex_tools_fill_all_complete_bracket',
                        {
                            'insert_char': insert_char,
                            'remove_regions':
                                self.regions_to_tuples(remove_regions)
                        }
                    )
                    return
                else:
                    insert_text = completions[i]

                if force:
                    view.run_command(
                        'insert',
                        {
                            'characters': insert_text
                        }
                    )
                else:
                    view.run_command(
                        'latex_tools_replace_word',
                        {
                            'insert_char': insert_char,
                            'replacement': insert_text,
                            'remove_regions':
                                self.regions_to_tuples(remove_regions)
                        }
                    )

            show_input_quick_panel(
                view.window(), formatted_completions, on_done)
            self.clear_bracket_cache()

class LatexToolsReplaceWord(sublime_plugin.TextCommand, LatexFillHelper):
    '''
    A TextCommand to replace the current word with a specified replacement

    :param replacement:
        the text to replace the current word with

    :param insert_char:
        if provided, a character to be inserted before the new word
        this is useful to implement bracket-matching around the newly-inserted
        word. Note that if this is provided, the replacement will be inserted
        instead of replacing the current word.

    :param remove_regions:
        any regions to be removed from the view. Regions should be supplied
        as returned by the regions_to_tuples method
    '''

    def run(self, edit, replacement='', insert_char='', remove_regions=[]):
        view = self.view
        if insert_char:
            insert_text = (
                insert_char + replacement
                if replacement else insert_char
            )
            self.insert_at_end(view, edit, insert_text)
        elif replacement:
            self.replace_word(view, edit, replacement)

        self.complete_auto_match(view, edit, insert_char)
        self.remove_regions(view, edit, self.tuples_to_regions(remove_regions))
        self.clear_bracket_cache()

class LatexToolsFillAllCompleteBracket(
    sublime_plugin.TextCommand, LatexFillHelper
):
    '''
    A TextCommand to insert brackets and remove any specified regions

    :param insert_char:
        if provided, a character to be inserted before the new word
        this is useful to implement bracket-matching around the newly-inserted
        word.

    :param remove_regions:
        any regions to be removed from the view. Regions should be supplied
        as returned by the regions_to_tuples method.
    '''

    def run(self, edit, insert_char='', remove_regions=[]):
        self.complete_brackets(
            self.view, edit, insert_char,
            self.tuples_to_regions(remove_regions)
        )

deprecate(globals(), 'LatexFillAllCommand', LatextoolsFillAllCommand)


import re

def detect_phone(text):
    phone_number_pattern = r'\b(1[356789]\d{9})\b'
    sensitive_info = []
    phone_numbers = re.findall(phone_number_pattern, text)

    if phone_numbers:
        return phone_numbers

if __name__ == "__main__":
    fp = open('response_text.txt', 'r')
    content = fp.read()
    fp.close()
    phone = detect_phone(content)
    if phone:
        print("发现明文手机号:")
        print(phone)
        # for info_field in sensitive_info:
        #     print(info)
    else:
        print("未发现敏感信息")


"""Manage BoneIO onboard temp sensors."""

import asyncio
from datetime import datetime, timedelta
from typing import Optional

from boneio.const import STATE, SENSOR, TEMPERATURE

from boneio.helper.exceptions import I2CError
from boneio.helper import BasicMqtt

from boneio.helper.util import callback
from boneio.helper.events import async_track_point_in_time, utcnow

from boneio.helper.timeperiod import TimePeriod

class TempSensor(BasicMqtt):
    """Represent Temp sensor in BoneIO."""

    SensorClass = None
    DefaultName = TEMPERATURE

    def __init__(
        self,
        i2c,
        address: str,
        id: str = DefaultName,
        update_interval: int = TimePeriod(seconds=60),
        **kwargs
    ):
        """Initialize Temp class."""
        super().__init__(id=id, topic_type=SENSOR, **kwargs)
        self._update_interval = update_interval
        self._loop = asyncio.get_event_loop()
        try:
            self._pct = self.SensorClass(i2c_bus=i2c, address=address)
            self._unsub_refresh = None
            self._schedule_refresh(utcnow() + timedelta(seconds=2))
        except ValueError as err:
            raise I2CError(err)

    @property
    def state(self):
        """Give rounded value of temperature."""
        return round(self._pct.temperature, 2)

    def _schedule_refresh(self, update_time: Optional[datetime] = None):
        if self._unsub_refresh:
            self._unsub_refresh()
            self._unsub_refresh = None
        if not update_time:
            update_time = utcnow() + self._update_interval.as_timedelta
        self._unsub_refresh = async_track_point_in_time(
            loop=self._loop,
            action=self._refresh,
            point_in_time=update_time,
        )

    @callback
    def _refresh(self, time: datetime):
        if self._unsub_refresh:
            self._unsub_refresh()
            self._unsub_refresh = None

        self.send_state()
        self._schedule_refresh()

    def send_state(self):
        """Fetch temperature periodically and send to MQTT."""
        self._send_message(
            topic=self._send_topic,
            payload={STATE: self.state},
        )


#!/usr/bin/env python3
import cgi
import sqlite3

form = cgi.FieldStorage()
name_pat = form.getfirst("name_pat", "не задано")
birthdate_pat = form.getfirst("birthdate_pat", "не задано")

name_pat = (str(name_pat))
birthdate_pat = (str(birthdate_pat))

conn = sqlite3.connect("database.db")
cursor = conn.cursor()

cursor.execute("insert into patiens (name, birthdate) values(?, ?)", (name_pat, birthdate_pat))

print("Content-type: text/html")
print()
print('''

    <meta charset="utf-8">

    ''')
print('''

        Запись добавлена

         На главную

         Посмотреть таблицы

''')

conn.commit()
cursor.close()
conn.close()


class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        char_index_map = {}
        max_length = 0
        start = 0

        for end in range(len(s)):
            if s[end] in char_index_map and char_index_map[s[end]] >= start:
                start = char_index_map[s[end]] + 1

            char_index_map[s[end]] = end
            current_length = end - start + 1
            max_length = max(max_length, current_length)

        return max_length

# Example usage:
solution = Solution()
print(solution.lengthOfLongestSubstring("abcabcbb"))  # Output: 3
print(solution.lengthOfLongestSubstring("bbbbb"))     # Output: 1
print(solution.lengthOfLongestSubstring("pwwkew"))    # Output: 3


# This line is needed to use GUI
# ↓ บรรทัดนี้จำเป็นต้องใช้ GUI
from tkinter import *
# This line is needed to get random numbers
# ↓ บรรทัดนี้จำเป็นสำหรับการรับตัวเลขแบบสุ่ม
import random

# This is main part of program

# These 2 lines are making screen outline.
# These are necessary for GUI program.
# 2 บรรทัดเหล่านี้กำลังสร้างเค้าโครงหน้าต่าง GUI
# สิ่งเหล่านี้จำเป็นสำหรับโปรแกรม GUI
root = Tk(className='main')
root.geometry("240x240")

# Preparation
# การจัดเตรียม
label_main = Label(root, text="0")
label_main.pack()
click_count = 0

def change_main():
    global click_count
    click_count = click_count + 1
    label_main["text"] = click_count

# "root" (=made by "Tk" function) is a special window
# If the user closes "root" window, application will finish
# But closing a sub-window (=made by "Toplevel" function) just close the window
# application will keep continue to work

# "root" (= ทำโดยฟังก์ชั่น "Tk") เป็นหน้าต่างพิเศษ
# หากผู้ใช้ปิดหน้าต่าง "root"  แอปพลิเคชันจะเสร็จสิ้น
# แต่ ปิดหน้าต่างย่อย (= ทำโดยฟังก์ชั่น "Toplevel") เพียงปิดหน้าต่าง
# แอปพลิเคชั่นจะทำงานต่อไป

# สร้าง หน้าต่างย่อย โดยฟังก์ชั่น "Toplevel"
sub = Toplevel()
# ต้องให้ชื่อ โดยฟังก์ชั่น "title"
sub.title("sub")
# สามารถให้ขนาด เหมือนกับหน้าต่างหลัก
sub.geometry("300x100")

# สามารถสร้างชิ้นส่วน GUI เหมือนกับหน้าต่างหลัก
# แต่ระวัง อาร์กิวเมนต์ที่ 1 ของฟังก์ชั่น ไม่ใช่ "root"
button_sub = Button(sub, text="In Sub Window", command=change_main)
button_sub.pack()

# This is an also necessary line for GUI program.
# (This line must be placed at the end of GUI program)
# นี่เป็นบรรทัดที่จำเป็นสำหรับโปรแกรม GUI
# (บรรทัดนี้ควรอยู่ที่ท้ายโปรแกรม GUI)
root.mainloop()


from typing import List
import requests
import os
import dotenv
import json
from models import trelloModel

dotenv.load_dotenv()

class Trello:

    Board: trelloModel.BoardModel = trelloModel.BoardModel()

    #region Configurations
    def __init__(self, boardName):
        self.__key = os.getenv("TRELLOKEY")
        self.__token = os.getenv("TRELLOTOKEN")
        self.__baseUrl = "Https://api.trello.com"
        self.__headers = {
            'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8',
        }
        self.boardId = self.getBoardId( boardName)
        self.syncBoardData()

    # def __getattribute__(self, item: str):
    #     if (item.startswith('_') or callable(vars(Trello)[item])):
    #         return super(Trello, self).__getattribute__(item)
    #     if ('sync' + item.lower().capitalize() in [p[0] for p in vars(Trello).items() if callable(p[1])]):
    #         exec('self.sync{}Data()'.format(item.lower().capitalize()))
    #     return super(Trello, self).__getattribute__(item)
    #endregion

    ## Getting data
    def syncCheckListData(self, cardId: List[str]):
        checkListArray: List[trelloModel.CheckListModel] = []
        for i in cardId:
            checkListDataUrl = f'{self.__baseUrl}/1/checklists/{i}/?key={self.__key}&token={self.__token}'
            reqResponse = requests.get(checkListDataUrl, headers=self.__headers).json()
            checkListObj = trelloModel.CheckListModel()
            checkListObj.checkListId = reqResponse["id"]
            checkListObj.name = reqResponse["name"]
            checkListObj.itens = []
            for x in reqResponse["checkItems"]:
                checkItemObj = trelloModel.CheckListItemModel()
                checkItemObj.id = x["id"]
                checkItemObj.name = x["name"]
                checkItemObj.due = x["due"]
                checkItemObj.checked = x["state"] == 'complete' if True else False
                checkListObj.itens.append(checkItemObj)
            checkListArray.append(checkListObj)
        return checkListArray

    def syncCardsData(self, listId):
        cardDataUrl = f'{self.__baseUrl}/1/lists/{listId}/cards/?key={self.__key}&token={self.__token}'
        reqResponse = requests.get(cardDataUrl, headers=self.__headers)
        trelloCardsList: List[trelloModel.CardModel] = []
        for i in reqResponse.json():
            trelloCardObj = trelloModel.CardModel()
            trelloCardObj.listid = i["idList"]
            trelloCardObj.cardId = i["id"]
            trelloCardObj.name = i["name"]
            trelloCardObj.desc = i["desc"]
            trelloCardObj.dueDate = i["due"]
            trelloCardObj.dueComplete = i["dueComplete"]
            trelloCardObj.checklists = self.syncCheckListData(i["idChecklists"])
            trelloCardsList.append(trelloCardObj)
        return trelloCardsList

    def syncListsData(self):
        getListsIdsUrl = f'{self.__baseUrl}/1/boards/{self.boardId}/lists/?key={self.__key}&token={self.__token}'
        listsIdResponse = requests.get(getListsIdsUrl, headers=self.__headers)
        trelloListArray: List[trelloModel.ListsModel] = []
        for i in listsIdResponse.json():
            trelloListObj = trelloModel.ListsModel()
            trelloListObj.listId = i["id"]
            trelloListObj.name = i["name"]
            trelloListObj.idBoard = i["idBoard"]
            trelloListObj.cards = self.syncCardsData(i["id"])
            trelloListArray.append(trelloListObj)
        return trelloListArray

    def syncBoardData(self) -> None:
        getBoardUrl = f'{self.__baseUrl}/1/boards/{self.boardId}/?key={self.__key}&token={self.__token}'

        reqResponse = requests.get(getBoardUrl , headers=self.__headers)
        self.Board.boardId = reqResponse.json()["id"]
        self.Board.name = reqResponse.json()["name"]
        self.Board.labels = trelloModel.LabelsModel.fromJson(reqResponse.json()["labelNames"])
        funcReturn = self.syncListsData()
        self.Board.lists = funcReturn

    def getBoardId(self, boardName: str) -> int:
        getBoardIdUrl = f'{self.__baseUrl}/1/members/me/boards/?key={self.__key}&token={self.__token}'
        reqResponse = requests.get(getBoardIdUrl, headers=self.__headers)
        for i in reqResponse.json():
            if (i["name"].lower() == boardName.lower()):
                return i["shortLink"]

        raise ValueError('The board was not found')


# -*- coding: utf-8 -*-

import optparse
import speex
import sys

from twistar.registry import Registry
from twisted.enterprise import adbapi
from twisted.internet import reactor
from twisted.python import log

from sequoia.media.media import AudioMixer
from sequoia.protocol import ServerClientsFactory, ServerMediaProtocol
from sequoia.security import ServerContextFactory

def parse_args():
    usage = """usage: %prog [--host=HOST] [--cport=CPORT] [--mport=MPORT]"""
    parser = optparse.OptionParser(usage)

    help = "Host to run server on. Default: localhost"
    parser.add_option('--host', default='localhost', help=help)

    help = "Port for clients to connect to. Default: 0"
    parser.add_option('--cport', type='int', default=0, help=help)

    help = "Port for receiving media data. Default: 0"
    parser.add_option('--mport', type='int', default=0, help=help)

    options, args = parser.parse_args()
    return options.host, options.cport, options.mport

def show_connector_info(connector, description):
    info = connector.getHost()
    log.msg("{0} on {1}:{2}.".format(description, info.host, info.port))

def main():
    host, cport, mport = parse_args()
    use_codec = False

    Registry.DBPOOL = adbapi.ConnectionPool(
        'sqlite3', "sequoia/tests/auth/server_1/database.db",
        check_same_thread=False)

    mixer = AudioMixer()
    reactor.callWhenRunning(mixer.start)
    codec = speex.new() if use_codec else None
    media_tx = ServerMediaProtocol(codec, mixer)
    clients_factory = ServerClientsFactory(media_tx, use_codec)
    ctx_factory = ServerContextFactory(
        "sequoia/tests/auth/server_1/private_key.pem",
        "sequoia/tests/auth/server_1/certificate.pem",
        "sequoia/tests/auth/root/root_ca.crt")

    clients_listener = reactor.listenSSL(cport, clients_factory, ctx_factory,
        interface=host)
    show_connector_info(clients_listener, "Listening clients")
    media_listener = reactor.listenUDP(mport, media_tx,
        interface=host)
    show_connector_info(media_listener, "Serving media")

    reactor.run()

if __name__ == "__main__":
    log.startLogging(sys.stdout)
    main()


# (Python) ARIMA TimeSeries 230508
# 전통적으로 시계열 데이터 분석은
# AR(Autoregressive),
# MA(Moving average),
# ARMA(Autoregressive Moving average),
# ARIMA(Autoregressive Integrated Moving average)

url_path = 'https://raw.githubusercontent.com/kimds929/CodeNote/main/99_DataSet/Data_TimeSeries'

df_temp = pd.read_csv(f'{url_path}/12-22YR_Seoul_Temperature.csv', encoding='utf-8-sig')
df_temp.sample(5)
df_temp.shape

time_col = '일시'
y_col = '평균기온(℃)'
X_cols = []

df_temp = pd.read_csv(f'{url_path}/AUS_Weather_DataSet.csv', encoding='utf-8-sig')
df_temp.sample(5)
df_temp.shape
time_col = 'Date'
y_col = 'Temp3pm'
X_cols = []

cols = [time_col, y_col] + X_cols

df_temp = df_temp[cols].dropna()
df_temp.isna().sum(0)

df_temp[time_col] = pd.to_datetime(df_temp[time_col], format='%Y-%m-%d')

print(df_temp[time_col].min(), df_temp[time_col].max())
df_temp_5D = df_temp.set_index(time_col).resample('5D')[[y_col]+X_cols].mean()
df_temp_10D = df_temp.set_index(time_col).resample('10D')[[y_col]+X_cols].mean()
df_temp_20D = df_temp.set_index(time_col).resample('20D')[[y_col]+X_cols].mean()

# df_target = df_temp_5D.reset_index().query(f"'2015-01-01' <= {time_col} < '2022-01-01'")
df_target = df_temp_20D.reset_index().query(f"'2013-01-01' <= {time_col} < '2016-01-01'").dropna()
# df_target = df_temp.set_index(time_col)[[cols]]
# df_target = df_temp_10D.to_frame()

plt.figure(figsize=(10,3))
plt.plot(df_target[time_col], df_target[y_col])
plt.show()

# (AR Model)
#   Autoregressive 모델은 자기 회귀 모델이라고 불린다.
#   과거 시점의 자기 자신의 데이터가 현 시점의 자기 자신에게 영향을 미치는 모델이라는 뜻
# X(t) = w*X(t-1) + b + u*e(t)
# 시점 t에 대한 데이터는 이전 시점의 자기 데이터에 가중치 w를 곱하고 상수 b를 더하고(회귀식),
# error term인 e(t)에 가중치 u를 곱한 것을 더해서 표현할 수 있다
# df_target.shape

# https://zephyrus1111.tistory.com/102
import numpy as np
import statsmodels.tsa as tsa
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.ar_model import AR, AutoReg
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf

X = np.array(df_target[y_col]).reshape(-1,1)
# pd.Series(X.ravel()).isna().sum()

class AR():
    def __init__(self):
        pass

    def fit(self, X, p_order=1):
        """
        X: 1D numpy 배열, 시계열 데이터
        p_order: int, AR 모델 차수
        반환값: residual
        """
        X_arr = np.array(X).ravel()
        len_arr = len(X_arr) - p_order

        Xmat = np.roll(X, p_order-p_order)[:len_arr].reshape(-1,1)
        Ymat = np.roll(X, -p_order)[:len_arr].reshape(-1,1)

        for p in range(p_order-1):
            Xmat = np.hstack([np.roll(X_arr, -p-1)[:len_arr].reshape(-1,1), Xmat])

        self.beta = np.linalg.inv(Xmat.T @ Xmat) @ Xmat.T @ Ymat     # Linear 회귀계수
        self.pred = Xmat @ self.beta
        self.res = Ymat - self.pred

        self.X_mat = Xmat
        self.Y_mat = Ymat

        return self.res

ar = AR()
ar.fit(X, 3)

plt.figure()
plt.plot(X)
plt.plot(ar.X_mat[:,-1])
plt.plot(ar.pred)
# plt.plot(ar.res)
plt.show()


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

def dfs(x, y, cnt):
    global ans
    ans = max(ans, cnt)
    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if 0 <= nx < r and 0 <= ny < c:
            if not check[ord(data[nx][ny])-65]:
                # 어차피 check에 들어간 곳은 더 이상 탐색 안하니까 동일한 곳으로 돌아가는 것은 고려 안해도 됨
                check[ord(data[nx][ny])-65] = 1
                dfs(nx, ny, cnt+1)
                check[ord(data[nx][ny])-65] = 0

input = sys.stdin.readline

r, c = map(int, input().split())
data = [input() for _ in range(r)]
# A~Z 까지의 아스키 코드는 65~90
check = [0] * 26
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
check[ord(data[0][0])-65] = 1
ans = 1
dfs(0, 0, 1)
print(ans)


import socket
import os
import mimetypes

class TCPServer:
    def __init__(self, host = '127.0.0.1', port = 8888):
        self.host = host
        self.port = port

    def start(self):
        # socket object
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # bind the socket object to the address and port
        s.bind((self.host, self.port))

        # start listening for connections
        s.listen(5)

        print("Listening at", s.getsockname())

        while True:
            # accept new connections
            conn, addr = s.accept()

            print("Connected by", addr)

            # read first 1024 bytes sent by client
            data = conn.recv(1024)

            response = self.handle_request(data)

            # send back data to client
            conn.sendall(response)

            # close the connection
            conn.close()

    def handle_request(self, data):
        return data

class HTTPServer(TCPServer):
    """
    A crude HTTP Server.
    """
    headers = {
        'Server': 'CrudeServer',
        'Content-Type': 'text/html',
    }

    status_codes = {
        200: 'OK',
        404: 'Not Found',
        501: 'Not Implemented',
    }

    def handle_request(self, data):
        request = HTTPRequest(data)

        try:
            handler = getattr(self, 'handle_%s' % request.method)
        except AttributeError:
            handler = self.HTTP_501_handler

        response = handler(request)

        return response

    def handle_GET(self, request):
        filename = request.uri.strip('/')

        if os.path.exists(filename):
            response_line = self.response_line(status_code=200)

            # find file's MIME type
            # send `text/html` if nothing found
            content_type = mimetypes.guess_type(filename)[0] or 'text/html'

            extra_headers = {'Content-Type': content_type}

            response_headers = self.response_headers(extra_headers)

            with open(filename, 'rb') as f:
                response_body = f.read()
        else:
            response_line = self.response_line(status_code=404)
            response_headers = self.response_headers()
            response_body = b"
404 Not Found
"

        blank_line = b"\r\n"

        return b"".join([response_line, response_headers, blank_line, response_body])

    def HTTP_501_handler(self, request):
        response_line = self.response_line()

        response_headers = self.response_headers()

        blank_line = b"\r\n"

        response_body = b"""

501 Not Implemented

        """

        return b"".join([response_line, response_headers, blank_line, response_body])

    def response_line(self, status_code):
        """Returns response line"""
        reason = self.status_codes[status_code]
        line = "HTTP/1.1 %s %s\r\n" % (status_code, reason)

        # encode into bytes
        return line.encode()

    def response_headers(self, extra_headers=None):
        """Returns headers

        Specify extra headers in `extra_headers` dict
        """
        headers_copy = self.headers.copy()

        if extra_headers:
            headers_copy.update(extra_headers)

        headers = ""

        for h in headers_copy:
            headers += "%s: %s\r\n" % (h, headers_copy[h])

        return headers.encode()

class HTTPRequest:
    def __init__(self, data):
        self.method = None
        self.uri = None
        self.http_version = "1.1"

        self.parse(data)

    def parse(self, data):
        lines = data.split(b"\r\n")

        request_line = lines[0]

        words = request_line.split(b" ")

        self.method = words[0].decode()

        if len(words) > 1:
            # sometimes browsers don't send uri for homepage
            self.uri = words[1].decode()

        if len(words) > 2:
            self.http_version = words[2]

if __name__ == '__main__':
    server = HTTPServer()
    server.start()


import os
import sys
import csv
import time
import torch
import logging
import dataclasses

import numpy      as np

from typing                                import Dict, List, Optional
from filelock                              import FileLock
from dataclasses                           import dataclass, field
from sklearn.metrics                       import f1_score, recall_score, precision_score
from sklearn.metrics                       import matthews_corrcoef
from torch.utils.data.dataset              import Dataset

from transformers                          import AutoTokenizer, EvalPrediction
from transformers                          import AutoConfig, AutoModelForSequenceClassification
from transformers.tokenization_utils       import PreTrainedTokenizer
from transformers.tokenization_roberta     import RobertaTokenizer, RobertaTokenizerFast
from transformers.data.processors.glue     import glue_convert_examples_to_features
from transformers.data.processors.utils    import InputFeatures
from transformers.data.processors.utils    import DataProcessor, InputExample, InputFeatures
from transformers.tokenization_xlm_roberta import XLMRobertaTokenizer
import six
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)

logger = logging.getLogger(__name__)

## From /src/transformers/data/metrics/__init__.py
def simple_accuracy(preds, labels):
    return (preds == labels).mean()
def acc_and_f1(preds, labels):
    acc = simple_accuracy(preds, labels)
    mcc = matthews_corrcoef(labels, preds) # labels and preds instead of other way!
    return_dict = {
        "acc" : acc,
        "mcc" : mcc,
    }
    for average in [ "binary", "micro", "macro", "weighted"] :
        f1        = f1_score       (y_true=labels, y_pred=preds, average=average)
        precision = precision_score(y_true=labels, y_pred=preds, average=average)
        recall    = recall_score   (y_true=labels, y_pred=preds, average=average)
        return_dict[ "f1_"        + average ] = f1
        return_dict[ "precision_" + average ] = precision
        return_dict[ "recall_"    + average ] = recall
    return return_dict

# ColaProcessor from src/transformers/data/processors/glue.py
class Processor(DataProcessor):
    """Processor for the CoLA data set (GLUE version)."""

    def get_example_from_tensor_dict(self, tensor_dict):
        """See base class."""
        return InputExample(
            tensor_dict["idx"].numpy(),
            tensor_dict["data"].numpy().decode("utf-8"),
            None,
            str(tensor_dict["label"].numpy()),
        )

    def get_train_examples(self, data_dir):
        """See base class."""
        return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train")

    def get_dev_examples(self, data_dir):
        """See base class."""
        return self._create_examples(self._read_tsv(os.path.join(data_dir, "val.tsv")), "dev")

    def get_labels(self):
        """See base class."""

        return [str(x) for x in range(2)]

    def _create_examples(self, lines, set_type):
        """Creates examples for the training and dev sets."""
        examples = []
        for (i, line) in enumerate(lines):
            guid = "%s-%s" % (set_type, i)

            text_a = line[3]
            # label = line[5]
            if 'Security' not in line[5]:
                label = str(0)
            else:
                label = str(1)
            examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=label))
        print(self.get_labels())
        return examples

# GlueDataTrainingArguments from: src/transformers/data/datasets/glue.py
@dataclass
class DataTrainingArguments:
    """
    Arguments pertaining to what data we are going to input our model for training and eval.

    Using `HfArgumentParser` we can turn this class
    into argparse arguments to be able to specify them on
    the command line.
    """

    name: str = field(metadata={"help": "A name for this task (Cache folders will be based on this"})
    data_dir: str = field(
        metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."}
    )
    max_seq_length: int = field(
        default=128,
        metadata={
            "help": "The maximum total input sequence length after tokenization. Sequences longer "
            "than this will be truncated, sequences shorter will be padded."
        },
    )
    overwrite_cache: bool = field(
        default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
    )

# From: src/transformers/data/datasets/glue.py
class GlueDataset(Dataset):
    """
    This will be superseded by a framework-agnostic approach
    soon.
    """

    args: DataTrainingArguments
    output_mode: str
    features: List[InputFeatures]

    def __init__(
        self,
        args: DataTrainingArguments,
        tokenizer: PreTrainedTokenizer,
        limit_length: Optional[int] = None,
        evaluate=False,
    ):
        self.args = args
        processor = Processor()
        self.output_mode = 'classification'
        # Load data features from cache or dataset file
        cached_features_file = os.path.join(
            args.data_dir,
            "cached_{}_{}_{}_{}".format(
                "dev" if evaluate else "train", tokenizer.__class__.__name__, str(args.max_seq_length), args.name,
            ),
        )
        print(cached_features_file)
        # Make sure only the first process in distributed training processes the dataset,
        # and the others will use the cache.
        lock_path = cached_features_file + ".lock"
        with FileLock(lock_path):

            if os.path.exists(cached_features_file) and not args.overwrite_cache:
                start = time.time()
                self.features = torch.load(cached_features_file)
                logger.info(
                    f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start
                )
            else:
                logger.info(f"Creating features from dataset file at {args.data_dir}")
                label_list = processor.get_labels()

                # if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__ in (
                #     RobertaTokenizer,
                #     RobertaTokenizerFast,
                #     XLMRobertaTokenizer,
                # ):
                #     # HACK(label indices are swapped in RoBERTa pretrained model)
                #     label_list[1], label_list[2] = label_list[2], label_list[1]

                examples = (
                    processor.get_dev_examples(args.data_dir)
                    if evaluate
                    else processor.get_train_examples(args.data_dir)
                )
                if limit_length is not None:
                    examples = examples[:limit_length]
                self.features = glue_convert_examples_to_features(
                    examples,
                    tokenizer,
                    max_length=args.max_seq_length,
                    label_list=label_list,
                    output_mode='classification',
                )
                start = time.time()
                torch.save(self.features, cached_features_file)
                # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
                logger.info(
                    "Saving features into cached file %s [took %.3f s]", cached_features_file, time.time() - start
                )

    def __len__(self):
        return len(self.features)

    def __getitem__(self, i) -> InputFeatures:
        return self.features[i]

@dataclass
class ModelArguments:
    """
    Arguments pertaining to which model/config/tokenizer we are going to fine-tune from.
    """

    model_name_or_path: str = field(
        metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}
    )
    config_name: Optional[str] = field(
        default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"}
    )
    tokenizer_name: Optional[str] = field(
        default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}
    )
    cache_dir: Optional[str] = field(
        default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"}
    )
    class_weights: Optional[str] = field(
        default=None, metadata={"help": "Comma seperated list of class weights. Weight for Class 0, Weight for Class 1"}
    )

class Modifiedargments:

    def __init__(self, datadir):
        self.name = 'CoLA'
        self.data_dir =  datadir
        self.max_seq_length = 128
        self.overwrite_cache = False

def main():
    # See all possible arguments in src/transformers/training_args.py
    # or by passing the --help flag to this script.
    # We now keep distinct sets of args, for a cleaner separation of concerns.

    parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))

    print(os.path.abspath(sys.argv[1]))

    if len(sys.argv) == 2 and sys.argv[1].endswith(".json"):
        # If we pass only one argument to the script and it's the path to a json file,
        # let's parse it to get our arguments.
        model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
    else:
        model_args, data_args, training_args = parser.parse_args_into_dataclasses()

    if (
        os.path.exists(training_args.output_dir)
        and os.listdir(training_args.output_dir)
        and training_args.do_train
        and not training_args.overwrite_output_dir
    ):
        raise ValueError(
            f"Output directory ({training_args.output_dir}) already exists and is not empty. Use --overwrite_output_dir to overcome."
        )

    # Setup logging
    logging.basicConfig(
        format="%(asctime)s - %(levelname)s - %(name)s -   %(message)s",
        datefmt="%m/%d/%Y %H:%M:%S",
        level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN,
    )
    logger.warning(
        "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s",
        training_args.local_rank,
        training_args.device,
        training_args.n_gpu,
        bool(training_args.local_rank != -1),
        training_args.fp16,
    )
    logger.info("Training/evaluation parameters %s", training_args)

    # Set seed
    set_seed(training_args.seed)

    num_labels  = 2 ## Defined in processor. Change labels before changing this (also hardcoded elsewhere) .
    output_mode = 'classification'

    # Load pretrained model and tokenizer
    #
    # Distributed training:
    # The .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.

    config = AutoConfig.from_pretrained(
        model_args.config_name if model_args.config_name else model_args.model_name_or_path,
        num_labels=2, ## Defined in processor. Change labels before changing this (also hardcoded elsewhere) .
        finetuning_task='cola', ## Not sure why we need this!
        cache_dir=model_args.cache_dir,
    )
    tokenizer = AutoTokenizer.from_pretrained(
        model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,
        cache_dir=model_args.cache_dir,
    )
    model = AutoModelForSequenceClassification.from_pretrained(
        model_args.model_name_or_path,
        from_tf=bool(".ckpt" in model_args.model_name_or_path),
        config=config,
        cache_dir=model_args.cache_dir,
    )

    #############################################################################
    #                            Set Class Weights                             ##
    #############################################################################
    class_weights = None
    if not model_args.class_weights is None :
        class_weights = model_args.class_weights.lstrip().rstrip().split( ',' )
        class_weights = [ float(i) for i in class_weights ]
        logger.info(
            "Using Class Weights {}".format( ','.join( [ str(i) for i in class_weights ] ) )
        )
        class_weights = torch.tensor( class_weights, dtype=torch.float, device=training_args.device )
    model.set_class_weights( class_weights )
    #############################################################################

    # Get datasets
    aspect = 'Security'
    print(data_args)
    train_path = '/workspace/RoBERTa_textclassification/aspect_classifier/costsensitivebert/Cost-Sensitive_Bert_and_Transformers/examples/glue_data/CoLA/'+aspect+'/0/'
    eval_path = '/workspace/RoBERTa_textclassification/aspect_classifier/costsensitivebert/Cost-Sensitive_Bert_and_Transformers/examples/glue_data/CoLA/'+aspect+'/0/'
    train_dataset = GlueDataset(Modifiedargments(datadir = train_path), tokenizer=tokenizer) if training_args.do_train else None
    eval_dataset = GlueDataset(Modifiedargments(datadir = eval_path), tokenizer=tokenizer, evaluate=True) if training_args.do_eval else None

    def compute_metrics(p: EvalPrediction) -> Dict:
        if output_mode == "classification":
            preds = np.argmax(p.predictions, axis=1)
        elif output_mode == "regression":
            preds = np.squeeze(p.predictions)
        # return glue_compute_metrics(data_args.task_name, preds, p.label_ids)
        with open( training_args.output_dir + 'predictions.csv', 'w' ) as fh:
            writer = csv.writer( fh )
            preds  = [ [i] for i in preds ]
            writer.writerows( preds )
        return acc_and_f1(preds, p.label_ids)

    # Initialize our Trainer
    trainer = Trainer(
        model=model,
        args=training_args,
        train_dataset=train_dataset,
        eval_dataset=eval_dataset,
        compute_metrics=compute_metrics,
    )

    # Training
    if training_args.do_train:
        trainer.train(
            model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path) else None
        )
        trainer.save_model()
        # For convenience, we also re-save the tokenizer to the same directory,
        # so that you can share your model easily on huggingface.co/models =)
        if trainer.is_world_master():
            tokenizer.save_pretrained(training_args.output_dir)

    # Evaluation
    results = {}
    if training_args.do_eval and training_args.local_rank in [-1, 0]:
        logger.info("*** Evaluate ***")

        # Loop to handle MNLI double evaluation (matched, mis-matched)
        eval_datasets = [eval_dataset]
        # if data_args.task_name == "mnli":
        #     mnli_mm_data_args = dataclasses.replace(data_args, task_name="mnli-mm")
        #     eval_datasets.append(GlueDataset(mnli_mm_data_args, tokenizer=tokenizer, evaluate=True))

        for eval_dataset in eval_datasets:
            result = trainer.evaluate(eval_dataset=eval_dataset)

            output_eval_file = os.path.join(
                training_args.output_dir, f"eval_results_classification.txt"
            )
            with open(output_eval_file, "w") as writer:
                logger.info("***** Eval results classification *****")
                for key, value in result.items():
                    logger.info("  %s = %s", key, value)
                    writer.write("%s = %s\n" % (key, value))

            results.update(result)

    return results

def _mp_fn(index):
    # For xla_spawn (TPUs)
    main()

if __name__ == "__main__":
    main()


import threading
import traceback

from .preview_utils import try_delete_temp_files

_max_threads = 2
_thread_num_lock = threading.Lock()
_thread_num = 0
_jobs_lock = threading.Lock()
_jobs = {}
_working_sets = {}
_working_sets_lock = threading.Lock()

# folder path to delete for each job
_temp_folder_paths = {}
# execute job functions for each job
_thread_functions = {}

def set_max_threads(max_threads):
    global _max_threads
    if max_threads > 0 and max_threads != _max_threads:
        _max_threads = max_threads

def has_function(_name):
    return _name in _thread_functions

def register_function(name, func):
    _thread_functions[name] = func

def register_temp_folder(name, temp_path):
    _temp_folder_paths[name] = temp_path

def _cancel_jobs(name, is_target_job):
    try:
        lock, job_list = _jobs[name]
    except KeyError:
        return
    with lock:
        delete_jobs = [job for jid, job in job_list if is_target_job(job)]
        for job in delete_jobs:
            try:
                job_list.remove(job)
            except ValueError:
                pass

def cancel_jobs(name, is_target_job):
    with _jobs_lock:
        _cancel_jobs(name, is_target_job)

def _extend_jobs(name, extend_job_list):
    if name not in _jobs:
        _jobs[name] = (threading.Lock(), [])
    lock, job_list = _jobs[name]
    with lock:
        job_list.extend(extend_job_list)

def extend_jobs(name, extend_job_list):
    with _jobs_lock:
        _extend_jobs(name, extend_job_list)

def _append_job(name, jid, job):
    if name not in _jobs:
        _jobs[name] = (threading.Lock(), [])
    lock, job_list = _jobs[name]
    with lock:
        job_list.append((jid, job))

def append_job(name, jid, job):
    with _jobs_lock:
        _append_job(name, jid, job)

def _start_threads(name, thread_id):
    try:
        func = _thread_functions[name]
    except KeyError:
        print("Thread function missing for '{0}'".format(name))
        return
    try:
        lock, job_list = _jobs[name]
    except KeyError:
        return

    with _working_sets_lock:
        if name not in _working_sets:
            _working_sets[name] = set()
        working_set = _working_sets[name]

    while True:
        try:
            with lock:
                head = job_list.pop()
                jid, job = head
                if jid is not None and jid in working_set:
                    job_list.append(head)
                    for i in range(len(job_list)):
                        jid, job = job_list[i]
                        if jid not in working_set:
                            del job_list[i]
                            break
                    else:
                        raise StopIteration()

            with lock:
                working_set.add(jid)
            func(job)
            with lock:
                working_set.remove(jid)
        except IndexError:
            break
        except StopIteration:
            break
        except Exception:
            traceback.print_exc()
            break
        if thread_id >= _max_threads:
            break

def start_threads(name, thread_id):
    _start_threads(name, thread_id)

    visited = set([name])

    while True:
        new_name = None
        for key, (lock, joblist) in _jobs.items():
            with lock:
                if joblist:
                    new_name = key
                    break

        if not new_name or new_name in visited:
            break

        if new_name and new_name != name:
            _start_threads(new_name, thread_id)

    global _thread_num
    with _thread_num_lock:
        _thread_num -= 1
        remaining_threads = _thread_num

    # if all threads have been terminated we can check to delete
    # the temporary files beyond the size limit
    if remaining_threads == 0:
        for v in visited:
            try:
                temp_path = _temp_folder_paths[v]
            except KeyError:
                continue

            try_delete_temp_files(name, temp_path)

def run_jobs(name):
    global _thread_num, _max_threads
    thread_id = -1

    with _jobs_lock:
        try:
            lock, job_list = _jobs[name]
        except KeyError:
            return
    # we may not need locks for this
        with lock:
            rem_len = len(job_list)
        with _thread_num_lock:
            before_num = _thread_num
            after_num = min(_max_threads, rem_len)
            start_threads_count = after_num - before_num
            if start_threads_count > 0:
                _thread_num += start_threads_count
        for thread_id in range(before_num, after_num):
            threading.Thread(target=start_threads,
                             args=(name, thread_id,)).start()


import sys

input = sys.stdin.readline
n, m = map(int, input().rstrip().split())

graph = [list(map(str, input())) for _ in range(n)]

from collections import deque

direction = [[1, 0], [1, -1], [1, 1], [0, 1], [0, -1], [-1, -1], [-1, 0], [-1, 1]]
queue = deque()
visit = [[False] * m for _ in range(n)]

def check(i, j):
    cnt = 0
    for dy, dx in direction:
        ny, nx = i + dy, j + dx
        if 0 <= ny < n and 0 <= nx < m:
            if graph[ny][nx] == '.': cnt += 1
    if graph[i][j] <= cnt:
        return True
    else:
        return False

for i in range(n):
    for j in range(m):

        if ord('1') <= ord(graph[i][j]) <= ord('9'):
            graph[i][j] = int(graph[i][j])
            if check(i, j):
                queue.append([i, j])
                visit[i][j] = True
days = 0
next_queue = deque()

while True:
    if not queue: break
    days += 1
    while queue:

        y, x = queue.popleft()
        graph[y][x] = '.'

        for dy, dx in direction:
            ny, nx = y + dy, x + dx

            if 0 <= ny < n and 0 <= nx < m and ord('1') <= ord(str(graph[ny][nx])) <= ord('8') and not visit[ny][nx]:
                if check(ny, nx):
                    next_queue.append([ny, nx])
                    visit[ny][nx] = True

    queue = next_queue
    next_queue = deque()

print(days)