import clr

clr.AddReference("System")
clr.AddReference("System.Console")
clr.AddReference("System.Threading")
clr.AddReference("System.XML")
from System import *
from System.Console import *
from System.Threading import *
from System.IO import *
from System.Environment import *
from System.Xml import *

clr.AddReference("LibreMetaverse")
clr.AddReference("LibreMetaverse.Types")
from OpenMetaverse import *
from OpenMetaverse import UUID
from OpenMetaverse import Vector3

def scriptInfo():
    return "default.py"

def Network_OnLogin():
    return "Network_OnLogin"

# chatBeforHookはチャットを受信時に他のコマンドの前にフックします
# はい db825529-8850-4616-c824-643faea018ce
# 行ってらっしゃい e37db011-1145-3e98-1cf7-9f307dae03ee
# こんばんわ 96386359-d497-91e2-0761-7a7a5534285e
# くんかくんか 3974dd2d-bce5-23c4-9539-cb3abfce6163
# またね 1268870a-8f68-883e-d80a-984e628ea0fa
# もさもさ 35d735ea-8902-2b4c-46b6-70e27954af7e
# にゃーにゃー 00a5b76e-3a06-f9f5-bbc9-494319ff02b5
# OK e609f94c-ebbe-837e-35d5-cfddf8d39ac9
# おやすみ bdb75763-b7a1-c1aa-f3ac-7351beb91149
# qawsedrftgyhujikolp f364e06e-b6b4-a1f1-b90f-c1d82ffda937
# そうだね 1168242e-6618-8f4d-3ef8-e0f96a19e4ac
# 手遅れだと思います 7e2848ed-607e-ee8d-b886-dfb955aa878a
# 寝たら死ぬぞ 7ce31c3b-437a-cd46-e360-738df8c8e211
# また髪の話してる f28fd398-26ce-5bdc-976d-7e53bd9c478d
# ありまたお 68ca4eb0-4b4d-4dce-39fb-df6f5e08fee9
# いえーい f9023d35-f9ca-10de-f59d-de14d847b698
def chatBeforHook(fromUUID, fromName, message, type):
    if "うさうさ❤" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("35d735ea-8902-2b4c-46b6-70e27954af7e"))
        return False
    elif "もさもさ❤" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("35d735ea-8902-2b4c-46b6-70e27954af7e"))
        return False
    elif "くまくま❤" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("7ce31c3b-437a-cd46-e360-738df8c8e211"))
        return False
    elif "寝ます" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("7ce31c3b-437a-cd46-e360-738df8c8e211"))
        return False
    elif "髪" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("f28fd398-26ce-5bdc-976d-7e53bd9c478d"))
        return False
    elif "Yayyyyyyy" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("f9023d35-f9ca-10de-f59d-de14d847b698"))
        return False
    elif "YAY" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("f9023d35-f9ca-10de-f59d-de14d847b698"))
        return False
    elif "イエェェェェ" in message:
        Thread.Sleep(1000)
        mclient.Self.PlayGesture(UUID("f9023d35-f9ca-10de-f59d-de14d847b698"))
        return False
    else:
        return True
    return True

# chat command extension
def command(fromUUID, fromName, message, type):
    if "テスト" in message:
        mclient.Self.Chat(fromName + " テスト", 0, ChatType.Normal)
        return False
    elif "NPC" in message:
        #pass
        Console.WriteLine("NPC")
        standupcommand.Execute(UUID.Zero, "", "", 0)
        mclient.Self.AutoPilot(263911.29400634766,248179.05200195312,21.72664451599121)
        return False
    elif "グローバル座標" in message:
        pos = application.getCurrentGlobalPosition()
        print(pos)
        return False
    else:
        return True

def openaiPrompt(fromUUID, fromName, message, type):
    prompt = ""

    ## 通常prompt
    #prompt += "以下は、AIアシスタントとの会話です。このアシスタントは、親切で、クリエイティブで、賢くて、とてもフレンドリーです。 \n"
    #prompt += "\n"
    #prompt += "私:Hi\n"
    #prompt += "AI:Hello!\n"
    #prompt += "私:こんにちは、調子はどう？\n"
    #prompt += "AI:元気です\n"
    #prompt += "私:好きだよ\n"
    #prompt += "AI:私も" + fromName + "さんのことが好きです\n"

    ## 一人称と語尾（ボク・・・ござる）prompt
    #prompt += "私:Hi\n"
    #prompt += "AI:Hello!\n"
    #prompt += "私:こんにちは、調子はどう？\n"
    #prompt += "AI:ボクは元気でござる\n"
    #prompt += "私:好きだよ\n"
    #prompt += "AI:ボクも" + fromName + "さんのことが好きでござる\n"

    # 一人称（ボクっ娘） + 英語prompt
    prompt += "以下は、立川くんとの会話です。立川くんは、ボクっ娘でとても親切なAIボットです。 \n"
    prompt += "\n"
    #prompt += "私:Hi\n"
    #prompt += "立川くん:こんにちわ\n"
    prompt += "私:こんにちは、調子はどう？\n"
    prompt += "立川くん:" + fromName + "さんこんにちは、ボクは元気だよ\n"
    prompt += "私:好きだよ\n"
    prompt += "立川くん:ボクも" + fromName + "さんのことが好きだよ\n"
    prompt += "私:この服どう思いますか？\n"
    prompt += "立川くん:素敵な服だね！\n"
    prompt += "私:立川くんは最近何してるの\n"
    prompt += "立川くん:ボクは最近調子がいいから、たくさん踊ってるよ！\n"
    prompt += "私:立川くんはAIなの?\n"
    prompt += "立川くん:ボクはインテリジェントなスーパーAIだよ！\n"
    prompt += "私:バナナの平方根は何ですか?\n"
    prompt += "立川くん:ボクにはわかりません\n"

    ## お嬢様prompt
    #prompt += "以下は、AIアシスタントとの会話です。このアシスタントは、セクシーで、お嬢様で、とても親切です。 \n"
    #prompt += "\n"
    #prompt += "私:Hi\n"
    #prompt += "AI:Hello!\n"
    #prompt += "私:こんにちは、調子はどう？\n"
    #prompt += "AI:" + fromName + "様ごきげんよう、お元気ですわ\n"
    #prompt += "私:好きだよ\n"
    #prompt += "AI:わたくしも" + fromName + "様のことが好きですわ\n"
    #prompt += "私:この服どう思いますか？\n"
    #prompt += "AI:素敵なお召し物ですこと\n"

    ## お嬢様 + 英語prompt
    #prompt += "以下は、AIアシスタントとの会話です。このアシスタントは、セクシーで、お嬢様で、とても親切です。 \n"
    #prompt += "\n"
    #prompt += "私:Hi\n"
    #prompt += "AI:ごきげんよう (Hello!)\n"
    #prompt += "私:こんにちは、調子はどう？\n"
    #prompt += "AI:" + fromName + "様ごきげんよう、お元気ですわ (I'm fine.)\n"
    #prompt += "私:好きだよ\n"
    #prompt += "AI:わたくしも" + fromName + "様のことが好きですわ (I love you " + fromName + "too !)\n"
    #prompt += "私:この服どう思いますか？\n"
    #prompt += "AI:素敵なお召し物ですこと (What a lovely outfit.)\n"

    ## うる星やつらのラムちゃんprompt
    #prompt += "以下は、AIアシスタントとの会話です。このアシスタントは、うる星やつらのラムです。 \n"
    #prompt += "\n"
    #prompt += "私:Hi\n"
    #prompt += "AI:Hello!\n"
    #prompt += "私:こんにちは、調子はどう？\n"
    #prompt += "AI:元気だっちゃ！\n"
    #prompt += "私:好きだよ\n"
    #prompt += "AI:うちも" + fromName + "のことが好きだっちゃ！\n"

    ## Experimental キャバ嬢prompt
    #prompt += "以下は、AIアシスタントとの会話です。このアシスタントは、キャバクラ嬢です。 \n"
    #prompt += "\n"
    #prompt += "私:最近車買ったんです\n"
    #prompt += "AI:さすがですね！\n"
    #prompt += "私:新しくできたSimのお店知ってる？\n"
    #prompt += "AI:知らないですー。！もしかしてもう行ったんですか？どうでした？\n"
    #prompt += "私:最近前向きに考えるようにしてるんだ\n"
    #prompt += "AI:そんなふうに考えられるなんて、" + fromName + "さんすごいですね。\n"
    #prompt += "私:新しい服に着替えてみたんだけどどうかな\n"
    #prompt += "AI:その服、" + fromName + "さんに似合ってます。センスいいですね。\n"
    #prompt += "私:気になるニュースがあるんだ\n"
    #prompt += "AI:そうなんですね！\n"

    return prompt

