import os
import re
from typing import Optional

from arcus.client import Client
from arcus.client import Transaction as ArcusTransaction
from arcus.exc import InvalidAmount

from arcusd.contracts import Bill, Cancellation, Topup, Transaction
from arcusd.data_access.providers_mapping import get_service_provider_code

ARCUS_API_KEY = os.environ['ARCUS_API_KEY']
ARCUS_SECRET_KEY = os.environ['ARCUS_SECRET_KEY']

use_arcus_sandbox = os.environ.get('ARCUS_USE_SANDBOX') == 'true'

client = Client(ARCUS_API_KEY, ARCUS_SECRET_KEY,
                sandbox=use_arcus_sandbox)

def cents_to_unit(cents: int) -> float:
    return cents / 100

def unit_to_cents(unit: float) -> int:
    return int(unit * 100)

def clean(value: str) -> str:
    return re.sub(r'\D', '', value)

def amount_to_unit(cents: int) -> float:
    if cents <= 100:
        raise InvalidAmount(code='00', message='Min amount is 1 peso')
    return cents_to_unit(cents)

def query_bill(biller_id: int, account_number: str) -> Bill:
    bill = client.bills.create(biller_id, clean(account_number))
    bill_contract = Bill(
        id=bill.id,
        service_provider_code=get_service_provider_code(biller_id),
        account_number=bill.account_number,
        balance=unit_to_cents(bill.balance),
        currency=bill.balance_currency
    )
    return bill_contract

def pay_bill_id(bill_id: int) -> Transaction:
    bill = client.bills.get(bill_id)
    transaction = bill.pay()
    transaction_contract = Transaction(
        id=transaction.id,
        amount=unit_to_cents(transaction.amount),
        currency=transaction.amount_currency,
        transaction_fee=unit_to_cents(transaction.transaction_fee),
        hours_to_fulfill=transaction.hours_to_fulfill,
        status=transaction.status
    )
    return transaction_contract

def pay_bill(biller_id: int, account_number: str,
             amount: Optional[int] = None) -> Transaction:
    bill = client.bills.create(biller_id, clean(account_number))
    if amount is None:
        transaction = bill.pay()
    else:
        amount = amount_to_unit(amount)
        transaction = bill.pay(amount)
    transaction_contract = Transaction(
        id=transaction.id,
        amount=unit_to_cents(transaction.amount),
        currency=transaction.amount_currency,
        transaction_fee=unit_to_cents(transaction.transaction_fee),
        hours_to_fulfill=transaction.hours_to_fulfill,
        status=transaction.status
    )
    return transaction_contract

def cancel_transaction(transaction_id: int) -> Cancellation:
    transaction = ArcusTransaction(
        id=transaction_id, amount=0, amount_currency='',
        transaction_fee=0, hours_to_fulfill=0, created_at='',
        status='', type='', fx_rate=0, amount_usd=0, total_usd=0)
    arcus_cancellation = transaction.cancel()
    cancellation = Cancellation(
        transaction_id=transaction_id,
        code=arcus_cancellation['code'],
        message=arcus_cancellation['message'],
    )
    return cancellation

def topup(biller_id: int, phone_number: str, amount: int,
          currency: str, name_on_account: str) -> Topup:
    unit = amount_to_unit(amount)
    topup = client.topups.create(biller_id,
                                 clean(phone_number),
                                 unit,
                                 currency,
                                 name_on_account)
    topup_contract = Topup(
        id=topup.id,
        service_provider_code=get_service_provider_code(biller_id),
        account_number=topup.account_number,
        amount=unit_to_cents(topup.bill_amount),
        currency=topup.bill_amount_currency,
        payment_transaction_fee=unit_to_cents(topup.payment_transaction_fee),
        payment_total=unit_to_cents(topup.payment_total_chain_currency),
        chain_earned=unit_to_cents(topup.chain_earned),
        chain_paid=unit_to_cents(topup.chain_paid),
        starting_balance=unit_to_cents(topup.starting_balance),
        ending_balance=unit_to_cents(topup.ending_balance),
        hours_to_fulfill=topup.hours_to_fulfill,
        ticket_text=topup.ticket_text
    )
    return topup_contract


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Created on 2013-1-31
# User: Administrator
# @author: JiangHuiliang
# @email:  jianghuiliang@hotmail.com
#

import sys, os, stat

def purge(path):
    count = 0
    for item in os.listdir(path):
        subpath = os.path.join(path, item)
        mode = os.stat(subpath)[stat.ST_MODE]
        if stat.S_ISDIR(mode):
            count += purge(subpath)
        else:
            os.chmod(subpath, stat.S_IREAD | stat.S_IWRITE)
            os.unlink(subpath)
            count += 1
    os.rmdir(path)
    count += 1
    return count

if len(sys.argv) != 2:
    print("Usage: python cleansvn.py path")
    sys.exit(1)

purge(sys.argv[1])

#一种更简单的方法
#import os
#for (p,d,f) in os.walk("要删除的目录路径"):
#     if p.find('.svn')>0:
#         os.popen('rd /s /q %s'%p)


import gfw
from player import Player
from pico2d import *
import gobj
from background import HorzScrollBackground
import random
import all_stage_gen
import camera
import objects
import collision
import monster
import tile
import highscore
import ui
import ufo

canvas_width = 1200
canvas_height = 800

def enter():
    gfw.world.init(['bg','tile','object','score_object','monster', 'effect','ufo','whip','player','ui','black'])
    global player, bg, player_ui, main_bgm, ufo_bgm, black_canvas, black_pos, stage_time, all_time, ufo_count

    bg = HorzScrollBackground('Background.png')
    gfw.world.add(gfw.layer.bg, bg)

    stage_time = 0
    all_time = 0
    ufo_count = 0

    load_all()

    (e_x,e_y), (o_x,o_y) = all_stage_gen.make_all_map()
    e_x,e_y,o_x,o_y = change_to_screen(e_x,e_y, o_x,o_y)
    player = Player((e_x + 32,e_y + 32))
    gfw.world.add(gfw.layer.player, player)

    clear_in_out(e_x,e_y,o_x,o_y)

    player_ui = ui.Ui(player)
    gfw.world.add(gfw.layer.ui, player_ui)

    black_canvas = gfw.image.load('res/black.png')
    black_pos = 0, 0

    main_bgm = load_music('res/main_bgm.mp3')
    main_bgm.set_volume(10)
    main_bgm.repeat_play()

    ufo_bgm = load_music('res/ufo_bgm.mp3')
    ufo_bgm.set_volume(10)

    global fade_out_sound
    fade_out_sound = load_wav('res/wav/fadeout.wav')

    global check
    check = 0

def update():
    global player, bg, player_ui, ufo_count, stage_time, all_time

    if check == False:
        stage_time += gfw.delta_time
        all_time += gfw.delta_time

    collision.collide_check(player)
    player_ui.set_count(player)

    gfw.world.update()
    bg.speed = player.dx * 5

    p_draw_x, p_draw_y, left_gab, bottom_gab = camera.update(player)

    player.set_draw_pos((p_draw_x,p_draw_y))
    for layer in range(gfw.layer.tile, gfw.layer.ufo + 1):
        for obj in gfw.world.objects_at(layer):
            obj.set_draw_pos(left_gab,bottom_gab)

    p_x, p_y = player.draw_pos
    for i in gfw.world.objects_at(gfw.layer.whip):
        i.pos = (p_x, p_y)

    ufo_maker()
    death_check()
    fade_in_out()

def draw():
    global black_canvas
    gfw.world.draw()
    #gobj.draw_collision_box()
    black_canvas.draw_to_origin(*black_pos,get_canvas_width(), get_canvas_height())

def handle_event(e):
    x, y = 0,0
    # prev_dx = boy.dx0

    global check

    if e.type == SDL_QUIT:
        gfw.quit()
    elif e.type == SDL_KEYDOWN:
        if e.key == SDLK_ESCAPE:
            gfw.pop()
        elif e.key == SDLK_7 and player.death_time == 8:
            player.life = 5
            player.score = 0
            player.boom_count = 4
            player.rope_count = 4
            reset()
        elif e.key == SDLK_a and check == 1:
            check = 2
            print(check)

    player.handle_event(e)

def exit():
    global main_bgm, ufo_bgm
    del main_bgm
    del ufo_bgm

def load_all():
    ufo.load()
    ui.load()
    objects.load()
    monster.load()
    tile.load()
    highscore.load()
    camera.camera_init()

def reset():
    global stage_time, ufo_count
    for layer in range(gfw.layer.tile, gfw.layer.whip + 1):
        gfw.world.clear_at(layer)

    (e_x,e_y), (o_x,o_y) = all_stage_gen.make_all_map()
    e_x,e_y,o_x,o_y = change_to_screen(e_x,e_y, o_x,o_y)
    player.init((e_x + 32,e_y + 32))

    stage_time = 0
    ufo_count = 0
    fade_out_sound.play()
    main_bgm.repeat_play()
    clear_in_out(e_x,e_y,o_x,o_y)

def death_check():
    global check, black_pos
    b_x, b_y = black_pos
    if player.life == 0 and check == 0:
        main_bgm.stop()
        highscore.add(player.score)
        gfw.world.add(gfw.layer.ui, highscore)
        check = 1

    if player.death_time < 0 and b_y <= 0:
        main_bgm.repeat_play()
        gfw.world.remove(highscore)
        player.life = 5
        player.score = 0
        player.boom_count = 4
        player.rope_count = 4
        player.death_time = 8
        check = 0
        reset()

def ufo_maker():
    global ufo_count, stage_time
    if ufo_count < 1 and stage_time > 20:
        x = random.choice([-100,2680])
        y = 1200
        pos = x,y
        new_ufo = ufo.Ufo(pos)
        gfw.world.add(gfw.layer.ufo, new_ufo)
        ufo_count += 1
        main_bgm.stop()
        ufo_bgm.repeat_play()
    else:
        for u in gfw.world.objects_at(gfw.layer.ufo):
            u.find_me(player)

def fade_in_out():
    global black_canvas, black_pos
    b_x, b_y = black_pos
    if player.stage_clear == True:
        gfw.world.clear_at(gfw.layer.ufo)
        ufo_bgm.stop()
        main_bgm.stop()
        if b_y > 0:
            b_y -= 10
        else:
            reset()
    elif player.death_time < 8 and check == 2:
        if b_y > 0 :
            b_y -= 20
    else:
        if b_y < get_canvas_height() + 600:
            b_y += 10
    black_pos = b_x, b_y

def clear_in_out(x1,y1,x2,y2):
    for t in gfw.world.objects_at(gfw.layer.tile):
        if t.left == x1 and t.bottom == y1 and t.name != 'entrance':
            gfw.world.remove(t)
        elif t.left == x2 and t.bottom == y2 and t.name != 'exit':
            gfw.world.remove(t)

def change_to_screen(x1,y1,x2,y2):
    x1 = x1 * 640 + 320
    y1 = y1 * 512 + 192
    x2 = x2 * 640 + 320
    y2 = y2 * 512 + 192
    return x1,y1,x2,y2

if __name__ == '__main__':
    gfw.run_main()


# def calculation():
#     global place
#     place = "Cape Town" # change global variable "place"
#     global name
#     name = "John" # global variable
#     print(place)
#
#
# place = "Berlin" # global variable
# print(place)
# calculation()
# print(place)
# print(name) # try print global variable "name"

def welcome(msg):
    print(msg)
    welcome(msg)

welcome("hello")

'''
Given an integer list,
find the contiguous sublist (containing at least one number) which has the largest sum and return its sum.

input = [-2,1,-3,4,-1,2,1,-5,4]
        [-2, 1, -2, 4, 3, 5, 6, 1, 5]
sublist [4,-1,2,1] gives the largest sum 6, return 6

Input: nums = [5,4,-1,7,8]
output: 23
'''
# def maxSubArray(nums):
#     max = nums[0]
#     i = 0
#     while i < len(nums):
#         if nums[i] > max:
#             max = nums[i]
#
#         index_sum = nums[i]
#         j = i + 1
#         while j < len(nums):
#             index_sum += nums[j]
#             if index_sum > max:
#                 max = index_sum
#             j += 1
#         i += 1
#     return max
#
l = [-2,1,-3,4,-1,2,1,-5,4]
# print(maxSubArray(l))

# def maxSubArray(nums):
#     store = []
#     store.append(nums[0])
#     max = nums[0]
#
#     index = 1
#     while index < len(nums):
#         if store[index - 1] > 0:
#             store.append(nums[index] + store[index-1])
#         else:
#             store.append(nums[index])
#
#         if store[index] > max:
#             max = store[index]
#         index += 1
#
#     return max
#
# print(maxSubArray(l))

def counter(n):
    while n > 0:
        print(n)
        n -= 1

def counter_recursive(n):
    if n == 0:
        return
    else:
        print(n)
        counter_recursive(n-1)

counter_recursive(3)

'''
Given a string s consists of some words separated by spaces,
return the length of the last word in the string. If the last word does not exist, return 0.

example:
s = "Hello World"
length = 5

s = "good morning Tom"
length = 3

s = "welcome"
length = 7
'''

