import numpy as np
import matplotlib.pyplot as plt

from matplotlib.ticker import FormatStrFormatter

def z_lambda(sigma, scale_h, p0, planet_radius, mass, T, g):
    # constants
    k = 1.38e-23  # boltzmann constant k_b in J/K
    amu_kg = 1.66e-27  # kg/amu

    # set mixing ratio to 1
    xi = 1
    # set equiv scale hight to 1
    tau_eq = 1

    # calculate beta
    beta = p0 / tau_eq * np.sqrt(2*np.pi*planet_radius)
    return scale_h * np.log(xi * sigma * 1/np.sqrt(k*mass*amu_kg*T*g) * beta)

def alpha_lambda(star_radius, planet_radius, z):
    return (planet_radius / star_radius)**2 + (2 * planet_radius * z)/(star_radius**2)

'''
generate absorption profile from cross section data
'''
# filename = 'project_data/1H2-16O_6250-12500_300K_20.000000.sigma'
filename = 'project_data/1H2-16O_6250-12500_300K_100.000000.sigma'
with open(filename) as file:
    raw_data = file.readlines()
    wave_numbers = []
    cross_sections = []
    for x in raw_data:
        wave_string, cross_string = x.split()
        wave_numbers.append(float(wave_string))
        cross_sections.append(float(cross_string))
    wave_numbers = np.array(wave_numbers)
    cross_sections = np.array(cross_sections)

# convert wavenumber to wavelength
cross_wavelengths = 1e7/wave_numbers

# reference pressure: 1 barr
p0 = 1 * 1e5

# scale height
k = 1.38e-23  # boltzmann constant k_b in J/K
amu_kg = 1.66e-27  # kg/amu
g = 10  # m/s^2
T = 290  # K
mass = 18  # amu
H = k*T/(mass*amu_kg * g)

# star and planet radii
r_p = 6.3710e6
r_star = 6.957e8
baseline_depth = (r_p/r_star)**2

eclipse_depth = alpha_lambda(star_radius=r_star,
                             planet_radius=r_p,
                             z=z_lambda(sigma=cross_sections,
                                        scale_h=H,
                                        p0=p0,
                                        planet_radius=r_p,
                                        mass=mass,
                                        T=T,
                                        g=g)
                             )

# mean spectral resolution
spec_res = np.mean(np.diff(np.flip(cross_wavelengths)))

plt.figure('transit depth %.2f' %spec_res, figsize=(8, 8))
plt.subplot(212)
plt.plot(cross_wavelengths, cross_sections)
plt.title('Cross section of H2O')
plt.xlabel('Wavelength (nm)')
plt.ylabel('cm^2/molecule')

plt.subplot(211)
plt.plot(cross_wavelengths, eclipse_depth)
plt.title('Transit depth, resolution %.2f nm' %spec_res)
plt.ylabel('($R_p$/$R_{star}$)$^2$')
plt.subplot(211).yaxis.set_major_formatter(FormatStrFormatter('% 1.1e'))

'project_data/1H2-16O_6250-12500_300K_20.000000.sigma'
'project_data/1H2-16O_6250-12500_300K_100.000000.sigma'


"""文字列基礎
特定の文字(群)を置換/削除する translateメソッド
（置換前文字（群）、置換後文字（群）、削除文字（群）を指定する方法）

[説明ページ]
https://tech.nkhn37.net/python-replace-translate/#i-3
"""
sample_text = "translateメソッドは,文字（群）を△置換／□削除します〇."

# メソッドに直接指定する
print(
    sample_text.translate(
        str.maketrans(
            ",.",
            "、。",
            "〇△□",
        )
    )
)


class StackObj:

    def __init__(self, data):
        self.data = data
        self.next = None

class Stack:

    def __init__(self):
        self.top = None
        self.__len = 0

    def push(self, obj):
        last = self[self.__len - 1] if self.__len > 0 else None

        if last:
            last.next = obj

        if self.top is None:
            self.top = obj
        self.__len += 1

    def pop(self):
        if self.__len == 0:
            return None
        obj = self[self.__len - 1]
        if self.__len == 1:
            self.top = None
        else:
            self[self.__len - 2].next = None
        self.__len -= 1
        return obj

    def __check_index(self, ind):
        if type(ind) != int or not (0 <= ind < self.__len):
            raise IndexError('неверный индекс')

    def __getitem__(self, item):
        self.__check_index(item)

        h = self.top
        k = 0
        while h and k < item:
            h = h.next
            k += 1

        return h

    def __setitem__(self, key, value):
        self.__check_index(key)
        obj = self[key]
        prev = self[key - 1] if key > 0 else None
        value.next = obj.next

        if prev:
            prev.next = value

    def show(self) -> None:
        tmp = self.top
        s = []
        while tmp.next is not None:
            s.append(tmp.data)
            tmp = tmp.next
        s.append(tmp.data)
        return ' '.join(s)

def test_push():
    st = Stack()
    st.push(StackObj("obj1"))
    st.push(StackObj("obj2"))
    st.push(StackObj("obj3"))
    assert st.show() == 'obj1 obj2 obj3'

def test_setitem():
    st = Stack()
    st.push(StackObj("obj1"))
    st.push(StackObj("obj2"))
    st.push(StackObj("obj3"))
    st[1] = StackObj("new obj2")
    assert st.show() == 'obj1 new obj2 obj3'

def test_getitem():
    st = Stack()
    st.push(StackObj("obj1"))
    st.push(StackObj("obj2"))
    st.push(StackObj("obj3"))
    st[1] = StackObj("new obj2")
    assert st[2].data == 'obj3'

def test_pop():
    st = Stack()
    st.push(StackObj("obj1"))
    st.push(StackObj("obj2"))
    st.push(StackObj("obj3"))
    st[1] = StackObj("new obj2")
    assert st.pop().data == 'obj3'


class Doggy:
    num_of_dogs = 0  # 클래스 변수 선언
    birth_of_dogs = 0

    def __init__(self, name, type):
        self.name = name  # 인스턴스 변수
        self.type = type  # 인스턴스 변수
        Doggy.num_of_dogs += 1
        Doggy.birth_of_dogs += 1
        # 생성자 함수 init이 실행될 때 클래스 변수의 숫자를 하나 올린다

    def bark(self):
        print(f'{self.name}(이)가 짖습니다. 월월월')

    def death(self):
        deaddog = input('name : ')
        if deaddog == self.name:
            Doggy.num_of_dogs -= 1

    @classmethod
    def get_status(cls):
        print(cls.birth_of_dogs, cls.num_of_dogs)

robert = Doggy('robert', 'Jindo')
cute = Doggy('cute', 'human')

print(robert.name, robert.type)
robert.bark()
cute.death()
Doggy.get_status()


from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from flask_cors import CORS
from flask_heroku import Heroku
from environs import Env
import os

app = Flask(__name__)
CORS(app)
heroku = Heroku(app)

env = Env()
env.read_env()
DATABASE_URL = env("DATABASE_URL")

basedir = os.path.abspath(os.path.dirname(__file__))
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + \
#     os.path.join(basedir, 'app.sqlite')
app.config['SQLALCHEMY_DATABASE_URI'] = DATABASE_URL
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
ma = Marshmallow(app)

# Adventures Table

class Adventure(db.Model):
    __tablename__ = "adventure"
    id = db.Column(db.Integer, primary_key=True)
    # health = db.Column(db.String(10), nullable=False)
    # family = db.Column(db.String(10), nullable=False)
    # points = db.Column(db.String(10), nullable=False)
    # security = db.Column(db.String(10), nullable=False)
    description = db.Column(db.String(2500), nullable=False)
    buttonOneName = db.Column(db.String(100), nullable=False)
    buttonTwoName = db.Column(db.String(100), nullable=False)
    buttonOnePath = db.Column(db.String(100), nullable=False)
    buttonTwoPath = db.Column(db.String(100), nullable=False)
    # resultOne = db.Column(db.String(2500), nullable=False)
    # resultTwo = db.Column(db.String(2500), nullable=False)
    # resultPath = db.Column(db.String(10), nullable=False)
    # adventurePath = db.Column(db.String(10), nullable=False)

    def __init__(self, description, buttonOneName, buttonTwoName, buttonOnePath, buttonTwoPath):
        # self.health = health
        # self.family = family
        # self.points = points
        # self.security = security
        self.description = description
        self.buttonOneName = buttonOneName
        self.buttonTwoName = buttonTwoName
        self.buttonOnePath = buttonOnePath
        self.buttonTwoPath = buttonTwoPath
        # self.resultOne = resultOne
        # self.resultTwo = resultTwo
        # self.resultPath = resultPath
        # self.adventurePath = adventurePath

class AdventureSchema(ma.Schema):
    class Meta:
        fields = ('id', 'description', 'buttonOneName', 'buttonTwoName', 'buttonOnePath', 'buttonTwoPath')

adventure_schema = AdventureSchema()
adventures_schema = AdventureSchema(many=True)

# Results Table

class Result(db.Model):
    __tablename__ = "result"
    id = db.Column(db.Integer, primary_key=True)
    health = db.Column(db.String(10), nullable=False)
    family = db.Column(db.String(10), nullable=False)
    points = db.Column(db.String(10), nullable=False)
    security = db.Column(db.String(10), nullable=False)
    resultDesc = db.Column(db.String(2500), nullable=False)
    resultPath = db.Column(db.String(10), nullable=False)

    def __init__(self, health, family, points, security, resultDesc, resultPath):
        self.health = health
        self.family = family
        self.points = points
        self.security = security
        self.resultDesc = resultDesc
        self.resultPath = resultPath

class ResultSchema(ma.Schema):
    class Meta:
        fields = ('id', 'health', 'family', 'points', 'security', 'resultDesc', 'resultPath')

result_schema = ResultSchema()
results_schema = ResultSchema(many=True)

# Routes

@app.route('/', methods=["GET"])
def home():
    return "
Text Adventure API
"

# Adventure Routes

@app.route('/adventure', methods=['POST'])
def add_adventure():
    # health = request.json['health']
    # family = request.json['family']
    # points = request.json['points']
    # security = request.json['security']
    description = request.json['description']
    buttonOneName = request.json['buttonOneName']
    buttonTwoName = request.json['buttonTwoName']
    buttonOnePath = request.json['buttonOnePath']
    buttonTwoPath = request.json['buttonTwoPath']
    # resultOne = request.json['resultOne']
    # resultTwo = request.json['resultTwo']
    # resultPath = request.json['resultPath']
    # adventurePath = request.json['adventurePath']

    new_adventure = Adventure(description, buttonOneName, buttonTwoName, buttonOnePath, buttonTwoPath)

    db.session.add(new_adventure)
    db.session.commit()

    adventure = Adventure.query.get(new_adventure.id)
    return adventure_schema.jsonify(adventure)

@app.route('/adventures', methods=["GET"])
def get_adventures():
    all_adventures = Adventure.query.all()
    result = adventures_schema.dump(all_adventures)

    return jsonify(result)

@app.route('/adventure/<id>', methods=['GET'])
def get_adventure(id):
    adventure = Adventure.query.get(id)

    result = adventure_schema.dump(adventure)
    return jsonify(result)

@app.route('/product/<id>', methods=['PATCH'])
def update_category(id):
    adventure = Adventure.query.get(id)

    # new_health = request.json['inventory']
    # new_family = request.json['family']
    # new_points = request.json['points']
    # new_security = request.json['security']
    new_description = request.json['description']
    new_buttonOneName = request.json['buttonOneName']
    new_buttonTwoName = request.json['buttonTwoName']
    new_buttonOnePath = request.json['buttonOnePath']
    new_buttonTwoPath = request.json['buttonTwoPath']
    # new_resultOne = request.json['resultOne']
    # new_resultTwo = request.json['resultTwo']
    # new_resultPath = request.json['resultPath']

    # adventure.health = new_health
    # adventure.family = new_family
    # adventure.points = new_points
    # adventure.security = new_security
    adventure.description = new_description
    adventure.buttonOneName = new_buttonOneName
    adventure.buttonTwoName = new_buttonTwoName
    adventure.buttonOnePath = new_buttonOnePath
    adventure.buttonTwoPath = new_buttonTwoPath
    # adventure.resultOne = new_resultOne
    # adventure.resultTwo = new_resultTwo
    # adventure.resultPath = new_resultPath

    db.session.commit()
    return adventure_schema.jsonify(adventure)