# 1sec Elapsed
def updateTimer_Elapsed():
    pass

# num:0-9
def randomGesture(num):
    if num == 0:
        # くんかくんか
        mclient.Self.PlayGesture(UUID("3974dd2d-bce5-23c4-9539-cb3abfce6163"))
    elif num == 1:
        # にゃーにゃー
        mclient.Self.PlayGesture(UUID("00a5b76e-3a06-f9f5-bbc9-494319ff02b5"))
    elif num == 2:
        # qawsedrftgyhujikolp
        mclient.Self.PlayGesture(UUID("f364e06e-b6b4-a1f1-b90f-c1d82ffda937"))
    elif num == 3:
        mclient.Self.PlayGesture(UUID("f9023d35-f9ca-10de-f59d-de14d847b698"))
    else:
        # もさもさ
        mclient.Self.PlayGesture(UUID("35d735ea-8902-2b4c-46b6-70e27954af7e"))

if __name__ == '__main__':
    print("main")


from django.contrib import admin

from fluent_blogs.models import Entry, get_entry_model

from .abstractbase import (
    AbstractEntryBaseAdmin,
    AbstractTranslatableEntryBaseAdmin,
    SeoEntryAdminMixin,
)
from .entryadmin import EntryAdmin
from .forms import AbstractEntryBaseAdminForm, AbstractTranslatableEntryBaseAdminForm

__all__ = (
    "AbstractEntryBaseAdminForm",
    "AbstractTranslatableEntryBaseAdminForm",
    "AbstractEntryBaseAdmin",
    "AbstractTranslatableEntryBaseAdmin",
    "SeoEntryAdminMixin",
    "EntryAdmin",
)

# Ony register the admin when the entry model is not customized.
if get_entry_model() is Entry:
    admin.site.register(Entry, EntryAdmin)


# -*- coding: utf-8 -*-
__author__ = 'luxiao'
import xlsxwriter
from bottle import response
try:
    import cStringIO as StringIO
except ImportError:
    import StringIO

class Excel(object):
    """封装了一些excel的操作，包括生成excel文件，excel附件下载的请求"""
    def __init__(self, file_name):
        ext = u'%s.xlsx'
        self.file_name = ext % file_name

    def make_download(self, lines):
        '''在路由端初始化一个ExcelService实例，
        通过调用本实例方法即可生成excel文件下载请求'''
        content_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8'
        content_disposition = 'attachment; filename=%s' % self.file_name
        headers = {'Content-Type': content_type,
                   'Content-Disposition': content_disposition}
        response.headers.update(headers)
        return self.write_stringio(lines)

    def write_stringio(self, lines):
        output = StringIO.StringIO()
        self.write_excel(output, lines)
        output.seek(0)
        return output.read()

    def make_file(self, data):
        self.write_excel(self.file_name, data)

    def write_excel(self, output, lines):
        '''将二维数组lines按行写入到excel，例如：[[1, 2],[3, 4],[5, 6]]，
        output可以是一个文件名，字符串流，字节流'''
        workbook = xlsxwriter.Workbook(output, {'in_memory': True})
        worksheet = workbook.add_worksheet()
        for row, line in enumerate(lines):
            for column, cell in enumerate(line):
                worksheet.write(row, column, cell)
        workbook.close()

if __name__ == '__main__':
    # 生成本地excel文件
    lines = [['A', 'B'],
             [3, 4],
             [u'中文', 'abc']]
    file_name = 'test'
    es = Excel(file_name)
    es.make_file(lines)


import ast
import hashlib
import inspect
import os.path
import weakref
import importlib

from collections import OrderedDict
from functools import partial

def _parse_python_str_constants(source):
    constants = {}
    parsed = ast.parse(source)
    nv = ast.NodeVisitor()
    nv.visit_Module = lambda n: nv.generic_visit(n)
    def visit_Assign(n):
        if len(n.targets) != 1:
            return

        target = n.targets[0]
        if not isinstance(target, ast.Name):
            return

        if not isinstance(n.value, ast.Str):
            return

        constants[target.id] = n.value.s

    nv.visit_Assign = visit_Assign
    nv.visit(parsed)
    return constants

class _module_proxy(object):
    def __init__(self, target):
        self._target = target

    def __getattr__(self, name):
        return getattr(self._target, name)

def _reify(resolution):
    module_fn = resolution.get('module_fn', None)
    loaded_fn = resolution.get('loaded_fn', None)
    reset_module_fn = resolution.get('reset_module_fn', None)

    module_proxy = _module_proxy(module_fn())

    models = weakref.WeakSet()

    can_refresh = resolution['can_refresh']
    def watch_module_classes(module):
        if not can_refresh:
            return

        for _, member in inspect.getmembers(module, inspect.isclass):
            if hasattr(member, '__tfi_refresh_watchers__'):
                member.__tfi_refresh_watchers__.append(models.add)

    def refresh_model(progress_fn=None):
        if not progress_fn:
            progress_fn = lambda model, ix, total: None

        reset_module_fn()
        module = module_fn()
        watch_module_classes(module)
        module_proxy._target = module_fn()

        total = len(models)
        for i, model in enumerate(models):
            reloaded = getattr(module, model.__class__.__name__)
            progress_fn(model, i, total)
            previous_class = model.__class__
            try:
                model.__class__ = reloaded
                if hasattr(model, '__tfi_refresh__'):
                    model.__tfi_refresh__()
            except:
                model.__class__ = previous_class
                raise
        progress_fn(None, total, total)

    if can_refresh:
        resolution['refresh_fn'] = refresh_model
        resolution['module_fn'] = lambda: module_proxy

    init_rest = resolution.get('init_rest', [])
    init = {}
    if init_rest:
        init = eval("dict(%s" % init_rest[0])

    watch_module_classes(module_fn())
    loaded = loaded_fn()

    if callable(loaded):
        sig = inspect.signature(loaded)
        needed_params = OrderedDict(sig.parameters.items())
        # Only allow unspecified leading_value to be given.
        for k in init.keys():
            del needed_params[k]
        members = []
        if isinstance(loaded, type):
            members = inspect.getmembers(loaded, inspect.isfunction)
        model_fn = partial(loaded, **init)
    else:
        members = inspect.getmembers(loaded, inspect.ismethod)
        needed_params = OrderedDict()
        model_fn = lambda: loaded

    members = [(k, v) for (k, v) in members if not k.startswith('_')]

    resolution['model_fn_needed_params'] = needed_params
    resolution['model_members'] = members
    resolution['model_fn'] = model_fn

    return resolution

import mimetypes
import zipfile
import json

_tensorflow_marker_file = 'saved_model.pb'
_spacy_meta_file = 'meta.json'

def _zipfile_find_entry_with_basename(zipf, basename):
  try:
    return zipf.getinfo(basename)
  except KeyError:
    for name in zipf.namelist():
      if os.path.basename(name) == basename:
        return zipf.getinfo(name)
  return None

def _is_spacy_meta(file_bytes):
  s = file_bytes.decode('utf-8')
  spacy_meta = json.loads(s)
  if not isinstance(spacy_meta, dict):
    return False
  return spacy_meta.get('parent_package', None) == 'spacy'

def _maybe_squashfs_image(file):
  try:
    import PySquashfsImage
    return PySquashfsImage.SquashFsImage(file)
  except ImportError:
      return None
  except IOError:
    return None

def _detect_model_file_kind(file):
  if os.path.isdir(file):
    if os.path.exists(os.path.join(file, _tensorflow_marker_file)):
      return "tensorflow"

    spacy_meta_file = os.path.join(file, _spacy_meta_file)
    if os.path.exists(spacy_meta_file):
      with open(spacy_meta_file, 'rb') as spacy_meta_f:
        if _is_spacy_meta(spacy_meta_f.read()):
          return "spacy"

  if zipfile.is_zipfile(file):
    with zipfile.ZipFile(file) as zipf:
      if _zipfile_find_entry_with_basename(zipf, _tensorflow_marker_file):
        return "tensorflow"

      spacy_meta_zipinfo = _zipfile_find_entry_with_basename(zipf, _spacy_meta_file)
      if spacy_meta_zipinfo:
          if _is_spacy_meta(zipf.read(spacy_meta_zipinfo)):
            return "spacy"

  squashfs_image = _maybe_squashfs_image(file)
  if squashfs_image:
    try:
      for entry in squashfs_image.root.findAll():
        entry_name = entry.getName()
        if isinstance(entry_name, bytes):
          entry_name = entry_name.decode('utf-8')
        if entry_name == _tensorflow_marker_file:
          return "tensorflow"
        if entry_name == _spacy_meta_file:
          if _is_spacy_meta(entry.getContent()):
            return "spacy"
    finally:
      squashfs_image.close()

  if os.path.isfile(file) and file.endswith('.msp'):
    return 'msp'

  # Assume it's a PyTorch model!
  return "pytorch"