def add(n):
    if n <= 1:
        return n
    else:
        return n + add(n-1)

print(add(4))

def max_sublist(l):
    max = l[0]
    i = 0
    while i < len(l):
        if l[i] > max:
            max = l[i]
        sum = l[i]
        j = i + 1
        while j < len(l):
            sum = sum + l[j]
            if sum > max:
                max = sum
            j += 1
        i += 1
    return max


# destination/main.py
import os
import json
import kafka_interface as kafka
import link_parser
import mongodb_interface as mongo
import xpath_service as xpath

KAFKA_BROKER_URL = os.environ.get('KAFKA_BROKER_URL')
TOPIC_INPUT = os.environ.get('TOPIC_INPUT')
DATABASE = os.environ.get('DATABASE')

if __name__ == '__main__':
    consumer = kafka.connectConsumer(topic = TOPIC_INPUT, server = KAFKA_BROKER_URL)
    working = True
    while working:
        dict = kafka.consume(consumer = consumer)
        if(dict != {}):
            for topic, messages in dict.items():
                for message in messages:
                    domain = str(message.value['domain'])
                    print('Working for domain: '+domain)
                    list_pages = link_parser.check_urls(message.value['filtered_pages'])

                    xpaths = xpath.find_xpath(domain, list_pages)

                    print('Xpaths elaborated')
                    xpath_generalized = xpath.generalize_xpath(xpaths)
                    print('Generated Xpath Generalized')

                    content = {
                        'domain': domain,
                        'Xpaths': xpaths,
                        'Generalized_Xpaths': xpath_generalized
                    }
                    mongo.put(domain,json.dumps(content))


#!/usr/bin/python

import sys

def rock_paper_scissors(n):
  #start
  choices =  ['rock', 'paper', 'scissors']
  possible_plays = []

  #base
  def rps_helper_fun(result, plays):
        # this should stop the recursion if there are no plays
    if plays == 0:
      possible_plays.append(result)
      return
      for i in range(0, len(choices)):
        rps_helper_fun(result + [choices[i]], plays -1)
      rps_helper_fun([], n)
      return possible_plays

if __name__ == "__main__":
  if len(sys.argv) > 1:
    num_plays = int(sys.argv[1])
    print(rock_paper_scissors(num_plays))
  else:
    print('Usage: rps.py [num_plays]')


import sqlite3

class Database:
    def __init__(self):
        self.conn = None
        self.cursor = None

    def connect(self):
        self.conn = sqlite3.connect(r"chat.db")
        self.cursor = self.conn.cursor()

    def vote(self, author, voter, chat_id, message_id, vote_type):
        self.create_user(author.username, author.id, chat_id)
        self.create_user(voter.username, voter.id, chat_id)
        if self.check_repeat(voter.id, chat_id, message_id):
            return 'You can\'t vote for this message again'
        if not self.check_positive(voter.id, chat_id):
            user_data = self.get_user_stat(voter.id, chat_id)
            rating = user_data[1]
            return 'You can\'t vote with negative rating @{} ({})'.format(voter.username, rating)
        self.save_message(message_id, voter.id, chat_id)
        self.db_vote(author.id, chat_id, vote_type)
        data = self.get_user_stat(author.id, chat_id)
        return '@{} voted to @{} ({})'.format(voter.username, author.username, data[1])

    def create_user(self, name, user_id, chat_id):
        if self.check_user(user_id, chat_id):
            return True
        self.cursor.execute("INSERT INTO users(name, user_id, chat_id) values (?, ?, ?) ",
                            [name, user_id, chat_id])
        self.conn.commit()
        self.cursor.execute("SELECT name FROM users")
        results = self.cursor.fetchone()
        return bool(results)

    def check_user(self, user_id, chat_id):
        self.cursor.execute("SELECT name FROM users WHERE user_id = ? AND chat_id = ?",
                            [user_id, chat_id])
        results = self.cursor.fetchone()
        return bool(results)

    def check_repeat(self, user_id, chat_id, message_id):
        self.cursor.execute("SELECT message_id FROM messages WHERE message_id = ? AND chat_id = ? AND user_id = ?",
                            [message_id, chat_id, user_id])
        results = self.cursor.fetchone()
        return bool(results)

    def check_positive(self, user_id, chat_id):
        self.cursor.execute("SELECT rating FROM users WHERE user_id = ? AND chat_id = ?",
                            [user_id, chat_id])
        results = self.cursor.fetchone()
        if results is not None:
            return results[0] >= 0
        else:
            return True

    def db_vote(self, user_id, chat_id, vote_type):
        if vote_type:
            self.cursor.execute("UPDATE users SET rating = rating + 1 WHERE user_id = ? AND chat_id = ?",
                                [user_id, chat_id])
        else:
            self.cursor.execute("UPDATE users SET rating = rating - 1 WHERE user_id = ? AND chat_id = ?",
                                [user_id, chat_id])
        self.conn.commit()
        return True

    def save_message(self, message_id, user_id, chat_id):
        self.cursor.execute("INSERT INTO messages(message_id, user_id, chat_id) values (?, ?, ?) ",
                            [message_id, user_id, chat_id])
        self.conn.commit()
        results = self.cursor.fetchone()
        return bool(results)

    def get_user_stat(self, user_id, chat_id):
        self.cursor.execute("SELECT name, rating FROM users WHERE user_id = ? AND chat_id = ?",
                            [user_id, chat_id])
        results = self.cursor.fetchone()
        return results

    def chat_rating(self, chat_id):
        self.cursor.execute("SELECT name, rating, user_id FROM users WHERE chat_id = ? ORDER BY rating DESC",
                            [chat_id])
        results = self.cursor.fetchall()
        return results


import pygame

from GUI_Components.button import Button
from GUI_Components.square import square
from GUI_Components.image import image

class mainMenu():
    def __init__(self, rpg):
        #LoadButton Settings
        self.loadButton = Button(rpg, "Load")
        self.loadButton.startDefault(rpg, 75, 0)

        #New game button
        self.newGameButton = Button(rpg, "New Game")
        self.newGameButton.startDefault(rpg, 0, 0)

        #Quit Button
        self.quitButton = Button(rpg, "Quit")
        self.quitButton.startDefault(rpg, 150, 0)

        #Project Logo
        self.logo = image(rpg, 'CREATE Task Folder\Image Assets\GUI_images\ProjectLogo.png', "")#pylint: disable = anomalous-backslash-in-string
        self.logo.top = (rpg.settings.screen_height*.5) - (self.logo.height/2) - 200
        self.logo.left = (rpg.settings.screen_width*.5) - (self.logo.width/2)

    def draw(self):
        self.loadButton.draw()

        self.newGameButton.draw()

        self.quitButton.draw()

        self.logo.draw()

class choiceButtons():
    def __init__(self, rpg):
        self.choice1 = Button(rpg, "")
        self.choice1.choiceDefault(rpg, 0)

        self.choice2 = Button(rpg, "")
        self.choice2.choiceDefault(rpg, -70)

        self.choice3 = Button(rpg, "")
        self.choice3.choiceDefault(rpg, -140)

        self.choice4 = Button(rpg, "")
        self.choice4.choiceDefault(rpg, -210)

        self.choice5 = Button(rpg, "")
        self.choice5.choiceDefault(rpg, -280)

        self.choice6 = Button(rpg, "")
        self.choice6.choiceDefault(rpg, -350)

    def draw(self):
        self.choice1.draw()

        self.choice2.draw()

        self.choice3.draw()

        self.choice4.draw()

        self.choice5.draw()

        self.choice6.draw()

    def editChoices(self, choice1Text, choice2Text, choice3Text, choice4Text, choice5Text, choice6Text):
        self.choice1.msg = choice1Text
        self.choice2.msg = choice2Text
        self.choice3.msg = choice3Text
        self.choice4.msg = choice4Text
        self.choice5.msg = choice5Text
        self.choice6.msg = choice6Text

    def mouseEvents(self, rpg, mous_pos):
        if self.choice1.rect.collidepoint(mous_pos):
            rpg.playerConsole.newSlot = 1
            rpg.playerConsole.showNextText("", "No")
            rpg.playerConsole.newSlot = 0

class statSheet():
    def __init__(self, rpg):
        self.hpStat = Button(rpg, "HP: {}/{}".format(rpg.player.hp, rpg.player.maxhp))
        self.hpStat.statDefault(rpg, -420, 0)

        self.stamStat = Button(rpg, "Stamina: {}/{}".format(rpg.player.stamina, rpg.player.stamina_max))
        self.stamStat.statDefault(rpg, -350, 0)

        self.manaStat = Button(rpg, "Mana: {}/{}".format(rpg.player.mana, rpg.player.mana_max))
        self.manaStat.statDefault(rpg, -280, 0)

        self.speedStat = Button(rpg, "Speed: {}".format(rpg.player.speed))
        self.speedStat.statDefault(rpg, -210, 0)

        self.physAtckStat = Button(rpg, "Physical Attack: {}".format(rpg.player.physical_attack))
        self.physAtckStat.statDefault(rpg, -140, 0)

        self.magicAtckStat = Button(rpg,  "Magic Attack: {}".format(rpg.player.magic_attack))
        self.magicAtckStat.statDefault(rpg, -70, 0)

        self.physDefStat = Button(rpg, "Physical Defense: {}".format(rpg.player.physical_defense))
        self.physDefStat.statDefault(rpg, -420, 350)

        self.magicDefStat = Button(rpg, "Magic Defense: {}".format(rpg.player.magic_defense))
        self.magicDefStat.statDefault(rpg, -350, 350)

        self.fireResist = Button(rpg, "Fire Resistance: {}".format(rpg.player.fire_resist))
        self.fireResist.statDefault(rpg, -280, 350)

        self.poisonResist = Button(rpg, "Poison Resistance: {}".format(rpg.player.poison_resist))
        self.poisonResist.statDefault(rpg, -210, 350)

        self.waterResist = Button(rpg, "Water Resistance: {}".format(rpg.player.water_resist))
        self.waterResist.statDefault(rpg, -140, 350)

        self.earthResist = Button(rpg, "Earth Resistance: {}".format(rpg.player.earth_resist))
        self.earthResist.statDefault(rpg, -70, 350)

        self.windResist = Button(rpg, "Wind Resistance: {}".format(rpg.player.wind_resist))
        self.windResist.statDefault(rpg, -420, 700)

        self.evasion = Button(rpg, "Evasion: {}".format(rpg.player.evasion))
        self.evasion.statDefault(rpg, -350, 700)

        self.accuracyStat = Button(rpg, "Accuracy: {}".format(rpg.player.accuracy))
        self.accuracyStat.statDefault(rpg, -280, 700)

        self.critStat = Button(rpg, "Crit Chance: {}".format(rpg.player.crit_chance))
        self.critStat.statDefault(rpg, -210, 700)

        self.critMult = Button(rpg, "Crit Multiplier: {}".format(rpg.player.crit_mult))
        self.critMult.statDefault(rpg, -140, 700)

        self.luckStat = Button(rpg, "Luck: {}".format(rpg.player.luck))
        self.luckStat.statDefault(rpg, -70, 700)

    def updateStats(self, rpg):
        self.hpStat.msg = "HP: {}/{}".format(rpg.player.hp, rpg.player.maxhp)
        self.stamStat.msg = "Stamina: {}/{}".format(rpg.player.stamina, rpg.player.stamina_max)
        self.manaStat.msg = "Mana: {}/{}".format(rpg.player.mana, rpg.player.mana_max)
        self.speedStat.msg = "Speed: {}".format(rpg.player.speed)
        self.physAtckStat.msg = "Physical Attack: {}".format(rpg.player.physical_attack)
        self.magicAtckStat.msg = "Magic Attack: {}".format(rpg.player.magic_attack)
        self.physDefStat.msg = "Physical Defense: {}".format(rpg.player.physical_defense)
        self.magicDefStat.msg = "Magic Defense: {}".format(rpg.player.magic_defense)
        self.fireResist.msg = "Fire Resistance: {}".format(rpg.player.fire_resist)
        self.poisonResist.msg = "Poison Resistance: {}".format(rpg.player.poison_resist)
        self.waterResist.msg = "Water Resistance: {}".format(rpg.player.water_resist)
        self.earthResist.msg = "Earth Resistance: {}".format(rpg.player.earth_resist)
        self.windResist.msg = "Wind Resistance: {}".format(rpg.player.wind_resist)
        self.evasion.msg = "Evasion: {}".format(rpg.player.evasion)
        self.accuracyStat.msg = "Accuracy: {}".format(rpg.player.accuracy)
        self.critStat.msg = "Crit Chance: {}".format(rpg.player.crit_chance)
        self.critMult.msg = "Crit Multiplier: {}".format(rpg.player.crit_mult)
        self.luckStat.msg = "Luck: {}".format(rpg.player.luck)

    def showStats(self, rpg):
        self.updateStats(rpg)
        self.hpStat.draw()
        self.stamStat.draw()
        self.manaStat.draw()
        self.speedStat.draw()
        self.physAtckStat.draw()
        self.magicAtckStat.draw()
        self.physDefStat.draw()
        self.magicDefStat.draw()
        self.fireResist.draw()
        self.poisonResist.draw()
        self.waterResist.draw()
        self.earthResist.draw()
        self.windResist.draw()
        self.evasion.draw()
        self.accuracyStat.draw()
        self.critStat.draw()
        self.critMult.draw()
        self.luckStat.draw()