@app.route('/adventure/<id>', methods=['DELETE'])
def delete_adventure(id):
    record = Adventure.query.get(id)
    db.session.delete(record)
    db.session.commit()

    return jsonify('Item deleted')

# Result Routes

@app.route('/result', methods=['POST'])
def add_result():
    health = request.json['health']
    family = request.json['family']
    points = request.json['points']
    security = request.json['security']
    resultDesc = request.json['resultDesc']
    resultPath = request.json['resultPath']

    new_result = Result(health, family, points, security, resultDesc, resultPath)

    db.session.add(new_result)
    db.session.commit()

    result1 = Result.query.get(new_result.id)
    return result_schema.jsonify(result1)

@app.route('/results', methods=["GET"])
def get_results():
    all_results = Result.query.all()
    result = results_schema.dump(all_results)

    return jsonify(result)

@app.route('/result/<id>', methods=['GET'])
def get_result(id):
    result = Result.query.get(id)

    result1 = result_schema.dump(result)
    return jsonify(result1)

@app.route('/result/<id>', methods=['PATCH'])
def update_result(id):
    result = Result.query.get(id)

    new_health = request.json['health']
    new_family = request.json['family']
    new_points = request.json['points']
    new_security = request.json['security']
    new_resultDesc = request.json['resultDesc']
    new_resultPath = request.json['resultPath']

    result.health = new_health
    result.family = new_family
    result.points = new_points
    result.security = new_security
    result.resultDesc = new_resultDesc
    result.resultPath = new_resultPath

    db.session.commit()
    return result_schema.jsonify(result)

@app.route('/result/<id>', methods=['DELETE'])
def delete_result(id):
    record = Result.query.get(id)
    db.session.delete(record)
    db.session.commit()

    return jsonify('Item deleted')


from subprocess import Popen, CREATE_NEW_CONSOLE
import time

CLIENT = 2
SET_TIME_OUT = 0.2

def main():
    process_list = []
    try:
        while True:
            print("Запустить программу (start) / Остановить программу (stop)")
            action = input("> ").lower()
            if action == 'stop':
                for p in process_list:
                    time.sleep(SET_TIME_OUT)
                    p.kill()
                process_list.clear()
                break
            elif action == 'start':
                process_list.append(Popen('python server.py'))
                time.sleep(SET_TIME_OUT)
                for _ in range(CLIENT):
                    process_list.append(Popen('python client.py', creationflags=CREATE_NEW_CONSOLE))
            else:
                print('Команда не распознана')
    except KeyboardInterrupt:
        pass

if __name__ == '__main__':
    main()


import contextlib
import json
import logging
import subprocess
from typing import Any, Dict, Iterator, List, Optional

from snapcraft_legacy.internal import repo

logger = logging.getLogger(__name__)

def _install_ua_tools() -> None:
    """Ensure UA tools are installed."""
    repo.Repo.install_build_packages(package_names=["ubuntu-advantage-tools"])

def _attach(ua_token: str) -> None:
    """Attach UA token (ua will update package lists)."""
    subprocess.check_call(["sudo", "ua", "attach", ua_token])

def _enable_services(services: List[str]) -> None:
    """Enable the specified UA services.

    If a service is already enabled, it will not be re-enabled because UA will raise
    an error.
    """
    service_data = _status().get("services")
    enabled_services = []
    disabled_services = []

    if service_data:
        # sort services into enabled and disabled
        for service in services:
            if _is_service_enabled(service, service_data):
                enabled_services.append(service)
            else:
                disabled_services.append(service)
    else:
        # assume all services are disabled if they are not in the status data
        disabled_services = services

    if enabled_services:
        logger.debug(
            "Not re-enabling services %s because the services are already enabled.",
            enabled_services,
        )

    if disabled_services:
        logger.debug("Enabling services %s.", disabled_services)
        subprocess.check_call(
            ["sudo", "ua", "enable", *disabled_services, "--beta", "--assume-yes"]
        )

def _detach() -> None:
    """Detach UA token (ua will update package lists)."""
    subprocess.check_call(["sudo", "ua", "detach", "--assume-yes"])

def _is_attached() -> bool:
    return _status()["attached"]

def _is_service_enabled(service_name: str, service_data: List[Dict[str, str]]) -> bool:
    """Check if a service is enabled.

    :param service_name: name of service to check
    :param service_data: list of dictionaries containing data for each service

    :return: True if the service is enabled. False is the service is disabled or not
    listed in the list of service data.
    """
    for service in service_data:
        if service.get("name") == service_name:
            # possible statuses are 'enabled', 'disabled', and 'n/a'
            return service.get("status") == "enabled"

    logger.debug("Could not find service %r.", service_name)
    return False

def _status() -> Dict[str, Any]:
    stdout = subprocess.check_output(
        ["sudo", "ua", "status", "--all", "--format", "json"]
    )
    return json.loads(stdout)

@contextlib.contextmanager
def ua_manager(
    ua_token: Optional[str], *, services: Optional[List[str]]
) -> Iterator[None]:
    """Attach and detach UA token as required.

    Uses try/finally to ensure that token is detached on error.

    If ua_token is None, neither attach / detach will occur and the context
    manager is effectively a noop.

    If ua_token is specified and the system is already attached, log a warning
    that we are refusing to configure specified token, but otherwise resume
    normally.

    :param ua_token: Optional ua_token.
    :param services: Optional ua services to enable.
    """
    ua_needs_detach = False

    if ua_token is not None:
        # Make sure the tools are installed first.
        _install_ua_tools()

        if _is_attached():
            logger.warning(
                "Refusing to attach specified UA token as system is already attached. "
            )
        else:
            ua_needs_detach = True
            logger.info("Attaching specified UA token...")
            _attach(ua_token)

    try:
        if services:
            logger.info("Enabling specified UA services...")
            _enable_services(services)

        yield
    finally:
        if ua_needs_detach:
            logger.info("Detaching specified UA token...")
            _detach()


from telegram.ext import Updater, MessageHandler, Filters
from telegram.ext import CallbackContext, CommandHandler
from wikiped import search_wiki
from vzevent import writeevent
from vznote import writenote
from wrnotes import printnotes
from wrevents import printevents
from odnote import noteone

with open("tokenbt.txt", "r") as ftb:
    TOKEN = ftb.readline().strip()

def start(update, context):
    update.message.reply_text(
        "Доброго времени суток! Я - ваш личный дворецкий. Чем могу быть полезен?")

def help(update, context):
    update.message.reply_text(
        "Приветствую, я - Темный Дворецкий, Ваш личный бот и слуга. Если хотите посмотреть, что я умею, то нажимайте это: \n"
        "/comands")

def comands(update, context):
    update.message.reply_text(
        "Раз уж Вы обратились ко мне за помощью, то вот список всех моих доступных команд:\n"
        "1. /eventwrite - создать событие (формат ввода команды: /eventwrite-[дата-время-заголовок-описание-время напоминания]\n"
        "2. /notewrite - создать заметку (формат ввода команды: /notewrite-[заголовок-описание]\n"
        "3. /allevents - вывести дату, время и заголовки всех событий\n"
        "4. /allnotes - вывести заголовки всех заметок\n"
        "5. !В разработке! /onenote - вывести заметку по заданному заголовку\n"
        "6. /wiki - поиск в Wikipedia (формат ввода команды: /wiki [слово для поиска])\n"
        "7. /comands - список всех команд\n"
        "/help - помощь\n"

    )

def eventwrite(update, context):
    writeevent(update.message.text)
    update.message.reply_text("Событие успешно создано")

def notewrite(update, context):
    writenote(update.message.text)
    update.message.reply_text("Заметка успешно создана")

def allnotes(update, context):
    update.message.reply_text(printnotes())

def allevents(update, context):
    update.message.reply_text(printevents())

def onenote(update, context):
    update.message.reply_text(noteone(update.message.text))

def wiki(update, context):
    print(context.args)
    word = ' '.join(context.args)
    if word:
        update.message.reply_text("Идет поиск...")
        response, url = search_wiki(word)
        update.message.reply_text(response + url)
    else:
        update.message.reply_text("Необходимо ввести данные для поиска")

def main():
    updater = Updater(TOKEN, use_context=True)
    dp = updater.dispatcher
    print("Ваш Темный Дворецкий пробудился....")
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))
    dp.add_handler(CommandHandler("comands", comands))
    dp.add_handler(CommandHandler("eventwrite", eventwrite))
    dp.add_handler(CommandHandler("notewrite", notewrite))
    dp.add_handler(CommandHandler("allnotes", allnotes))
    dp.add_handler(CommandHandler("allevents", allevents))
    dp.add_handler(CommandHandler("onenote", onenote))
    dp.add_handler(CommandHandler("wiki", wiki))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()


def selection_sort(l_):
	if l_:
		for i in range(len(l_)):
			min = i
			for k in range(i+1, len(l_)):
				if l_[k] < l_[min]:
					min = k
			l_[min], l_[i]=l_[i], l_[min]
	return l_

print(selection_sort([4,3,2,1]))


'''
import pytesseract as ocr
from PIL import Image
import PIL
import pytesseract

pytesseract.pytesseract.tesseract_cmd =r'local-onde-tesseract-foi-instalado'

print(pytesseract.image_to_string(Image.open('testDataset/2.png')))
'''
import cv2
import pytesseract