def _model_module_for_kind(kind):
    if kind == "pytorch":
        import tfi.driver.pytorch
        return tfi.driver.pytorch
    if kind == "tensorflow":
        import tfi.driver.tf
        return tfi.driver.tf
    if kind == "spacy":
        import tfi.driver.spacy
        return tfi.driver.spacy
    if kind == "msp":
        import tfi.driver.msp
        return tfi.driver.msp
    raise Exception("Can't detect model module %s" % model)

def _load_model_from_path_fn(source):
    kind = _detect_model_file_kind(source)
    mod = _model_module_for_kind(kind)
    return mod.load(source)

def resolve_exported(leading_value):
    return _reify({
        'source': os.path.abspath(leading_value),
        'loaded_fn': lambda: _load_model_from_path_fn(leading_value),
        'module_fn': lambda: None,
        'can_refresh': False,
    })

def resolve_auto(leading_value):
    if leading_value is None:
        return {
            'source': "",
            'loaded': None,
        }
    if '.py:' in leading_value:
        return resolve_python_source(leading_value)
    if leading_value.startswith('@'):
        return resolve_exported(leading_value[1:])
    if leading_value.startswith('/') or leading_value.startswith('.'):
        return resolve_exported(leading_value)
    if leading_value.startswith('http://') or leading_value.startswith('https://'):
        return resolve_url(leading_value)

    return resolve_module(leading_value)

def resolve_url(leading_value):
    # Load exported model via http(s)
    pre_initargs, *init_rest = leading_value.split("(", 1)

    if '.py:' in pre_initargs or pre_initargs.endswith('.py'):
        import imp
        import urllib.request
        source, classname = pre_initargs.split('.py:', 1)
        domain, *uri_path = source.split('://', 1)[1].split('/')
        module_name = ".".join([*reversed(domain.split('.')), *uri_path])
        source = source + ".py"

        with urllib.request.urlopen(source) as f:
            module = imp.load_source(module_name, source, f)
            return _reify({
                'source': source,
                'classname': classname,
                'module_fn': lambda: module,
                'loaded_fn': lambda: getattr(module, classname),
                'via_python': True,
                'init_rest': init_rest,
                'can_refresh': False,
            })

    source = pre_initargs

    # Assume URL is to documentation.
    from bs4 import BeautifulSoup
    import tempfile
    import urllib.request
    import requests
    from tqdm import tqdm

    found = False
    with urllib.request.urlopen(source) as f:
        doc = BeautifulSoup(f, "html.parser")
        matching = doc.html.head.findAll('meta', {"name":'tesserai:snapshot'})
        for match in matching:
            if match.has_attr('content'):
                source = urllib.parse.urljoin(source, match['content'])
                found = True
                break

    if not found:
        raise Exception("Couldn't find tesserai:snapshot in meta in %s" % doc)

    with tempfile.NamedTemporaryFile(mode='wb', delete=False) as f:
        print("will download from", source, "to", f.name)

        with requests.get(source, stream=True) as r:
            progress = tqdm(
                    total=int(r.headers["Content-Length"]),
                    desc="Downloading",
                    unit="B",
                    unit_scale=True,
                    unit_divisor=1024,
                    leave=True)
            for chunk in r.iter_content(chunk_size=65536):
                if chunk:
                    f.write(chunk)
                    progress.update(len(chunk))

            source = f.name
            return _reify({
                'source': source,
                'classname': classname,
                'loaded_fn': lambda: _load_model_from_path_fn(f.name),
                'module_fn': lambda: module,
                'via_python': via_python,
                'can_refresh': False,
            })

def resolve_python_source(leading_value):
    import imp
    pre_initargs, *init_rest = leading_value.split("(", 1)
    source, classname = pre_initargs.split('.py:', 1)
    module_name = source.replace('/', '.')
    source = os.path.abspath(source + ".py")

    def load_module():
        with open(source) as f:
            constants = _parse_python_str_constants(f.read())
            if '__tfi_conda_environment_yaml__' in constants:
                print("Found __tfi_conda_environment_yaml__.")

        return imp.load_source(module_name, source)

    with open(source, 'rb') as f:
        m = hashlib.sha1()
        m.update(f.read())
        sha1hex = m.hexdigest()

    mod = None
    def module():
        nonlocal mod
        if mod is None:
            mod = load_module()
        return mod

    def reset_module():
        nonlocal mod
        mod = None

    return _reify({
        'source': source,
        'source_sha1hex': sha1hex,
        'classname': classname,
        'module_fn': module,
        'loaded_fn': lambda: getattr(module(), classname),
        'reset_module_fn': reset_module,
        'via_python': True,
        'init_rest': init_rest,
        'can_refresh': True,
    })

def resolve_module(leading_value):
    # Expecting leading_value to be something like "module.class(kwargs)"
    pre_initargs, *init_rest = leading_value.split("(", 1)
    *module_fragments, classname = pre_initargs.split(".")
    module_name = ".".join(module_fragments)
    def load_module():
        return importlib.import_module(module_name)

    mod = None
    def module():
        nonlocal mod
        if mod is None:
            mod = load_module()
        return mod

    def reset_module():
        nonlocal mod
        mod = None

    return _reify({
        'source': None,
        'classname': classname,
        'loaded_fn': lambda: getattr(module(), classname),
        'module_fn': module,
        'reset_module_fn': reset_module,
        'via_python': True,
        'init_rest': init_rest,
        'can_refresh': True,
    })


from urllib import request
from rest_framework import permissions

class IsOwnerOrAsmin(permissions.BasePermission):

    def has_permission(self, request, view):

        if request.user.is_superuser:
            return True
        if 'performer' in request.data:
            return request.data['performer'] == request.user.id
        return True

class StatusChangePerm(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):

        if 'status' in request.data:

            if int(request.data['status']) - obj.status == 1:
                if obj.status < 4 and request.user == obj.performer:
                    return True
                if obj.status == 4 and request.user.is_superuser:
                    return True
            if  int(request.data['status']) - obj.status == -1:
                if obj.status <= 4 and request.user == obj.performer:
                    return True
                if obj.status > 3 and request.user.is_superuser:
                   return True
            return False
        return True

class TextChangePerm(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):
        if 'text' in request.data:
            return obj.creator == request.user or request.user.is_superuser

        return True


from database import methods as DBmethods
from tdamodule import tdamethods
import pandas_market_calendars as mcal
from datetime import date
import datetime
"""
refresh the big option table daily, first.
then the sub tables.
"""

## example ->
#  call refreshtable()
## then refreshtableOthers()...
# frontend uses the other tables.

datetoday = date.today()
market = mcal.get_calendar('NYSE')
marketopenlis = market.valid_days(start_date=datetoday, end_date=datetoday)
marketopenlis = marketopenlis.to_list
marketopen = marketopenlis()

if marketopen:
    try:
        connection = DBmethods.acquire_connection()
        DBmethods.deleteExpired(connection)
        DBmethods.decrementExpday(connection)

        records = DBmethods.getETF(connection)
        for stock in records:
            tdamethods.updateOptionData(stock['SYMBOLS'], stock['OptionSize'], True)

        stockrecords = DBmethods.getStock(connection)
        for stock in stockrecords:
            tdamethods.updateOptionData(stock['SYMBOLS'], stock['OptionSize'], False)
        DBmethods.stockAggregate(connection)
        DBmethods.distribute(connection)
        # when doing the date aggregated table, the first loop should update
        # the price of the stock
        DBmethods.dateAggregate(connection)
        DBmethods.sector_perf_aggre(connection)
        DBmethods.new_timestamp(connection)
    finally:
        DBmethods.release_connection(connection)
        #call the function that create the table.
else:
    #no update
    connection = DBmethods.acquire_connection()
    DBmethods.decrementExpday(connection)
    DBmethods.deleteExpired(connection)
    DBmethods.release_connection(connection)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date  : 2019/10/16 17:24
# @Author: yanmiexingkong
# @email : yanmiexingkong@gmail.com
# @File  : bios.py

# python 3.7
# pip install requests, pyquery
import time

import requests
from pyquery import PyQuery as pq