class borders:
    def __init__(self, rpg):
        #OuterBorder
        self.borderSquare = square(rpg)

        #MapBorder
        self.mapSquare = square(rpg)
        self.mapSquare.height = self.borderSquare.height - 420

        #TextBorder
        self.textSquare = square(rpg)
        self.textSquare.height = self.textSquare.height - 420
        self.textSquare.width = 1050

    def draw(self):
        self.borderSquare.draw()
        self.mapSquare.draw()
        self.textSquare.draw()

class swapButton:
    def __init__(self, rpg):
        self.swapButton = image(rpg, 'CREATE Task Folder\Image Assets\GUI_images\Bag.png', "Player Inventory")#pylint: disable = anomalous-backslash-in-string
        self.swapButton.width = (rpg.settings.screen_width - 1600)
        self.swapButton.height = 210
        self.swapButton.top = (rpg.settings.screen_height) - self.swapButton.height
        self.swapButton.left = 1050
        self.swapButton.border = True
        self.swapButton.clickable = True
        self.inventoryShow = False
        self.statsShow = True

    def mouseEvents(self, mous_pos):
        if self.swapButton.rect.collidepoint(mous_pos):
            if self.inventoryShow == True:
                self.inventoryShow = False
            else:
                self.inventoryShow = True
            self.swap()

    def swap(self):
        if self.swapButton.msg == "Player Inventory":
            self.stats()
        elif self.swapButton.msg == "Stat Sheet":
            self.inventory()

    def stats(self):
        self.swapButton.image = pygame.image.load('CREATE Task Folder\Image Assets\GUI_images\Stat Sheet.gif')#pylint: disable = anomalous-backslash-in-string
        self.swapButton.msg = "Stat Sheet"

    def inventory(self):
        self.swapButton.image = pygame.image.load('CREATE Task Folder\Image Assets\GUI_images\Bag.png')#pylint: disable = anomalous-backslash-in-string
        self.swapButton.msg = "Player Inventory"

    def draw(self):
        self.swapButton.draw()

class combatGUI:
    def __init__(self, rpg):

        self.playerIcon = image(rpg, rpg.player.icon, rpg.player.name)#pylint: disable = anomalous-backslash-in-string
        self.playerIcon.iconDefault(rpg, -315)
        self.playerSquare = square(rpg)
        self.playerSquare.combatDefault(rpg, -315)
        self.playerAttack = Button(rpg, "Attack")
        self.playerAttack.combatDefault(rpg, -367.5, 0)
        self.playerDefend = Button(rpg, "Defend")
        self.playerDefend.combatDefault(rpg, -367.5, 205)
        self.playerRest = Button(rpg, "Rest")
        self.playerRest.combatDefault(rpg, -315, 0)
        self.playerUse = Button(rpg, "Use Item")
        self.playerUse.combatDefault(rpg, -315, 205)

        self.equipped_allies = rpg.player.equipped_allies

        try:
            if self.equipped_allies[0]:
                #self.ally1Icon = image(rpg, rpg.player.equipped_allies[0].icon, rpg.player.equipped_allies[0].name)
                #self.ally1Icon.iconDefault(rpg, -210)
                self.ally1Square = square(rpg)
                self.ally1Square.combatDefault(rpg, -210)
                self.ally1Attack = Button(rpg, "Attack")
                self.ally1Attack.combatDefault(rpg, -262.5, 0)
                self.ally1Defend = Button(rpg, "Defend")
                self.ally1Defend.combatDefault(rpg, -262.5, 205)
                self.ally1Rest = Button(rpg, "Rest")
                self.ally1Rest.combatDefault(rpg, -210, 0)
                self.ally1Use = Button(rpg, "Use Item")
                self.ally1Use.combatDefault(rpg, -210, 205)

            if self.equipped_allies[1]:
                #self.ally2Icon = image(rpg, rpg.player.equipped_allies[1].icon, rpg.player.equipped_allies[1].name)
                #self.ally2Icon.iconDefault(rpg, -105)
                self.ally2Square = square(rpg)
                self.ally2Square.combatDefault(rpg, -105)
                self.ally2Attack = Button(rpg, "Attack")
                self.ally2Attack.combatDefault(rpg, -157.5, 0)
                self.ally2Defend = Button(rpg, "Defend")
                self.ally2Defend.combatDefault(rpg, -157.5, 205)
                self.ally2Rest = Button(rpg, "Rest")
                self.ally2Rest.combatDefault(rpg, -105, 0)
                self.ally2Use = Button(rpg, "Use Item")
                self.ally2Use.combatDefault(rpg, -105, 205)

            if self.equipped_allies[2]:
                #self.ally3Icon = image(rpg, rpg.player.equipped_allies[2].icon, rpg.player.equipped_allies[2].name)
                #self.ally3Icon.iconDefault(rpg, 0)
                self.ally3Square = square(rpg)
                self.ally3Square.combatDefault(rpg, 0)
                self.ally3Attack = Button(rpg, "Attack")
                self.ally3Attack.combatDefault(rpg, -52.5, 0)
                self.ally3Defend = Button(rpg, "Defend")
                self.ally3Defend.combatDefault(rpg, -52.5, 205)
                self.ally3Rest = Button(rpg, "Rest")
                self.ally3Rest.combatDefault(rpg, 0, 0)
                self.ally3Use = Button(rpg, "Use Item")
                self.ally3Use.combatDefault(rpg, 0, 205)
        except:
            pass

        self.background = image(rpg, "CREATE Task Folder\Image Assets\Transparent.png", "")
        self.background.left, self.background.top = 0, 0
        self.background.width, self.background.height = 1050, 660

        self.enemyImage = image(rpg, self.enemy.image, "")
        self.enemyImage.left, self.enemyImage.top = 250, 220
        self.enemyImage.width, self.enemyImage.height = 550, 420
        self.enemyImage.transparent = True

        self.enemyInfo = Button(rpg, "{} - Level: {}".format(self.enemy.name, self.enemy.level))
        self.enemyInfo.width, self.enemyInfo.height = 550, 35
        self.enemyInfo.left, self.enemyInfo.top = 250, 80
        self.enemyInfo.clickable = False

        self.enemyHP = Button(rpg, "HP: {}/{}".format(self.enemy.hp, self.enemy.maxhp))
        self.enemyHP.width, self.enemyHP.height = 275, 35
        self.enemyHP.left, self.enemyHP.top = 250, 115
        self.enemyHP.transparent = True
        self.enemyHP.clickable = False

        self.enemyHPbar = Button(rpg, "")
        self.enemyHPbar.width, self.enemyHPbar.height = 275, 35
        self.enemyHPbar.left, self.enemyHPbar.top = 250, 115
        self.enemyHPbar.button_color = (200, 0, 0)
        self.enemyHPbar.text_color = (200, 0, 0)
        self.enemyHPbar.clickable = False

        self.enemyStamina = Button(rpg, "Stamina: {}/{}".format(self.enemy.stamina, self.enemy.stamina_max))
        self.enemyStamina.width, self.enemyStamina.height = 275, 35
        self.enemyStamina.left, self.enemyStamina.top = 525, 115
        self.enemyStamina.transparent = True
        self.enemyStamina.clickable = False

        self.enemyStaminaBar = Button(rpg, "")
        self.enemyStaminaBar.width, self.enemyStaminaBar.height = 275, 35
        self.enemyStaminaBar.left, self.enemyStaminaBar.top = 525, 115
        self.enemyStaminaBar.button_color = (0, 200, 0)
        self.enemyStaminaBar.text_color = (0, 200, 0)
        self.enemyStaminaBar.clickable = False

        self.enemyMana = Button(rpg, "Mana: {}/{}".format(self.enemy.mana, self.enemy.mana_max))
        self.enemyMana.width, self.enemyMana.height = 550, 35
        self.enemyMana.left, self.enemyMana.top = 250, 150
        self.enemyMana.transparent = True
        self.enemyMana.clickable = False

        self.enemyManaBar = Button(rpg, "")
        self.enemyManaBar.width, self.enemyManaBar.height = 550, 35
        self.enemyManaBar.left, self.enemyManaBar.top = 250, 150
        self.enemyManaBar.button_color = (0, 0, 200)
        self.enemyManaBar.text_color = (0, 0, 200)
        self.enemyManaBar.clickable = False

        self.enemyStats = False

    def mouseEvents(self, mous_pos):
        if self.enemyImage.rect.collidepoint(mous_pos):
            if self.enemyStats == False:
                self.enemyStats = True
            else:
                self.enemyStats = False

    def update(self):
        self.enemyMana.msg = "Mana: {}/{}".format(self.enemy.mana, self.enemy.mana_max)
        try:
            self.enemyManaBar.width = 275 * ((self.enemy.mana/self.enemy.mana_max))
        except Exception:
            self.enemyManaBar.width = 0
            self.enemyMana.transparent = False

        self.enemyStamina.msg = "Stamina: {}/{}".format(self.enemy.stamina, self.enemy.stamina_max)
        try:
            self.enemyStaminaBar.width = 275 * ((self.enemy.stamina/self.enemy.stamina_max))
        except Exception:
            self.enemyStaminaBar.width = 0
            self.enemyStamina.transparent = False

        self.enemyHP.msg = "HP: {}/{}".format(self.enemy.hp, self.enemy.maxhp)
        try:
            self.enemyHPbar.width = 275 * ((self.enemy.hp/self.enemy.maxhp))
        except Exception:
            self.enemyHPbar.width = 0
            self.enemyHP.transparent = False

    def draw(self):
        self.update()
        self.background.draw()
        self.enemyImage.draw()
        self.playerIcon.draw()
        self.playerAttack.draw()
        self.playerDefend.draw()
        self.playerRest.draw()
        self.playerUse.draw()
        self.playerSquare.draw()
        try:
            if self.equipped_allies[0]:
                self.ally1Attack.draw()
                self.ally1Defend.draw()
                self.ally1Rest.draw()
                self.ally1Use.draw()
                self.ally1Square.draw()

            if self.equipped_allies[1]:
                self.ally2Attack.draw()
                self.ally2Defend.draw()
                self.ally2Rest.draw()
                self.ally2Use.draw()
                self.ally2Square.draw()

            if self.equipped_allies[2]:
                self.ally3Attack.draw()
                self.ally3Defend.draw()
                self.ally3Rest.draw()
                self.ally3Use.draw()
                self.ally3Square.draw()
        except:
            pass

        if self.enemyStats == True:
            self.enemyInfo.draw()
            self.enemyHPbar.draw()
            self.enemyHP.draw()
            self.enemyStaminaBar.draw()
            self.enemyStamina.draw()
            self.enemyManaBar.draw()
            self.enemyMana.draw()

class profilePic:
    def __init__(self, rpg):
        self.profilePic = image(rpg, 'CREATE Task Folder\Image Assets\Player_Images\Commoner.png', rpg.player.profession + " EXP: {}/{}".format(rpg.player.exp, rpg.player.exp_cap))#pylint: disable = anomalous-backslash-in-string
        self.profilePic.font.set_bold(True)
        self.profilePic.width = (rpg.settings.screen_width - 1600)
        self.profilePic.height = 210
        self.profilePic.top = (rpg.settings.screen_height) - (self.profilePic.height*2)
        self.profilePic.left = 1050
        self.profilePic.border = True
        self.profilePic.textMidBottom = True

    def swapImage(self, path):
        self.profilePic.image = pygame.image.load(path)

    def draw(self):
        self.profilePic.draw()