pytesseract.pytesseract.tesseract_cmd = 'local-onde-tesseract-foi-instalado'
img = cv2.imread('databse/MILK/MILK0154.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
print(pytesseract.image_to_string(img))

'''
### Detecting Characters
hImg,wImg,_ = img.shape
cong = r'--oem 3 --psm 6 outputbase digits'
boxes = pytesseract.image_to_boxes(img, config=cong)
for b in boxes.splitlines():
    #print(b)
    b = b.split(' ')
    #print(b)
    x,y,w,h = int(b[1]),int(b[2]),int(b[3]),int(b[4])
    cv2.rectangle(img,(x,hImg-y),(w,hImg-h),(0,0,255),1)
    cv2.putText(img,b[0],(x,hImg-y+25),cv2.FONT_HERSHEY_COMPLEX,1,(50,50,250),2)
'''

### Detecting Words
hImg,wImg,_ = img.shape
boxes = (pytesseract.image_to_data(img))
for x, b in enumerate(boxes.splitlines()):
    if x!=0:
        b = b.split()
        print(b)
        if len(b)==12:
            x,y,w,h = int(b[6]),int(b[7]),int(b[8]),int(b[9])
            cv2.rectangle(img,(x,y),(w+x,h+y),(0,0,255),1)
            cv2.putText(img,b[11],(x,y),cv2.FONT_HERSHEY_COMPLEX,1,(50,50,250),2)

'''
## Detecting Numbers
hImg,wImg,_ = img.shape
cong = r'--oem 3 --psm 6 outputbase digits'
boxes = pytesseract.image_to_data(img, config=cong)
for x, b in enumerate(boxes.splitlines()):
    if x!=0:
        b = b.split()
        print(b)
        if len(b)==12:
            x,y,w,h = int(b[6]),int(b[7]),int(b[8]),int(b[9])
            cv2.rectangle(img,(x,y),(w+x,h+y),(0,0,255),1)
            cv2.putText(img,b[11],(x,y),cv2.FONT_HERSHEY_COMPLEX,1,(50,50,250),2)
'''
cv2.imshow('Result' ,img)
cv2.waitKey(0)


import scrapy

class TweetsSpider(scrapy.Spider):
    name = 'tweets'
    start_urls = [
        'https://twitter.com/marvel',
        'https://twitter.com/dccomics',
    ]

    def parse(self, response):
        for tweet in response.css('div#timeline div.tweet'):
            item = {
                'id': tweet.css('::attr(data-tweet-id)').get(),
                'author': {
                    'id': tweet.css('a.account-group::attr(data-user-id)').get(),
                    'full_name': tweet.css('strong.fullname::text').get(),
                    'href': 'https://twitter.com' + tweet.css('a.account-group::attr(href)').get()
                },
                'text': ''.join(tweet.css('p.tweet-text::text, p.tweet-text s::text, p.tweet-text b::text').getall()),
                'links': (
                    tweet.css('a.twitter-timeline-link::attr(data-expanded-url), '
                              'div.js-macaw-cards-iframe-container::attr(data-card-url)').getall()
                )
            }
            inner_request = self.parse_tweet_iframe(tweet, item)
            yield inner_request

    @staticmethod
    def parse_tweet_iframe(tweet, parent_item):
        url = tweet.css('div.js-media-container .js-macaw-cards-iframe-container::attr(data-full-card-iframe-url)').get()

        if not url:
            return parent_item

        def iframe_parser(response):
            item = response.meta['item']
            item['links'] += response.css('a::attr(href)').getall()
            yield item

        request = scrapy.Request('https://twitter.com{url}'.format(url=url), iframe_parser)
        request.meta['item'] = parent_item
        return request


#!/usr/bin/python

import itertools
import operator
import random
import sys

from collections import deque

def from_file(name):
    with open(name, "r") as handle:
        for line in handle:
            line = line.rstrip("\r\n")
            yield line

def write(iterable):
    for item in iterable:
        sys.stdout.write(item)
        sys.stdout.write("\n")

def op_identity(ctx, positional):
    if len(positional) != 1:
        raise Exception("Syntax violation.")

    return from_file(positional[0])

def op_sample(ctx, positional):
    if len(positional) != 2:
        raise Exception("Syntax violation.")

    n = int(positional[0])
    x = from_file(positional[1])
    x = list(x)
    x = random.sample(x, n)

    return x

def op_shuffle(ctx, positional):
    if len(positional) != 1:
        raise Exception("Syntax violation.")

    x = from_file(positional[0])
    x = list(x)

    random.shuffle(x)

    return x

def op_subtract(ctx, positional):
    if len(positional) != 2:
        raise Exception("Syntax violation.")

    a = from_file(positional[0])
    b = from_file(positional[1])

    return set(a) - set(b)

def op_noop():
    raise Exception("No operation.")
    pass

def main():
    import argparse
    parser = argparse.ArgumentParser(description = "Set operations.")

    # Positional.
    positional = parser.add_argument_group(title = "Positional arguments")
    positional.add_argument("positional", metavar = "A",
        type = str, nargs = "+",
        help = "Arguments for the operation.")

    # Operations.
    operations = parser.add_mutually_exclusive_group(required = True)
    operations.add_argument("--identity", dest = "op",
        action = "store_const", const = op_identity, default = op_noop,
        help = "Perform nothing. (Syntax: <S>)")
    operations.add_argument("--sample", dest = "op",
        action = "store_const", const = op_sample, default = op_noop,
        help = "Perform sampling. (Syntax: <N> <S>; samples N items from S)")
    operations.add_argument("--shuffle", dest = "op",
        action = "store_const", const = op_shuffle, default = op_noop,
        help = "Perform shuffling. (Syntax: <S>)")
    operations.add_argument("--subtract", dest = "op",
        action = "store_const", const = op_subtract, default = op_noop,
        help = "Perform set subtraction. (Syntax: <A> <B>; subtracts B from A)")

    args = parser.parse_args()
    write(args.op(args, args.positional))

if __name__ == "__main__":
    main()


# 2021. 02. 08. 월
# 3052번
# 수 10개를 입력 받아 42로 나눈 후 서로 다른 나머지의 갯수

num = []

for i in range(10):
    n = int(input())
    r = n % 42
    num.append(n)

num2 = set(num)
# set 함수 : 중복값을 제외시키는 함수

print(len(num2))


# -*- coding: utf-8 -*-
"""
Created on Thu Jul 22 13:35:07 2021

@author: Administrator
"""
import yfinance as yf
import plotly
import plotly.express as px
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
from sqlalchemy import create_engine
import numpy as np
import geojson
import plotly.graph_objs as go
import dash_bootstrap_components as dbc
import json
import plotly.graph_objects as go
import dash_table
#import webscrape_investing
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from dash_extensions.enrich import Output, DashProxy, Input, MultiplexerTransform, State
gbl = globals()

#with open('./assets/custom_georegions.json', 'r') as fp:
#    custom_geoj = json.load(fp)

engine = create_engine('sqlite:///forex.db')

country_convert = {'JPY':'JPN',
                   'GBP':'GBR',
                   'EUR':'DEU',
                   'AUD':'AUS',
                   'NZD':'NZL',
                   'CNY':'CHN',
                   'HKD':'HKG',
                   'SGD':'SGP',
                   'INR':'IDN',
                   'MXN':'MEX',
                   'PHP':'PHL',
                   'THB':'THA',
                   'MYR':'MYS',
                   'ZAR':'ZAF',
                   'RUB':'RUS'}

futuresdict = {'Japanese Yen':'JPY',
            'British Pound':'GBP',
            'Euro':'EUR',
            'Australian Dollar':'AUD',
            'New Zealand Dollar':'NZD',
            'Mexican Peso':'MXN',
            'South African Rand':'ZAR'}

app = dash.Dash(__name__)

min_times = {'Last 24 hours': 1,
              'Last 3 days': 2,
              'Last 7 days': 3}

def arbitragetable(money,p,rf):
    row1 = html.Tr([html.Td("First currency"), html.Td("United States Dollar")])
    row2 = html.Tr([html.Td("Second currency"), html.Td(money)])
    row3 = html.Tr([html.Td(p), html.Td("0")])
    row4 = html.Tr([html.Td(str(money)+"/USD futures quote"), html.Td(" ")])
    row5 = html.Tr([html.Td(str(money)+"/USD spot quote"), html.Td(" ")])
    row6 = html.Tr([html.Td("Contracts to trade"), html.Td(" ")])
    row7 = html.Tr([html.Td("Contract size"), html.Td(" ")])
    row8 = html.Tr([html.Td("Delivery"), html.Td(" ")])
    table_body = [html.Tbody([row1, row2, row3, row4,row5,row6,row7,row8])]
    table = dbc.Table(table_body, bordered=False,style={'border-collapse':'collapse'})
    return table

table = arbitragetable('Euro','12 months',0.0)

hrly_times = {'30 days': 30,
              '60 days':60,
              '6 months': 182,
              '1 year':365}

rfrates_USD = {30:0.04,
               60:0.04,
               90:0.05,
               365:0.07,
               730:0.2,
               1095:0.37,
               1825:0.71,
               2555:1.02,
               3650:1.27,
               7300:1.82,
               10950:1.9}

rfrates_NZD = {365:0,
    730:0.74,
    1825:1.15,
    3650:1.52}

rfrates_EUR = {90:-0.663,
               365:-0.663,
               730:-0.725,
               1095:-0.789}

header_line = html.H1("Foreign Exchange Dashboard")
second_line = html.H5("Jamie Stephens • July 2021 • Metis",style={'textAlign':'center'})

body = html.Div([
    header_line
    , second_line
    , dbc.Row([
            dbc.Col(html.Div(dbc.Alert([html.P("Time Duration",style={'font-weight':'700'}),
                                        html.P("Percent change in value relative to the United States Dollar")
                                        ,dcc.RadioItems(id='heatmaptimes',options=[{"label":k, "value":v} for k,v in min_times.items()],
                                             value=list(min_times.values())[2],
                                             labelStyle={'display': 'block'})]),style={'textAlign':'center','color':'black'}), width=3)
            , dbc.Col(dbc.Alert(html.Div( dcc.Graph(id='heatmap_map'),style={})))
            ])
    , dbc.Row(dbc.Col(html.Div(dbc.Alert(html.Div([dcc.Dropdown(
                                                        id='futuresdropdown',
                                                        searchable=False,
                                                        clearable=False,
                                                        options=[{"label":k, "value":v} for k,v in futuresdict.items()],
                                                        value = list(futuresdict.values())[0])])))))
    ,dbc.Row([dbc.Col(dbc.Alert([html.Div(id='linegraphheader'),
                                          html.Div( dcc.Graph(id='singleforex'),style={}),
                                          html.Div([dcc.RadioItems(
                                                        id='hrly_timerange',
                                                        options=[{"label":k, "value":v} for k,v in hrly_times.items()],
                                                        value = list(hrly_times.values())[3],
                                                        labelStyle={'display': 'block'})],style={"width": "50%"})]))

             ,dbc.Col(dbc.Alert([html.P("Futures Contracts",style={'textAlign':'center','color':'black','font-weight':'700'}),
                                          html.Div(id='content')]),
                                        style={'textAlign':'center','color':'black'})

             ,dbc.Col(dbc.Alert([html.P("Futures Contracts",style={'textAlign':'center','color':'black','font-weight':'700'}),
                                          html.Div(id='content7')]),
                                        style={'textAlign':'center','color':'black'})
    ])])
#    ])

app.layout = html.Div([body])

@app.callback(
    Output('heatmap_map','figure'),
    Input('heatmaptimes','value'))
def heatmap(d):
    df = pd.read_sql_table('heatmaptable', engine)
    final_df = pd.DataFrame(columns=['Currency','First','Last'])

    lastdatetimevalue = df['Datetime'].loc[~df['Datetime'].isnull()].iloc[-1]

    if d == 2:
        threedaysprior = lastdatetimevalue - relativedelta(days=3)
        df = df[df['Datetime'] > threedaysprior]
    elif d == 1:
        onedayprior = lastdatetimevalue - relativedelta(days=1)
        df = df[df['Datetime'] > onedayprior]

    for i,u in country_convert.items():
        if i in df.columns:
            first_value = df[i].loc[~df[i].isnull()].iloc[0]
            last_value = df[i].loc[~df[i].isnull()].iloc[-1]
            final_df.loc[len(final_df.index)] = [i, first_value,last_value]

    final_df['Difference'] = final_df['Last'] - final_df['First']
    final_df['Percent Chg'] = (final_df['Difference'] / final_df['First'])*100

    final_df['Currency'] = final_df['Currency'].map(country_convert)
    fig = px.choropleth(final_df, locations="Currency",
                color="Percent Chg",
                hover_name="Currency",
                range_color = (-2,2),
                color_continuous_scale=px.colors.sequential.Plasma)
    fig.update_layout(paper_bgcolor='rgb(169,169,169)')
    fig.show()
    return fig

@app.callback(Output('linegraphheader','children'),
            Output('singleforex','figure'),
              Output('content', 'children'),
            Input('futuresdropdown', 'value'),
            Input('hrly_timerange', 'value'))
def newlinegraphanddatatable(currencyname,hrlychoiceline):
    sqltablename = 'hrlytable_'+str(currencyname)
    hourlychosenmap = pd.read_sql_table(sqltablename, engine,index_col='index')

    lowestvalue = hourlychosenmap['Close'].max()
    highestvalue = hourlychosenmap['Close'].min()

    lastdatetimevalue = hourlychosenmap.index[-1]

    if hrlychoiceline == 182:
        sixmonths = lastdatetimevalue - relativedelta(months=6)
        hourlychosenmap = hourlychosenmap[hourlychosenmap.index > sixmonths]
    elif hrlychoiceline == 60:
        threemonths = lastdatetimevalue - relativedelta(months=3)
        hourlychosenmap = hourlychosenmap[hourlychosenmap.index > threemonths]
    elif hrlychoiceline == 30:
        onemonth = lastdatetimevalue - relativedelta(months=1)
        hourlychosenmap = hourlychosenmap[hourlychosenmap.index > onemonth]

    hourly_fig = go.Figure(data=go.Scatter(x = hourlychosenmap.index, y = hourlychosenmap.Close))
    hourly_fig.update_traces(line_color='#000000')
    hourly_fig.update_layout(paper_bgcolor='rgb(169,169,169)')

    if currencyname != "":
        sqlfuturesname = 'futures_' + str(currencyname)
        fut_datatable = pd.read_sql_table(sqlfuturesname, engine,index_col='index')
        xyz = dash_table.DataTable(id='futures_datatable',
                columns=[{"name": i, "id": i} for i in fut_datatable.columns],
                row_selectable='single',
                data=fut_datatable.to_dict('records'),
                style_data={'backgroundColor': 'transparent','align':"center"},
                style_cell={'fontSize':10, 'font-family':'sans-serif'})

    hourly_fig.update_layout(yaxis_range=[lowestvalue,highestvalue])
    hourly_fig.show()
    linechartheader = html.P(currencyname + "/USD Change in Value",style={'textAlign':'center','color':'black','font-weight':'700'})

    return linechartheader,hourly_fig,xyz

@app.callback(
    Output('content3','children'),
    Input('linegraphheader', "children"),
    Input('content','data'),
    Input('content','selected_rows'))
def docalculations(currname,data,selected_rows):
    var = str(currname['props'])
    var_partt = var.split('USD')[0]
    curr = var_partt[-4:-1]
    rf = 0
    p= "0"
    row1 = html.Tr([html.Td("First currency"), html.Td("United States Dollar")])
    row2 = html.Tr([html.Td("Second currency"), html.Td(curr)])
    row3 = html.Tr([html.Td(p), html.Td("0")])
    row4 = html.Tr([html.Td(str(curr)+"/USD futures quote"), html.Td(" ")])
    row5 = html.Tr([html.Td(str(curr)+"/USD spot quote"), html.Td(" ")])
    row6 = html.Tr([html.Td("Contracts to trade"), html.Td(" ")])
    row7 = html.Tr([html.Td("Contract size"), html.Td(" ")])
    row8 = html.Tr([html.Td("Delivery"), html.Td(" ")])
    row9 = html.Tr([html.Td(str(curr) + " " + p + " interest rate"), html.Td(" ")])
    row10 = html.Tr([html.Td("USD " + p + " interest rate"), html.Td(" ")])
    row11 = html.Tr([html.Td("Interest rate spread"), html.Td(" ")])
    row12 = html.Tr([html.Td("Fair value"), html.Td(" ")])
    row13 = html.Tr([html.Td("Anomaly"), html.Td(" ")])
    row14 = html.Tr([html.Td("Sell 1x " + curr + "/USD future at:"), html.Td(" ")])
    row15 = html.Tr([html.Td("Borrow USD"), html.Td(" ")])
    row16 = html.Tr([html.Td("Convert USD"), html.Td(" ")])
    row17 = html.Tr([html.Td("Deposit ",curr), html.Td(" ")])
    row18 = html.Tr([html.Td("After "+p), html.Td(" ")])
    row19 = html.Tr([html.Td("Value of "+curr), html.Td(" ")])
    row22 = html.Tr([html.Td("Deliver amount"), html.Td(" ")])
    row23 = html.Tr([html.Td("Receive interest"), html.Td(" ")])
    row24 = html.Tr([html.Td("Repay loan interest at " + str(rf) + "%"), html.Td(" ")])
    row25 = html.Tr([html.Td("Profit"), html.Td(" ")])
    table_body = [html.Tbody([row1, row2, row3, row4,row5,row6,row7,row8,row9,row10,row11,row12,row13,row14,row15,row16,row17,row18,
                          row19,row22,row23,row24,row25])]
    table = html.Div(html.P(dbc.Table(table_body, bordered=False)))

  #  if len(curr)

    # if selected_rows != None:
    #     print(data)
    #     print(currname)
    #     copy = str(data)
    #     copy_split = copy.split('}')
    #     print(copy_split)
    #     print("NOT NONE")
    #     print(selected_rows)
    return table

if __name__ == '__main__':
 #   app.run_server(host='0.0.0.0', port=8080, debug=True, use_reloader=False)
    app.run_server()


'''File to train and save Classical ML model'''
import pandas as pd
import pickle
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import cross_val_score

def calculate_confidence_interval(model, x, y, CV):
    '''function to calculate the confidence interval of a classification made.
    I do not know if accuracy is normally distributed for this data, so I am going to
    calcuate confidence interval using bootstrap resampling methods'''
    accuracies = cross_val_score(model,x,y,scoring='accuracy',cv=CV) #get accuracies from bootstrapped test data
    mean_acc = accuracies.mean()
    bounds_acc = accuracies.std() * 2
    print(f"Accuracy: {mean_acc}% +/- {bounds_acc}% with 95% likelihood")

def get_data():
    x_train = pd.read_csv("data/x_train.csv", header=0)
    y_train = pd.read_csv("data/y_train.csv", header=0)
    x_test = pd.read_csv("data/x_test.csv", header=0)
    y_test = pd.read_csv("data/y_test.csv", header=None)
    x_val = pd.read_csv("data/x_val.csv", header=0)
    y_val = pd.read_csv("data/y_val.csv", header=None)
    return x_train, y_train, x_test, y_test, x_val, y_val

random_seed = 0 # should be same across all files
x_train, y_train, x_test, y_test, x_val, y_val = get_data()
models = [
    RandomForestClassifier(n_estimators=200, max_depth=3, random_state=random_seed),
    MultinomialNB(),
    LogisticRegression(random_state=random_seed),
    #SVC(gamma='auto'),
    #KNeighborsClassifier(n_neighbors=3)
]

# Experimentation
CV = 5
for model in models:
    model_name = models.__class__.__name__
    accuracies = cross_val_score(model,x_train,y_train,scoring='accuracy',cv=CV)
    print(model_name, accuracies)

# on best model: LR
from sklearn.metrics import confusion_matrix
clf = LogisticRegression(random_state=random_seed).fit(x_train,y_train)
# save model
pickle.dump(clf, open('saved_data_objects/LRModel.pkl', 'wb'))
y_pred = clf.predict(x_val)
print("Accuracy on Val set: ", clf.score(x_val,y_val))
print("Confusion Matrix for validation data set: ")
print(confusion_matrix(y_val, y_pred))
calculate_confidence_interval(clf,x_train,y_train,10)


from django.conf.urls import *

urlpatterns = patterns('comunicacion.notas.views',
    url(r'^$', 'index'),
    url(r'^index-filtrado/(?P<pais_id>\d+)/$', 'index_filtrado', name='filtrar-index'),
    url(r'^notas/$', 'lista_notas', name="notas_list"),
    url(r'^notas-contraparte/(?P<id>\d+)/$', 'lista_notas_contraparte', name="notas_list_contraparte"),
    url(r'^notas-usuario/(?P<id>\d+)/$', 'lista_notas_usuario', name="notas_list_usuario"),
    url(r'^pais/(?P<id>\d+)/$', 'lista_notas_pais', name="notas-list-pais"),
    url(r'^ver/(?P<id>\d+)/$', 'comentar_nota', name='comentar-nota'),
    url(r'^(?P<id>\d+)/$', 'detalle_notas', name='detalle-notas'),
    url(r'^crear/$', 'crear_nota', name="crear-nota"),
    url(r'^editar/(?P<id>\d+)/$', 'editar_nota', name='editar-nota'),
    url(r'^borrar/(?P<id>\d+)/$', 'borrar_nota', name='borrar-nota'),

    )


#!/usr/bin/env python

from __future__ import print_function
import pylab as pl

import merge_sensor_data as msd

def main():
	data, fmt = msd.unpack_binary_data_into_list(
		'/home/t/Desktop/fatigueBSN/fatigue_test_data/Terence/12_03_2002_mind.dat'
	)

	low_alpha_data = [x[3] for x in data]
	high_alpha_data = [x[4] for x in data]

	differences = []
	for i in range(len(low_alpha_data)):
		differences.append(high_alpha_data[i] - low_alpha_data[i])

	pl.plot(range(len(high_alpha_data)), high_alpha_data, label = 'High Alpha')
	pl.plot(range(len(low_alpha_data)), low_alpha_data, label = 'Low Alpha')
	pl.xlabel("Time Step")
	pl.ylabel("Reading Value (Hz)")
	pl.title("Alpha EEG Readings")

	legend = pl.legend(loc='best', ncol=2, shadow=None)
	legend.get_frame().set_facecolor('#00FFCC')
	pl.show()

	# pl.plot(range(len(high_alpha_data)), high_alpha_data, label = 'High')
	# pl.xlabel("Time Step")
	# pl.ylabel("Reading Value")
	# legend = pl.legend(loc='best', ncol=2, shadow=None)
	# legend.get_frame().set_facecolor('#00FFCC')
	# pl.show()

  # plot data
#  print len(eeg_datapoints)
#  print len(attention_datapoints)

#  attention_datapoint_vals = [point.attentionValue for point in attention_datapoints]

  # will the following give us a good speed increase over using list comprehensions?
  # or will the readability be better?
#  delta_points = []
#  theta_points = []
#  lowAlpha_points = []
#  highAlpha_points = []
#  lowBeta_points = []
#  highBeta_points = []
#  lowGamma_points = []
#  midGamma_points = []

#  for datapoint in eeg_datapoints:
    # print(datapoint)
#    delta_points.append(datapoint.delta)
#    theta_points.append(datapoint.theta)
#    lowAlpha_points.append(datapoint.lowAlpha)
#    highAlpha_points.append(datapoint.highAlpha)
#    lowBeta_points.append(datapoint.lowBeta)
#    highBeta_points.append(datapoint.highBeta)
#    lowGamma_points.append(datapoint.lowGamma)
#    midGamma_points.append(datapoint.midGamma)

  # two plots will make the data look more presentable since the scales
  # of the data vary widely (maybe even more, like a plot per greek letter
  # or something)

  # plot the EEG components (scale: 0 - large)
#  pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(delta_points)) for i in delta_points], label="Delta")
#  pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(theta_points)) for i in theta_points], label="Theta")
#  pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(lowAlpha_points)) for i in lowAlpha_points], label="Low-Alpha")
#  pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(highAlpha_points)) for i in highAlpha_points], label="High-Alpha")
#  pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(lowBeta_points)) for i in lowBeta_points], label="Low-Beta")
#  pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(highBeta_points)) for i in highBeta_points], label="High-Beta")
#  pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(lowGamma_points)) for i in lowGamma_points], label="Low-Gamma")
#  pl.plot(range(len(eeg_datapoints)), [float(i)/float(sum(midGamma_points)) for i in midGamma_points], label="Mid-Gamma")

#  pl.xlabel("Time Step")
#  pl.ylabel("Reading Value")

#  legend = pl.legend(loc='best', ncol=2, shadow=None)
#  legend.get_frame().set_facecolor('#00FFCC')

  # pl.yscale('log')

#  pl.show()

  # plot the attention reading (scale: 1- 1001)
#  pl.plot(range(len(attention_datapoints)), attention_datapoint_vals, label="Attention")
#  pl.xlabel("Time Step")
#  pl.ylabel("Reading Value")

#  legend = pl.legend(loc='best', ncol=2, shadow=None)
#  legend.get_frame().set_facecolor('#00FFCC')
#  pl.show()

if __name__ == '__main__':
  main()


class pasien:
    #class variabel
    jumlah_pasien = 0
    #konstruktor
    def __init__(self, nama, berat, tinggi):
        self.nama = nama
        self.berat = berat
        self.tinggi = tinggi
        pasien.jumlah_pasien += 1

    #methode / fungsi
    def bmi(self):
        bmi = self.berat/(self.tinggi**2)
        print("BMI = ", bmi)
        if bmi < 18.5:
            print("kekurangan berat badan.")
        elif bmi > 18.5 and bmi <=24.9:
            print("berat badan ideal.")
        elif bmi > 24.9 and bmi <= 29.9:
            print("berat badan berlebih.")
        else:
            print("obesitas.")

    def beratIdeal(self):
        ideal = (self.tinggi*100 - 100) - (10/100 * (self.tinggi*100 - 100))
        print("BB Ideal = ", ideal)
        print("---------------------")

#instansiasi objek / pembuatan objek
pasien1 = pasien("wawan", 110, 1.7)
pasien2 = pasien("umi", 62, 1.65)
#pemanggilan pasien 1
pasien1.bmi()
pasien1.beratIdeal()
#pemanggilan pasien 2
pasien2.bmi()
pasien2.beratIdeal()

print("jumlah pasien : ", pasien.jumlah_pasien)


from flask_restplus import Namespace, Resource, fields, reqparse
from flask import request, jsonify, make_response,g
import json
from app.models import Bucketlist, Item, dump_datetime
from app import db
from sqlalchemy import func, Column, Integer, String
from sqlalchemy.orm import joinedload
from app.apis.auth import auth
from datetime import datetime, date
from flask_cors import CORS, cross_origin
# from app.apis.parsers import pagination_arguments

# This namespace is used to control CRUD operations for buckets and items
api = Namespace('bucketlists',
                description='Create, Read, Update, Display Buckets and Items')
# CORS(api) #S,resources={r"/": {"origins": "*"}},allow_headers = ['Content-Type', 'Authorization'])

# This holds the name of bucket being created
bucketlist= api.model('BucketlistPost', {
                    'name': fields.String(required=True,
                            description = "The Bucket List name"),
                    'description': fields.String(description ="Details about the Bucketlist")
                    })
# This holds names of items being created in a bucket list
items_fields = api.model('BucketlistItemUpdate', {
                    'name': fields.String(
                            description = "Item name to be Edited"),
                    'description': fields.String(description= "Item Description"),
                    'done': fields.Boolean(
                            description = 'Status of Item True or False',
                            default = "false")
                            })

# The parsers below are used to get apylod data from the user
parser = reqparse.RequestParser()
parser.add_argument('bucketlist_id')
parser.add_argument('item_id')
parser.add_argument('name')
parser.add_argument('item_name')
parser.add_argument('done')
parser.add_argument('user_id')

bucket_lists = api.model('Bucketlist', {
                    'id':fields.Integer(description = "Bucket ID"),
                    'name': fields.String(
                            description = "Bucket name"),
                    'description': fields.String(description ="Details about the Bucketlist"),
                    'date_created':fields.DateTime,
                    'date_modified': fields.DateTime,
                    'created_by': fields.Integer(
                            description= "User whoc created this bucket")
                    })
bucket_list_items = api.model('BucketListItems', {
                    'id': fields.Integer(description = "Bucket Item ID"),
                    'name': fields.String(
                            description = "Bucketlist Name"),
                    'description': fields.String(description ="Details about the Item"),
                    'done': fields.Boolean( description = "True or False"),
                    'date_created':fields.DateTime,
                    'date_modified': fields.DateTime,
                    'created_by': fields.Integer(
                            description= "User who created this bucket")
})

#Set minimum number of items per page
min_number_of_buckets_per_page = 20
max_number_of_buckets_per_page = 100
# Pagination parsers
pagination_arguments = reqparse.RequestParser()
pagination_arguments.add_argument('page', type=int, required=False,
                                    default=1, help='Page number')
pagination_arguments.add_argument('bool', type=bool, required=False,
                                    default=1, help='Page number')
#Set number of results per page
pagination_arguments.add_argument('per_page', type=int, required=False,
                            default=20, help='Results per page {error_msg}')
pagination_arguments.add_argument('search', type=str, required=False, default = '')

pagination = api.model('A page of results', {
    'page': fields.Integer(description='Number of this page of results'),
    'pages': fields.Integer(description='Total number of pages of results'),
    'per_page': fields.Integer(description='Number of items per page of results'),
    'total': fields.Integer(description='Total number of results'),
})

page_of_bucket_lists = api.inherit('Page of blog posts', pagination, {
    'items': fields.List(fields.Nested(bucket_lists))
})

@api.route('/')
class BucketLists(Resource):
    """This Resource is used to create buckets and lists all buckets"""
    @api.response(200,'Success')
    @auth.login_required
    @api.expect(pagination_arguments)
    @api.marshal_with(page_of_bucket_lists)
    # @cross_origin(origin='*')
    def get(self):
        """ This method returns buckets created by an individual user."""
        args = pagination_arguments.parse_args(request)
        page = args.get('page', 1)
        search = args.get('search','')
        per_page = args.get('per_page', 6)
        if per_page < min_number_of_buckets_per_page:
            per_page = min_number_of_buckets_per_page

        if per_page > max_number_of_buckets_per_page:
            per_page = max_number_of_buckets_per_page

        if search:
            search = search.lower()
            bucket_lists = Bucketlist.query.filter(
                (Bucketlist.created_by == g.user.id),
                (func.lower(Bucketlist.name).like("%"+search+"%"))
                )
        else:
            bucket_lists = Bucketlist.query.filter(Bucketlist.created_by == g.user.id)

        bucket_list_page = bucket_lists.paginate(page, per_page, error_out=False)
        return bucket_list_page, 200

    @api.response(201, 'Success')
    @api.expect(bucketlist)
    @auth.login_required
    def post(self):
        """
        This post method is used to create buckets for a user already logged in.
        :params :name
        :returns :200 for succesful post
        """
        args = parser.parse_args()
        name = args.name.strip()
        created_by = g.user.id
        if not name:
            return {"message": "Please provide a name for your bucketlist"}, 405

        bucketlist = Bucketlist.query.filter_by(name=name, created_by=created_by).first()
        if bucketlist:
            return {'message': 'Bucket with similar name already exists'}, 400

        bucketlist = Bucketlist(name,created_by)
        db.session.add(bucketlist)
        db.session.commit()
        return {'message': 'Bucket list created Successfully'}, 201

@api.route('/<bucketlist_id>')
class BucketListView(Resource):
    """This Resource displays, edits and deleted as single bucket"""
    @auth.login_required
    # @api.marshal_with(bucket_list_items)
    def get(self, bucketlist_id):
        """
        This method is used to list details of a bucket and it's items
        :params bucketlist_id: id of individaual bucket to retrieved from the db
        :returns - bucketlist and all it's items
        """
        bucketlist_items = Bucketlist.query.options(joinedload(Bucketlist.items)).filter_by(id = bucketlist_id).first()
        if not bucketlist_items:
            return {"message": "Bucket " + bucketlist_id + " Doesn't Exist"}, 404
        result ={}
        result['id'] = bucketlist_items.id
        result['name'] = bucketlist_items.name
        result['created_by'] = bucketlist_items.created_by
        result['date_modified'] = dump_datetime(bucketlist_items.date_modified)
        result['date_created'] = dump_datetime(bucketlist_items.date_created)
        result['items'] = ([i.serialize for i in bucketlist_items.items])
        return result , 200

    # @api.response(204, "Update Successful")
    @api.expect(bucketlist)
    @auth.login_required
    def put(self, bucketlist_id):
        """
        This method is used to edit/ update the name and status of a bucket
        :params bucketlist_id:
        """
        args = parser.parse_args()
        name = args.name

        if not name:
                return {"message": "Please provide a new name for your bucketlist"}, 400
        bucketlist = Bucketlist.query.filter(Bucketlist.id == bucketlist_id).first()

        if not bucketlist:
            return {"message": "The Buckelist " + bucketlist_id + " provided doesn't exist ...."}, 404

        bucketlist.name = args.name
        db.session.add(bucketlist)
        db.session.commit()
        return {"message": "Bucket list name updated or changed Successfully"}, 204

    @auth.login_required
    # @api.doc(params={'bucketlist_id': 'Bucketlist ID'})
    def delete(self, bucketlist_id):
        """
        This method is used to delete buckets and there respective items
        :params bucketlist_id: ID of bucket being deleted
        """
        bucketlist = Bucketlist.query.filter(Bucketlist.id == bucketlist_id).first()

        if not bucketlist:
            return {"message": "The Buckelist "+bucketlist_id+ " provided doesn't exist ...."}, 400

        db.session.delete(bucketlist)
        db.session.commit()
        return{"message" : "Bucketlist "+bucketlist_id+" deleted succesfully."}, 201

@api.route('/<bucketlist_id>/items/')
class BucketListItem(Resource):
    """
    This resource is used to manage creating, updating and deleting items from
    a bucket.
    """
    @api.expect(items_fields)
    @auth.login_required
    def post(self, bucketlist_id):
        """
        This method creates an item in a particular bucket
        :params bucketlist_id: ID of the bucket that we are creating item for
        """
        args = parser.parse_args()
        name = args.name
        if not name:
            return {"message": "Please provide a name for your item"}, 400

        bucketlist = Bucketlist.query.filter_by(id = bucketlist_id)
        if not bucketlist:
            return {"message": "Bucketlist Doesn't exist"}, 404

        bucketlist_item = Item.query.filter_by(
            name=name, bucketlist_id=bucketlist_id).first()
        if bucketlist_item:
            return {"message": "Item with this name already exits"}, 400

        name = args.name
        done = args.done
        new_item = Item(name, bucketlist_id)
        db.session.add(new_item)
        db.session.commit()
        return {'message': 'Item created Successfully'}, 201

@api.route('/<bucketlist_id>/items/<item_id>')
class BucketListItems(Resource):
    @api.expect(items_fields)
    @auth.login_required
    def put(self, bucketlist_id, item_id):
        """
        This method is used to update the name and status of an item.
        :params bucketlist_id: ID of bucket that contains the item
        :params item_id: ID of the item being updated
        :return : Returns the message item status updated succesfully
        """
        args = parser.parse_args()
        name = args.name.strip()
        done = args.done.strip()
        if not name:
            return {"message" : "Please Supply Name and done status."}, 400

        if not done:
            return {"message": "Please Supply Name and done status."}, 400

        bucketlist = Bucketlist.query.filter(
            Bucketlist.id == bucketlist_id).first()

        if not bucketlist:
            return {"message": "Bucketlist ID " + bucketlist_id + " is incorrect"}, 404
        bucketlist_item = Item.query.filter(Item.id == item_id).first()

        if not bucketlist_item:
            return {"message": "Item " + item_id + "Doesn't Exist"}

        bucketlist_item.name = args.name
        bucketlist_item.done = args.done
        db.session.add(bucketlist_item)
        db.session.commit()
        return {'message': 'Item Status updated Successfully'}, 204

    @auth.login_required
    def  delete(self, bucketlist_id, item_id):
        """
        This method deletes an item from a bucket list
        :params bucketlist_id: ID of bucketlist the item will be deleted from
        :params item_id: ID of the item being deleted"""
        bucketlist = Bucketlist.query.filter(Bucketlist.id == bucketlist_id).first()
        if not bucketlist:
            return {'message': "The Bucket " + bucketlist_id + " passed does not exist"}, 404

        bucketlist_item = Item.query.filter(Item.id == item_id).first()
        if not bucketlist_item:
            return {"message": "Item " + item_id + " Doesn't Exist"}, 404

        db.session.delete(bucketlist_item)
        db.session.commit()
        return {'message':'Item Deleted succesfully'}, 200


#!/usr/local/bin/env python3
# -*- coding: utf-8 -*-#
#
# Author      : Bhishan Poudel; Physics Graduate Student, Ohio University
# Date        : Jan 4, 2017
# Update      : Jun 22, 2017 Thu

# Imports
import os
import subprocess
import glob
import re
import natsort
from astropy.io.fits import getval
import numpy as np

# Variables
NCOLS                 = 5
NROWS                 = 4
flgs                  = '-scale log -cmap a -tile grid ' +\
                        'layout %d %d'%(NCOLS, NROWS)    + ' ' +\
                        '-match colorbar -match scale -match scalelimits' + ' '
# Variables for input fitsfiles to open
fit                   = '/Users/poudel/Research/galfit_usage/' +\
                        'verify_2cmp_fitting/f814w_fitting'
devauc_one_comp       = '%s/devauc_one_comp/f814w_devauc_one_comp'%fit
res_one_comp_devauc   = '%s/residual_one_comp_devauc/f814w_res_one_comp_devauc'%fit
expdisk_one_comp      = '%s/expdisk_one_comp/f814w_expdisk_one_comp'%fit
res_one_comp_expdisk  = '%s/residual_one_comp_expdisk/f814w_res_one_comp_expdisk'%fit
devauc_two_comp       = '%s/devauc_two_comp/f814w_devauc_two_comp'%fit
expdisk_two_comp      = '%s/expdisk_two_comp/f814w_expdisk_two_comp'%fit
res_two_comp          = '%s/residual_two_comp/f814w_res_two_comp'%fit
gal                   = '%s/stamps_f8/f814w_gal'%fit

nums = [1, 14, 31, 33, 38, 40, 41, 44, 46, 52, 54, 56, 59, 69, 73,
                76, 79, 80, 81, 85, 90, 92, 95, 138, 139, 141, 166, 180, 181,
                200, 203, 218, 230, 243, 265, 266, 278, 293]

def open_in_ds9(nums):
    """Open fitsfiles in ds9 with some flgs.

    ds9 flgs:
        ds9 -scale log -cmap a -tile grid layout 6 4 -match colorbar
            -match scale -match scalelimits FITSFILES_NAMES

    Reference:
        http://ds9.si.edu/doc/ref/command.html#scale

    """

    files     = [devauc_one_comp, res_one_comp_devauc,  res_one_comp_expdisk, expdisk_one_comp, gal ]
    chunks = [nums[i:i + NROWS] for i in range(0, len(nums), NROWS)]
    for chunk in chunks:
        files_lst = [ (f + str(_) + '.fits ' + flgs)  for _ in chunk for f in files]
        files_all = " ".join(files_lst)

        # ds9 command with flags
        ds9 = '/Applications/ds9.app/Contents/MacOS/ds9' + ' '
        cmd = ds9 + ' -height 1200 ' + ' -width 2500 ' + files_all
        subprocess.call(cmd, shell=True)

if __name__ == "__main__":
    open_in_ds9(nums)


#coding:utf-8
import unittest
import HTMLTestRunner
from LX import *
class Testxl(unittest.TestCase):
    # TestCase基类方法，所有case执行之前自动执行
    @classmethod
    def setUpClass(cls):
        print('测试用例前的准备工作')
    @classmethod
    def tearDownClass(cls):
        print('测试用例后的清理工作')
    # 测试前准备环境的搭建(setUp)
    def setUp(self):
        print('这是一个用例前的准备工作')
    # 测试后环境的还原(tearDown),相当于初始化
    def tearDown(self):
        print('这是一个用例后的清理工作')
    def test_add(self):
        self.assertEqual(3,add(1,2))
        print('执行完毕1')
        # self.assertEqual(4,add(2,3))
    def test_a(self):
        self.assertEqual(3,a(9,6))
        print('执行完毕2')
        # self.assertEqual(3, a(12, 6))
    def test_ad(self):
        # self.assertEqual(3, ad(9, 6))
        self.assertEqual(18, ad(3, 6))
        print('执行完毕3')
    def test_dd(self):
        self.assertEqual(3, dd(9, 3))
        print('执行完毕4')
        # self.assertEqual(3, dd(12, 6))

if __name__ == '__main__':
######## 第一种方法：
     # verbosity报告的详细程度
     # unittest.main(verbosity=2)
######## 第二种方法：
    # 实例化unittest对象
    # suite = unittest.TestSuite()
     # 调用TestSuite类中的addTest：suite.addTest(类名(‘类中的方法名’))
     # 执行顺序是按照添加的顺序执行，先添加的先执行
    # suite.addTest(Testxl('test_dd'))
    # suite.addTest(Testxl('test_a'))
    # runner = unittest.TextTestRunner()
    # runner.run(suite)
######## 第三种方法：
    # start_dir ：要测试的模块名或测试用例目录。（采用双斜线或目录前加r）
    # pattern='test*.py' ：表示用例文件名的匹配原则。星号“*”表示任意多个字符。
    # top_level_dir=None：测试模块的顶层目录。如果没顶层目录（也就是说测试用例不是在该目录下则需要分别指定），默认为 None。
    discover = unittest.defaultTestLoader.discover('F:\\test\\code\\vip3test\\unittest_lx',pattern='test*.py',top_level_dir=None)
    print('11111')
    filename = 'F:\\test\\code\\vip3test\\unittest_lx\\result.html'
    fp = open(filename,'wb')
    print('报告')
    runner = HTMLTestRunner.HTMLTestRunner(
        stream =fp,
        title =u'测试报告',
        description = u'用例执行情况'
    )
    print('报告写入完毕')
    runner.run(discover)
    fp.close()


import random
import time
import threading

PARKOMAT_PRICE = 50000
SERVICE_PRICE = 100
SALARY = 50
MAX_DEBT = -90000
MONTH = 60
RENT_TICK = 20
global gameStatus

class Model:

    def __init__(self):
        self.__availableParcomats = 0
        self.__rentedParkomat = 0
        self.__staffAmount = 0
        self.__budget = 500000
        self.__price = 700

    def buyParkomats(self, num = 1):
        if (PARKOMAT_PRICE*num) > self.__budget:
            print("\nУ Вас не хватает денег")
        elif (self.__rentedParkomat + self.__availableParcomats + 1)//10 >= self.__staffAmount:
            print("\nУ Вас недостаточно сотрудников")
        else:
            self.__budget -= (PARKOMAT_PRICE*num)
            self.__availableParcomats += num

    def rentParkomat(self, num=1):
        if self.__availableParcomats < num:
            print('\nУ Вас недостаточно паркоматов')
        else:
            self.__rentedParkomat += num
            self.__availableParcomats -= num

    def getAvailableParkomats(self):
        return self.__availableParcomats

    def hireStaff(self, num=1):
        self.__staffAmount += num

    def calculateProfit(self):
        income = self.__getIncome()
        print(f"\nДоход: {income}")
        expenses = self.__calculateExpenses()
        print(f"\nРасход: {expenses}")
        profit = income - expenses
        print(f"\nПрибыль: {profit}")
        self.__budget += profit

    def getBuget(self):
        return self.__budget

    def __getIncome(self):
        return self.__rentedParkomat*self.__price

    def __calculateExpenses(self):
        temp = .5 * self.__availableParcomats + .8 * self.__rentedParkomat
        temp += SALARY * self.__staffAmount
        return temp

    def setPrice(self, price):
        self.__price = price

def generateClient(model):
    time.sleep(RENT_TICK)
    while gameStatus:
        clients = random.randint(0, model.getAvailableParkomats())
        model.rentParkomat(num=clients)
        print(f"\nПришло клиентов: {clients}")
        time.sleep(RENT_TICK)

def environment(model):
    time.sleep(MONTH)
    while model.getBuget() > MAX_DEBT:
        model.calculateProfit()
        time.sleep(MONTH)
    gameStatus = False

if __name__ == '__main__':
    model = Model()
    gameStatus = True
    threads = list()
    threads.append(threading.Thread(target=generateClient, args=(model, )))
    threads.append(threading.Thread(target=environment, args=(model, )))
    [t.start() for t in threads]
    states = {'1': model.buyParkomats,
              '2': model.hireStaff}
    while gameStatus:
        do = input('\n1:Купить паркомат. 2: Нанять сотрудников')
        if 'q' == do:
            gameStatus = False
            exit()
        col = input('\nКоличество: ')
        action = states.get(do, None)
        if action is None:
            print("\nНет такого действия")
            continue
        action(num=int(col))
    [t.join() for t in threads]
    print("\nКонец игры!")


"""
File: complement.py
Name: Isabelle
----------------------------
This program uses string manipulation to
tackle a real world problem - finding the
complement strand of a DNA sequence.
THe program asks uses for a DNA sequence as
a python string that is case-insensitive.
Your job is to output the complement of it.
"""

def main():
    """
    The program will find the complement of DNA strand the user input.
    """
    dna=input("Please gibe me a DNA strand and I'll find the complement: ").upper()
    new_dna=build_complement(dna)

def build_complement(dna):
    ans=''
    for i in dna:
        if i=='A':
            ans+='T'
        elif i=='T':
            ans+='A'
        elif i=='C':
            ans+='G'
        elif i=='G':
            ans+='C'
    print('The complement of '+ dna+' is '+ ans)

###### DO NOT EDIT CODE BELOW THIS LINE ######
if __name__ == '__main__':
    main()


import cv2
import numpy as np
import random

def text_to_image(text, output_file="output.png", font_scale=0.6, font_thickness=1, image_size=(800, 400), text_color=(0, 0, 0), bg_color=(255, 255, 255), font=cv2.FONT_HERSHEY_SIMPLEX):
    try:
        # Create a blank image with the specified background color and size
        image = np.ones((image_size[1], image_size[0], 3), dtype=np.uint8)
        image[:] = bg_color

        # Create a font scale and thickness for text rendering
        font_scale = image_size[1] * font_scale
        font_thickness = int(image_size[1] * font_thickness)

        # Calculate the text size and position it in the center
        text_size = cv2.getTextSize(text, font, font_scale, font_thickness)[0]
        x = (image_size[0] - text_size[0]) // 2
        y = (image_size[1] + text_size[1]) // 2

        # Generate a random text color if not specified
        if text_color == "random":
            text_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

        # Draw the text on the image
        cv2.putText(image, text, (x, y), font, font_scale, text_color, font_thickness, lineType=cv2.LINE_AA)

        # Save the image as the specified output file
        cv2.imwrite(output_file, image)

        print(f"Image saved as '{output_file}'")

    except Exception as e:
        print(f"Error: {str(e)}")

if __name__ == "__main__":
    text = input("Enter the text you want to convert to an image: ")
    output_file = input("Enter the output image file name (e.g., 'output.png'): ")

    text_to_image(text, output_file)


import pandas as pd
import hhelper
import htf
import numpy as np

class Data:

    def __init__(self, dir_data, dir_doid,max_depth):
        self.data_mit = pd.read_csv(dir_data)
        self.doid_labels = pd.read_pickle(dir_doid)
        self.max_depth = max_depth

    def filter_data(self, tpm_cutoff=1):
        # idx for exons with TPM >1
        # TODO: investigate with 1 is a good cutoff
        rm_me = list(self.data_mit.max(axis=1) > tpm_cutoff)
        # set exon names as index
        self.data_mit.set_index('exons', inplace=True, drop=False)
        # select exons with TPM >1
        self.data_mit = self.data_mit.loc[rm_me]
        # select exons with valid labeling
        self.data_mit = self.data_mit[~pd.isna(self.data_mit['labels']) == True]
        # send to preprocess (drops zeros, ambigious exons (exons annotated with multiple diseases)
        # and does max-min scaling)
        self.data_mit = htf.pre_process(self.data_mit)
        # convert label string to list
        self.data_mit['labels'] = self.data_mit['labels'].apply(hhelper.str_to_list)
        # list of lenghts (i.e. depth) of label list per exon
        labeling_depth = list(map(len, self.data_mit['labels'].values))
        # idx for exons with depth >= XX
        min_length = list(map(lambda x: x >= self.max_depth + 1, labeling_depth))
        # select exons with min depth
        self.data_mit = self.data_mit[min_length]

    def build_tree(self):
        df_tree = hhelper.build_tree(self.data_mit, self.doid_labels)

        # this tree has to be pruned now to the desired subtree
        # 'disease' is the only entry on lvl 0
        # drop all lvl 1 nodes that are not XX and 'disease'
        use_this_tree = df_tree.drop(df_tree[(df_tree['label'] != 'disease of anatomical entity') &
                                             (df_tree['lvl'] <= 1)].index)

        # now that we removed some of the top nodes, let's remove all their children
        # starting one lvl below new root node to not remove root node
        for lvl in range(2, self.max_depth + 1):
            # remove parent less nodes
            use_this_tree.drop(use_this_tree[~use_this_tree['parent'].isin(use_this_tree['id'].values) &
                                             (use_this_tree['lvl'] == lvl)].index, inplace=True)

        # drop all nodes below lvl 1 that have less than XX members
        use_this_tree.drop(use_this_tree[(use_this_tree['count_all'] < 50) &
                                         (use_this_tree['lvl'] > 1)].index, inplace=True)
        # drop all nodes below max depth
        use_this_tree.drop(use_this_tree[use_this_tree['lvl'] > self.max_depth].index, inplace=True)

        # remove leaf nodes w/o siblings
        number_of_sib = []
        for label in use_this_tree['label'].values:
            # get int value of parent for given label and the number of siblings for label
            parent = use_this_tree.loc[use_this_tree['label'] == label, 'parent'].values[0]
            number_of_sib.append(use_this_tree[use_this_tree['parent'] == parent].shape[0])

        # number_of_sib if 1 it has 0 siblings, the 1 come from counting the node itself
        use_this_tree['number_of_sib'] = number_of_sib
        use_this_tree.drop(use_this_tree[(use_this_tree['number_of_sib'] < 2) &
                                         (use_this_tree['lvl'] == self.max_depth)].index, inplace=True)

        # remove children less nodes from bottom up
        for lvl in range(self.max_depth - 1, 1, -1):
            print(lvl)
            use_this_tree.drop(use_this_tree[~use_this_tree['id'].isin(use_this_tree['parent'].values) &
                                             (use_this_tree['lvl'] == lvl)].index, inplace=True)

        # reindex df such that idx corresponds to axis=1 cooridnate in label matrix
        # UWAGA:the root node (idx=0) is not a label and labels are therefor 1 indexed
        use_this_tree = use_this_tree.sort_values('lvl')
        use_this_tree['idx'] = range(use_this_tree.shape[0])
        use_this_tree.set_index('idx', inplace=True)

        # now make sure we only have data that is labeled for this tree
        # get all the leaf nodes
        leaf_nodes = use_this_tree.loc[use_this_tree['lvl'] == self.max_depth, 'label'].values
        # get the leaf node label for all data
        list_leaf_data = [x[4] for x in self.data_mit['labels'].values]
        # does the exon labeling contain one of the leaf nodes?
        bool_keep_data = [True if x in leaf_nodes else False for x in list_leaf_data]
        self.data_mit = self.data_mit[bool_keep_data]

        return use_this_tree

    def label_matrix(self, use_this_tree):
        label_matrix = np.zeros((self.data_mit.shape[0], use_this_tree.shape[0] - 1))

        # TODO: find a way to avoid at least one loop

        # loop through each exon and assign labels to label_matrix
        for i, list_labels in enumerate(self.data_mit['labels']):
            # loop through the list starting on the first lvl after root node
            for label in list_labels[2:5]:
                # get label idx
                idx = use_this_tree[use_this_tree['label'] == label].index[0]
                # add to idx-1 (shift due to root node not beign a class)
                label_matrix[i, idx - 1] = 1

        # drop meta data and hstack to datamatrix
        # for_np = self.data_mit.drop(['labels', 'COID', 'phenString', 'DOID', 'exons'], axis=1)
        # np_data_mit = np.hstack([for_np, label_matrix])
        return label_matrix


from __future__ import unicode_literals
import frappe

def execute(filters=None):
	columns, data = [], []

	bulan = filters.get("month")
	string_bulan = ""
	if bulan == "January" :
		string_bulan = str("01")
	elif bulan == "February" :
		string_bulan = str("02")
	elif bulan == "March" :
		string_bulan = str("03")
	elif bulan == "April" :
		string_bulan = str("04")
	elif bulan == "May" :
		string_bulan = str("05")
	elif bulan == "June" :
		string_bulan = str("06")
	elif bulan == "July" :
		string_bulan = str("07")
	elif bulan == "August" :
		string_bulan = str("08")
	elif bulan == "September" :
		string_bulan = str("09")
	elif bulan == "October" :
		string_bulan = str("10")
	elif bulan == "November" :
		string_bulan = str("11")
	elif bulan == "December" :
		string_bulan = str("12")

	tahun = str(filters.get("year"))

	string_kondisi = str(tahun) + "-" + str(string_bulan) + "%"
	date_clause = """ WHERE l.`creation` LIKE "{0}" """.format(string_kondisi)

	result = frappe.db.sql("""
		SELECT l.`source`,s.`name`,SUM(1) FROM `tabLead`l JOIN `tabUser`u ON u.`name`=l.`lead_owner`
		JOIN `tabSales Person`s ON s.`name`=u.`sales_person`
		{0}
		GROUP BY l.`source`,s.`name`
		ORDER BY s.`name`
		""".format(date_clause),as_list=1)

	source_list = []
	sales_list = []
	data_dict = {}
	columns = ["Lead Source:Link/Lead Source:150"]
	for res in result :
		if res[0] not in source_list :
			source_list.append(res[0])
		if res[1] not in sales_list :
			sales_list.append(res[1])
			columns.append(res[1]+":Int:100")
		key = (res[0],res[1])
		data_dict[key] = res[2]
	columns.append("Total:Int:60")

	source_list.sort()
	data = []
	for source in source_list :
		total = 0
		data_row = [source]
		for sales in sales_list :
			key = (source,sales)
			if key in data_dict :
				lead_num = data_dict[key]
				total = total + lead_num
				data_row.append(lead_num)
			else :
				data_row.append(0)
		data_row.append(total)
		data.append(data_row)
	return columns, data


import torchvision
from torch import nn
from torch.nn import ReLU, Sigmoid
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

dataset = torchvision.datasets.CIFAR10('./dataset', train=False, transform=torchvision.transforms.ToTensor(),download=True)

dateloader = DataLoader(dataset, batch_size=64)

class reluEx(nn.Module):
    def __init__(self):
        super(reluEx, self).__init__()
        self.relu1 = ReLU()
        self.sigmoid1 = Sigmoid()

    def forward(self,x):
        x = self.sigmoid1(x)
        return x

relu = reluEx()
step = 0
writer = SummaryWriter('sigmoid')
for data in dateloader:
    imgs,targets = data
    output = relu(imgs)
    writer.add_images('input',imgs,step)
    writer.add_images('output', output, step)
    step += 1

writer.close()


# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
import tweepy

class Command(BaseCommand):

    def handle(self, *args, **options):
        api_keys = settings.TWITTER_USER_KEYS
        auth = tweepy.OAuthHandler(api_keys['consumer_key'], api_keys['consumer_secret'])

        try:
            redirect_url = auth.get_authorization_url()
        except tweepy.TweepError as e:
            print('Error! Failed to get request token.')
            raise e

        print(redirect_url)
        verifier = input('Verifier:')

        print(auth.get_access_token(verifier=verifier))


import numpy as np
import yfinance as yf
import pandas as pd
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense, LSTM
import os
# Lets save as csv and then upload to view and change to numpy. store all data in 1 file

symbols_file = pd.read_csv('static/mysite/nasdaq-listed-symbols_csv.csv')
symbols = symbols_file.pop('Symbol')
company_names = symbols_file.pop('Company Name')
data = []
preddata = []
# symbol_data = []
# prediction_data = []
count = 1

for symbol in range(len(symbols)):
    predict = []
    to_remove = []

    try:
        data = yf.download(tickers=symbols[symbol], period='max', interval='1d', group_by='ticker', auto_adjust=True,
                           prepost=True, proxy=None)
        print(symbols[symbol], count)
        OPEN, high, low, close, volume = data.pop('Open'), data.pop('High'), data.pop('Low'), data.pop(
            'Close'), data.pop('Volume')
        y = close
        y = y[1:]

        for i in range(len(close)):
            if np.isnan(close[i]):
                to_remove.append(i)
        for i in range(len(to_remove)):
            OPEN = OPEN[:to_remove[i] - i] + OPEN[to_remove[i] - i + 1:]
            high = high[:to_remove[i] - i] + high[to_remove[i] - i + 1:]
            low = low[:to_remove[i] - i] + low[to_remove[i] - i + 1:]
            close = close[:to_remove[i] - i] + close[to_remove[i] - i + 1:]
            volume = volume[:to_remove[i] - i] + volume[to_remove[i] - i + 1:]
            y = y[:to_remove[i] - i] + y[to_remove[i] - i + 1:]

        OPEN = (OPEN - min(OPEN)) / (max(OPEN) - min(OPEN))
        high = (high - min(high)) / (max(high) - min(high))
        low = (low - min(low)) / (max(low) - min(low))
        close = (close - min(close)) / (max(close) - min(close))
        volume = (volume - min(volume)) / (max(volume) - min(volume))

        for i in range(len(close)):
            predict.append([OPEN[i], high[i], low[i], close[i], volume[i]])

        predict, train_labels = np.array(predict), np.array(y)
        mx, mn = max(train_labels), min(train_labels)
        tl = train_labels
        train_labels = (train_labels - min(train_labels)) / (max(train_labels) - min(train_labels))
        train_data = predict[:-1]
        train_data = train_data.reshape(-1, 5, 1)

        model = Sequential()
        model.add(LSTM(256, activation='sigmoid', kernel_initializer='he_normal', input_shape=(train_data.shape[1:]),
                       return_sequences=True))
        model.add(LSTM(64, activation='sigmoid', kernel_initializer='he_normal', return_sequences=True))
        model.add(LSTM(64, activation='sigmoid', kernel_initializer='he_normal'))
        model.add(Dense(1, activation='linear'))

        model.compile(optimizer='adam', loss='mse', metrics=['mse'])
        model.fit(train_data, train_labels, epochs=10, batch_size=256, verbose=0)
        mse, mae = model.evaluate(train_data, train_labels, verbose=0)
        print('MSE: %.3f,  MAE: %.3f' % (mse, mae))

        predictions = model.predict(predict.reshape(-1, 5, 1))
        prediction = float(predictions[-1] * (mx - mn) + mn)
        print('Previous:', tl[-1], 'Prediction:', prediction)
        preddata.append([symbols[symbol], prediction, mse, np.array2string(np.flipud(tl[-7:]), separator=', ')[1:-1]])

        df = pd.DataFrame(np.array(preddata))
        for i in os.listdir('static/mysite/'):
            if i == 'data.csv':
                os.unlink('static/mysite/data.csv')
        df.to_csv('static/mysite/data.csv', index=False)
        # change to csv
        # data_file = open('static/mysite/prediction_data.txt', 'w')
        # for i in prediction_data:
        #     data_file.write(str(i))
        #     data_file.write(' ')
        # data_file.close()
        #
        # data_file = open('static/mysite/symbol_data.txt', 'w')
        # for i in symbol_data:
        #     data_file.write(str(i))
        #     data_file.write(' ')
        # data_file.close()
        # print('Predictions saved')

    except ValueError:
        print('Err~~')
        count -= 1

    count += 1

########################################################################################################################
# import numpy as np
# import yfinance as yf
# import pandas as pd
# from matplotlib.figure import Figure
# from tensorflow.keras import Sequential
# from tensorflow.keras.layers import Dense, LSTM
# import os
# import shutil
#
# symbols_file = pd.read_csv('static/mysite/nasdaq-listed-symbols_csv.csv')
# symbols = symbols_file.pop('Symbol')
# company_names = symbols_file.pop('Company Name')
#
# for file in os.listdir('static/mysite/saved_model_weights/'):
#     file_path = os.path.join('static/mysite/saved_model_weights/', file)
#     if os.path.isfile(file_path):
#         os.unlink(file_path)
#     else:
#         shutil.rmtree(file_path)
#
# for file in os.listdir('static/mysite/plots/'):
#     file_path = os.path.join('static/mysite/plots/', file)
#     os.unlink(file_path)
#
# for i in range(len(symbols)):
#     to_remove = []
#     count = 0
#     try:
#         data = yf.download(tickers=symbols[i], period='max', interval='1d', group_by='ticker', auto_adjust=True,
#                            prepost=True, proxy=None)
#         print(symbols[i], i)
#
#         train_data = np.array(data.pop('Open'))
#         train_labels = np.array(data.pop('Close'))
#         for _ in range(len(train_data)):
#             if np.isnan(train_data[_]):
#                 to_remove.append(_)
#
#         for _ in to_remove:
#             train_data = np.delete(train_data, _ - count)
#             count += 1
#         to_remove.clear()
#         count = 0
#
#         for _ in range(len(train_labels)):
#             if np.isnan(train_labels[_]):
#                 to_remove.append(_)
#
#         for _ in to_remove:
#             train_labels = np.delete(train_labels, _ - count)
#             count += 1
#
#         test = train_data
#         graph = train_data
#         close = train_labels
#         test = test.reshape(-1, 1, 1)
#         graph = graph.reshape(-1, 1, 1)
#         mx = max(train_data)
#         mn = min(train_data)
#         graph = (graph - mn) / (mx - mn)
#         train_data, train_labels = (train_data - mn) / (mx - mn), (train_labels - mn) / (mx - mn)
#         train_data = train_data.reshape(-1, 1, 1)
#
#         model = Sequential()
#         model.add(LSTM(256, activation='sigmoid', kernel_initializer='he_normal', input_shape=(train_data.shape[1:])))
#         model.add(Dense(128, activation='sigmoid', kernel_initializer='he_normal'))
#         model.add(Dense(64, activation='sigmoid', kernel_initializer='he_normal'))
#         model.add(Dense(1, activation='linear'))
#
#         model.compile(optimizer='adam', loss='mse', metrics=['mse'])
#         model.fit(train_data, train_labels, epochs=18, batch_size=256)
#         mse, mae = model.evaluate(train_data, train_labels, verbose=0)
#         print('MSE: %.3f,  MAE: %.3f' % (mse, mae))
#
#         predictions = model.predict(graph)
#         for _ in range(len(predictions)):
#             predictions[_] = predictions[_] * (mx - mn) + mn
#
#         fig = Figure()
#         ax = fig.subplots()
#         ax.plot(predictions, linewidth=0.6, label='Predicted Closing Price')
#         ax.plot(close, linewidth=0.6, label='Actual Closing Price')
#         ax.set_title(symbols[i] + ' (' + company_names[i] + ')' + ' Results From Model Training')
#         ax.set_xlabel('Days since IPO')
#         ax.set_ylabel('Price ($)')
#         ax.legend()
#         fig.savefig('static/mysite/plots/' + symbols[i] + '.PNG', dpi=300)
#
#         model.save('static/mysite/saved_model_weights/' + symbols[i] + '_saved_model.h5')
#         data_file = open(symbols[i] + ' data.txt', 'w')
#         for _ in test:
#             data_file.write(str(_[0][0]))
#             data_file.write(' ')
#         data_file.close()
#         os.rename(symbols[i] + ' data.txt', 'static/mysite/saved_model_weights/' + symbols[i] + ' data.txt')
#         print('Model saved')
#
#     except:
#         pass


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

import socket
# import test_pb2

server_address = "127.0.0.1"
server_port = 2233

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.bind(("127.0.0.1", 0))
client_socket.connect((server_address, server_port))
# client_socket.setblocking(False)

# test_msg = test_pb2.TestMessage()

# test_msg.id = 5226
# test_msg.name = "test_name"
# test_msg.content = "test_message_content"

# def parsMessage(msg):
#     length = len(msg)+8
#     size = (length).to_bytes(4, byteorder="big")
#     ty = (1).to_bytes(4, byteorder="big")
#     return size+ty+msg

for item in range(0, 100):
    # data = test_msg.SerializeToString()
    # print(data)
    # data = parsMessage(data)
    data= "test message "
    print(data)
    # str.encode(data)
    client_socket.send(data)

print("test-success!")

while True:
    data = client_socket.recv(1024)
    if data:
        print(data.decode('utf-8'))


from typing import Union, List, Dict

import pymongo
from pymongo.collection import Collection
from bson.son import SON

from .commands import AggregateCommand, FindCommand, CountCommand, \
    UpdateCommand, DistinctCommand, DeleteCommand, FindAndModifyCommand

Document = Union[dict, SON]

class ExplainableCollection():
    def __init__(self, collection, verbosity=None, comment=None):
        self.collection = collection
        self.last_cmd_payload = None
        self.verbosity = verbosity or "queryPlanner"
        self.comment = comment

    def _explain_command(self, command):
        command_son = command.get_SON()
        explain_command = SON([("explain", command_son)])
        explain_command["verbosity"] = self.verbosity
        if self.comment:
            explain_command["comment"] = self.comment
        self.last_cmd_payload = command_son
        return self.collection.database.command(explain_command)

    def update_one(self, filter, update, upsert=False,
                   bypass_document_validation=False,
                   collation=None, array_filters=None, hint=None,
                   session=None, **kwargs):
        command = UpdateCommand(self.collection, filter, update,
                                bypass_document_validation=
                                    bypass_document_validation,
                                array_filters=array_filters,
                                collation=collation, hint=hint,
                                upsert=upsert, multi=False)
        return self._explain_command(command)

    def update_many(self, filter: Document, update: Document, upsert=False,
                    array_filters=None, bypass_document_validation=False,
                    collation=None, hint=None, session=None, **kwargs):
        command = UpdateCommand(self.collection, filter, update, multi=True,
                                bypass_document_validation=bypass_document_validation, upsert=upsert, collation=collation, array_filters=array_filters, hint=hint)
        return self._explain_command(command)

    def distinct(self, key: str, filter: Document=None, session=None, **kwargs):
        command = DistinctCommand(self.collection, key, filter, kwargs)
        return self._explain_command(command)

    def aggregate(self, pipeline: List[Document], session=None, **kwargs):
        command = AggregateCommand(self.collection, pipeline,
                                   {}, kwargs)
        return self._explain_command(command)

    def estimated_document_count(self,
                                 **kwargs):

        command = CountCommand(self.collection, None, kwargs)
        return self._explain_command(command)

    def count_documents(self, filter: Document, session=None,
                                 **kwargs):

        command = AggregateCommand(self.collection, [{'$match': filter},
                                                     {'$group': {'n': {'$sum': 1}, '_id': 1}}]
                                   , {}, kwargs)
        return self._explain_command(command)

    def delete_one(self, filter: Document, collation=None, session=None,
                   **kwargs):
        limit = 1
        command = DeleteCommand(self.collection, filter, limit, collation,
                                kwargs)
        return self._explain_command(command)

    def delete_many(self, filter: Document, collation=None,
                    session=None, **kwargs: Dict[str, Union[int, str,
                                                            Document,
                                                      bool]]):
        limit = 0
        command = DeleteCommand(self.collection, filter, limit, collation,
                                kwargs)
        return self._explain_command(command)

    def watch(self, pipeline: Document = None, full_document: Document = None,
              resume_after= None,
              max_await_time_ms: int = None, batch_size: int = None,
              collation=None, start_at_operation_time=None, session=None,
              start_after=None):

        change_stream_options = {}
        if start_after:
            change_stream_options["startAfter"] = start_after
        if resume_after:
            change_stream_options["resumeAfter"] = resume_after
        if start_at_operation_time:
            change_stream_options["startAtOperationTime"] = start_at_operation_time
        if full_document:
            change_stream_options["fullDocument"] = full_document

        if pipeline is not None:
            pipeline = [{"$changeStream": change_stream_options}]+pipeline
        else:
            pipeline = [{"$changeStream": change_stream_options}]
        cursor_args = {}
        if batch_size:
            cursor_args["batchSize"] = batch_size
        command = AggregateCommand(self.collection, pipeline,
                                   cursor_args,
                                   {"collation":collation, "max_await_time_ms":
                                       max_await_time_ms})
        return self._explain_command(command)

    def find(self, filter: Document = None,
             **kwargs: Dict[str, Union[int, str,Document, bool]]):
        kwargs.update(locals())
        del kwargs["self"], kwargs["kwargs"]
        command = FindCommand(self.collection,
                              kwargs)

        return self._explain_command(command)

    def find_one(self, filter: Document = None, **kwargs: Dict[str,
                                                               Union[int, str,
                                                                Document, bool]]):
        kwargs.update(locals())
        del kwargs["self"], kwargs["kwargs"]
        kwargs["limit"] = 1
        command = FindCommand(self.collection, kwargs)
        return self._explain_command(command)

    def find_one_and_delete(self, filter: Document, projection: list = None,
                            sort: Document=None, session=None,
                        **kwargs):
        kwargs["query"] = filter
        kwargs["fields"] = projection
        kwargs["sort"] = sort
        kwargs["remove"] = True
        kwargs["session"] = session

        command = FindAndModifyCommand(self.collection,
                                       kwargs)
        return self._explain_command(command)

    def find_one_and_replace(self, filter: Document, replacement:
    Document={},
                            projection: list = None, sort=None,
                             return_document=pymongo.ReturnDocument.BEFORE,
                             session=None, **kwargs):
        kwargs["query"] = filter
        kwargs["fields"] = projection
        kwargs["sort"] = sort
        kwargs["new"] = False
        kwargs["update"] = replacement
        kwargs["session"] = session
        command = FindAndModifyCommand(self.collection,
                                       kwargs)
        return self._explain_command(command)

    def find_one_and_update(self, filter: Document, update: Document,
                            projection: list = None, sort=None,
                             return_document=pymongo.ReturnDocument.BEFORE,
                             session=None, **kwargs):
        kwargs["query"] = filter
        kwargs["fields"] = projection
        kwargs["sort"] = sort
        kwargs["upsert"] = False
        kwargs["update"] = update
        kwargs["session"] = session

        command = FindAndModifyCommand(self.collection,
                                       kwargs)
        return self._explain_command(command)

    def replace_one(self, filter: Document, replacement: Document,
                    upsert=False, bypass_document_validation=False,
                    collation=None, hint=None, session=None, **kwargs):
        command = UpdateCommand(self.collection, filter, update=replacement,
                                bypass_document_validation=bypass_document_validation,
                                hint=hint, collation=collation, multi=False, upsert=upsert)

        return self._explain_command(command)

# Alias
ExplainCollection = ExplainableCollection


class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None

class LinkedList:
    def __init__(self):
        self.head = None
        self.tail = None

    def add(self, data):
        newNode = ListNode(data)
        if not self.head:
            self.head = newNode
            self.tail = self.head
        else:
            self.tail.next = newNode
            self.tail = newNode

class solution:
    def mergeKLists(self, lists: list[ListNode]):

        if not lists or len(lists) == 0:
            return None

        while len(lists) > 1:
            mergedList = []
            for i in range(0, len(lists), 2):
                list1 = lists[i]
                list2 = lists[i + 1] if (i+1) < len(lists) else None
                mergedList.append(self.kMergeLists(list1, list2))
            lists = mergedList
        return lists[0]

    def kMergeLists(self, l1, l2):
        dummy = ListNode(0)
        tail = dummy

        while l1 and l2:
            if l1.val < l2.val:
                tail.next = l1
                l1 = l1.next
            else:
                tail.next = l2
                l2 = l2.next
            tail = tail.next
        if l1:
            tail.next = l1
        if l2:
            tail.next = l2

        return dummy.next

l1 = LinkedList()
l1.add(1)
l1.add(4)
l1.add(5)

l2 = LinkedList()
l2.add(1)
l2.add(3)
l2.add(4)

l3 = LinkedList()
l3.add(2)
l3.add(6)

lists = [l1.head, l2.head, l3.head]

x = solution()
res = x.mergeKLists(lists)

# printing the result
while res:
    print(res.val, end=" ")
    res = res.next