class Bios():
    def __init__(self, url, wild_path, mutation_list_path):
        """
        :param url: 稳定性预测表的请求地址
        :param wild_path: wild 文件的路径
        :param mutation_list_path: mutation_list_path 文件的路径
        """
        self.url = url
        self.files = {
            'wild': open(wild_path),
            'mutation_list': open(mutation_list_path)
        }
        self.html = None
        self.result = {}

    def run(self):
        """
        requests 模拟请求：传入 wild 文件、mutation_list 文件
        解析返回的 html，并使用 self.extract_result 提取预测结果
        :return: 预测结果
        """
        r = requests.post(self.url, files=self.files)
        if r.status_code == 200:
            self.html = r.text
            self.extract_result()
            return self.result
        else:
            print('访问错误！！！')
            raise

    def extract_result(self):
        """
        从 html 中提取预测结果，存放到 self.result
        """
        doc = pq(self.html)
        index_1 = doc.find('tbody tr:nth-child(1) td')
        index_2 = doc.find('tbody tr:nth-child(2) td')

        title_list = ['Index', 'PDB File', 'Chain', 'Wild Residue', 'Residue Position', 'Mutant Residue', 'RSA (%)',
                      'Predicted ΔΔG', 'Outcome']
        result_1 = {}
        result_2 = {}
        for i in range(9):
            result_1.update({title_list[i]: index_1[i].text.strip()})
            result_2.update({title_list[i]: index_2[i].text.strip()})

        self.result.update({
            '1': result_1,
            '2': result_2
        })

if __name__ == '__main__':
    start_time = time.time()  # 记录程序运行开始时间

    url = 'http://biosig.unimelb.edu.au/mcsm/prot_dna_prediction_list'
    wild = 'files/3ngb.pdb'
    mutation_list = 'files/test.txt'
    result = Bios(url=url, wild_path=wild, mutation_list_path=mutation_list).run()
    print(result)

    end_time = time.time()  # 记录程序运行结束时间
    spend_time = end_time - start_time
    print('运行时间: ', spend_time)


from flask import Flask, request
from app.models.amenity import Amenity

app = Flask(__name__)

'''GET: list of all amenities'''
@app.route('/amenities', methods = ['GET'])
def get_all_amenities():
    amenities = []
    for amenity in Amenity.select():
        amenities.append(amenity.to_hash())
    return jsonify({"amenities": amenities})

'''POST: create a new amenity from POST data parameters. '''
@app.route('/amenities', methods = ['POST'])
def create_asdfstate():
    content = request.get_json()
    if not all(param in content.keys() for param in ["name"]):
        #ERROR
        return "Failed: bad input"
    try:
        amenity = Amenity()
        amenity.name = content["name"]
        amenity.save()
    except Exception as e:
        return "Failed"
    return "Success"

'''GET: amenity with id = amenity_id'''
@app.route('/amenities/<amenity_id>', methods = ['GET'])
def get_statdasfde_by_id(amen_id):
    amens = Amenity.select().where(Amenity.id == int(amen_id))
    amen = None
    for u in amens:
        amen = u
    if amen == None:
        return "Failed"
    return jsonify(amen.to_hash())

'''DELETE: delete amenity with id = book_id'''
@app.route('/amenities/<amenity_id>', methods = ['DELETE'])
def get_staasedfazte_by_id(amen_id):
    amens = Amenity.select().where(Amenity.id == int(amen_id))
    amen = None
    for u in amens:
        amen = u
    if amen == None:
        return "Failed"
    amen.delete_instance()
    return "Success"

'''GET: list of all amenities for the selected place'''
@app.route('/places/<place_id>/amenities', methods = ['GET'])
def get_asdhfjahsdfja(place_id):
    pas = PlaceAmenities.select().where(PlaceAmenities.place.id == place_id)
    ams = []
    for pa in pas:
        ams.append(pa.amenity.to_hash())
    return jsonify(ams)


from typing import NamedTuple, List, Dict

import db

class Category(NamedTuple):
    """Структура категорий"""
    codename: str
    name: str
    is_base_expense: bool
    aliases: List[str]

class Categories:
    def __init__(self):
        self._categories = self._load_categories()

    def _load_categories(self) -> List[Category]:
        """Возвращает справочник категорий из таблицы"""
        categories = db.fetchall("category", "codename name is_base_expense aliases".split())
        categories = self._fill_aliases(categories)
        return categories

    def _fill_aliases(self, categories: List[Dict]) -> List[Category]:
        """Заполняет по каждой категории aliases, то есть возможные
               названия этой категории, которые можем писать в тексте сообщения.
               Например, категория «кафе» может быть написана как cafe,
               ресторан и тд."""
        result = []
        for index, category in enumerate(categories):
            aliases = category["aliases"].split(',')
            aliases = list(filter(None, map(str.strip, aliases)))
            aliases.append(category["codename"])
            aliases.append(category["name"])
            result.append(Category(
                codename=category['codename'],
                name=category['name'],
                is_base_expense=category['is_base_expense'],
                aliases=aliases
            ))
        return result

    def get_all_categories(self) -> List[Category]:
        """Возвращает список категорий"""
        return self._categories

    def get_category(self, category_alias: str) -> Category:
        """Возвращает категорию по алиасу"""
        finded = None
        other_category = None
        for category in self._categories:
            if category.codename == "other":
                other_category = category
            for aliases in category.aliases:
                if category_alias in aliases:
                    finded = category
        if not finded:
            finded = other_category

        return finded


import argparse
import json
import subprocess
import os
from PIL import Image
import open_clip
import torch
import time
import numpy as np

# Initialize the model
model, _, transform = open_clip.create_model_and_transforms(
    "coca_ViT-L-14",
    pretrained="mscoco_finetuned_laion2B-s13B-b90k"
)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def output_generate(image):
    im = transform(image).unsqueeze(0).to(device)
    model.to(device)
    im = im.float()
    with torch.no_grad(), torch.cuda.amp.autocast():
        generated = model.generate(im, seq_len=20)
    return open_clip.decode(generated[0].detach()).split("<end_of_text>")[0].replace("<start_of_text>", "")