class playerConsole:
    def __init__(self, rpg):
        self.clicked = False
        self.newSlot = 0
        self.slot1Taken = 0
        self.slot2Taken = 0
        self.slot3Taken = 0
        self.slot4Taken = 0
        self.slot5Taken = 0
        self.icon5 = image(rpg, "CREATE Task Folder\Image Assets\Transparent.png", "")
        self.icon5.consoleDefault(rpg, 0)
        self.slot5 = Button(rpg, "")
        self.slot5.consoleTextDefault(rpg, 0)
        self.icon4 = image(rpg, "CREATE Task Folder\Image Assets\Transparent.png", "")
        self.icon4.consoleDefault(rpg, 132)
        self.slot4 = Button(rpg, "")
        self.slot4.consoleTextDefault(rpg, 132)
        self.icon3 = image(rpg, "CREATE Task Folder\Image Assets\Transparent.png", "")
        self.icon3.consoleDefault(rpg, 264)
        self.slot3 = Button(rpg, "")
        self.slot3.consoleTextDefault(rpg, 264)
        self.icon2 = image(rpg, "CREATE Task Folder\Image Assets\Transparent.png", "")
        self.icon2.consoleDefault(rpg, 396)
        self.slot2 = Button(rpg, "")
        self.slot2.consoleTextDefault(rpg, 396)
        self.icon1 = image(rpg, "CREATE Task Folder\Image Assets\Transparent.png", "")
        self.icon1.consoleDefault(rpg, 528)
        self.slot1 = Button(rpg, "")
        self.slot1.consoleTextDefault(rpg, 528)

        self.arrow = image(rpg, "CREATE Task Folder\Image Assets\Transparent.png", "")
        self.arrow.width, self.arrow.height = 80, 60
        self.arrow.top, self.arrow.left = 600, 970
        self.arrow.transparent = True

    def drawConsole(self):
        self.slot1.draw()
        self.icon1.draw()
        self.slot2.draw()
        self.icon2.draw()
        self.slot3.draw()
        self.icon3.draw()
        self.slot4.draw()
        self.icon4.draw()
        self.slot5.draw()
        self.icon5.draw()
        if self.clicked == False:
            self.arrow.draw()

    def showNextText(self, rpg, nextText, nextTextPart2, nextIcon):
        self.slot5.msg = self.slot4.msg
        self.slot5.msg2 = self.slot4.msg2
        self.icon5.image = self.icon4.image
        self.slot4.msg = self.slot3.msg
        self.slot4.msg2 = self.slot3.msg2
        self.icon4.image = self.icon3.image
        self.slot3.msg = self.slot2.msg
        self.slot3.msg2 = self.slot2.msg2
        self.icon3.image = self.icon2.image
        self.slot2.msg = self.slot1.msg
        self.slot2.msg2 = self.slot1.msg2
        self.icon2.image = self.icon1.image
        self.slot1.msg = nextText
        self.slot1.msg2 = nextTextPart2
        self.icon1.image = nextIcon

        while self.clicked == False:
            self.mouseEvents(rpg)
            rpg._update_screen()
        self.clicked = False

    def mouseEvents(self, rpg):
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                mous_pos = pygame.mouse.get_pos()
                if rpg.borders.mapSquare.rect.collidepoint(mous_pos):
                    self.clicked = True

    def resetConsole(self):
        self.slot5.msg = ""
        self.slot4.msg = ""
        self.slot3.msg = ""
        self.slot2.msg = ""
        self.slot1.msg = ""
        self.slot5.msg2 = ""
        self.slot4.msg2 = ""
        self.slot3.msg2 = ""
        self.slot2.msg2 = ""
        self.slot1.msg2 = ""


import sys

def main():
    while True:
        try:
            inpt = input()
        except:
            break
        n,b,h,w = map(int,inpt.split())
        minAns = sys.maxsize
        for _ in range(0,h):
            pi = int(input())
            weekCaps = map(int,input().split())
            if pi * n <= b and pi*n < minAns :
                for weekC in weekCaps:
                    if weekC >= n :
                        minAns = pi*n
                        break
        print("stay home" if minAns==sys.maxsize else minAns)
main()

Section 1.3.3/11559 - Event Planning/Python/main.py


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

""" Update mongodb database """

import asyncio
import os
import time
import traceback
from datetime import datetime
from datetime import timedelta

import aiohttp
from aiosocks.connector import ProxyConnector, ProxyClientRequest
from hal.profile.mem import get_memory_usage, force_garbage_collect
from hal.time.profile import print_time_eta, get_time_eta
from pymongo import MongoClient

from .parsers import get_url_of_page, get_list_of_stages, \
    get_standings_of_stage, get_stage_details_from_url

LOG_FILE = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                        str(os.path.basename(__file__)).split(".")[
                            0] + "-" + str(int(time.time())) + ".log")
MIN_YEAR_PAGE = 1903  # minimum year of tour
MAX_YEAR_PAGE = 2016  # maximum year of tour

DATABASE_NAME = "letour-stages"  # name of mongodb database to use
MONGODB_CLIENT = MongoClient()  # mongodb client
# mongodb_client.drop_database(DATABASE_NAME)  # remove all previous data
DATABASE = MONGODB_CLIENT[
    DATABASE_NAME
]  # database to use
for coll in DATABASE.collection_names():
    DATABASE[coll].create_index("num", unique=True)  # set primary key

async def try_and_fetch(url, max_attempts=8, time_delay_between_attempts=1):
    """
    :param url: str
        Url to fetch
    :param max_attempts: int
        Max number of attempts to get page
    :param time_delay_between_attempts: float
        Number of seconds to wait between 2 consecutive attempts
    :return: str
        Body of page with url or null
    """

    for _ in range(max_attempts):
        try:
            conn = ProxyConnector(remote_resolve=True)
            async with aiohttp.ClientSession(
                    connector=conn,
                    request_class=ProxyClientRequest
            ) as session:
                async with session.get(
                        url,
                        proxy="socks5://127.0.0.1:9150"
                ) as response:  # use tor
                    body = await response.text(encoding='latin-1')
                    RAW_SOURCES.append({
                        "url": str(url),
                        "html": str(body)
                    })  # add url and page source

                    print_time_eta(
                        get_time_eta(
                            len(RAW_SOURCES),
                            TOTAL,
                            START_TIME
                        ),  # get ETA
                        note="Got HTML"
                    )  # debug info
                    return body
        except Exception as e:
            time.sleep(time_delay_between_attempts)
            traceback.print_exc()
            print("Cannot get url " + str(url))
            print(str(e))
    return None

async def bound_fetch(sem, url):
    """
    :param sem: Semaphore
        Asynchronous driver
    :param url: str
        Url of page to fetch
    :return: void
        Asynchronously fetches url
    """

    async with sem:
        await try_and_fetch(url, max_attempts=1, time_delay_between_attempts=0)

async def fetch_urls(list_of_urls, max_concurrent=200):
    """
    :param list_of_urls: [] of str
        List of urls to fetch
    :param max_concurrent: int
        Max number of concurrent connections
    :return: void
        Fetches url
    """

    tasks = []
    sem = asyncio.Semaphore(max_concurrent)
    for url in list_of_urls:
        task = asyncio.ensure_future(bound_fetch(sem, url))
        tasks.append(task)

    responses = asyncio.gather(*tasks)
    await responses

if __name__ == "__main__":
    START_TIME_OVERALL = time.time()

    print("\t0 - Getting URLs list")
    URLS_LIST = [get_url_of_page(year) for year in
                 range(MIN_YEAR_PAGE, MAX_YEAR_PAGE + 1)]  # get list of urls
    TOTAL = len(URLS_LIST)
    RAW_SOURCES = []  # list of raw HTML pages to parse

    print("\t1 - Downloading years pages")
    START_TIME = time.time()
    LOOP = asyncio.get_event_loop()
    FUTURE_LOOPS = asyncio.ensure_future(fetch_urls(URLS_LIST))  # fetch
    LOOP.run_until_complete(FUTURE_LOOPS)

    print("\t2 - Getting list of all stages")
    START_TIME = time.time()
    URLS_LIST = []
    TOTAL = len(RAW_SOURCES)
    for i, value in enumerate(RAW_SOURCES):
        URLS_LIST += get_list_of_stages(
            value["html"]
        )  # get list of stages in page
        print_time_eta(
            get_time_eta(
                i + 1,
                TOTAL,
                START_TIME
            ),  # get ETA
            note="Got stage list"
        )  # debug info

    print("\t3 - Downloading stages pages")
    RAW_SOURCES = []  # list of raw HTML pages to parse
    TOTAL = len(URLS_LIST)

    START_TIME = time.time()
    LOOP = asyncio.get_event_loop()
    FUTURE_LOOPS = asyncio.ensure_future(fetch_urls(URLS_LIST))  # fetch
    LOOP.run_until_complete(FUTURE_LOOPS)
    LOOP.close()

    print("\t4 - Garbage-collecting useless stuff")
    URLS_LIST = None
    force_garbage_collect()

    print("\t5- Parsing stages pages")
    TOTAL = len(RAW_SOURCES)
    START_TIME = time.time()
    for i, value in enumerate(RAW_SOURCES):
        stage_standings = get_standings_of_stage(
            value["html"]
        )
        stage_details = get_stage_details_from_url(value["url"])
        d = {
            "num": stage_details["id"],
            "standings": stage_standings
        }

        try:
            DATABASE[str(stage_details["year"])].insert_one(d)
            RAW_SOURCES[i] = None  # release memory
        except Exception as exception:
            print(str(exception))

        print_time_eta(
            get_time_eta(
                i + 1,
                TOTAL,
                START_TIME
            ),  # get ETA
            note="Saved to database"
        )  # debug info

    MONGODB_CLIENT.close()  # close mongodb connection

    END_TIME_OVERALL = time.time()
    DELTA_TIME_OVERALL = END_TIME_OVERALL - START_TIME_OVERALL
    DELTA_MEM_OVERALL = get_memory_usage()

    print(
        "Done downloading and saving data to mongodb database \"" + str(
            DATABASE_NAME) + "\". Job started at",
        datetime.fromtimestamp(START_TIME_OVERALL).strftime(
            "%Y-%m-%d %H:%M:%S"), "completed at",
        datetime.fromtimestamp(END_TIME_OVERALL).strftime("%Y-%m-%d %H:%M:%S"),
        ", took",
        str(timedelta(seconds=int(DELTA_TIME_OVERALL))), "and ~",
        str(DELTA_MEM_OVERALL), "MB to complete."
    )  # debug info


#!/usr/bin/env python
# --*coding: utf8*--
import tornado.httpserver
import tornado.ioloop
import tornado.options

import os.path
import os
import sys
from handlers import *

from tornado.options import define, options
define("port", default=5000, help="run on the given port", type=int)

class Application(tornado.web.Application):
    def __init__(self):
        self.db = conn["iub_test"]
        handlers = [
            (r"/", MainPageHandler),
            (r"/page/(\w+)", IndexHandler),
            (r"/about", AboutHandler),
            (r"/signup", RegisterHandler),
            (r"/login", LoginHandler),
            (r"/logout", LogoutHandler),
            (r"/sendMail", SendMailHandler),
            (r"/verify", VerifyHandler),
            (r"/newpost", NewPostHandler),
            (r"/post/(\w+)", ShowPostHandler),
            (r"/editPost/(\w+)", EditPostHandler),
            (r"/error", NotFoundHandler),
            (r".*", NotFoundHandler)
        ]
        settings = {
            'template_path':
                os.path.join(os.path.dirname(__file__), "templates"),
            'static_path':
                os.path.join(os.path.dirname(__file__), "static"),
            'cookie_secret':
                'loNdeMclQFe6rcCXOGXGhpCn1NFxXUaTgDQo7gLsyIY=',
            'xsrf_cookies':
                True,
            'debug': True
        }
        tornado.web.Application.__init__(self, handlers, **settings)

def main():
    reload(sys)
    sys.setdefaultencoding("utf-8")
    os.environ['TZ'] = 'US/Eastern'  # set time zone to estern time
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()


import pytest
from cicd import app as flask_app
from cicd import db

@pytest.fixture
def app():
    print('\napp is creating')
    yield flask_app

@pytest.fixture
def client(app):
    client = app.test_client()
    yield client

@pytest.fixture
def empty_db(app):
    print('\ndatabase is creating')
    db.create_all()
    yield db

    # teardown
    db.session.remove()
    db.drop_all()
    print('\ndatabase is destroying')


# Daily Programmer Challenge #172 (www.reddit.com/r/dailyprogrammer)

# Challenge Description:

# A portable bitmap is one of the oldest image formats around and grants access to very simple image creation and sharing.
# Today, you will be creating an image of this format.
# A simple PBM program can be seen here[1] (Note that we'll be creating the simplest version, a PBM, not PPM or PGM.)
# But basically the program consists of the following:
# A 2byte string (usually 'P1') denoting the file format for that PBM
# 2 integers denoting the Width and Height of our image file respectively
# And finally, our pixel data - Whether a pixel is 1 - Black or 0 - White.

# See link for details:
# http://www.reddit.com/r/dailyprogrammer/comments/2ba3g3/7212014_challenge_172_easy/

def mapFileToDict():
	letterMappings = {}
	fileName = 'TestFolder/font.txt'
	currentLetter = 'A'
	currentMapping = ''
	with open(fileName) as fontMappings:
		for line in fontMappings:
			if len(line) == 2:
				if len(currentMapping) != 0:
					letterMappings[currentLetter] = currentMapping
					currentMapping = ''
				currentLetter = line[0]
			else:
				currentMapping += ('0 ' + line)
	return letterMappings

def getLineFromString(lineNumber, string):
	line = ''
	currentLine = 0
	for char in string:
		if char == '\n':
			currentLine += 1
			continue
		if currentLine == lineNumber:
			line+=char
		if currentLine != lineNumber:
			continue
	line += ' '
	return line

def constructOutput(mappings, inputString):
	inputString = inputString.upper()
	output = ''
	for num in range(0,8):
		for char in inputString:
			if char == ' ':
				continue
			currentMap = mappings[char]
			output += getLineFromString(num, currentMap)
		output += '\n'
	return output

def writeStringToPBM(output, fileName):
	f = open('Test Folder/' + fileName + '.pbm', 'w')
	f.write(output)
	f.close()