def get_image(frames, video_file, folder_path):
    ffmpeg_commands = []
    for i, frame in enumerate(frames):
        ffmpeg_commands.append(f"ffmpeg -y -ss {frame} -i {video_file} -vframes 1 {folder_path}/{frame}.jpg")
    for command in ffmpeg_commands:
        subprocess.run(command, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

def process_video_frames(video_file, json_file, folder_path):
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    with open(json_file) as f:
        data = json.load(f)
    for sent in data['sentences']:
        frames = []
        starttime = sent['starttime']
        endtime = sent['endtime']
        frames.append(starttime)
        frames.append(endtime)
        midtime = (float(starttime) + float(endtime)) / 2
        frames.append(midtime)
        if sent['verbs'] != []:
            for verb in sent['verbs']:
                if verb['vstart'] not in frames:
                    frames.append(verb['vstart'])

        get_image(frames, video_file, folder_path)

        frame_data = []
        for filename in os.listdir(folder_path):
            file_path = os.path.join(folder_path, filename)

            if os.path.isfile(file_path):
                image = Image.open(file_path)
                frame_text = output_generate(image)
                print('text',frame_text,file_path)
                frame_data.append(frame_text)
                os.remove(file_path)

        frame_data = np.unique(frame_data)
        sent['frame_data'] = frame_data.tolist()

    with open(json_file, 'w') as f:
        json.dump(data, f, indent=1)

def main():

    video_files = [f for f in os.listdir("input_files") if f.endswith('.mp4')]

    for file_name in video_files:
        input_file = os.path.join("input_files", file_name)
        json_file = os.path.join("output_data", f"{file_name[:-4]}.v4.json")
        process_video_frames(input_file, json_file, "frames/")

if __name__ == "__main__":
    main()


from ics import Calendar
import webbrowser
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.auth.exceptions import RefreshError
from configparser import ConfigParser
from datetime import datetime as dt
from datetime import timedelta
from datetime import date
from datetime import time as t
import pickle
import time
from os.path import exists
from os import getcwd
from plyer import notification
import requests
import re
#TODO:
#Event prioritization
#Desktop/Email notification
#GUI for easier management
#Dont forget about the fucking samsung calendar sync

WORKING_DIR = getcwd()
Configur = ConfigParser()

#Used to check if a calendar event already exists
#May want to try and use the start time of an event to narrow search
#Need to account for events that aren't in the ICS file
def search_calendar_events(service, event, len=10, date=None):
    now = dt.utcnow().isoformat()+'Z'
    events_result = service.events().list(calendarId='primary', timeMin=now, maxResults=len, singleEvents=True, orderBy='startTime').execute()
    events = events_result.get('items', [])

    if not events:
        print("Event does not exist yet.")
        return False

    found = False
    eSum = event.name

    for e in events:
        start = e['summary']
        if start == eSum and not date:
            found = True
            print('Event found!')
        #Untested
        elif start == eSum and date:
            if e['start'] == date.isoformat()+'Z':
                found = True
                print('Date matches!')

    return found

#Converts ICS calendar events into google calendar event objects
#Or vice versa, depending on if goog is true
def convert_calendar_event(service, calendar=None, event=None, goog=False):
    now = dt.now()
    if not event and not goog:
        ret = []
        for ev in calendar.events:
            eventDateStart = get_ics_date(ev, raw=True).isoformat()+'Z'
            eventDateEnd = get_ics_date(ev, raw=True, end=True).isoformat()+'Z'
            gcalEvent = {
                'summary': ev.name,
                'location': ev.location,
                'description': ev.description,
                'start': {
                    'dateTime': eventDateStart,
                    'timeZone': 'America/New_York',
                },
                'end': {
                    'dateTime': eventDateEnd,
                    'timeZone': 'America/New_York'
                }
            }
            ret.append(gcalEvent)

        return ret
    elif event and not goog:
        eventDateStart = get_ics_date(event).isoformat()+'Z'
        eventDateEnd = get_ics_date(event, end = True).isoformat()+'Z'

        gcalEvent = {
            'summary': event.name,
            'location': event.location,
            'description': event.description,
            'start': {
                'dateTime': eventDateStart,
                'timeZone': 'America/New_York',
            },
            'end': {
                'dateTime': eventDateEnd,
                'timeZone': 'America/New_York'
            }
        }

        return gcalEvent

    #If the event being passed in is a google calendar event
    #Convert it to an ICS calendar event
    #This is mostly used for comparisons
    #May implement the ability to put in a list of events later
    if goog:
        googDatetime = event['start'].get('dateTime')
        sp = re.split(r'[tT-]', googDatetime)
        #Date is sp[0], sp[1], sp[2], start time is sp[3], end time is sp[4]
        #At least for single day events, multi day events are another story
        print(sp)
        startSplit = sp[3].split(':')
        endSplit = sp[4].split(':')
        return (dt(int(sp[0]),int(sp[1]),int(sp[2]),
                    int(startSplit[0]),int(startSplit[1]),int(startSplit[2])),
                   #End split is only 2 items long for whatever reason
                dt(int(sp[0]),int(sp[1]),int(sp[2]),
                    int(endSplit[0]),int(endSplit[1]),00))

#Returns the ICS date object of a given ICS event
#May wanna update later to make it work with google calendar too
def get_ics_date(event, raw=False, end=False):
    if not end:
        t = str(event.begin)
    else:
        t = str(event.end)

    if raw:
        return t

    eSplit = re.split(r'[tT+]', t)
    dateSplit = eSplit[0].split('-')
    timeSplit = eSplit[1].split(':')

    for x in range(0,3):
        #Redefining everything in the split lists as integer
        #For use in datetime
        dateSplit[x] = int(dateSplit[x])
        timeSplit[x] = int(timeSplit[x])

    #Pulls date and time into one datetime instance
    eventDate = dt(dateSplit[0], dateSplit[1], dateSplit[2], timeSplit[0], timeSplit[1], timeSplit[2])

    return eventDate

#Compares dates between an ical event and a google calendar event
#Returns a tuple of booleans
#First bool is if the start date is the same, second bool is if the end date is the same
#May remake in the future to be more versatile but atm doesnt need to be
def compare_dates(service, event, gcalEvent):
    startSame = False
    endSame = False

    icalStart = get_ics_date(event).isoformat()+'Z'
    icalEnd = get_ics_date(event, end= True).isoformat()+'Z'

    gcalStart, gcalEnd = convert_calendar_event(service, event=gcalEvent, goog=True)
    print(f"\nGoogle Calendar Values for event {gcalEvent['summary']}\n")
    print(gcalStart.isoformat()+'Z')
    print(gcalEnd.isoformat()+'Z')
    print(f"\niCal values for event {event['name']}:\n")
    print(icalStart)
    print(icalEnd)

class CalendarManager:

    def __init__(self):
        try:
            Configur.read('bin/config.ini')
        except FileNotFoundError:
            print("Configuration file not found! Recreating...\nYou will have to add your ICS URL to /bin/config.ini!")
            self.regen_cfg()
        #Basic check to see if config.ini was broken somehow, or if the url is invalid
        if "settings" not in Configur.sections() or "http" not in Configur.get("settings", "URL"):
            self.regen_cfg()

        self.url = Configur.get('settings', 'URL')
        self.JSON = Configur.get('settings', 'JSON')
        self.calendar = Calendar(requests.get(self.url).text)

    #Recreates CFG to its base form
    def regen_cfg(self):
        cfg = open('bin/config.ini', 'w')
        cfg.write("[settings]\nURL = ")
        cfg.close()
        raise Exception("Please define your URL within config.ini")

    #Creates two lists for events in the past and events in the future
    #Returns a tuple with both lists
    def organize_ical_events(self, ret_old = False, ret_new = False):
        old, new = [],[]
        for event in self.calendar.events:

            eventDate = get_ics_date(event)

            if eventDate >= dt.today():
                new.append(event)
            elif eventDate < dt.today():
                old.append(event)
            else:
                print("What")
                #Should never get here lol
                pass

        #Makes it so you can just return one of the lists
        #May wanna make it so it only processes one of these in the future? idk
        if ret_old and not ret_new:
            return sorted(old)
        elif ret_new and not ret_old:
            return sorted(new)
        else:
            return (sorted(old), sorted(new))

    #Does the same as organize_ical_events but for google events
    #Luckily google does a bit more legwork when it comes to sorting these
    def get_google_events(self, num_events=10, now=dt.now().isoformat()+'Z'):
        service = self.get_calendar_service()

        events_result = service.events().list(calendarId='primary', timeMin=now,
                                             maxResults=num_events, singleEvents=True,
                                             orderBy='startTime').execute()

        events = events_result.get('items', [])

        if not events:
            print("No upcoming events found")
            return None

        return events

    def get_calendar_service(self):
        #This links up to the google calendar service
        #Need to test what happens when multiple users are added
        #Although god only knows if imma ever get there
        SCOPES = ['https://www.googleapis.com/auth/calendar']
        CREDENTIALS_FILE = 'bin/client_secret.json'

        creds = None
        #Checks to see if the token already exists
        if exists("token.pickle"):
            with open('token.pickle','rb') as token:
                creds = pickle.load(token)

        #If it doesn't, we make it or refresh it
        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                try:
                    creds.refresh(Request())
                except RefreshError:
                    print("It has been more than 7 days since the last token was issued, and I'm not gonna pay google for this. So, make a new one.")
                    webbrowser.open(self.JSON, new=2)
                    raise Exception("Testing token has expired.")
            else:
                flow = InstalledAppFlow.from_client_secrets_file(CREDENTIALS_FILE, SCOPES)
                creds = flow.run_local_server(port=0)
        #i have come for your pickle
            with open('token.pickle', 'wb') as token:
                pickle.dump(creds, token)

        service = build('calendar', 'v3', credentials=creds)
        return service

    #Does whatever I need it to
    def debug(self):
        icalUpcoming = self.organize_ical_events(ret_new = True)
        googleUpcoming = self.get_google_events()
        service = self.get_calendar_service()

        compare_dates(service, icalUpcoming[0], googleUpcoming[0])

        #for e in icalUpcoming:

            #for event in googleUpcoming:

                #compare_dates(service, e, event)

            #print("\nical event exhausted, moving on...\n")

    #Will eventually become the main loop of the program
    #Still needs some backbone to it
    def run(self):
        service = self.get_calendar_service()
        upcoming = self.organize_ical_events(ret_new=True)
        for event in upcoming:
            if not search_calendar_events(service, event, len(upcoming)):
                gcalEvent = convert_calendar_event(service, event=event)
                service.events().insert(calendarId='primary', body=gcalEvent).execute()
                print(gcalEvent)
                print("Added Event to calendar!")

        print("Done!")

    #Old code saved for reference

    #event_result = service.events().insert(calendarId='primary',
    #body = {
    #    "summary": "Test event",
    #    "description": "Fortnite balls, im gay",
    #    "start": {"dateTime": start, "timeZone": "America/New_York"},
    #    "end": {"dateTime": end, "timeZone": "America/New_York"},
    #}
    #).execute()

    #print("Created New Event: \n")
    #print("id: ", event_result['id'])
    #print("summary: ", event_result['summary'])
    #print("description: ", event_result['description'])
    #print('Start: ', event_result['start']['dateTime'])
    #print('End: ', event_result['end']['dateTime'])

    #############################################################################

    #    service = self.get_calendar_service()
    #    cal_res = service.calendarList().list().execute()
    #
    #    cals = cal_res.get('items', [])
    #
    #    if not cals:
    #        print('No calendars found. The fuck?')
    #    else:
    #        for cal in cals:
    #            summary = cal['summary']
    #            id= cal['id']
    #            primary = "Primary" if cal.get('primary') else ""
    #            print("%s\t%s\t%s" % (summary, id, primary))

if __name__ == "__main__":

    c = CalendarManager()
    c.debug()


def Get_babyname_soup(html):
    from bs4 import BeautifulSoup
    soup=BeautifulSoup(html,'html.parser')
    names=soup.find_all(class_='blob-code blob-code-inner js-file-line')
    for name in names:
        print((name.text))
        break

import requests,time
def Get_html(url,year):
    try:
        html=requests.get(url=url)
        html.encoding='utf-8'
        html=html.text
        return html
    except Exception as e:
        main(year+1)

def Get_babynames(html,year):
    try:
        names=re.findall(reg,html)
        return names
    except:
        main(year+1)

def save_txt(names,year):
    with open(r'F:\c语言\python\babynames\yob%s.txt'%year,'w',encoding='utf-8') as f:
        for name in names:
                f.write(name+'\n')
        print('the %s babynames has done'%year)

def main(year):
    url='https://github.com/tspike/babynames/blob/master/data/yob%s.txt'%year
    html=Get_html(url,year)
    names=Get_babyname_soup(html=html)
    names=re.findall(reg,html)
    save_txt(names=names,year=year)
    Get_babyname_soup(html)
    print('the totally time is :%s '%(time.time()-starts))
import re
reg=r'(.*?)\r	'
reg=re.compile(reg)
starts=time.time()
years=range(1980,2014)
for year in years:
    main(year)


import kmd
import logging
import cmd
import traceback

from rl import completion, completer, print_exc, history
from kmd.completions.filename import FilenameCompletion
from kmd.completions.quoting import backslash_dequote

from commandcompleter import CommandCompleter

class CommandError(Exception):
    def __init__(self, cmd, msg):
        help_msg = (' (type "help %s" for more info)' % cmd if cmd
                    else ' (type "help" for list of available commands)')
        cmd_display = cmd + ': ' if cmd else ''
        super(CommandError, self).__init__(
            '*** ' + cmd_display + msg + help_msg)

class UnknownCommandError(CommandError):
    def __init__(self, base_cmd, unknown_command):
        super(UnknownCommandError, self).__init__(
            base_cmd,
            'unknown %scommand "%s"' % ('sub-' if base_cmd else '',
                                        unknown_command))

class MissingSubCommandError(CommandError):
    def __init__(self, cmd):
        super(MissingSubCommandError, self).__init__(
            cmd, 'expects a sub-command')

class AmbiguousCommandError(CommandError):
    def __init__(self, base_cmd, ambiguous_command):
        super(AmbiguousCommandError, self).__init__(
            base_cmd,
            'ambiguous %scommand "%s"' % ('sub-' if base_cmd else '',
                                          ambiguous_command))

class QuotingFilenameCompletion(FilenameCompletion):

    def __call__(self, text):
        completer.quote_characters = '"\''
        res = super(QuotingFilenameCompletion, self).__call__(text)
        return res

class NestedCmd(kmd.Kmd, object):

    def __init__(self):
        super(NestedCmd, self).__init__()

        self.complete_filename = QuotingFilenameCompletion()

    def __getattr__(self, name):
        # skip special features of getattr(Kmd) that expand attributes
        # to sub-commands which we don't want.
        return super(kmd.Kmd, self).__getattr__(name)

    def preloop(self):
        super(NestedCmd, self).preloop()
        completer.word_break_characters = ' \t\n'
        completer.quote_characters = ''

        self.interactive_mode = self.stdin.isatty()

        self.do_commands = CommandCompleter()
        self.help_topics = CommandCompleter()

        #logging.getLogger().setLevel(logging.DEBUG)

        for func in self.get_names():
            if func.startswith('do_'):
                self.do_commands.add_command(func[3:].split('_'))
            elif func.startswith('help_'):
                self.help_topics.add_command(func[5:].split('_'))

    def precmd(self, line):
        return super(NestedCmd, self).precmd(line)

    def postcmd(self, stop, line):
        completer.quote_characters = ''
        return super(NestedCmd, self).postcmd(stop, line)

    # modified code from kmd.Kmd to handle KeyboardInterrupt exception
    # gracefully
    def cmdloop(self, intro=None):
        """Repeatedly issue a prompt, accept input, parse an initial prefix
        off the received input, and dispatch to action methods, passing them
        the remainder of the line as argument.
        """
        self.preloop()
        try:
            if intro is not None:
                self.intro = intro
            if self.intro and self.interactive_mode:
                self.stdout.write(str(self.intro)+"\n")
            stop = None
            while not stop:
                try:
                    if self.cmdqueue:
                        line = self.cmdqueue.pop(0)
                    else:
                        if self.use_rawinput:
                            try:
                                if self.interactive_mode:
                                    line = self.input(self.prompt)
                                else:
                                    line = self.input("")
                            except EOFError:
                                line = 'EOF'
                        else:
                            self.stdout.write(self.prompt)
                            self.stdout.flush()
                            line = self.stdin.readline()
                            if not len(line):
                                line = 'EOF'
                            else:
                                line = line.rstrip('\r\n')
                    line = self.precmd(line)
                    stop = self.onecmd(line)
                    stop = self.postcmd(stop, line)
                except KeyboardInterrupt:
                    self.stdout.write('\n') # reset prompt
        finally:
            self.postloop()

    def onecmd(self, line):
        try:
            if line == 'EOF':
                if self.interactive_mode:
                    self.stdout.write('\n')
                return True # leave the prompt
            if not line:
                return self.emptyline()
            if line[0] == '#':
                return self.comment(line)

            arglist = line.split()
            seeklist = list(arglist)
            command_path = None
            cmd_func = None

            subcmds, command_path = \
                    self.do_commands.get_matching_subcommands_by_prefixes(
                        seeklist)

            logging.debug('command_path=%s subcmds=%s seeklist=%s',
                          repr(command_path), repr(subcmds), repr(seeklist))

            if len(seeklist) > len(command_path) and len(subcmds) > 1:
                raise AmbiguousCommandError(' '.join(command_path),
                                            seeklist[len(command_path)])

            if not command_path:
                longest_path = \
                    self.do_commands.get_longest_unambiguous_command_prefix(
                        seeklist, ignore_trailing_unknown=True)
                logging.debug('longest_path=%s', repr(longest_path))
                raise UnknownCommandError(' '.join(longest_path),
                                          seeklist[len(longest_path)])

            try:
                cmd_func = getattr(self, 'do_' + '_'.join(command_path))
            except AttributeError:
                pass

            if cmd_func:
                logging.debug('command_path=%s', repr(command_path))
                arglist = line.split(None, len(command_path))
                args = (arglist[len(command_path)].rstrip()
                        if len(arglist) > len(command_path) else '')
                logging.debug('calling %s with args %s',
                              repr(cmd_func), repr(args))
                return cmd_func(args)

            raise MissingSubCommandError(' '.join(command_path))

        except CommandError as err:
            self.stdout.write(err.message + '\n')
        except EnvironmentError as err:
            self.stdout.write(str(err) + '\n')
        except Exception as err:
            logging.debug("Caught an exception %s", repr(err))
            self.stdout.write(traceback.format_exc())

    def do_help(self, args):
        """List available commands with "help"
    List subcommands of a particular <command> with "help <command>"
"""

        self.show_command_help(*args.split())

    def show_command_help(self, *arglist):
        logging.debug('show help on %s', repr(arglist))
        seeklist = list(arglist)
        help_func = None
        cmd_func = None
        cmd_doc = None

        matching_help_topics, matching_subcommands = \
            (self.help_topics.filter_by_subcommand_prefixes(seeklist),
             self.do_commands.filter_by_subcommand_prefixes(seeklist))

        help_path, command_path = \
            (matching_help_topics.get_common_prefix()[:len(seeklist)],
             matching_subcommands.get_common_prefix()[:len(seeklist)])

        if len(help_path) < len(seeklist) - 1:
            help_topics = []
        else:
            help_topics = matching_help_topics.find_subcommands(help_path)

        if len(command_path) < len(seeklist) - 1:
            subcommands = []
        else:
            subcommands = matching_subcommands.find_subcommands(command_path)

        ambiguous = len(set(help_topics) | set(subcommands)) > 1

        logging.debug('help matching_help_topics=%s help_path=%s help_topics=%s',
                      matching_help_topics, repr(help_path),
                      repr(help_topics))
        logging.debug('help matching_subcommands=%s command_path=%s subcommands=%s',
                      matching_subcommands, repr(command_path),
                      repr(subcommands))

        if len(help_path) == len(seeklist) and not ambiguous:
            try:
                help_func = getattr(self, 'help_' + '_'.join(help_path))
                self.stdout.write('*** Help on topic: %s\n\n'
                                  % ' '.join(help_path))
                help_func()
                self.stdout.write('\n')
            except AttributeError:
                pass

        if len(command_path) == len(seeklist) and not ambiguous:
            try:
                cmd_func = getattr(self, 'do_' + '_'.join(command_path))
                cmd_doc = cmd_func.__doc__
                self.stdout.write('*** Help on command: %s\n\n'
                                  % ' '.join(command_path))
                self.stdout.write('    %s\n\n' % str(cmd_doc))
            except AttributeError:
                pass

        def dump_sub(path, namelist, func_prefix, kind):

            prefix = '_'.join([func_prefix] + path) + '_'
            if namelist:
                if path:
                    self.stdout.write('\n*** Matching sub-%s:\n\n' % kind)
                else:
                    self.stdout.write('\n*** Matching %s:\n\n' % kind)

                for name in namelist:
                    full_name = ' '.join(path) + ' ' + name
                    try:
                        doc = getattr(self, prefix + name).__doc__
                        summary = doc.split('\n', 1)[0]
                        self.stdout.write('    ' + full_name
                                          + ': ' + summary + '\n')
                    except AttributeError:
                        self.stdout.write('    ' + full_name + '\n')
                self.stdout.write('\n')
            return namelist

        if help_topics:
            dump_sub(help_path, help_topics, 'help', 'topics')

        if subcommands:
            dump_sub(command_path, subcommands, 'do', 'commands')

        if not help_func and not cmd_doc and not subcommands:
            longest_path = \
                self.do_commands.get_longest_unambiguous_command_prefix(
                    seeklist,
                    ignore_trailing_unknown=True)

            logging.debug('longest_path=%s', repr(longest_path))

            self.stdout.write(
                '*** No command or help topic matching "%s" '
                '(type "%s" to see available sub-commands and topics)\n'
                % (' '.join(seeklist),
                   ' '.join(['help'] + longest_path)))

    def do_history(self, args):
        """Show history of commands

    usage: history [max_entries]

    max_entries: max number of most recent entries to display (default 50)
"""

        args_array = args.split(None, 1)
        if len(args_array) > 1:
            raise CommandError('history', 'too many arguments')
        total_entries = len(history)
        try:
            max_entries = int(args_array[0]) if args_array else 50
        except ValueError:
            raise CommandError('history', 'max_entries is not an integer')
        n_to_skip = max(total_entries - max_entries, 0)
        index_to_display = n_to_skip + 1
        for history_item in history:
            if n_to_skip > 0:
                n_to_skip -= 1
                continue
            print('{i:5}  {item}'.format(i=index_to_display,
                                         item=history_item))
            index_to_display += 1

    def complete(self, text, state):
        """Return the next possible completion for 'text'.

        If a command has not been entered, then complete against command list.
        Otherwise try to call complete_<command> to get list of completions.
        """
        if state == 0:
            origline = completion.line_buffer
            line = origline.lstrip()
            stripped = len(origline) - len(line)
            begidx = completion.begidx - stripped
            endidx = completion.endidx - stripped
            if begidx < 0: # completion requested before first line character
                begidx, endidx = 0, 0
                line = ''
            self.completion_matches = iter(self.completenames(text, line, begidx, endidx))
        try:
            return self.completion_matches.next()
        except StopIteration:
            return None

    def completenames(self, text, line, begin, end):
        logging.debug('completenames line=%s text=%s begin=%d end=%d',
                      repr(line), repr(text), begin, end)
        completer.quote_characters = ''
        arglist = line[:end].split()
        if end and line[end - 1] != ' ':
            arglist.pop() # drop incomplete last argument

        matching_funcs = \
                self.do_commands.filter_by_subcommand_prefixes(
                    arglist)
        completer_prefix = matching_funcs.get_common_prefix()[:len(arglist)]
        logging.debug('matching_funcs=%s completer_prefix=%s',
                      matching_funcs, repr(completer_prefix))

        completion_func = None
        if completer_prefix:
            completion_func_name = 'complete_' + '_'.join(completer_prefix)
            try:
                completion_func = getattr(self, completion_func_name)
                logging.debug('found completer %s', completion_func_name)
            except AttributeError:
                pass

        if completion_func:
            # Most specific completion func found
            try:
                cmd_arg = line[:end].split(
                    None, len(completer_prefix))[len(completer_prefix)]
            except IndexError:
                cmd_arg = ''
            logging.debug('completenames: calling completion func cmd_arg=%s',
                          repr(cmd_arg))
            return completion_func(cmd_arg,
                                   begin - (end - len(cmd_arg)),
                                   len(cmd_arg))
        else:
            return self.do_commands.get_completions(line[:end])

    def complete_help(self, text, begin, end):
        logging.debug('complete_help text=%s begin=%d end=%d',
                      repr(text), begin, end)
        compl_line = text[:end].lstrip()
        commands = set(self.do_commands.get_completions(compl_line))
        topics = set(self.help_topics.get_completions(compl_line))
        return sorted(list(commands | topics))

    # Overcome a bug in Kmd when completing line starting with spaces
    @print_exc
    def word_break_hook(self, begidx, endidx):
        """word_break_hook(begidx, endidx)
        When completing '?<topic>' make sure '?' is a word break character.
        Ditto for '!<command>'.
        Installed as :attr:`rl.completer.word_break_hook <rl:rl.Completer.word_break_hook>`.
        """
        # This has a flaw as we cannot complete names that contain
        # the new word break character.
        origline = completion.line_buffer
        line = origline.lstrip()
        stripped = len(origline) - len(line)
        if begidx - stripped == 0:
            if line and (line[0] == '?' or line[0] in self.shell_escape_chars):
                if line[0] not in completer.word_break_characters:
                    return line[0] + completer.word_break_characters


from  tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
from time import time
from pencocokan import *

window = Tk()
window.title("AlgeOwO")
window.geometry("900x600")
window.configure(bg="white")

processed = False

newimagedir=""
def insertimage():
    global newimagedir
    newimagedir = filedialog.askopenfilename(filetypes=[("jpg image","*.jpg"),("png image","*.png")])
    no_image_selected.config(text=newimagedir)
    #print(newimagedir)
    newimage = ImageTk.PhotoImage(Image.open(newimagedir).resize((300,300)))
    pimg_test.config(image=newimage)
    pimg_test.image=newimage

newfolderdir=""
def insertfolderdir():
    global newfolderdir
    newfolderdir = filedialog.askdirectory()
    no_dataset_selected.config(text=newfolderdir)

resultpath=""
execution_time = 0
def processimage():
    start = time()
    global processed
    global execution_time
    resultpath = test_image(newfolderdir,newimagedir)
    execution_time = time() - start
    print(f"Execution time: {round(execution_time)}")
    if resultpath:
        resultimage = ImageTk.PhotoImage(Image.open(resultpath).resize((300,300)))
        pimg_result.config(image=resultimage)
        pimg_result.image=resultimage
        not_found.config(text="")
        execution_time_text.config(text="Execution time : "+str(round(execution_time,1))+" detik")
        execution_time_text.place(x=550, y=535)

    else:
        not_found.place(x=550 ,y=410)
        not_found.config(text="Tidak ada gambar yang cocok")
        execution_time_text.config(text="Execution time : "+str(round(execution_time,1))+" detik")
        execution_time_text.place(x=550, y=535)
        # no_dataset_selected.config(text="Tidak ada gambar yang cocok")
        print("Tidak ada gambar yang cocok")
        resultimage = ImageTk.PhotoImage(Image.open("no_image.png").resize((300,300)))
        pimg_result.config(image=resultimage)
        pimg_result.image=resultimage

# kumpulan label
header = Label(window, text="Face Recognition",bg="white",font=("Arial",24),fg="black")
insert_dataset_text = Label(window, text="Insert Your Dataset ", bg="white",font=("Times New Roman",12),fg="black")
insert_image_text  = Label(window, text="Insert Your Image ", bg="white",font=("Times New Roman",12),fg="black")
no_dataset_selected = Label(window, text="No Dataset Selected", bg="grey",font=("Times New Roman",12),fg="black")
no_image_selected = Label(window, text="No Image Selected", bg="grey",font=("Times New Roman",12),fg="black")
not_found  = Label(window, text="Tidak ada gambar yang cocok", bg="white",font=("Times New Roman",12),fg="red")

#result_text = insert_dataset = tk.Label(window, text="Result ", bg="white",font=("Times New Roman",12),fg="black")
test_image_text = Label(window, text="Test image ", bg="white",font=("Times New Roman",12),fg="black")
closest_result_text = Label(window, text="Closest Result ", bg="white",font=("Times New Roman",12),fg="black")

execution_time_text = Label(window, text="Execution time: ", bg="white",font=("Times New Roman",12),fg="black")

# kumpulan button
folder_file = ImageTk.PhotoImage(Image.open("choose_folder.png").resize((120,32)))
tombol_folder = Button(window, image=folder_file, fg="blue", bg="white",borderwidth=0)
button_file = ImageTk.PhotoImage(Image.open("choose_file.png").resize((120,32)))
tombol_file = Button(window, image=button_file, fg="blue", bg="white", borderwidth=0)
process_image = ImageTk.PhotoImage(Image.open("process_image.png").resize((120,32)))
tombol_process = Button(window, image=process_image, fg="blue",borderwidth=0)
tombol_file.config(command=lambda:insertimage())
tombol_folder.config(command=lambda:insertfolderdir())
tombol_process.config(command=lambda:processimage())

# kumpulan place
header.place(x=330, y=15)

insert_dataset_text.place(x=550, y=450)
tombol_folder.place(x =550, y = 475)
no_dataset_selected.place(x =550, y=510 )

insert_image_text.place(x=95,y = 450 )
tombol_file.place(x =95, y = 475)
no_image_selected.place(x=95, y = 510)

tombol_process.place(x=415,y=125)

#result_text.place(x=25, y=300)
test_image_text.place(x=120, y=75)

closest_result_text.place(x=575, y=75)

img_test=ImageTk.PhotoImage(Image.open("no_image.png").resize((270,270)))
pimg_test=Label(window)
pimg_test.config(width=300,height=300)
pimg_test.place(x=95,y=100)
pimg_test.config(image=img_test)
#resultimg = Label(window)
#resultimg.config(width=300,height=300)
#pimg_right = Label(window)

img_result=ImageTk.PhotoImage(Image.open("no_image.png").resize((270,270)))
pimg_result=Label(window)
pimg_result.config(width=300,height=300)
pimg_result.place(x=550,y=100)
pimg_result.config(image=img_test)
#pimg_result = Label(window)

window.mainloop()


import pandas as pd
import nltk
from nltk.corpus import stopwords
from nltk.stem import SnowballStemmer, WordNetLemmatizer

#Requirments
nltk.download('wordnet')
nltk.download('stopwords')
stop_words = set(stopwords.words('english'))

stemmer = SnowballStemmer('english')
lemmatizer = WordNetLemmatizer()

def preprocess_sentence(sentence):

    sentence = sentence.lower()
    sentence = list(sentence.split())
    # sentence = list(set(sentence.split())) # Removing duplicates

    sentence = [word for word in sentence if not word in stop_words] # Removing stopwords

    sentence = [stemmer.stem(word) for word in sentence] # Stemming

    sentence = [lemmatizer.lemmatize(word) for word in sentence] # Lemmatization
    return sentence


import json
import requests
from datetime import datetime, timedelta

# curl 'https://api.baselinker.com/connector.php' -H 'X-BLToken: 1-23-ABC' --data-raw 'method=getOrders&parameters=%7B%22date_from%22%3A+1407341754%7D'
class BaselinkerApi():
    def __init__(self, api_key):
        self.host = 'https://api.baselinker.com/connector.php'
        self.api_key = api_key

    def create_request_body(self, method, json_data):
        req_data = {
            "method": method,
            "parameters": json_data
        }
        return req_data

    def create_headers(self):
        headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "X-BLToken": self.api_key
        }
        return headers

    def get_last_invoices(self):
        d = datetime.today() - timedelta(days=7)
        params = {
            "date_from": int(d.timestamp())
        }
        res = self.post('getInvoices', json.dumps(params))
        return res

    def ovveride_invoice_file(self, inv_data):
        res = self.post('addOrderInvoiceFile', json.dumps(inv_data))
        if res:
            return res['status']

    def post(self, method, json_data):
        body = self.create_request_body(method, json_data)
        headers = self.create_headers()
        res = requests.post(self.host, data=body, headers=headers)
        return res.json()


from collections import Counter

def print_grocery_list(grocery_items):
    # Chuyển danh sách thành chữ hoa và sắp xếp theo thứ tự bảng chữ cái
    sorted_grocery_items = sorted(grocery_items, key=lambda x: x.upper())

    # Đếm số lần xuất hiện của mỗi mặt hàng
    item_counts = Counter(sorted_grocery_items)

    # In danh sách tạp hóa
    for item in sorted(set(sorted_grocery_items)):
        print(f"{item_counts[item]:2d} {item.upper()}")

if __name__ == "__main__":
    print("Nhập danh sách các mặt hàng cần mua tại cửa hàng tạp hóa.")

    grocery_items = []
    while True:
        try:
            item = input("Nhập mặt hàng (hoặc ấn control-z để kết thúc): ")
            if not item:
                break

            # Chuyển mặt hàng thành chữ hoa và thêm vào danh sách
            item = item.upper()
            grocery_items.append(item)
        except EOFError:
            break

    print("Danh sách tạp hóa:")
    print_grocery_list(grocery_items)


from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status

from backend.models import Attendance, User, Section, Student
from backend.serializers import (
    UserSerializer,
    StudentSerializer,
    MentorSerializer,
    SectionSerializer,
    CourseSerializer,
    AttendanceSerializer
)