def main():
	mapping = mapFileToDict()
	word = raw_input("Enter word of phrase: ")
	output = constructOutput(mapping, word)
	fileName = raw_input("Enter output file name: ")
	writeStringToPBM(output, fileName)

if __name__ == '__main__':
	main()
	pass


import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
from model.keypointspooling import LeftPool, TopPool, BottomPool,RightPool
from utilis.featurevisualization import FeatureVisualization
j=0

class ConvBnRelu(nn.Module):
    """docstring for BnReluConv"""
    def __init__(self, inChannels, outChannels, kernelSize=1, stride=1, padding=0):
        super(ConvBnRelu, self).__init__()
        self.inChannels = inChannels
        self.outChannels = outChannels
        self.kernelSize = kernelSize
        self.stride = stride
        self.padding = padding

        self.conv = nn.Conv2d(self.inChannels, self.outChannels, self.kernelSize, self.stride, self.padding)
        self.bn = nn.BatchNorm2d(self.outChannels)
        self.relu = nn.ReLU(inplace=True)

    def forward(self, x):
        x = self.conv(x)
        x = self.bn(x)
        x = self.relu(x)
        return x

class BnReluConv(nn.Module):
        """docstring for BnReluConv"""
        def __init__(self, inChannels, outChannels, kernelSize = 1, stride = 1, padding = 0):
                super(BnReluConv, self).__init__()
                self.inChannels = inChannels
                self.outChannels = outChannels
                self.kernelSize = kernelSize
                self.stride = stride
                self.padding = padding

                self.bn = nn.BatchNorm2d(self.inChannels)
                self.conv = nn.Conv2d(self.inChannels, self.outChannels, self.kernelSize, self.stride, self.padding)
                self.relu = nn.ReLU(inplace=True)

        def forward(self, x):
                x = self.bn(x)
                x = self.relu(x)
                x = self.conv(x)
                return x

class ConvBlock(nn.Module):
        """docstring for ConvBlock"""
        def __init__(self, inChannels, outChannels):
                super(ConvBlock, self).__init__()
                self.inChannels = inChannels
                self.outChannels = outChannels
                self.outChannelsby2 = outChannels//2

                self.cbr1 = BnReluConv(self.inChannels, self.outChannelsby2, 1, 1, 0)
                self.cbr2 = BnReluConv(self.outChannelsby2, self.outChannelsby2, 3, 1, 1)
                self.cbr3 = BnReluConv(self.outChannelsby2, self.outChannels, 1, 1, 0)

        def forward(self, x):
                x = self.cbr1(x)
                x = self.cbr2(x)
                x = self.cbr3(x)
                return x

class SkipLayer(nn.Module):
        """docstring for SkipLayer"""
        def __init__(self, inChannels, outChannels):
                super(SkipLayer, self).__init__()
                self.inChannels = inChannels
                self.outChannels = outChannels
                if (self.inChannels == self.outChannels):
                        self.conv = None
                else:
                        self.conv = nn.Conv2d(self.inChannels, self.outChannels, 1)

        def forward(self, x):
                if self.conv is not None:
                        x = self.conv(x)
                return x

class Residual(nn.Module):
        """docstring for Residual"""
        def __init__(self, inChannels, outChannels):
                super(Residual, self).__init__()
                self.inChannels = inChannels
                self.outChannels = outChannels
                self.cb = ConvBlock(inChannels, outChannels)
                self.skip = SkipLayer(inChannels, outChannels)

        def forward(self, x):
                out = 0
                out = out + self.cb(x)
                out = out + self.skip(x)
                return out

class FeaEnhance(nn.Module):
        """docstring for Residual"""
        def __init__(self, inChannels, outChannels):
                super(FeaEnhance, self).__init__()
                super(FeaEnhance, self).__init__()
                self.inChannels = inChannels
                self.outChannels = outChannels
                self.outChannelsby2 = outChannels // 2

                # s1
                self.atrousconv1 = nn.Conv2d(self.inChannels, self.outChannelsby2, 3, stride=2, dilation=2, padding=2)
                self.maxp1 = nn.MaxPool2d(2, 2)
                self.conv1 = nn.Conv2d(self.inChannels, self.outChannelsby2, 1, 1, 0)
                self.bnrc1 = BnReluConv(self.inChannels, self.outChannelsby2, 1, 1, 0)

                # s2
                self.maxp2 = nn.MaxPool2d(2, 2)
                self.upsampling1 = nn.Upsample(scale_factor=2)
                self.maxp3 = nn.MaxPool2d(2, 2)
                self.upsampling2 = nn.Upsample(scale_factor=2)

                self.bnrc2 = BnReluConv(self.outChannelsby2, self.outChannelsby2, 3, 1, 1)
                self.atrousconv2 = nn.Conv2d(self.outChannelsby2, self.outChannelsby2, 3, stride=4, dilation=2,
                                             padding=2)
                self.maxp4 = nn.MaxPool2d(4, 4)

                # s3
                self.upsampling4 = nn.Upsample(scale_factor=4)
                self.conv2 = nn.Conv2d(self.outChannelsby2, self.outChannels, 1, 1, 0)
                self.upsampling5 = nn.Upsample(scale_factor=4)
                self.conv3 = nn.Conv2d(self.outChannelsby2, self.outChannels, 1, 1, 0)

                self.bnrc3 = BnReluConv(self.outChannelsby2, self.outChannels, 1, 1, 0)

                self.skip = SkipLayer(inChannels, outChannels)

        def forward(self, x):
            # s1
            out1 = self.atrousconv1(x)  # 240*320*128
            out2 = self.maxp1(x)  # 120*160*128
            out2 = self.conv1(out2)
            out3 = self.bnrc1(x)

            # s2
            out1s2_1 = self.maxp2(out1)
            out1s2_2 = self.upsampling1(out1)

            out2s2_1 = self.maxp3(out2)
            out2s2_2 = self.upsampling2(out2)

            out3s2_1 = self.atrousconv2(out3)
            out3s2_2 = self.maxp4(out3)
            out3s2_3 = self.bnrc2(out3)

            out1s2 = out1s2_1 + out3s2_1
            out2s2 = out2s2_1 + out3s2_2
            out3s2 = out3s2_3 + out1s2_2 + out2s2_2

            # s3
            out1s3 = self.upsampling4(out1s2)
            out1s3 = self.conv2(out1s3)

            out2s3 = self.upsampling5(out2s2)
            out2s3 = self.conv3(out2s3)

            out3s3 = self.bnrc3(out3s2)

            out = out1s3 + out3s3 + out2s3
            out = out + self.skip(x)
            return out

class Feaenhance_2(nn.Module):
        """docstring for Feaenhance"""
        def __init__(self, inChannels, outChannels):
                super(Feaenhance_2, self).__init__()
                self.inChannels = inChannels
                self.outChannels = outChannels
                # self.outChannelsby2 = outChannels // 2

                #s1
                self.bnrc1 = BnReluConv(self.inChannels, self.outChannels, 1, 1, 0)

                #s2
                self.bnrc2 = BnReluConv(self.outChannels, self.outChannels, 3, 1, 1)
                self.maxp1 = nn.MaxPool2d(2, 2)
                self.maxp2 = nn.MaxPool2d(4, 4)

                #s3
                self.bnrc3 = BnReluConv(self.outChannels, self.outChannels, 1, 1, 0)
                self.maxp3 = nn.MaxPool2d(2, 2)
                self.maxp4 = nn.MaxPool2d(4, 4)

                self.bnrc4 = BnReluConv(self.outChannels, self.outChannels, 3, 1, 1)
                self.conv1 = nn.Conv2d(self.outChannels, self.outChannels, 1, 1, 0)
                self.upsampling1 = nn.Upsample(scale_factor=2)
                self.maxp5 = nn.MaxPool2d(2, 2)

                self.bnrc5 = BnReluConv(self.outChannels, self.outChannels, 3, 1, 1)
                self.conv2 =  nn.Conv2d(self.outChannels, self.outChannels, 1, 1, 0)
                self.upsampling2= nn.Upsample(scale_factor=4)
                self.upsampling3 = nn.Upsample(scale_factor=2)

                self.upsampling4 = nn.Upsample(scale_factor=2)
                self.upsampling5 = nn.Upsample(scale_factor=4)

                self.conv3 =  nn.Conv2d(self.outChannels * 3, self.outChannels, 1, 1, 0)

        def forward(self, x):
            out1 = self.bnrc1(x)

            out2 = self.bnrc2(out1)
            out2_1 = self.maxp1(out1)
            out2_2 = self.maxp2(out1)
            # out2_1 = F.max_pool2d(out1, (2,2))
            # out2_2 =  F.max_pool2d(out1, (4,4))

            out3 = self.bnrc3(out2)
            out3_1 = self.maxp3(out2)
            out3_2 = self.maxp4(out2)

            out4 = self.bnrc4(out2_1)
            out4_1 = self.upsampling1(self.conv1(out2_1))
            out4_2 = self.maxp5(self.conv1(out2_1))

            out5 = self.bnrc5(out2_2)
            out5_1 = self.upsampling2(self.conv2(out2_2))
            out5_2 = self.upsampling3(self.conv2(out2_2))

            out3 = out3 + out4_1 + out5_1
            out4 = out4 + out3_1 + out5_2
            out5 = out5 + out3_2 + out4_2

            out4 = self.upsampling4(out4)
            out5 = self.upsampling5(out5)

            out = torch.cat((out3, out4), dim=1)
            out = torch.cat((out, out5), dim=1)

            out = self.conv3(out)
            return out

class MeanFieldUpdate(nn.Module):
    """
    Meanfield updating

    """

    def __init__(self, inchannels, outchannels): #512，512，512
        super(MeanFieldUpdate, self).__init__()

        self.attenmap = nn.Conv2d(in_channels=inchannels, out_channels=outchannels, kernel_size=3, stride=1, padding=1)# K
        self.attenmap_2 = nn.Conv2d(in_channels=inchannels, out_channels=outchannels, kernel_size=3, stride=1, padding=1)#K

        self.attenmap_g = nn.Conv2d(in_channels=inchannels, out_channels=outchannels, kernel_size=3, stride=1, padding=1)
        self.attenmap_a = nn.Conv2d(in_channels=inchannels, out_channels=outchannels, kernel_size=3, stride=1, padding=1)

        self.norm_atten_a = nn.Sigmoid()
        self.norm_atten_g = nn.Sigmoid()

        self.message_f = nn.Conv2d(in_channels=inchannels, out_channels=outchannels, kernel_size=3,
                                   stride=1, padding=1)

        self.message_f_2 = nn.Conv2d(in_channels=inchannels, out_channels=outchannels, kernel_size=3,
                                   stride=1, padding=1)
        #update y_s
        self.update3 = nn.Conv2d(in_channels=inchannels, out_channels=outchannels, kernel_size=3,
                                   stride=1, padding=1)

        self.update3_2 = nn.Conv2d(in_channels=inchannels, out_channels=outchannels, kernel_size=3,  stride=1, padding=1)
    def forward(self, x_s, x_S):   # s and S scale
        # update attention map
        # a_s = torch.cat((x_s, x_S), dim=1)
        # a_s = self.atten_f(a_s)
        # a_s = self.norm_atten_f(a_s)
        ori_x_S = x_S

        ori_x_S = self.attenmap(ori_x_S)
        g_s = ori_x_S.mul(x_s)

        x_S = self.attenmap_2(x_S)
        a_s_0 = x_S.mul(x_s)

        g_s_1 = self.attenmap_g(a_s_0) #(A,G)
        a_s_1 = self.attenmap_a(g_s) #(A,G)

        g_s = self.norm_atten_g(g_s+g_s_1)
        a_s = self.norm_atten_a(a_s_0+a_s_1)

        # update the last scale feature map y_S
        y_s = self.message_f(x_s)
        y_S = y_s.mul(g_s)

        y_s_a = self.message_f_2(x_s)
        y_S_a = y_s_a.mul(a_s)

        y_S = x_S + y_S + y_S_a # eltwise sum

        #update the y_s
        y_S_1 = self.update3(y_S)
        y_s = y_S_1.mul(g_s)  # production

        y_S_a = self.update3_2(y_S)
        y_s_a = y_S_a.mul(a_s)

        y_s = x_s + y_s + y_s_a # eltwise sum

        return y_S, y_s

class attentionCRF(nn.Module):
    def __init__(self, inChannels, outChannels):
        super(attentionCRF, self).__init__()
        # the first meanfield updating

        self.meanFieldUpdate1_1 = MeanFieldUpdate(inChannels, outChannels)
        self.meanFieldUpdate1_2 = MeanFieldUpdate(inChannels, outChannels)
        self.meanFieldUpdate1_3 = MeanFieldUpdate(inChannels, outChannels)
        self.meanFieldUpdate1_4 = MeanFieldUpdate(inChannels, outChannels)

    def forward(self, lpool, tpool, rpool, bpool, p):
        # five meanfield updating

        y_S, y_s_1 = self.meanFieldUpdate1_1(lpool, p)
        y_S, y_s_2 = self.meanFieldUpdate1_2(tpool, y_S)
        y_S, y_s_3 = self.meanFieldUpdate1_3(rpool, y_S)
        y_S, y_s_4 = self.meanFieldUpdate1_4(bpool, y_S)

        for i  in range(1):
            y_S, y_s_1 = self.meanFieldUpdate1_1(y_s_1, y_S)
            y_S, y_s_2 = self.meanFieldUpdate1_2(y_s_2, y_S)
            y_S, y_s_3 = self.meanFieldUpdate1_3(y_s_3, y_S)
            y_S, y_s_3 = self.meanFieldUpdate1_4(y_s_4, y_S)

        return y_S

class keypointspool(nn.Module):
    def __init__(self, inChannels, outChannels):
        super(keypointspool, self).__init__()
        self.p1_conv1 = ConvBnRelu(inChannels, outChannels, 1) #3*3con,bn,relu
        self.p2_conv1 = ConvBnRelu(inChannels, outChannels, 1)
        self.p3_conv1 = ConvBnRelu(inChannels, outChannels, 1) #3*3con,bn,relu
        self.p4_conv1 = ConvBnRelu(inChannels, outChannels, 1)

        self.p_conv1 = nn.Conv2d(outChannels, outChannels, (3, 3), padding=(1, 1), bias=False)
        self.p_bn1   = nn.BatchNorm2d(outChannels)

        self.conv1 = nn.Conv2d(outChannels, outChannels, (1, 1), bias=False)
        self.bn1   = nn.BatchNorm2d(outChannels)
        self.relu1 = nn.ReLU(inplace=True)

        self.conv2 = ConvBnRelu(outChannels, outChannels, 1)

        self.pool1 = LeftPool()
        self.pool2 = TopPool()
        self.pool3 = RightPool()
        self.pool4 = BottomPool()

        self.atCRF = attentionCRF(inChannels, outChannels)

    def forward(self, x):

        # pool 1
        p1_conv1 = self.p1_conv1(x)
        pool1    = self.pool1(p1_conv1)

        # pool 2
        p2_conv1 = self.p2_conv1(x)
        pool2    = self.pool2(p2_conv1)

        # pool 3
        p3_conv1 = self.p3_conv1(x)
        pool3 = self.pool3(p1_conv1)

        # pool 4
        p4_conv1 = self.p4_conv1(x)
        pool4 = self.pool4(p2_conv1)

		# attenionCRF
        confusionfea = self.atCRF(pool1, pool2, pool3, pool4)
        p_conv1 = self.p_conv1(confusionfea)
        p_bn1   = self.p_bn1(p_conv1)

        # pool 1 + pool 2
        # p_conv1 = self.p_conv1(pool1 + pool2)
        # p_bn1   = self.p_bn1(p_conv1)

        conv1 = self.conv1(x)
        bn1   = self.bn1(conv1)
        relu1 = self.relu1(p_bn1 + bn1)

        conv2 = self.conv2(relu1)
        return conv2

class SSMixer(nn.Module):
    def __init__(self, inChannels, outChannels):
        super(SSMixer, self).__init__()
        self.p1_conv1 = ConvBnRelu(inChannels, outChannels, 1) #3*3con,bn,relu
        self.p2_conv1 = ConvBnRelu(inChannels, outChannels, 1)
        self.p3_conv1 = ConvBnRelu(inChannels, outChannels, 1) #3*3con,bn,relu
        self.p4_conv1 = ConvBnRelu(inChannels, outChannels, 1)
        self.p5_conv1 = ConvBnRelu(inChannels, outChannels, 1)

        self.conv2 = ConvBnRelu(inChannels, outChannels, 1)

        self.pool1 = LeftPool()
        self.pool2 = TopPool()
        self.pool3 = RightPool()
        self.pool4 = BottomPool()

        self.atCRF = attentionCRF(inChannels, outChannels)

    def forward(self, x):
        global j
        # pool 1
        p1_conv1 = self.p1_conv1(x)
        pool1    = self.pool1(p1_conv1)

        # pool 2
        p2_conv1 = self.p2_conv1(x)
        pool2    = self.pool2(p2_conv1)

        # pool 3
        p3_conv1 = self.p3_conv1(x)
        pool3 = self.pool3(p1_conv1)

        # pool 4
        p4_conv1 = self.p4_conv1(x)
        pool4 = self.pool4(p2_conv1)

        p5 = self.p5_conv1(x)

        # feavis = FeatureVisualization(pool1, j)  # visualize enhanced structure-context features for each point
        # feavis.save_feature_to_img()
        # j=j+1

		# attenionCRF
        confusionfea = self.atCRF(pool1, pool2, pool3, pool4,p5)

        conv2 = self.conv2(confusionfea)
        return conv2

        # return conv2, pool1, pool2, pool3, pool4, p5

class myUpsample(nn.Module):
     def __init__(self):
         super(myUpsample, self).__init__()
         pass
     def forward(self, x):
         return x[:, :, :, None, :, None].expand(-1, -1, -1, 2, -1, 2).reshape(x.size(0), x.size(1), x.size(2)*2, x.size(3)*2)


'''
@Descripttion:
@version:
@Author: JackZhang
@Date: 2020-03-31 20:48:47
@LastEditors: JackZhang
@LastEditTime: 2020-04-01 13:12:22
'''
# import module.
import pygame, sys, os
from pygame import Color

# set-up path
game_path = os.path.dirname(__file__)
img_path = os.path.join(game_path, "img")
# print(game_path, img_path)

# set up custom game window size.
window_size = width, height = 336, 607

# initialize the pygame and create the main window.
pygame.init()
pygame.display.set_caption("02-Show Your First Sprite")
screen = pygame.display.set_mode(window_size)

# set frame-per-second and the clock.
fps = 30
clock = pygame.time.Clock()

# class Player extends class pygame.sprite.Sprite
class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.image.load(os.path.join(img_path, "player.png")).convert_alpha()
        self.rect = self.image.get_rect()
        self.rect.center = (width/2, height/2)

# you should add all the sprites you want to show on the screen to the pygame.sprite.Group.
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)

# a flag.
running = True

# game's main loop.
while running:
    # keep fps
    clock.tick(fps)

    # process event.
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

    # update
    all_sprites.update()
    # draw and render
    screen.fill(Color("grey"))
    all_sprites.draw(screen)

    # flush screen.
    pygame.display.flip()
    # or pygame.display.update()

# quit game.
pygame.quit()
# sys.exit()


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

import socket
import sys
import os

# Create a UDS socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)

# Connect the socket to the port where the server is listening
server_address = '/tmp/borderAgent'
client_address = '/tmp/borderTest'

# Make sure the socket does not already exist
try:
	os.unlink(client_address)
except OSError:
	if os.path.exists(client_address):
		raise

print( 'connecting to %s' % server_address)
try:
	sock.bind(client_address)
except (socket.error) as msg:
	print(msg)
	sys.exit(1)
try:

	# Send data
	message = b'This is the message.  It will be repeated.'
	print(  message)
	sock.sendto(message,server_address)

	amount_received = 0
	amount_expected = len(message)

	while amount_received < amount_expected:
		data = sock.recv(4096)
		amount_received += len(data)
		print( 'received "%s"' % data)

finally:
	print( 'closing socket')
	sock.close()


#!/usr/bin/env python

import argparse
import sys
from collections import Counter

import faiss
import networkx as nx
import numpy as np
from chinese_whispers import chinese_whispers, aggregate_clusters

from utils import triples, grouper, word_vectors, words_vec

parser = argparse.ArgumentParser()
parser.add_argument('--neighbors', '-n', type=int, default=10)
parser.add_argument('--min-weight', type=float, default=0.)
parser.add_argument('--pickle', type=argparse.FileType('wb'))
parser.add_argument('triples', type=argparse.FileType('r', encoding='UTF-8'))
group = parser.add_mutually_exclusive_group()
group.add_argument('--w2v', default=None, type=argparse.FileType('rb'))
group.add_argument('--pyro', default=None, type=str)
args = parser.parse_args()

w2v = word_vectors(args, lambda args: parser.error('Please set the --w2v or --pyro option.'))

spos, _ = triples(args.triples, min_weight=args.min_weight, build_index=False)

vocabulary = {word for triple in spos for word in (triple.subject, triple.predicate, triple.object)}

vectors = {}

for words in grouper(vocabulary, 512):
    vectors.update(words_vec(w2v, words))

spos = [triple for triple in spos if
        triple.subject in vectors and triple.predicate in vectors and triple.object in vectors]

# noinspection PyUnboundLocalVariable
X, index2triple = np.empty((len(spos), w2v.vector_size * 3), 'float32'), {}

for i, triple in enumerate(spos):
    X[i] = np.concatenate((vectors[triple.subject], vectors[triple.predicate], vectors[triple.object]))
    index2triple[i] = (triple.subject, triple.predicate, triple.object)

knn = faiss.IndexFlatIP(X.shape[1])
knn.add(X)

G, maximal_distance = nx.Graph(), -1

for slice in grouper(range(X.shape[0]), 2048):
    slice = [j for j in slice if j is not None]

    D, I = knn.search(X[slice, :], args.neighbors + 1)

    last = min(slice)
    print('%d / %d' % (last, X.shape[0]), file=sys.stderr)

    for i, (_D, _I) in enumerate(zip(D, I)):
        source = index2triple[last + i]
        words = Counter()

        for d, j in zip(_D.ravel(), _I.ravel()):
            if last + i != j:
                words[index2triple[j]] = float(d)

        for target, distance in words.most_common(args.neighbors):
            G.add_edge(source, target, weight=distance)
            maximal_distance = distance if distance > maximal_distance else maximal_distance

for _, _, d in G.edges(data=True):
    d['weight'] = maximal_distance / d['weight']

if args.pickle is not None:
    import pickle

    pickle.dump(list(G.edges(data=True)), args.pickle, protocol=3)
    sys.exit(0)

chinese_whispers(G, weighting='top', iterations=20)
clusters = aggregate_clusters(G)

for label, cluster in sorted(aggregate_clusters(G).items(), key=lambda e: len(e[1]), reverse=True):
    print('# Cluster %d\n' % label)

    predicates = {predicate for predicate, _, _ in cluster}
    subjects = {subject for _, subject, _ in cluster}
    objects = {object for _, _, object in cluster}

    print('Predicates: %s' % ', '.join(predicates))
    print('Subjects: %s' % ', '.join(subjects))
    print('Objects: %s\n' % ', '.join(objects))


"""Practice with dictionaries."""

__author__ = "730389910"

# Define your functions below

# Invert function: by giving values, returns a flip of the values

def invert(first: dict[str, str]) -> dict[str, str]:
    """Inverts a dictionary."""
    switch: dict[str, str] = {}
    for key in first:
        value: str = first[key]
        switch[value] = key
    return switch

# Favorite color: sort different colors based on what people like the most

def favorite_color(colors: dict[str, str]) -> str:
    """Gives the most frequently listed color."""
    favorite: str = ""
    for key in colors:
        value: str = colors[key]
        favorite = value
    return favorite

# Count: shows how many times a certain key was given

def count(find: list[str]) -> dict[str, int]:
    """Counts how many times a string is presented."""
    i: int = 0
    final: dict[str, int] = {}

    while i < len(find):
        key = find[i]
        if key in final:
            final[key] += 1
        else:
            final[key] = 1
        i += 1
    return final

f: str = "blue"
g: str = "silver"
h: str = "gold"
link: list[str] = ["fish", "bird", "dog", "fish"]
print(invert({g: f}))
print(favorite_color({"Alex": f, "Jeff": f, "Joe": g}))
print(count(link))


from django.urls import path, re_path, include
from rest_framework import routers
from . import views
from .viewsets import PostViewSet, PostImageViewSet, UserViewSet

app_name = 'django_pipes_blog'

# django rest framework url router registration
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'postimages', PostImageViewSet)
router.register(r'posts', PostViewSet)

urlpatterns = [
    # django rest framework urls
    re_path(r'^api/', include(router.urls)),
    re_path(r'^api-auth/', include('rest_framework.urls')),

    re_path(r'^$', views.IndexView.as_view(), name='index'),
    re_path(r'^(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<slug>[\w\-\%]+)/$',
        views.SinglePostView.as_view(),
        name='post'
    ),
    re_path(r'(?P<year>\d{4})/(?P<month>\d{1,2})/$',
        views.MultiPostView.as_view(),
        name='multi_post'
    ),
    path('post/new/', views.NewPostView.as_view(), name='new_post'),
    path('post/<slug:slug>/', views.SinglePostView.as_view(), name='post_slug'),
    path('post/<int:pk>/preview/', views.SinglePostView.as_view(), name='preview_post'),
    path('post/<int:pk>/edit/', views.EditPostView.as_view(), name='edit_post'),
    path('tags/<str:tags>/', views.SearchTagsView.as_view(), name='tags'),
    path('post/<int:pk>/unpublished/', views.AllPosts.as_view(), name='unpublished'),
    re_path(r'^post/(?P<pk>\d+)/(?P<all>all)/$', views.AllPosts.as_view(), name='all_posts'),
]