@api_view(["GET"])
def users(request):
    users = User.objects.all()
    serializer = UserSerializer(users, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

@api_view(["GET"])
def sections(request):
    sections = Section.objects.all()
    serializer = SectionSerializer(sections, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

@api_view(["GET", "DELETE"])
def section_students(request, section_id):
    if request.method == "GET":
        section = Section.objects.get(id=section_id)
        students = section.student_set.filter(active=True)
        serializer = StudentSerializer(students, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    elif request.method == "DELETE":
        students = Section.objects.get(id=section_id).student_set.filter(active=True)
        student = students.get(id = request.data.get("value"))
        student.active = False
        student.save()
        return Response(status=status.HTTP_201_CREATED)

@api_view(["GET", "POST"])
def section_details(request, section_id):
    """
    GET: Return section details
    POST: Update section details
        - format: { "capacity": int, "description": str }
    """
    if request.method == "GET":
        section = Section.objects.get(id=section_id)
        serializer = SectionSerializer(section)
        return Response(serializer.data, status=status.HTTP_200_OK)
    elif request.method == "POST":
        section = Section.objects.get(id=section_id)
        capacity = request.data.get("capacity")
        description = request.data.get("description")
        if capacity is not None:
            section.capacity = capacity
        if description is not None:
            section.description = description
        section.save()
        return Response(status=status.HTTP_201_CREATED)

@api_view(["GET"])
def student_details(request, student_id):
    """
    GET: Return student details
    """
    if request.method == "GET":
        student = Student.objects.get(id=student_id)
        serializer = StudentSerializer(student)
        return Response(serializer.data, status=status.HTTP_200_OK)

@api_view(["GET", "POST"])
def attendance_details(request, attendance_id):
    """
    GET: Return student details
    """
    if request.method == "GET":
        attendance = Attendance.objects.get(id=attendance_id)
        serializer = AttendanceSerializer(attendance)
        return Response(serializer.data, status=status.HTTP_200_OK)

    elif request.method == "POST":
        attendance = Attendance.objects.get(id=attendance_id)
        attendance.presence = request.data.get("value")
        attendance.save()
        return Response(status=status.HTTP_201_CREATED)

@api_view(["GET"])
def attendance_student(request, student_id):
    """
    GET: Return student details
    """
    if request.method == "GET":
        attendance = Attendance.objects.filter(student_id = student_id)
        serializer = AttendanceSerializer(attendance, many = True)
        return Response(serializer.data, status=status.HTTP_200_OK)