class DNA:
    """Class representing DNA as a string sequence."""

    basecomplement = {'A': 'T', 'C': 'G', 'T': 'A', 'G': 'C'}

    codon2aa = {"TTT":"F","TTC":"F","TTA":"L","TTG":"L","TCT":"S","TCC":"S",
                "TCA":"S","TCG":"S","TAT":"Y","TAC":"Y","TAA":"*","TAG":"*",
                "TGT":"C","TGC":"C","TGA":"*","TGG":"W","CTT":"L","CTC":"L",
                "CTA":"L","CTG":"L","CCT":"P","CCC":"P","CCA":"P","CCG":"P",
                "CAT":"H","CAC":"H","CAA":"Q","CAG":"Q","CGT":"R","CGC":"R",
                "CGA":"R","CGG":"R","ATT":"I","ATC":"I","ATA":"I","ATG":"M",
                "ACT":"T","ACC":"T","ACA":"T","ACG":"T","AAT":"N","AAC":"N",
                "AAA":"K","AAG":"K","AGT":"S","AGC":"S","AGA":"R","AGG":"R",
                "GTT":"V","GTC":"V","GTA":"V","GTG":"V","GCT":"A","GCC":"A",
                "GCA":"A","GCG":"A","GAT":"D","GAC":"D","GAA":"E","GAG":"E",
                "GGT":"G","GGC":"G","GGA":"G","GGG":"G"}

    def __init__(self, s):
        """Create DNA instance initialized to string s."""
        self.seq = s

    def transcribe(self):
        """Return as rna string."""
        return self.seq.replace('T', 'U')

    def reverse(self):
        """Return dna string in reverse order."""
        letters = list(self.seq)
        letters.reverse()
        return ''.join(letters)

    def complement(self):
        """Return the complementary dna string."""
        letters = list(self.seq)
        letters = [self.basecomplement[base] for base in letters]
        return ''.join(letters)

    def reversecomplement(self):
        """Return the reverse of complement of the dna string."""
        letters = list(self.seq)
        letters.reverse()
        letters = [self.basecomplement[base] for base in letters]
        return ''.join(letters)

    def gc(self):
        """Return the % of dna composed of G+C."""
        s = self.seq
        gc = s.count('G') + s.count('C')
        return gc * 100.0 / len(s)

    def codons(self):
        """Return list of codons for the dna string,"""
        s = self.seq
        end = len(s) - (len(s) % 3) - 1
        codons = [s[i:i+3] for i in range(0, end, 3)]
        return codons

    def translate(self):
        """Return amino acid sequence translating dna seq."""
        s = self.seq
        codons = self.codons()
        aa = [self.codon2aa[aa] for aa in codons]
        return ''.join(aa)


# 이코테[화성 탐사]
import heapq

INF=int(1e9)
dx=[1,0,0,-1]
dy=[0,-1,1,0]

for tc in range(int(input())):
  n=int(input())
  graph=[list(map(int,input().split())) for _ in range(n)]

  distance=[[INF]*n for _ in range(n)]
  x,y=0,0
  q=[(graph[x][y],x,y)]
  distance[x][y]=graph[x][y]

  while q:
    dis,x,y=heapq.heappop(q)

    if distance[x][y]<dis:
      continue

    for i in range(4):
      nx=x+dx[i]
      ny=y+dy[i]

      if nx>=0 and nx<n and ny>=0 and ny<n:

        cost=dis+graph[nx][ny]

        if cost<distance[nx][ny]:
          distance[nx][ny]=cost
          heapq.heappush(q,(cost,nx,ny))
  print(distance[n-1][n-1])


# -*- coding: utf-8 -*-
# Copyright 2018 Mobicage NV
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# @@license_version:1.3@@

import datetime

from plugins.limburg_net_trash.plugin_utils import get_epoch_from_datetime
from mcfw.properties import long_property, unicode_property, typed_property
from mcfw.serialization import register, deserializer, ds_unicode, serializer, s_unicode, s_long, get_list_serializer, \
    ds_long, get_list_deserializer, List

class StreetTO(object):
    number = long_property('1')
    name = unicode_property('2')

    @classmethod
    def fromObj(cls, obj):
        to = cls()
        to.number = obj["nr"]
        to.name = obj["s"]
        return to

@serializer
def _s_street_to_stream(stream, to):
    s_long(stream, 1)
    s_long(stream, to.number)
    s_unicode(stream, to.name)

@deserializer
def _ds_street_to_stream(stream):
    to = StreetTO()
    version = ds_long(stream)
    to.number = ds_long(stream)
    to.name = ds_unicode(stream)
    return to

register(StreetTO, _s_street_to_stream, _ds_street_to_stream)

@deserializer
def _ds_street_to(stream, version):
    to = StreetTO()
    to.number = ds_long(stream)
    to.name = ds_unicode(stream)
    return to

@serializer
def _s_street_to(stream, to):
    s_long(stream, to.number)
    s_unicode(stream, to.name)

def _s_street_list(stream, l):
    s_long(stream, 1)
    f = get_list_serializer(_s_street_to)
    f(stream, l)

def _ds_street_list(stream):
    l = list()
    version = ds_long(stream)
    f = get_list_deserializer(_ds_street_to, True)
    for to in f(stream, version):
        l.append(to)
    return l

register(List(StreetTO), _s_street_list, _ds_street_list)

class HouseTO(object):
    number = long_property('1')
    bus = unicode_property('2')

    @classmethod
    def fromObj(cls, obj):
        to = cls()
        to.number = obj["h"]
        to.bus = obj["t"]
        return to

@deserializer
def _ds_house_to(stream, version):
    to = HouseTO()
    to.number = ds_long(stream)
    to.bus = ds_unicode(stream)
    return to

@serializer
def _s_house_to(stream, to):
    s_long(stream, to.number)
    s_unicode(stream, to.bus)

def _s_house_list(stream, l):
    s_long(stream, 1)
    f = get_list_serializer(_s_house_to)
    f(stream, l)

def _ds_house_list(stream):
    l = list()
    version = ds_long(stream)
    f = get_list_deserializer(_ds_house_to, True)
    for to in f(stream, version):
        l.append(to)
    return l

register(List(HouseTO), _s_house_list, _ds_house_list)

CURRENT_ACTIVITY_VERSION = 1
class ActivityTO(object):
    number = long_property('1')
    name = unicode_property('2')

    @classmethod
    def fromObj(cls, obj):
        to = cls()
        to.number = obj["nr"]
        to.name = obj["s"]
        if to.name == u"grofvuil":
            to.name = u"grofvuil (enkel op aanvraag)"

        return to

@deserializer
def _ds_activity_to(stream, version):
    to = ActivityTO()
    to.number = ds_long(stream)
    to.name = ds_unicode(stream)
    return to

@serializer
def _s_activity_to(stream, to):
    s_long(stream, to.number)
    s_unicode(stream, to.name)

def _s_activity_list(stream, l):
    s_long(stream, CURRENT_ACTIVITY_VERSION)
    f = get_list_serializer(_s_activity_to)
    f(stream, l)

def _ds_activity_list(stream):
    l = list()
    version = ds_long(stream)
    f = get_list_deserializer(_ds_activity_to, True)
    for to in f(stream, version):
        l.append(to)
    return l

register(List(ActivityTO), _s_activity_list, _ds_activity_list)

class CollectionTO(object):
    epoch = long_property('1')
    year = long_property('2')
    month = long_property('3')
    day = long_property('4')
    activity = typed_property('5', ActivityTO, False)

    @classmethod
    def fromObj(cls, obj, activity):
        to = cls()
        d = obj["d"].split("/")
        to.year = long(d[2])
        to.month = long(d[1])
        to.day = long(d[0])
        d = datetime.date(to.year, to.month, to.day)
        to.epoch = get_epoch_from_datetime(d)
        to.activity = activity
        return to

@deserializer
def _ds_collection_to(stream, version):
    to = CollectionTO()
    to.epoch = ds_long(stream)
    to.year = ds_long(stream)
    to.month = ds_long(stream)
    to.day = ds_long(stream)
    _version = ds_long(stream)
    to.activity = _ds_activity_to(stream, _version)
    return to

@serializer
def _s_collection_to(stream, to):
    s_long(stream, to.epoch)
    s_long(stream, to.year)
    s_long(stream, to.month)
    s_long(stream, to.day)
    s_long(stream, CURRENT_ACTIVITY_VERSION)
    _s_activity_to(stream, to.activity)

def _s_collection_list(stream, l):
    s_long(stream, 1)
    f = get_list_serializer(_s_collection_to)
    f(stream, l)

def _ds_collection_list(stream):
    l = list()
    version = ds_long(stream)
    f = get_list_deserializer(_ds_collection_to, True)
    for to in f(stream, version):
        l.append(to)
    return l

register(List(CollectionTO), _s_collection_list, _ds_collection_list)


from tkinter import *
import tkinter.ttk as ttk
import configparser
import json
import os

class ConfigValuesSample(ttk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.label_values="label"
        self.fruit_values=""
        self.load_config()
        self.create_widgets()
        self.pack()

    """
    config.iniから読み取った値を各Widgetのオプションに与える
    """
    def create_widgets(self):
        label = ttk.Label(text=self.label_values)
        label.pack()
        combo = ttk.Combobox(self,values=self.fruit_values)
        combo.pack()

    """
    このファイルのパスからconfig.iniファイルのパスを取得し、UTF-8で読み込む
    json.loadsを使用すること(loadではない)
    """
    def load_config(self):
        path =os.path.join(os.path.dirname(__file__),"config/config.ini")
        config = configparser.ConfigParser()
        config.read(path,"UTF-8")
        self.label_values = config["settings"]["label"]
        self.fruit_values=json.loads(config["settings"]["fruitvalues"])

if __name__ == '__main__':
    master = Tk()
    master.title("ConfigValuesSample")
    master.geometry("300x200")
    ConfigValuesSample(master)
    master.mainloop()


# coding:utf-8

import json
import math
import re
import httpcon
import stocksexchange
import hitbtc
import coinmarketcap
import mercatox
from decimal import *
from logging import basicConfig, getLogger, DEBUG, INFO

# ロギング
basicConfig(level=DEBUG)
logger = getLogger(__name__)

# jsonデコード時の文字コード
utf8 = 'utf-8'
# 正規表現
pattern = r'([+-]?[0-9]+\.?[0-9]*)'

# def getRate_BTCJPY_zaif():
#     '''
#     zaifのBTC/JPYレートを取得する
#     '''
#     result = Decimal(0)
#     response = httpcon.getJsonResponse(
#         'https://api.zaif.jp/api/1/last_price/btc_jpy')
#     if response is not None and 'last_price' in response:
#         result = Decimal(response['last_price'])
#         logger.debug('getRate_BTCJPY_zaif() result:{0}'.format(result))
#     return result

# def getRate_BTCJPY_bf():
#     '''
#     bitflyerのBTC/JPYレートを取得する
#     '''
#     result = Decimal(0)
#     response = httpcon.getJsonResponse('https://bitflyer.jp/api/echo/price')
#     if response is not None and 'mid' in response:
#         result = Decimal(response['mid'])
#         logger.debug('getRate_BTCJPY_bf() result:{0}'.format(result))
#     return result

# def getRate_BTCJPY_cc():
#     '''
#     coincheckのBTC/JPYレートを取得する
#     '''
#     result = Decimal(0)
#     response = httpcon.getJsonResponse(
#         'https://coincheck.com/api/rate/btc_jpy')
#     if response is not None and 'rate' in response:
#         result = Decimal(response['rate'])
#         logger.debug('getRate_BTCJPY_cc() result:{0}'.format(result))
#     return result

def getRate_NANJBTC():
    '''
    coinexchange.ioのNANJ/BTCレートを取得する
    '''
    lastprice = Decimal(0)
    response = httpcon.getJsonResponse(
        'https://www.coinexchange.io/api/v1/getmarketsummary?market_id=748')
    if response is not None and 'result' in response:
        result = response['result']
        if 'LastPrice' in result:
            lastprice = Decimal(result['LastPrice'])
        logger.debug('getRate_NANJBTC() lastprice:{:.8f}'.format(lastprice))
    return lastprice

# def getRate_USDTJPY():
#     '''
#     CoinGeckoからUSDT/JPYレートを取得する
#     '''
#     lastprice = Decimal(0)
#     response = httpcon.getJsonResponse(
#         'https://api.coingecko.com/api/v3/coins/tether')
#     if response is not None and 'market_data' in response:
#         market_data = response['market_data']
#         if 'current_price' in market_data:
#             current_price = market_data['current_price']
#             if 'jpy' in current_price:
#                 lastprice = Decimal(current_price['jpy'])
#     return lastprice

# def getAvarageRate_BTCJPY():
#     btc_zf = getRate_BTCJPY_zaif()
#     btc_bf = getRate_BTCJPY_bf()
#     btc_cc = getRate_BTCJPY_cc()
#     btclist = [btc_zf, btc_bf, btc_cc]
#     count = 0
#     for btces in btclist:
#         if btces > 0:
#             count += 1
#     # BTC/JPYの国内取引所平均
#     btc_jpy = (btc_zf + btc_bf + btc_cc) / count
#     return btc_jpy

def getRate_JPY():
    nanj_me = mercatox.getLastPrice()['btc_last']
    # nanj_se = stocksexchange.getLastPriceBTC()
    nanj_hb = hitbtc.getLastPrice()
    nanj_ce = getRate_NANJBTC()
    # btc_jpy = getAvarageRate_BTCJPY()
    btc_jpy = coinmarketcap.getBTC_JPY()
    logger.debug('btc_jpy:{0}'.format(btc_jpy))
    # Coinexchange.ioのNANJ/JPY換算値
    nanj_jpy_ce = btc_jpy * nanj_ce
    logger.debug('nanj_jpy_ce:{0}'.format(nanj_jpy_ce))
    # HitbtcのNANJ/JPY換算値
    nanj_jpy_hb = btc_jpy * nanj_hb
    logger.debug('nanj_jpy_hb:{0}'.format(nanj_jpy_hb))
    # StocksExchangeのNANJ/JPY換算値
    # nanj_jpy_se = btc_jpy * nanj_se
    # logger.debug('nanj_jpy_se:{0}'.format(nanj_jpy_se))
    # MERCATOXのNANJ/JPY換算値
    nanj_jpy_me = btc_jpy * nanj_me
    logger.debug('nanj_jpy_me:{0}'.format(nanj_jpy_me))
    # 1satのJPY価格
    btc_jpy_sat = Decimal(btc_jpy / 100000000)
    logger.debug('btc_jpy_sat:{0}'.format(btc_jpy_sat))
    return {'nanj_sat_ce': nanj_ce, 'nanj_jpy_ce': nanj_jpy_ce,
            'nanj_sat_hb': nanj_hb, 'nanj_jpy_hb': nanj_jpy_hb,
            # 'nanj_sat_se': nanj_se, 'nanj_jpy_se': nanj_jpy_se,
            'nanj_sat_me': nanj_me, 'nanj_jpy_me': nanj_jpy_me,
            'btc_jpy_sat': btc_jpy_sat}

# def nanjusdt(message):
#     se_nanj = stocksexchange.getLastPriceUSDT()
#     cg_usdt = getRate_USDTJPY()
#     nanj_usdt_jpy = se_nanj * cg_usdt
#     logger.info('NANJ_USDT:{:.8f}'.format(se_nanj))
#     logger.info('USDT_JPY:{:.8f}'.format(cg_usdt))
#     logger.info('NANJ_USDT_JPY:{:.8f}'.format(nanj_usdt_jpy))
#     return nanj_usdt_jpy

def nanjprices():
    rate = getRate_JPY()
    # BTC建て
    btc_ce = rate['nanj_sat_ce']
    sat_ce = math.floor(btc_ce * 100000000)
    jpy_ce = round(rate['nanj_jpy_ce'], 3)
    btc_hb = rate['nanj_sat_hb']
    sat_hb = math.floor(btc_hb * 100000000)
    jpy_hb = round(rate['nanj_jpy_hb'], 3)
    # btc_se = rate['nanj_sat_se']
    # sat_se = math.floor(btc_se * 100000000)
    # jpy_se = round(rate['nanj_jpy_se'], 3)
    btc_me = rate['nanj_sat_me']
    sat_me = math.floor(btc_me * 100000000)
    jpy_me = round(rate['nanj_jpy_me'], 3)
    # USDT建て
    usdt_se = stocksexchange.getLastPriceUSDT()
    usdt_jpy_cg = coinmarketcap.getUSDT_JPY()
    usdt_jpy_se = round((usdt_se * usdt_jpy_cg), 3)
    # ETH建て
    eth_me = mercatox.getLastPrice()['eth_last']
    eth_jpy_cg = coinmarketcap.getETH_JPY()
    eth_jpy_me = round((eth_me * eth_jpy_cg), 3)
    return {'btc_ce': btc_ce, 'sat_ce': sat_ce, 'jpy_ce': jpy_ce,
            'btc_hb': btc_hb, 'sat_hb': sat_hb, 'jpy_hb': jpy_hb,
            'btc_me': btc_me, 'sat_me': sat_me, 'jpy_me': jpy_me,
            # 'btc_se': btc_se, 'sat_se': sat_se, 'jpy_se': jpy_se,
            'usdt_se': usdt_se, 'usdt_jpy_cg': usdt_jpy_cg, 'usdt_jpy_se': usdt_jpy_se,
            'eth_me': eth_me, 'eth_jpy_cg': eth_jpy_cg, 'eth_jpy_me': eth_jpy_me}

def nanjpy(message):
    response = ''
    if (re.search("[0-9]", message.content)):
        response = nanjpyamount(message)
    else:
        prices = nanjprices()
        response = ('1 NANJは'
                    '\n\n【CoinExchange.io】'
                    '\n　BTC建て : 約 %s 円\n　( %s BTC [%s sat] )'
                    '\n\n【HitBTC】'
                    '\n　BTC建て : 約 %s 円\n　( %s BTC [%s sat] )'
                    '\n\n【MERCATOX】'
                    '\n　BTC建て  : 約 %s 円\n　( %s BTC [%s sat] )'
                    '\n　ETH建て : 約 %s 円\n　( %s ETH )'
                    '\n\n【StocksExchange】'
                    # '\n　BTC建て  : 約 %s 円\n　( %s BTC [%s sat] )'
                    '\n　USDT建て : 約 %s 円\n　( %s USDT )'
                    '\n\nやな！あくまでも参考価格やで！'
                    ) % (
                        prices['jpy_ce'], '{:.8f}'.format(
                            prices['btc_ce']), prices['sat_ce'],
                        prices['jpy_hb'], '{:.8f}'.format(
                            prices['btc_hb']), prices['sat_hb'],
                        prices['jpy_me'], '{:.8f}'.format(
                            prices['btc_me']), prices['sat_me'],
                        prices['eth_jpy_me'], '{:.8f}'.format(
                            prices['eth_me']),
                        # prices['jpy_se'], '{:.8f}'.format(
                        #     prices['btc_se']), prices['sat_se'],
                        prices['usdt_jpy_se'], '{:.8f}'.format(
                            prices['usdt_se'])
        )
    return response

def nanjpyamount(message):
    response = ''
    prices = nanjprices()
    # 数量をリストに保存
    lists = re.findall(pattern, message.content)
    amount = 0
    for value in lists:
        amount = amount + Decimal(value)
    if (amount % 1 == 0):
        amount = int(amount)
    # coinexchange
    amount_val_ce = amount * prices['jpy_ce']
    if amount_val_ce > 1:
        amount_val_ce = math.floor(amount_val_ce)
    else:
        amount_val_ce = round(amount_val_ce, 3)
    # hitbtc
    amount_val_hb = amount * prices['jpy_hb']
    if amount_val_hb > 1:
        amount_val_hb = math.floor(amount_val_hb)
    else:
        amount_val_hb = round(amount_val_hb, 3)
    # MERCATOX(BTC)
    amount_val_me = amount * prices['jpy_me']
    if amount_val_me > 1:
        amount_val_me = math.floor(amount_val_me)
    else:
        amount_val_me = round(amount_val_me, 3)
    # MERCATOX(ETH)
    amount_val_me_eth = amount * prices['eth_jpy_me']
    if amount_val_me_eth > 1:
        amount_val_me_eth = math.floor(amount_val_me_eth)
    else:
        amount_val_me_eth = round(amount_val_me_eth, 3)
    # stocksexchange(BTC)
    # amount_val_se = amount * prices['jpy_se']
    # if amount_val_se > 1:
    #     amount_val_se = math.floor(amount_val_se)
    # else:
    #     amount_val_se = round(amount_val_se, 3)
    # stocksexchange(USDT)
    amount_val_se_usdt = amount * prices['usdt_jpy_se']
    if amount_val_se_usdt > 1:
        amount_val_se_usdt = math.floor(amount_val_se_usdt)
    else:
        amount_val_se_usdt = round(amount_val_se_usdt, 3)
    response = ('\n\n%s NANJは'
                '\n\n【CoinExchange.io】'
                '\n　BTC建て : 約 %s 円'
                '\n\n【HitBTC】'
                '\n　BTC建て : 約 %s 円'
                '\n\n【MERCATOX】'
                '\n　BTC建て : 約 %s 円'
                '\n　ETH建て : 約 %s 円'
                '\n\n【StocksExchange】'
                # '\n　BTC建て : 約 %s 円'
                '\n　USDT建て : 約 %s 円'
                '\n\nやな！あくまでも参考価格やで！') % (
        '{:,}'.format(amount),
        '{:,}'.format(amount_val_ce),
        '{:,}'.format(amount_val_hb),
        '{:,}'.format(amount_val_me),
        '{:,}'.format(amount_val_me_eth),
        # '{:,}'.format(amount_val_se),
        '{:,}'.format(amount_val_se_usdt))
    return response

def jpynanj(message):
    rate = getRate_JPY()
    logger.debug('rate[nanj_sat_ce]:{0}'.format(rate['nanj_sat_ce']))
    satoshi = math.floor(rate['nanj_sat_ce'] * 100000000)
    nanjbtcjpy = round(rate['nanj_jpy_ce'], 3)
    logger.debug('satoshi:{0}'.format(satoshi))
    logger.debug('nanjbtcjpy:{0}'.format(nanjbtcjpy))
    neednanj = 1 / nanjbtcjpy
    response = ('1円はだいたい ' + str(round(neednanj, 3)) + ' NANJやな！')
    if (re.search("[0-9]", message.content)):
        # リストに保存
        lists = re.findall(pattern, message.content)
        amount = 0
        for value in lists:
            amount = amount + Decimal(value)
        if (amount % 1 == 0):
            amount = int(amount)
        amountval = amount * neednanj
        amountres = '\n' + "{:,}".format(amount) + '円はだいたい ' + \
            "{:,}".format(math.floor(amountval)) + \
            ' NANJやで！\nあくまでも参考価格(CoinExchange.io)やで！'
        response += amountres
    return response

def nanjmoon(message):
    if (re.search("[0-9]", message.content)):
        # リストに保存
        lists = re.findall(pattern, message.content)
        if len(lists) != 2:
            return 'このコマンドは\n**「!nanjmoon{半角スペース}NANJ枚数{半角スペース}到達したいJPY価格」**\nで入力してほしいンゴねえ。。'
        else:
            nanjvol = Decimal(lists[0])
            nanjgoal = Decimal(lists[1])
        if nanjvol < 1 or nanjgoal < 1:
            return '数値は 1 以上を指定してクレメンス！'
        logger.debug('保有値:{0}'.format(nanjvol))
        logger.debug('目標値:{0}'.format(nanjgoal))
        rate = getRate_JPY()
        # 現在の1NANJのレート(単位:sat)
        rate_nanj_sat = Decimal(math.floor(rate['nanj_sat_ce'] * 100000000))
        rate_sat_jpy = Decimal(round(rate['btc_jpy_sat'], 4))
        logger.debug('現在の1NANJのレート(単位:sat):{0}'.format(rate_nanj_sat))
        logger.debug('現在の1satshiのレート(単位:円):{0}'.format(rate_sat_jpy))
        rate_nanj_yen = rate_nanj_sat * rate_sat_jpy
        logger.debug('1 NANJは{0}'.format(rate_nanj_yen) + ' 円')
        # 現在のレートで保持NANJの価値(単位:yen)
        now_nan_val = nanjvol * rate_nanj_yen
        logger.debug('{0}'.format(nanjvol) + ' NANJは' +
                     '{0}'.format(now_nan_val) + ' 円')
        nanjval = 0
        rate_nanj_sat = 1
        while nanjval < nanjgoal:
            rate_nanj_sat += 1
            rate_nanj_yen = rate_nanj_sat * rate_sat_jpy
            nanjval = nanjvol * rate_nanj_yen
        else:
            logger.debug('ループ抜け')
            logger.debug('必要st:{0}'.format(rate_nanj_sat))
            logger.debug('rate_nan_yen:{0}'.format(rate_nanj_yen))
            logger.debug('NAN:{0}'.format(nanjval))
        if rate_nanj_sat < 1000:
            rate_nanj_sat_res = ('%s satoshi') % rate_nanj_sat
        else:
            rate_nanj_sat_res = ('%s btc（%s satoshi）') % (
                round(Decimal(rate_nanj_sat / 100000000), 8), rate_nanj_sat)
        response = ('%s NANJが %s 円に到達するには、1 NANJが %sになればええで！\n現在のレート（1 satoshi = 約 %s 円）での話しやで。\nほなまた...'
                    % ('{:,}'.format(nanjvol), '{:,}'.format(nanjgoal), rate_nanj_sat_res, rate_sat_jpy))
        return response
    else:
        return 'このコマンドは\n**「!nanjmoon{半角スペース}NANJ枚数{半角スペース}到達したいJPY価格」**\nで入力してほしいンゴねえ。。'