import datetime
import os
import queue
import sys
import threading
import time
import atexit

from kuai_log._datetime import aware_now

class Stream:
    @classmethod
    def stdout(cls, msg):
        print(msg)

    @classmethod
    def print(cls, *args, sep=' ', end='\n', file=None, flush=True, sys_getframe_n=2):
        args = (str(arg) for arg in args)  # REMIND 防止是数字不能被join
        msg = sep.join(args) + end
        print(msg)

class BulkStream:
    q = queue.SimpleQueue()
    _lock = threading.Lock()
    _has_start_bulk_stdout = False

    @classmethod
    def _bulk_real_stdout(cls):
        with cls._lock:
            msg_str_all = ''
            while not cls.q.empty():
                msg_str_all += str(cls.q.get())
            if msg_str_all:
                sys.stdout.write(msg_str_all)

    @classmethod
    def stdout(cls, msg):
        with cls._lock:
            cls.q.put(msg)

    @classmethod
    def print(cls, *args, sep=' ', end='\n', file=None, flush=True, sys_getframe_n=2):
        args = (str(arg) for arg in args)  # REMIND 防止是数字不能被join
        msg = sep.join(args) + end
        fra = sys._getframe(1)  # noqa
        line = fra.f_lineno
        full_path = fra.f_code.co_filename  # type :str
        # file_name = full_path.split('/')[-1].split('\\')[-1]
        full_path_and_line = f'"{full_path}:{line}"'
        fun = fra.f_code.co_name
        full_msg = f'{aware_now()} - {full_path_and_line} - {fun} - [print] - {msg}'
        color_msg = f'\033[0;34m{full_msg}\033[0m'
        with cls._lock:
            cls.q.put(color_msg)

    @classmethod
    def _when_exit(cls):
        # stdout_raw('结束 stdout_raw')
        return cls._bulk_real_stdout()

    @classmethod
    def start_bulk_stdout(cls):
        def _bulk_stdout():
            while 1:
                cls._bulk_real_stdout()
                time.sleep(0.1)

        if not cls._has_start_bulk_stdout:
            cls._has_start_bulk_write = True
            threading.Thread(target=_bulk_stdout, daemon=True).start()

    @classmethod
    def patch_print(cls):
        """
        Python有几个namespace，分别是

        locals

        globals

        builtin

        其中定义在函数内声明的变量属于locals，而模块内定义的函数属于globals。

        https://codeday.me/bug/20180929/266673.html   python – 为什么__builtins__既是模块又是dict

        :return:
        """
        try:
            __builtins__.print = cls.print
        except AttributeError:
            """
            <class 'AttributeError'>
            'dict' object has no attribute 'print'
            """
            # noinspection PyUnresolvedReferences
            __builtins__['print'] = cls.print
        # traceback.print_exception = print_exception  # file类型为 <_io.StringIO object at 0x00000264F2F065E8> 单独判断，解决了，不要加这个。

OsStream = Stream

if os.name == 'nt':  # windows io性能差
    OsStream = BulkStream
    BulkStream.start_bulk_stdout()
    BulkStream.patch_print()
    atexit.register(BulkStream._when_exit)


import numpy as np
import imutils
import cv2
import glob

def compute_iou(bbox1, bbox2):
    x1, y1, h1, w1 = bbox1
    x2, y2, h2, w2 = bbox2
    x_min = max(x1, x2)
    y_min = max(y1, y2)
    x_max = min(x1 + w1, x2 + w2)
    y_max = min(y1 + h1, y2 + h2)

    area1 = h1 * w1
    area2 = h2 * w2
    area12 = max(0, x_max - x_min + 1) * max(0, y_max - y_min + 1)

    iou = area12 / float(area1 + area2 - area12)
    return iou

def create_template(tpl_path):
    tpl = cv2.imread(tpl_path)
    if tpl is None:
        raise ValueError('Cannot create tpl from {}'.format(tpl_path))
    tpl = cv2.cvtColor(tpl, cv2.COLOR_BGR2GRAY)
    tpl = cv2.Canny(tpl, 50, 200)
    return tpl

def match_template(img, template, min_ratio=0.2, max_ratio=1, interp=20, auto=False, suffix='detect_arrow'):
    if isinstance(img, str):
        img = cv2.imread(img)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    tH, tW = template.shape[:2]
    H, W = gray.shape
    if auto:
        ratio = max(tH / H, tW / W)
        min_ratio = ratio
        max_ratio = ratio + 1
        interp = 10
    found = None
    for scale in np.linspace(min_ratio, max_ratio, interp)[::-1]:
        resized = imutils.resize(gray, width = int(gray.shape[1] * scale))
        if resized.shape[0] < tH or resized.shape[1] < tW:
            break
        r = gray.shape[1] / float(resized.shape[1])
        edged = cv2.Canny(resized, 50, 200)
        result = cv2.matchTemplate(edged, template, cv2.TM_CCOEFF)
        _, maxVal, _, maxLoc = cv2.minMaxLoc(result)
        if found is None or maxVal > found[0]:
            found = (maxVal, maxLoc, r)
    (_, maxLoc, r) = found
    (startX, startY) = (int(maxLoc[0] * r), int(maxLoc[1] * r))
    (endX, endY) = (int((maxLoc[0] + tW) * r), int((maxLoc[1] + tH) * r))

    # cv2.rectangle(img, (startX, startY), (endX, endY), (0, 0, 255), 2)
    # cv2.imshow("detected", img)
    # cv2.waitKey(0)
    # cv2.imwrite(img_path[:-4]+'_'+suffix+'_png', img)

    res = (startX, startY, endY - startY, endX - startX)
    return res

def match_multi_template(img, template, num=10, radius=10, min_ratio=0.2, max_ratio=5, interp=20, auto=False, suffix='detect_star'):
    if isinstance(img, str):
        img = cv2.imread(img)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    tH, tW = template.shape[:2]
    H, W = gray.shape
    if auto:
        ratio = max(tH / H, tW / W)
        min_ratio = ratio
        max_ratio = ratio + 1
        interp = 10
    found = []
    for scale in np.linspace(min_ratio, max_ratio, interp)[::-1]:
        resized = imutils.resize(gray, width = int(gray.shape[1] * scale))
        if resized.shape[0] < tH or resized.shape[1] < tW:
            break
        r = gray.shape[1] / float(resized.shape[1])
        edged = cv2.Canny(resized, 50, 200)
        result = cv2.matchTemplate(edged, template, cv2.TM_CCOEFF)
        for _ in range(num):
            _, maxval, _, maxloc = cv2.minMaxLoc(result)
            cv2.circle(result, maxloc, radius, (0.0), -1)
            found.append((maxval, maxloc, r))
    found = sorted(found, key=lambda x: -x[0])
    results = []
    # for f in found[:num]:
    #     _, maxLoc, r = f
    #     (startX, startY) = (int(maxLoc[0] * r), int(maxLoc[1] * r))
    #     (endX, endY) = (int((maxLoc[0] + tW) * r), int((maxLoc[1] + tH) * r))
    #     results += [(startX, startY, endY - startY, endX - startX)]
    for f in found:
        _, maxLoc, r = f
        (startX, startY) = (int(maxLoc[0] * r), int(maxLoc[1] * r))
        (endX, endY) = (int((maxLoc[0] + tW) * r), int((maxLoc[1] + tH) * r))
        bbox = (startX, startY, endY - startY, endX - startX)
        nms = False
        for result in results:
            iou = compute_iou(bbox, result)
            if iou > 0.5:
                nms = True
        if not nms:
            results += [bbox]
            # cv2.rectangle(img, (startX, startY), (endX, endY), (0, 0, 255), 2)
            if len(results) >= num:
                break
    # cv2.imshow("detected", img)
    # cv2.waitKey(0)
    # cv2.imwrite(img_path[:-4]+'_'+suffix+'.png', img)
    return results

if __name__ == '__main__':
    import time
    photos = glob.glob('assets/lianjia/800p/*.png')
    # photos = ['1.png']
    if 0:
        template = create_template('assets/match_tpl/hstar.png')
        for fpath in photos:
            r = match_multi_template(fpath, template, num=2)
            print(r)
    if 0:
        template = create_template('assets/match_tpl/star.png')
        for fpath in photos:
            t0 = time.time()
            match_multi_template(fpath, template, suffix='detect_star')
            print('{} s'.format(time.time() - t0))
    template = create_template('assets/match_tpl/arrow.png')
    for fpath in photos:
        t0 = time.time()
        match_template(fpath, template)
        print('{} s'.format(time.time() - t0))


import sys
input = sys.stdin.readline

# 점화식 규칙: dp[n] = dp[n-1] + dp[n-2] + dp[n-3]

T = int(input())

# n=1, n=2, n=3일 때의 개수
dp = [1, 2, 4]

tmp_list = []

for _ in range(T):
    tmp_list.append((int(input())))

# 3까지의 값은 이미 존재하니 3부터 시작
for i in range(3, max(tmp_list)):
    dp.append(dp[i-1] + dp[i-2] + dp[i-3])

for i in tmp_list:
    print(dp[i-1])


import sys
input = sys.stdin.readline
from collections import deque
dx = [-1, 1, 0 ,0]
dy = [0, 0, -1, 1]

def bfs(i, j):
    q = deque()
    q.append((i, j))
    cnt = 0
    while q:
        x, y = q.popleft()
        visited[x][y] = 1
        cnt += 1
        for d in range(4):
            nx = x + dx[d]
            ny = y + dy[d]
            if 0 <= nx < N and 0 <= ny < M and not visited[nx][ny] and maps[nx][ny]:
                q.append((nx, ny))
                visited[nx][ny] = 1
    return cnt

N, M, K = map(int, input().split())
maps = [[0] * M for _ in range(N)]
visited = [[0] * M for _ in range(N)]
ans = 0
for _ in range(K):
    r, c = map(int, input().split())
    maps[r-1][c-1] = 1

for i in range(N):
    for j in range(M):
        if not visited[i][j] and maps[i][j]:
            chk = bfs(i, j)
            if ans < chk:
                ans = chk
print(ans)

백준/Silver/1743. 음식물 피하기/음식물 피하기.py


import os
import io
import sys
from tempfile import TemporaryFile

STDOUT = 1
STDERR = 2
SYS_FDS = {
    STDOUT: 'stdout',
    STDERR: 'stderr',
}

class CallbackFile(io.TextIOWrapper):
    def __init__(self, callback: callable = None):
        super().__init__(
            TemporaryFile(buffering=0),
            encoding='utf-8',
            errors='replace',
            write_through=True,
            newline='',
        )
        self.callback = callback

    def write(self, data) -> None:
        super().write(data)
        if '\n' in data:
            self.flush()

    def getvalue(self) -> str:
        self.buffer.seek(0)
        res = self.buffer.read()
        self.buffer.seek(0)
        self.buffer.truncate()
        return res.decode('utf-8')

    def flush(self) -> None:
        if self.callback is not None:
            text = self.getvalue()
            if len(text) > 0:
                self.callback(text)
        else:
            super().flush()

class FDCapture:
    def __init__(self, targetfd: int, callback: callable = None) -> None:
        self.targetfd = targetfd
        self.targetfd_save = os.dup(targetfd)
        self.callback = callback
        self.tmpfile = CallbackFile(callback)
        self._capturing = False

    def start(self) -> None:
        """Start capturing on targetfd using memorized tmpfile."""
        assert not self._capturing

        # redirect the target fd to our temporary file
        os.dup2(self.tmpfile.fileno(), self.targetfd)

        if self.targetfd in SYS_FDS:
            # for system file descriptors (stdout, stderr) we also need to replace the sys.stdout/sys.stderr streams.
            # this allows us to capture output from the local python process
            self.sysfile = getattr(sys, SYS_FDS[self.targetfd])
            setattr(sys, SYS_FDS[self.targetfd], self.tmpfile)

        self._capturing = True

    def stop(self) -> None:
        """Stop capturing, restore streams & return original capture file"""
        assert self._capturing

        # disable output redirection
        os.dup2(self.targetfd_save, self.targetfd)

        # if we have a callback, flush any remaining data
        if self.callback:
            remainder = self.getvalue()
            if len(remainder) > 0:
                self.callback(remainder)

        # close temporary file descriptor
        os.close(self.targetfd_save)

        if self.targetfd in SYS_FDS:
            # restore the original sys stream
            setattr(sys, SYS_FDS[self.targetfd], self.sysfile)

        self._capturing = False

    def writeorg(self, data) -> None:
        """Write to original file descriptor."""
        if self._capturing:
            os.write(self.targetfd_save, data.encode('utf-8'))
        else:
            os.write(self.targetfd, data.encode('utf-8'))

    def getvalue(self) -> str:
        return self.tmpfile.getvalue()

    def __del__(self) -> None:
        self.tmpfile.close()

class FileCapturing(object):
    def __init__(
        self,
        on_stdout: callable = None,
        on_stderr: callable = None,
    ):
        self.stdout = FDCapture(STDOUT, on_stdout)
        self.stderr = FDCapture(STDERR, on_stderr)

    def __enter__(self) -> None:
        self.stdout.start()
        self.stderr.start()
        return self

    def __exit__(self, *args) -> None:
        self.stdout.stop()
        self.stderr.stop()

    def __del__(self) -> None:
        del self.stdout
        del self.stderr


def f(u, t):
    return [u[1], 3.*(1. - u[0]*u[0])*u[1] - u[0]]

u0 = [2.0, 0.0]
import odespy, numpy

for method in odespy.Lsode, odespy.DormandPrince, odespy.Vode:

    solver = method(f, rtol=0.0, atol=1e-6,
                    adams_or_bdf='adams', order=10)
    solver.set_initial_condition(u0)
    t_points = numpy.linspace(0, 30, 150)
    u, t = solver.solve(t_points)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 12 11:06:59 2020

@author: arjun
"""

import logging
# Imports the Google Cloud client library

from flask import Flask, request,render_template,jsonify
from models import db, Ballot,Candidate, User
import json
import traceback
import requests

blockchain_service_url = "http://0.0.0.0:5006/blockchain"
notification_service_url = "http://0.0.0.0:5005/notification"
ballot_service_url = "http://192.168.0.102:5003"

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:root@127.0.0.1:3306/evdb"

db.init_app(app)

with app.app_context():
    db.create_all()

@app.route('/ballot', methods=["POST"])
def vote():
    '''
    create a new poll.
    callers: all users
    '''
    data = request.form.to_dict()
    ballot = Ballot()
    try:
        payload = {'candidate_id': data["candidate_id"]}
        response = requests.request("POST", blockchain_service_url+"/vote", data = payload)
        data["transaction_id"] = json.loads(response.text)["receipt"]
        ballot.deserialize(json=data)
        ballot.save()
        response_object = ballot.serialize()

        try:
            payload = {
                    'number': User.query.filter(
                            User.id==response_object["user_id"]
                            ).first().phone,
                    'link': ballot_service_url+"/"+str(response_object["id"])
                    }

            requests.request("POST", notification_service_url, data = payload)
        except:
            traceback.print_exc()
            pass

        return json.dumps(response_object),200
    except Exception as e:
        traceback.print_exc()
        return str(e),500

@app.route('/ballot/<int:id>', methods=["GET"])
def get_ballot_object(id):
    '''
    get ballot object by id
    callers: system
    '''
    ballot = Ballot.query.filter(Ballot.id == id).first()
    if ballot:
        ballot = ballot.serialize()
        return json.dumps(ballot)
    else:
        return "",404

@app.route('/<int:id>', methods=["GET"])
def short_get_ballot_object(id):
    '''
    get ballot object by id
    callers: system
    '''
    ballot = Ballot.query.filter(Ballot.id == id).first()
    if ballot:
        ballot = ballot.serialize()

        response = requests.request("GET", blockchain_service_url+"/results");

        if response:
            results = json.loads(response.text)["result"]

        return render_template('layouts/index.html',
                               voter_data=ballot,
                               results=results
                               )
    else:
        return "not found",404

@app.route('/candidates', methods=["GET"])
def list_candidates():
    '''
    list candidates
    callers: all users
    '''
    candidates = Candidate.query.all()

    if candidates:
        candidate_list = [candidate.serialize() for candidate in candidates]

        return json.dumps(candidate_list)
    else:
        return "",404

@app.route('/')
def hello():
    return 'Ballot Service is active'

@app.errorhandler(500)
def server_error(e):
    # Log the error and stacktrace.
    logging.exception('An error occurred during a request.')
    return 'An internal error occurred.', 500
# [END app]

if __name__ =="__main__":
    app.run(debug=True,host="0.0.0.0",port=5003)


# Import pySpark
from pyspark.sql import SparkSession
from pyspark.sql.functions import expr

# Create SparkSession
spark = SparkSession.builder.appName('SparkByExamples.com').getOrCreate()

bucket = "sarthak11"
spark.conf.set('temporaryGcsBucket', bucket)

# Create DataFrame
#columns= ["employee_name", "department", "salary"]
df =spark.read.parquet('gs://sarthak11/data_parq.parquet')
#df = spark.createDataFrame(data = data, schema = columns)
df2 = df.distinct()
df2.write.format("bigquery") \
  .option("table", "mlconsole-poc.sarthak.srh") \
  .mode("append") \
  .save()


import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import numpy as np
plt.style.use('book.mplstyle')
import gaud_sty

#
# 1. Plot random lines
for foo in range(10):
    a = np.random.uniform(-50.0,+50.0,1)
    b = np.random.uniform(0.0,+150.0,1)
    x = np.linspace(0,2.0,10)
    y = a*x+b
    if gaud_sty.color==True:
        plt.plot(x,y)
    else:
        plt.plot(x,y,c=gaud_sty.gray10[foo])
plt.title('Suoria y=ax+b parametrien a ja b eri arvoilla (x: pituus, y: paino)')
plt.xlabel('pituus [m]')
plt.ylabel('paino [kg]')
plt.axis([0,2,0,150])
if gaud_sty.savefig:
    if gaud_sty.color:
        plt.savefig(gaud_sty.save_dir+'ch02_line_fitting_1_col.png')
    else:
        plt.savefig(gaud_sty.save_dir+'ch02_line_fitting_1.png')
plt.show()

#
# 2. Plot pre-defined lines
plt.clf()
a=0
b=0
y = a*x+b
if gaud_sty.color==True:
    plt.plot(x,y,label='a=0 b=0', linestyle=gaud_sty.line5[0], marker=gaud_sty.marker5[0])
else:
    plt.plot(x,y,label='a=0 b=0', c=gaud_sty.gray10[0], linestyle=gaud_sty.line5[0], marker=gaud_sty.marker5[0])
a=10
b=0
y = a*x+b
if gaud_sty.color==True:
    plt.plot(x,y,label='a=10 b=0', linestyle=gaud_sty.line5[1], marker=gaud_sty.marker5[1])
else:
    plt.plot(x,y,label='a=10 b=0', c=gaud_sty.gray10[1], linestyle=gaud_sty.line5[1], marker=gaud_sty.marker5[1])
a=0
b=40
y = a*x+b
if gaud_sty.color==True:
    plt.plot(x,y,label='a=0 b=40', linestyle=gaud_sty.line5[2], marker=gaud_sty.marker5[2])
else:
    plt.plot(x,y,label='a=0 b=40', c=gaud_sty.gray10[2], linestyle=gaud_sty.line5[2], marker=gaud_sty.marker5[2])
a=10
b=40
y = a*x+b
if gaud_sty.color==True:
    plt.plot(x,y,label='a=10 b=40', linestyle=gaud_sty.line5[3], marker=gaud_sty.marker5[3])
else:
    plt.plot(x,y,label='a=10 b=40', c=gaud_sty.gray10[3], linestyle=gaud_sty.line5[3], marker=gaud_sty.marker5[3])
a=0
b=80
y = a*x+b
if gaud_sty.color==True:
    plt.plot(x,y,label='a=0 b=80', linestyle=gaud_sty.line5[4], marker=gaud_sty.marker5[4])
else:
    plt.plot(x,y,label='a=0 b=80', c=gaud_sty.gray10[4], linestyle=gaud_sty.line5[4], marker=gaud_sty.marker5[4])
plt.legend()
plt.title('Suoria parametrien a ja b eri arvoilla.')
plt.xlabel('pituus [m]')
plt.ylabel('paino [kg]')
plt.axis([0,2,-20,150])
if gaud_sty.savefig:
    if gaud_sty.color:
        plt.savefig(gaud_sty.save_dir+'ch02_line_fitting_2_col.png')
    else:
        plt.savefig(gaud_sty.save_dir+'ch02_line_fitting_2.png')
plt.show()

#
# 3. Plot lines through one given point
plt.clf()
# point 1
x1 = 1.11
y1 = 85.0
if gaud_sty.color==True:
    plt.plot(x1, y1)
else:
    plt.plot(x1, y1, 'ko')
plt.annotate("(1.11,85.0)", (x1, y1), textcoords="offset points",xytext=(-0.1,10),ha='right')
a=0
b=y1-a*1.11
y = a*x+b
if gaud_sty.color==True:
    plt.plot(x,y,label='a=0', linestyle=gaud_sty.line6[0])
else:
    plt.plot(x,y,label='a=0',c=gaud_sty.gray6[0], linestyle=gaud_sty.line6[0])
a=1
b=y1-a*1.11
y = a*x+b
if gaud_sty.color==True:
    plt.plot(x,y,label='a=1', linestyle=gaud_sty.line6[1])
else:
    plt.plot(x,y,label='a=1', c=gaud_sty.gray6[1], linestyle=gaud_sty.line6[1])
a=5
b=y1-a*1.11
y = a*x+b
if gaud_sty.color==True:
    plt.plot(x,y,label='a=5', linestyle=gaud_sty.line6[2])
else:
    plt.plot(x,y,label='a=5', c=gaud_sty.gray6[2], linestyle=gaud_sty.line6[2])
a=10
b=y1-a*1.11
y = a*x+b
if gaud_sty.color==True:
    plt.plot(x,y,label='a=10', linestyle=gaud_sty.line6[3])
else:
    plt.plot(x,y,label='a=10', c=gaud_sty.gray6[3], linestyle=gaud_sty.line6[3])
a=20
b=y1-a*1.11
y = a*x+b
if gaud_sty.color==True:
    plt.plot(x,y,label='a=20', linestyle=gaud_sty.line6[4])
else:
    plt.plot(x,y,label='a=20', c=gaud_sty.gray6[4], linestyle=gaud_sty.line6[4])
a=40
b=y1-a*1.11
x = np.linspace(0,2.0,10)
y = a*x+b
if gaud_sty.color==True:
    plt.plot(x,y,label='a=40', linestyle=gaud_sty.line6[5])
else:
    plt.plot(x,y,label='a=40', c=gaud_sty.gray6[5], linestyle=gaud_sty.line6[5])
plt.legend()
plt.title('Suoria, jotka toteuttavat yhtälön 85=a*1.11+b')
plt.xlabel('pituus [m]')
plt.ylabel('paino [kg]')
plt.axis([0,2,0,150])
if gaud_sty.savefig:
    if gaud_sty.color:
        plt.savefig(gaud_sty.save_dir+'ch02_line_fitting_3_col.png')
    else:
        plt.savefig(gaud_sty.save_dir+'ch02_line_fitting_3.png')
plt.show()

#
# 4. Plot the line through two given points
plt.clf()
# point 1
x1 = 1.11
y1 = 85.0
plt.plot(x1, y1,'ko')
plt.annotate("(1.11,85.0)", (x1, y1), textcoords="offset points",xytext=(-0.1,10),ha='right')
x2 = 1.52
y2 = 110.0
plt.plot(x2, y2,'ko')
plt.annotate("(1.52,110.0)", (x2, y2), textcoords="offset points",xytext=(-0.1,10),ha='right')
a=60.98
b=17.32
x = np.linspace(0,2.0,10)
y = a*x+b
if gaud_sty.color==True:
    plt.plot(x,y,'r-',label='y=60.98x+17.32')
else:
    plt.plot(x,y,'k-',label='y=60.98x+17.32')
plt.legend()
plt.title('Suora kahden tunnetun opetuspisteen kautta')
plt.xlabel('pituus [m]')
plt.ylabel('paino [kg]')
plt.axis([0,2,0,150])
if gaud_sty.savefig:
    if gaud_sty.color:
        plt.savefig(gaud_sty.save_dir+'ch02_line_fitting_4_col.png')
    else:
        plt.savefig(gaud_sty.save_dir+'ch02_line_fitting_4.png')
plt.show()

#
# 5. Plot MSE heat map for N points
np.random.seed(42) # to always get the same points
N = 50
x = np.random.normal(1.1,0.3,N)
a_gt = 50.0
b_gt = 20.0
y_noise =  np.random.normal(0,8,N) # Measurements from the class 1\n",
y = a_gt*x+b_gt+y_noise
plt.plot(x,y,'ko')
plt.title('Opetusaineisto suoran sovitukseen')
plt.xlabel('pituus [m]')
plt.ylabel('paino [kg]')
plt.axis([0,2,0,150])
if gaud_sty.savefig:
    if gaud_sty.color:
        plt.savefig(gaud_sty.save_dir+'ch02_line_fitting_5_col.png')
    else:
        plt.savefig(gaud_sty.save_dir+'ch02_line_fitting_5.png')
plt.show()

# Compute MSE heat map for different a and b
MSE_ab = np.empty([11,11])
for ai,a in enumerate((range(0,110,10))):
    for bi, b in enumerate((range(0,110,10))):
        y_hat = a*x+b
        MSE_ab[ai][bi] = np.sum((y-y_hat)**2)/N

if gaud_sty.color==True:
    plt.imshow(MSE_ab,extent= [-5,105,-5,105], cmap='hot', norm=LogNorm(), interpolation='nearest')
else:
    plt.imshow(MSE_ab,extent= [-5,105,-5,105], cmap='gray', norm=LogNorm(), interpolation='nearest')
plt.colorbar()
plt.ylabel('a')
plt.xlabel('b')
plt.title('MSE a ja b eri arvoille')
if gaud_sty.savefig:
    if gaud_sty.color:
        plt.savefig(gaud_sty.save_dir+'ch02_line_fitting_6_col.png')
    else:
        plt.savefig(gaud_sty.save_dir+'ch02_line_fitting_6.png')
plt.show()

#
# 6. Plot least-square fit through N points
a = (N*np.sum(x*y)-sum(y)*sum(x))/(N*sum(x*x)-sum(x)*sum(x))
b = (-a*sum(x)+sum(y))/N
y_h = a*x+b
MSE = np.sum((y-y_h)**2)/N

plt.plot(x,y,'ko')
x = np.linspace(0,2.0,10)
if gaud_sty.color==True:
    plt.plot(x,a*x+b,'r-')
else:
    plt.plot(x,a*x+b,'k-')
plt.title(f"Sovitettu suora (a={a:.1f}, b={b:.1f}, MSE={MSE:.1f})")
plt.xlabel('pituus [m]')
plt.ylabel('paino [kg]')
plt.axis([0,2,0,150])
if gaud_sty.savefig:
    if gaud_sty.color:
        plt.savefig(gaud_sty.save_dir+'ch02_line_fitting_7_col.png')
    else:
        plt.savefig(gaud_sty.save_dir+'ch02_line_fitting_7.png')
plt.show()


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import os
import platform
import subprocess
from distutils.version import StrictVersion

from mozboot.util import get_tools_dir
from mozfile import which
from six import PY3

NODE_MIN_VERSION = StrictVersion("12.22.12")
NPM_MIN_VERSION = StrictVersion("6.14.16")

def find_node_paths():
    """Determines the possible paths for node executables.

    Returns a list of paths, which includes the build state directory.
    """
    mozbuild_tools_dir = get_tools_dir()

    if platform.system() == "Windows":
        mozbuild_node_path = os.path.join(mozbuild_tools_dir, "node")
    else:
        mozbuild_node_path = os.path.join(mozbuild_tools_dir, "node", "bin")

    # We still fallback to the PATH, since on OSes that don't have toolchain
    # artifacts available to download, Node may be coming from $PATH.
    paths = [mozbuild_node_path] + os.environ.get("PATH").split(os.pathsep)

    if platform.system() == "Windows":
        paths += [
            "%s\\nodejs" % os.environ.get("SystemDrive"),
            os.path.join(os.environ.get("ProgramFiles"), "nodejs"),
            os.path.join(os.environ.get("PROGRAMW6432"), "nodejs"),
            os.path.join(os.environ.get("PROGRAMFILES"), "nodejs"),
        ]

    return paths

def check_executable_version(exe, wrap_call_with_node=False):
    """Determine the version of a Node executable by invoking it.

    May raise ``subprocess.CalledProcessError`` or ``ValueError`` on failure.
    """
    out = None
    # npm may be a script (Except on Windows), so we must call it with node.
    if wrap_call_with_node and platform.system() != "Windows":
        binary, _ = find_node_executable()
        if binary:
            out = (
                subprocess.check_output(
                    [binary, exe, "--version"], universal_newlines=PY3
                )
                .lstrip("v")
                .rstrip()
            )

    # If we can't find node, or we don't need to wrap it, fallback to calling
    # direct.
    if not out:
        out = (
            subprocess.check_output([exe, "--version"], universal_newlines=PY3)
            .lstrip("v")
            .rstrip()
        )
    return StrictVersion(out)

def find_node_executable(
    nodejs_exe=os.environ.get("NODEJS"), min_version=NODE_MIN_VERSION
):
    """Find a Node executable from the mozbuild directory.

    Returns a tuple containing the the path to an executable binary and a
    version tuple. Both tuple entries will be None if a Node executable
    could not be resolved.
    """
    if nodejs_exe:
        try:
            version = check_executable_version(nodejs_exe)
        except (subprocess.CalledProcessError, ValueError):
            return None, None

        if version >= min_version:
            return nodejs_exe, version.version

        return None, None

    # "nodejs" is first in the tuple on the assumption that it's only likely to
    # exist on systems (probably linux distros) where there is a program in the path
    # called "node" that does something else.
    return find_executable("node", min_version)

def find_npm_executable(min_version=NPM_MIN_VERSION):
    """Find a Node executable from the mozbuild directory.

    Returns a tuple containing the the path to an executable binary and a
    version tuple. Both tuple entries will be None if a Node executable
    could not be resolved.
    """
    return find_executable("npm", min_version, True)

def find_executable(name, min_version, use_node_for_version_check=False):
    paths = find_node_paths()
    exe = which(name, path=paths)

    if not exe:
        return None, None

    # Verify we can invoke the executable and its version is acceptable.
    try:
        version = check_executable_version(exe, use_node_for_version_check)
    except (subprocess.CalledProcessError, ValueError):
        return None, None

    if version < min_version:
        return None, None

    return exe, version.version


#
# Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies).
# All rights reserved.
# This component and the accompanying materials are made available
# under the terms of "Eclipse Public License v1.0"
# which accompanies this distribution, and is available
# at the URL "http://www.eclipse.org/legal/epl-v10.html".
#
# Initial Contributors:
# Nokia Corporation - initial contribution.
#
# Contributors:
#
# Description:  Flag scanner for source, header and project files
#

import re
from processors.scanners.file_scanner import FileScanner

_reDefine = re.compile(r'(?:#define|MACRO)\s+([\w\d_]+)\s*(.*)')
_reUndef = re.compile(r'#undef[ \t]+([\w\d_]+)')
_reMisformattedStart = re.compile(r'#\s+(if|undef|def)')
MULTILINE = '__MULTI_LINE$__'

def DBG(txt):
    #print txt
    pass

class FlagScanner(FileScanner):
    def __init__(self, progressStr='', progressTreshold=-1):
        super(FlagScanner, self).__init__(progressStr, progressTreshold)

        # list of (filename, lineno, define, value)
        self.defines = []
        # list of (filename, startLineNo, endLineNo, flagname, operator, value)
        self.checks = []

        self.publicData.extend([self.defines, self.checks])

    def interested_extensions(self):
        return ['cpp', 'mmp', 'iby', 'oby', 'inf', 'rss', 'c', 'h', 'hpp', 'hrh', 'rh', 'inl', 'rsg']

    def needs_parsed_contents(self):
        return True

    def _move_define_params(self, name, value):
        if len(value) and (value[0] == '('):
            # assign parameters to name portion
            pstack = 1
            name += value[0];
            value = value[1:]
            while pstack > 0 and value:
                if value[0] == '(':
                    pstack += 1
                elif value[0] == ')':
                    pstack -= 1
                name += value[0];
                value = value[1:]
            name = name.replace(' ', '').replace('\t', '')
            value = value.strip()
        return name, value

    def _get_define_decl(self, text):
        if ((text.find("#define") == -1) and (text.find("#undef") == -1)):
            return (None, None)
        text = text.replace(MULTILINE, '\n')
        m = _reDefine.search(text)
        if m:
            name, value = self._move_define_params(m.group(1), m.group(2))
            DBG('Defines found: %s --- %s' % (name, value))
            return (name, value)
        m = _reUndef.search(text)
        if m:
            name = m.group(1)
            DBG('undef found for ' + name)
            return (name, None)
        DBG('No defines found after all')
        return (None, None)

    def _get_checked_defines(self, text):
        'returns list of flagnames. plain [] in case there is no checks in text'

        # at first remove "misformatted" preprocessor usage (e.g. #    if -> #if)
        text = re.sub(_reMisformattedStart, r'#\1', text)
        if len(text) < 3 or text[0:3].find('#if') == -1:
            return []

        parts, tmpParts = [text.replace(MULTILINE, '\n')], []
        for s in ('#ifdef', '#ifndef', '#if', 'defined', '(', ')', '&', '|', '[', ']', '!', '=', '<', '>'):
            #DBG('PARTS --- ' + str(parts))
            for part in parts:
                tmpParts.extend(part.split(s))
            parts, tmpParts = tmpParts, []

        tmpParts, parts = parts, []
        for part in tmpParts:
            part = part.strip()
            if part and part not in parts:
                parts.append(part)
        DBG('checked defines = ' + str(parts))
        return parts

    def process_file(self, contents, fullFileName, shortFileName):
        # store (filename, usages, usedLineNo) values based on #if... #endif declarations here
        #   during scanning
        checkStack = []

        lineCount = contents.get_linecount()
        lineNo = 0
        multilineLineNo = -1
        multilineLineTxt = ''
        for img in contents.iter_lineimages():
            self.print_progress(lineNo, lineCount)
            lineNo += 1
            txt = img.code_and_strings().strip()
            DBG('line: ' + txt)
            if txt and txt[-1] == '\\':
                if multilineLineNo < 0:
                    multilineLineNo = lineNo
                multilineLineTxt = multilineLineTxt + txt[:-1] + MULTILINE
                continue
            elif multilineLineNo > 0:
                DBG('closing multiline')
                txt = multilineLineTxt + txt
                multilineLineTxt = ''

            if len(txt) >= 6 and txt[0:6].find('#endif') != -1:
                DBG('found endif, closing latest define checks')
                try:
                    usageInfo = checkStack.pop()
                    usages = usageInfo[1]
                    for usage in usages:
                        self.checks.append([usageInfo[0], usage, usageInfo[2], lineNo])
                except IndexError:
                    self.warn('Encountered unmatching #endif in %s:%d' % (shortFileName, lineNo))
                continue

            name, value = self._get_define_decl(txt)
            if name:
                usedLineNo = lineNo
                if multilineLineNo > 0:
                    usedLineNo = multilineLineNo
                    multilineLineNo = -1
                self.defines.append((shortFileName, lineNo, name, value))
            else:
                usages = self._get_checked_defines(txt)
                if usages:
                    usedLineNo = lineNo
                    if multilineLineNo > 0:
                        usedLineNo = multilineLineNo
                        multilineLineNo = -1
                    checkStack.append([shortFileName, usages, usedLineNo])

    def store_to_db(self, snapshotId, file2id, cursor):
        SQL = 'INSERT INTO defines (snapshotId, fileId, lineNo, defname, defvalue) VALUES (%s, %s, %s, %s, %s)'
        for define in self.defines:
            cursor.execute(SQL, (snapshotId, file2id[define[0]], define[1], define[2], define[3]))
        SQL = 'INSERT INTO define_checks (snapshotId, fileId, definition, startLineNo, endLineNo)' + \
              'VALUES (%s, %s, %s, %s, %s)'
        for check in self.checks:
            cursor.execute(SQL, (snapshotId, file2id[check[0]], check[1], check[2], check[3]))

_CLAZZ_ = FlagScanner


from typing import IO
import copy

def read_file(input_file):
    '''read the input file'''
    return [list(x.replace('\n', '')) for x in input_file.readlines()]

def get_eligible_adj(coord_, max_):
    '''return one of [0,1], [-1,0], [-1,0,1] depending on the coord'''
    if coord_ == 0:
        eligible = [0, 1]
    elif coord_ == max_:
        eligible = [-1, 0]
    else:
        eligible = [-1, 0, 1]
    return eligible

def get_new_seat_contents(current_seat, num_occupied, tolerance):
    '''determine what the new seat will become based on the number of occupied seats around it'''
    new_seat = current_seat
    if current_seat == 'L':
        if num_occupied == 0:
            new_seat = '#'
    elif current_seat == '#':
        if num_occupied >= tolerance:
            new_seat = 'L'
    return new_seat

def calc_multiplier(seat_coord, max_, chg):
    '''calc how many times out we have to go'''
    out = [0, 0]  # x out, y out
    for dim in range(2):
        if chg[dim] < 0:
            out[dim] = seat_coord[dim]
        elif chg[dim] > 0:
            out[dim] = max_[dim] - seat_coord[dim]
        else:  # if 0 out
            out[dim] = ValueError
    return min(mult for mult in out if mult is not ValueError)

def get_new_seat(seats, seat_coord, max_, tolerance, vision=False):
    '''get what a given seat coord should become based on the rules'''
    x_eligible, y_eligible = get_eligible_adj(seat_coord[0], max_[0]), \
        get_eligible_adj(seat_coord[1], max_[1])
    num_occupied = 0
    for x_chg in x_eligible:
        for y_chg in y_eligible:
            if x_chg == 0 and y_chg == 0:
                continue
            if vision:
                multiplier = calc_multiplier(
                    seat_coord, max_, (x_chg, y_chg))
                for mult in range(1, multiplier+1):
                    seat_contents = seats[seat_coord[0]+mult*x_chg][seat_coord[1]+mult*y_chg]
                    if seat_contents == '#':
                        num_occupied += 1
                        break
                    if seat_contents == 'L':
                        break
            else:
                seat_contents = seats[seat_coord[0]+x_chg][seat_coord[1]+y_chg]
                if seat_contents == '#':
                    num_occupied += 1
    current_seat = seats[seat_coord[0]][seat_coord[1]]
    return get_new_seat_contents(current_seat, num_occupied, tolerance)

def count_seats(seats):
    '''count number of occupied seats'''
    num_occupied = 0
    for row in seats:
        for col in row:
            if col == '#':
                num_occupied += 1
    return num_occupied

def print_seats(seats):
    '''print out the seat map for ease of debugging'''
    for row in seats:
        print(''.join(row))

def p_1(input_file: IO,
        debug=False):  # pylint: disable=unused-argument
    '''apply the seating algo and until the number of occupied seats are stable
    then return number of occupied seats'''
    seats = read_file(input_file)
    max_x = len(seats)-1
    max_y = len(seats[0])-1
    # x will denote the row (the first index in the array of arrays)
    # y will denote the col (the index within the array of an array)
    stable = False
    idx = 0
    tolerance = 4
    while not stable and idx < 2000:
        new_seats = copy.deepcopy(seats)
        for x_coord in range(max_x+1):
            for y_coord in range(max_y+1):
                new_seats[x_coord][y_coord] = get_new_seat(seats, (x_coord, y_coord),
                                                           (max_x, max_y), tolerance)
        if new_seats == seats:
            stable = True
        else:
            seats = copy.deepcopy(new_seats)
            idx += 1
    return count_seats(seats)

def p_2(input_file: IO,
        debug=False):  # pylint: disable=unused-argument
    '''now we care about all the seats within a passenger's range of vision
    #1: 337 too low'''
    seats = read_file(input_file)
    (max_x, max_y) = (len(seats)-1, len(seats[0])-1)

    # x will denote the row (the first index in the array of arrays)
    # y will denote the col (the index within the array of an array)
    stable = False
    idx = 0
    tolerance = 5
    while not stable and idx < 2000:
        new_seats = copy.deepcopy(seats)
        for x_coord in range(max_x+1):
            for y_coord in range(max_y+1):
                new_seats[x_coord][y_coord] = get_new_seat(seats, (x_coord, y_coord),
                                                           (max_x, max_y), tolerance, True)
        if new_seats == seats:
            stable = True
        else:
            seats = copy.deepcopy(new_seats)
            idx += 1
    return count_seats(seats)


AREE_PATH="aree/"
totale_stanze = 2

class Load_room():
  def __init__(self):
    self.num = ''
    self.name = ''
    self.desc = []

def carica(area):

  lista = []
  afile = open("%s%s" % (AREE_PATH, area), "r")
  for i in range (totale_stanze):
#    print i
    riga = []

#    while True:
    riga = afile.readline()
#    print riga[:-1]
#    if riga == "EOF\n": break
    r = Load_room()
    r.num = int(riga[:-1])
    r.name = afile.readline()[:-1]
    while ( True ):                          #leggo la descrizione
      riga = afile.readline()[:-1]
      if riga == "'''" : break
      r.desc.append(riga)
    lista.append(r)
#  print lista[1].desc
  return lista

#  print lista[0].num
#  print lista[1].num
carica("area_prova")


from io import StringIO
import bit
import module
import stream

class reg(module.module):
	def __init__(self, width=1, rst_value=None):
		self.rst_value = 0 if rst_value is None else rst_value
		self.w = width
		super().__init__()

	def width(self):
		return self.w

	def name(self):
		return 'register_%d_%d' % (self.width(), self.rst_value)

	def impl(self):
		self.clk = bit.input(bit.bit(1))
		self.rst_l = bit.input(bit.bit(1))
		self.en = bit.input(bit.bit(1))
		self.clear = bit.input(bit.bit(1))
		self.D = bit.input(bit.bit(self.width()))
		self.Q = bit.output(bit.bit(self.width()))

	def __inst_repr__(self, id):
		s = StringIO()
		f = stream.stream(s)
		f.write('register #(%d, %d) REG%s(' % (
			self.width(), self.rst_value, id))
		more_than_one = False
		indented = False
		decls = self.decls()
		for k in decls:
			p = decls[k]
			if p.dxn() is not None:
				if more_than_one:
					f.writenl(',', i=0)
					if not indented:
						f.indent()
						indented = True
				f.write('.%s(%s)' % (self.cxnport(p.name()), self.cxnname(p.name())))
				more_than_one = True

		f.unindent()
		f.writenl(');')

		return s.getvalue()

	def __repr__(self):
		return ''


#!/usr/bin/env python

# from scum.main import MainGUI, START_PATH, TABS_PATH
from main import MainGUI, START_PATH, TABS_PATH
import os
import signal

def main():
    os.system('stty -ixon') # disable XOFF to accept Ctrl-S
    # instantiate it!
    main = MainGUI()
    signal.signal(signal.SIGTSTP, signal.SIG_IGN)
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    status = main.display()
    os.system('stty ixon') # re-enable XOFF!
    if status == 'failure':
        with open(TABS_PATH, 'w') as f:
            f.write(START_PATH + '\n')
            f.write('False')

if __name__=="__main__":
       main()


# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np

def hello_tf():
    hello = tf.constant('Hello, TensorFlow!')
    sess = tf.Session()
    a = tf.constant(10)
    b = tf.constant(32)
    print(sess.run([a + b, hello]))
    sess.close()

def math_op():
    a = tf.constant(3)  # 定义常量3
    b = tf.constant(4)  # 定义常量4

    add = tf.add(a, b)
    mul = tf.multiply(a, b)

    with tf.Session() as sess:  # 建立session
        print("相加: %i" % sess.run(a + b))
        print("相乘: %i" % sess.run(a * b))
        # Run every operation with variable input
        print("相加: %i" % sess.run(add, feed_dict={a: 3, b: 4}))
        print("相乘: %i" % sess.run(mul, feed_dict={a: 3, b: 4}))

def linear_model():
    # 使用 NumPy 生成假数据(phony data), 总共 100 个点.
    x_data = np.float32(np.random.rand(2, 100))  # 随机输入
    y_data = np.dot([0.100, 0.200], x_data) + 0.300

    # 构造一个线性模型
    #
    b = tf.Variable(tf.zeros([1]))
    W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0))
    y = tf.matmul(W, x_data) + b

    # 最小化方差
    loss = tf.reduce_mean(tf.square(y - y_data))
    optimizer = tf.train.GradientDescentOptimizer(0.5)
    train = optimizer.minimize(loss)

    # 初始化变量
    init = tf.initialize_all_variables()

    # 启动图 (graph)
    sess = tf.Session()
    sess.run(init)

    # 拟合平面
    for step in range(0, 201):
        sess.run(train)
        if step % 20 == 0:
            print(step, sess.run(W), sess.run(b))

    # 得到最佳拟合结果 W: [[0.100  0.200]], b: [0.300]
    sess.close()

def device_demo():
    with tf.Session() as sess:
        with tf.device("/cpu:0"):
            matrix1 = tf.constant([[3., 3.]])
            matrix2 = tf.constant([[2.], [2.]])
            product = tf.matmul(matrix1, matrix2)
            print(sess.run(product))

def count_demo():
    # 创建一个变量, 初始化为标量 0.
    state = tf.Variable(0, name="counter")

    # 创建一个 op, 其作用是使 state 增加 1

    one = tf.constant(1)
    new_value = tf.add(state, one)
    update = tf.assign(state, new_value)

    # 启动图后, 变量必须先经过`初始化` (init) op 初始化,
    # 首先必须增加一个`初始化` op 到图中.
    init_op = tf.initialize_all_variables()

    # 启动图, 运行 op
    with tf.Session() as sess:
        # 运行 'init' op
        sess.run(init_op)
        # 打印 'state' 的初始值
        print(sess.run(state))
        # 运行 op, 更新 'state', 并打印 'state'
        for _ in range(3):
            sess.run(update)
            print(sess.run(state))

def feed_demo():
    input1 = tf.placeholder(tf.float32)
    input2 = tf.placeholder(tf.float32)
    output = tf.multiply(input1, input2)

    with tf.Session() as sess:
        print(sess.run([output], feed_dict={input1: [7.], input2: [2.]}))

def random_demo():
    # Create a tensor of shape [2, 3] consisting of random normal values, with mean
    # -1 and standard deviation 4.
    norm = tf.random_normal([2, 3], mean=-1, stddev=4)

    # Shuffle the first dimension of a tensor
    c = tf.constant([[1, 2], [3, 4], [5, 6]])
    shuff = tf.random_shuffle(c)

    # Each time we run these ops, different results are generated
    sess = tf.Session()
    print(sess.run(norm), sess.run(norm))

    # Set an op-level seed to generate repeatable sequences across sessions.
    norm = tf.random_normal([2, 3], seed=1234)
    sess = tf.Session()
    print(sess.run(norm))
    print(sess.run(norm))
    sess = tf.Session()
    print(sess.run(norm))
    print(sess.run(norm))

if __name__ == "__main__":
    # hello_tf()
    # linear_model()
    # device_demo()
    # count_demo()
    # feed_demo()
    # random_demo()
    math_op()


import json
import boto3

#getMyEvents
def lambda_handler(event, context):
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table("Events")
    try:
        user = event["requestContext"]["authorizer"]["claims"]
        email = user["email"]
    except Exception as inst:
        print("")
        return {
            "statusCode": 400,
            "headers": {
                "Access-Control-Allow-Origin": "*"
            },
            "body": json.dumps("Error getting the user of request\n\n" + str(type(inst)) + "\n\n" + str(inst.args))
        }

    #search in db for email as organiser
    try:
        response = table.scan()
        all_items = response["Items"]
        items = []
        for item in all_items:
            try:
                if item["organizer"] == email:
                    items.append(item)
            except:
                items.append(item)
        return {
            'statusCode': 200,
            "headers": {
                    "Access-Control-Allow-Origin": "*"
                },
            'body': json.dumps(items)
        }
    except Exception as inst:
        return {
            "statusCode": 500,
            "headers": {
                "Access-Control-Allow-Origin": "*"
            },
            "body": json.dumps("Error getting events from db with given user as organizer\n\n" + str(type(inst)) + "\n\n" + str(inst.args))
    }


from torch import nn
import torch.nn.functional as F

from .init import init_uniform, init_bn

class FC(nn.Module):
    """Applies a linear transformation to the incoming data
    optionally followed by batch normalization and relu activation

    Attributes:
        conv (nn.Module): convolution module
        bn (nn.Module): batch normalization module
        relu (bool): whether to activate by relu

    """

    def __init__(self, in_channels, out_channels,
                 relu=True, bn=True, bn_momentum=0.1):
        super(FC, self).__init__()

        self.fc = nn.Linear(in_channels, out_channels, bias=(not bn))
        self.bn = nn.BatchNorm1d(out_channels, momentum=bn_momentum) if bn else None
        self.relu = relu

        self.init_weights()

    def forward(self, x):
        x = self.fc(x)
        if self.bn is not None:
            x = self.bn(x)
        if self.relu:
            x = F.relu(x, inplace=True)
        return x

    def init_weights(self):
        """default initialization"""
        init_uniform(self.fc)
        if self.bn is not None:
            init_bn(self.bn)


import requests
import pandas as pd
from pandas import DataFrame

url = 'https://www.twse.com.tw/exchangeReport/STOCK_DAY?response=html&date=20200530&stockNo=2330'
data_temp = pd.read_html(requests.get(url).text)

data = pd.read_html(requests.get(url).text)[0]

data.columns = data.columns.droplevel(0)

data.to_csv('2330_20200201.csv', index=False)

dates = [20200201, 20200101, 20191201]
stockNo = 2330
url_template = "https://www.twse.com.tw/exchangeReport/STOCK_DAY?response=html&date={}&stockNo={}"

for date in dates:
    url = url_template.format(date, stockNo)
    file_name = "{}_{}.csv".format(stockNo, date)

    data = pd.read_html(requests.get(url).text)
    print(data)

    data.columns = data.columns.droplevel(0)
    data.to_csv(file_name, index=False)


from configs.config import config

import torch
import torch.nn as nn
import torch.nn.functional as F

from sync_bn.nn.modules import SynchronizedBatchNorm2d
from functools import partial

norm_layer = partial(SynchronizedBatchNorm2d, momentum=3e-4)

class myLayerNorm(nn.Module):
    def __init__(self, inChannels):
        super().__init__()
        self.norm == nn.LayerNorm(inChannels, eps=1e-5)

    def forward(self, x):
        # reshaping only to apply Layer Normalization layer
        B, C, H, W = x.shape
        x = x.flatten(2).transpose(1,2) # B*C*H*W -> B*C*HW -> B*HW*C
        x = self.norm(x)
        x = x.reshape(B, H, W, -1).permute(0, 3, 1, 2).contiguous() # B*HW*C -> B*H*W*C -> B*C*H*W

        return x

class NormLayer(nn.Module):
    def __init__(self, inChannels, norm_type=config['norm_typ']):
        super().__init__()
        self.inChannels = inChannels
        self.norm_type = norm_type
        if norm_type == 'batch_norm':
            # print('Adding Batch Norm layer') # for testing
            self.norm = nn.BatchNorm2d(inChannels, eps=1e-5, momentum=float(config['BN_MOM']))
        elif norm_type == 'sync_bn':
            # print('Adding Sync-Batch Norm layer') # for testing
            self.norm = norm_layer(inChannels)
        elif norm_type == 'layer_norm':
            # print('Adding Layer Norm layer') # for testing
            self.norm == nn.myLayerNorm(inChannels)
        else:
            raise NotImplementedError

    def forward(self, x):

        x = self.norm(x)

        return x

    def __repr__(self):
        return f'{self.__class__.__name__}(dim={self.inChannels}, norm_type={self.norm_type})'

#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

class LayerScale(nn.Module):
    '''
    Layer scale module.
    References:
      - https://arxiv.org/abs/2103.17239
    '''
    def __init__(self, inChannels, init_value=1e-2):
        super().__init__()
        self.inChannels = inChannels
        self.init_value = init_value
        self.layer_scale = nn.Parameter(init_value * torch.ones((inChannels)), requires_grad=True)

    def forward(self, x):
        if self.init_value == 0.0:
            return x
        else:
            scale = self.layer_scale.unsqueeze(-1).unsqueeze(-1) # C, -> C,1,1
            return scale * x

    def __repr__(self):
        return f'{self.__class__.__name__}(dim={self.inChannels}, init_value={self.init_value})'

#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
def stochastic_depth(input: torch.Tensor, p: float,
                     mode: str, training: bool =  True):

    if not training or p == 0.0:
        # print(f'not adding stochastic depth of: {p}')
        return input

    survival_rate = 1.0 - p
    if mode == 'row':
        shape = [input.shape[0]] + [1] * (input.ndim - 1) # just converts BXCXHXW -> [B,1,1,1] list
    elif mode == 'batch':
        shape = [1] * input.ndim

    noise = torch.empty(shape, dtype=input.dtype, device=input.device)
    noise = noise.bernoulli_(survival_rate)
    if survival_rate > 0.0:
        noise.div_(survival_rate)
    # print(f'added sDepth of: {p}')
    return input * noise

class StochasticDepth(nn.Module):
    '''
    Stochastic Depth module.
    It performs ROW-wise dropping rather than sample-wise.
    mode (str): ``"batch"`` or ``"row"``.
                ``"batch"`` randomly zeroes the entire input, ``"row"`` zeroes
                randomly selected rows from the batch.
    References:
      - https://pytorch.org/vision/stable/_modules/torchvision/ops/stochastic_depth.html#stochastic_depth
    '''
    def __init__(self, p=0.5, mode='row'):
        super().__init__()
        self.p = p
        self.mode = mode

    def forward(self, input):
        return stochastic_depth(input, self.p, self.mode, self.training)

    def __repr__(self):
       s = f"{self.__class__.__name__}(p={self.p})"
       return s

#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

def resize(input,
           size=None,
           scale_factor=None,
           mode='bilinear',
           align_corners=False):

    return F.interpolate(input, size, scale_factor, mode, align_corners)

#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

class DownSample(nn.Module):
    def __init__(self, kernelSize=3, stride=2, in_channels=3, embed_dim=768):
        super().__init__()
        self.proj = nn.Conv2d(in_channels, embed_dim, kernel_size=(kernelSize, kernelSize),
                              stride=stride, padding=(kernelSize//2, kernelSize//2))
        # stride 4 => 4x down sample
        # stride 2 => 2x down sample
    def forward(self, x):

        x = self.proj(x)
        B, C, H, W = x.size()
        # x = x.flatten(2).transpose(1,2)
        return x, H, W

#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class ConvModule(nn.Module):
    def __init__(self, inChannels, outChannels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, act_layer=nn.ReLU):
        super().__init__()
        self.conv = nn.Conv2d(inChannels, outChannels, kernel_size=kernel_size,
                              stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias)
        self.norm = norm_layer(outChannels)
        self.act = act_layer()

    def forward(self, x):
        x = self.conv(x)
        x = self.norm(x)
        x = self.act(x)
        return x

#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class DepthWiseConv(nn.Module):
    def __init__(self, inChannels, outChannels, kernel_size, stride=1, padding=0, dilation=1, bias=True):
        super(DepthWiseConv, self).__init__()
        self.kernel_size = kernel_size

        if self.kernel_size != 1:
            self.depthwise = ConvModule(inChannels, inChannels, kernel_size=kernel_size,
                                        stride=stride,  padding=padding, dilation=dilation, groups=inChannels, bias=bias)
        self.pointwise = ConvModule(inChannels, outChannels, kernel_size=1, bias=bias)

    def forward(self, x):
        if self.kernel_size != 1:
            x = self.depthwise(x)
        out = self.pointwise(x)
        return out

# ASPP //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class DWConv(nn.Module):
    def __init__(self, dim=768):
        super(DWConv, self).__init__()
        self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)

    def forward(self, x, H, W):
        B, N, C = x.shape # N -> HxW
        x = x.transpose(1, 2).view(B, C, H, W)
        x = self.dwconv(x)
        x = x.flatten(2).transpose(1, 2)

        return x

#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

class DWConv3x3(nn.Module):
    '''Depth wise conv'''
    def __init__(self, dim=768):
        super(DWConv3x3, self).__init__()
        self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)

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

class ConvNormAct(nn.Module):

    @classmethod
    def _same_paddings(cls, kernel_size):
        if kernel_size == 1:
            return 0
        elif kernel_size == 3:
            return 1

    def __init__(self, inChannels, outChannels, kernel_size=3, stride=1, padding='same',
                 dilation=1, groups=1, bias=False, norm_type='sync_bn', act_layer=nn.ReLU):
        super().__init__()

        if padding == 'same':
            padding = self._same_paddings(kernel_size)

        self.conv = nn.Conv2d(inChannels, outChannels, kernel_size=kernel_size,
                              padding=padding, stride=stride, dilation=dilation,
                              groups=groups, bias=bias)
        self.norm = NormLayer(outChannels, norm_type=norm_type)
        self.act = act_layer()

    def forward(self, x):

        x = self.conv(x)
        x = self.norm(x)
        x = self.act(x)

        return x

class twiceConvNormAct(nn.Module):
    def __init__(self, inChannels, outChannels, kernel=3, stride=1, padding='same',
                 dilation=1, groups=1):
        super().__init__()
        self.conv1 = ConvNormAct(inChannels, outChannels, kernel=kernel, stride=stride, padding=padding,
                                dilation=dilation, groups=groups)
        self.conv2 = ConvNormAct(outChannels, outChannels, kernel=kernel, stride=stride, padding=padding,
                                dilation=dilation, groups=groups)

    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        return x

class SeprableConv2d(nn.Module):
    def __init__(self, inChannels, outChannels, kernal_size=3, bias=False):
        self.dwconv = nn.Conv2d(inChannels, inChannels, kernal_size=kernal_size,
                                groups=inChannels, bias=bias)
        self.pwconv = nn.Conv2d(inChannels, inChannels, kernal_size=1, bias=bias)

    def forward(self, x):

        x = self.dwconv(x)
        x = self.pwconv(x)

        return x

class ConvRelu(nn.Module):
    def __init__(self, inChannels, outChannels, kernel=1, bias=False):
        super().__init__()
        self.conv = nn.Conv2d(inChannels, outChannels, kernel_size=kernel, bias=False)
        self.act = nn.ReLU(inplace=True)

    def forward(self, x):

        x = self.conv(x)
        x = self.act(x)

        return x
#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class AUX_Head(nn.Module):
    '''
    Used for calculating auxiliary loss before final loss during training
    from ground truths.
    '''
    def __init__(self, inChannels, num_classes, kernel=1, stride=1, padding='same',
                 dilation=1, groups=1):
        super().__init__()

        self.conv1 = nn.Conv2d(inChannels, inChannels, kernel_size=kernel,
                               padding=0, stride=stride, dilation=dilation,
                               groups=groups, bias=True)
        self.norm = NormLayer(inChannels, norm_type=config['norm_typ'])
        self.act = nn.ReLU(inplace=True)

        self.conv2 = nn.Conv2d(inChannels, num_classes, kernel_size=kernel,
                               padding=0, stride=stride, dilation=dilation,
                               groups=groups, bias=True)

    def forward(self, x):

        x = self.conv1(x)
        x = self.norm(x)
        x = self.act(x)
        x = self.conv2(x)

        return x
#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#//////////////////////////////////////////////////////////////////////////////////////////////////////////////////


#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @brief: publish module to maven
# @date:   2023.08.10 14:40:50

import os
import sys

g_this_file = os.path.realpath(sys.argv[0])
g_this_path = os.path.dirname(g_this_file)
sys.path.append(os.path.dirname(g_this_path))

from utils.utils_cmn import CmnUtils
from utils.utils_logger import LoggerUtils
from utils.utils_file import FileUtils
from utils.utils_import import ImportUtils
from basic.git import BasicGit
from basic.arguments import BasicArgumentsValue
from basic.space import BasicSpace
from basic.gradle import BasicGradle

g_wing_path = ImportUtils.initEnv()

# --------------------------------------------------------------------------------------------------------------------------
class ProjectCollector:
    def __init__(self, spacePath):
        self.mSpacePath = spacePath
        self.space = {}
        self.projects = []

    def doCollect(self):
        self.__doCollectSpace__()
        self.__doCollectModule__()

        jdata = {
            'space': self.space,
            'project': self.projects
        }
        FileUtils.saveJsonToFile(self.mSpacePath + '/out/project.json', jdata)

    def __doCollectSpace__(self):
        """
          "space": {
            "group": "xxx",
            "branch": "main",
            "manifest": "admin.xml"
            "remote": "wing"
          }
        """
        space = BasicSpace(self.mSpacePath)
        path = self.mSpacePath + '/.wing/manifests'
        branch, sname = ProjectCollector.getGitInfo(path)
        assert not CmnUtils.isEmpty(sname), "No manifests found !"
        self.space["name"] = "manifests"
        self.space["path"] = path
        self.space["branch"] = branch
        self.space["remote"] = sname
        self.space["group"] = space.getGroup()
        self.space["manifest"] = space.getManifest()

    def __doCollectModule__(self):
        """
          "${module name}": {
            "branch": "${git branch name}",
            "type": "${project type}"
            "remote": "$git remote name"
          }
        """
        self.scanPath(self.mSpacePath, 1)

    def doParseBase(self, d, pname, branch, sname):
        pitem = {
            "name": pname,
            "path": d,
            "branch": branch,
            "remote": sname
        }
        return pitem

    def doParseWithAndroid(self, path, pitem):
        """
          "${module name}": {
            "type": "aar"
          }
        """
        gradle = BasicGradle(path)
        if not gradle.isValid(): return False

        pitem['type'] = "gradle"
        modules = []
        pitem['module'] = modules
        for module in gradle.getModules():
            LoggerUtils.w('    :' + module)
            mm = {}
            mm['name'] = module
            mode = gradle.getMode(module)
            if None != mode: mm['mode'] = mode
            modulePath = gradle.getModulePath(module)
            if os.path.isfile(modulePath + '/.checkignore'): mm['ignore-check'] = True
            modules.append(mm)
        return True

    def scanPath(self, path, level):
        ll = os.listdir(path)
        for l in ll:
            if l.startswith('.'): continue
            d = path + os.sep + l
            if not os.path.isdir(d): continue
            branch, sname = ProjectCollector.getGitInfo(d)
            if not CmnUtils.isEmpty(sname):
                pname = d[len(self.mSpacePath) + 1:]
                LoggerUtils.light(pname)
                pitem = self.doParseBase(d, pname, branch, sname)
                self.projects.append(pitem)
                if self.doParseWithAndroid(d, pitem): continue
                # TODO add more parser here ...
                continue
            if 3 < level: continue
            self.scanPath(d, level + 1)

    @staticmethod
    def getGitInfo(projPath):
        git = BasicGit(projPath)
        return git.getCurrentBranch(), git.getServerName()

def run():
    """
    wing -project
    """
    argv = BasicArgumentsValue()
    envPath, spacePath, projPath, cmd = argv.get(0), argv.get(1), argv.get(2), argv.get(3)
    ProjectCollector(spacePath).doCollect()

if __name__ == "__main__":
    run()


import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np

# Define placeholders for input and ouput values
x = tf.placeholder(tf.float32, [None, 1], name='x')
y = tf.placeholder(tf.float32, [None, 1], name='y')

# Define fully-connected layer with 10 hidden units
h = tf.layers.dense(x, 10, activation=tf.nn.relu)

# Define fully-connected layer with 20 hidden units
h = tf.layers.dense(h, 20, activation=tf.nn.relu)

# Define fully-connected layer with 10 hidden units
h = tf.layers.dense(h, 10, activation=tf.nn.relu)

# Define fully-connected layer to single ouput prediction
pred = tf.layers.dense(h, 1, activation=None)

# Define loss function
loss = tf.reduce_mean(tf.pow(pred - y, 2))

# Define optimizer
optim = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)

# Define variable initializer
init = tf.global_variables_initializer()

# Initialize TensorFlow session
with tf.Session() as sess:

    # Initialize variables
    sess.run(init)

    # Iterate through 10000 training steps
    for n in range(0,10000):

        # Create artificial data with mini-batch size 100
        x_batch = np.pi/2 * np.random.normal(size=[100, 1])
        y_batch = np.sin(x_batch)

        # Run optimization operation for current mini-batch
        fd = {x: x_batch, y: y_batch}
        sess.run(optim, feed_dict=fd)

    # Plot predicted and true values for qualitative evaluation
    eval_pts = np.expand_dims(np.linspace(-np.pi/2, np.pi/2, 1000) , 1)
    predictions = sess.run(pred, feed_dict={x: eval_pts})
    true_values = np.sin(eval_pts)
    plt.plot(eval_pts[:,0], predictions[:,0], 'b')
    plt.plot(eval_pts[:,0], true_values[:,0], 'r')
    plt.show()


"""
Problem Link: https://leetcode.com/problems/sliding-window-maximum/

You are given an array of integers nums, there is a sliding window of size k which is moving
from the very left of the array to the very right. You can only see the k numbers in the window.
Each time the sliding window moves right by one position.
Return the max sliding window.

Example 1:
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:
Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

Example 2:
Input: nums = [1], k = 1
Output: [1]

Constraints:
1 <= nums.length <= 105
-104 <= nums[i] <= 104
1 <= k <= nums.length
"""
# Time Complexity: O(N)
class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        next_greater = [0] * len(nums)
        stack = []

        for index in range(len(nums)-1, -1, -1):
            while stack and nums[stack[-1]] <= nums[index]:
                stack.pop()

            next_greater[index] = stack[-1] if stack else len(nums)
            stack.append(index)

        res = []
        max_index = 0
        for index in range(len(nums) - k + 1):
            if max_index < index:
                # to handle case where greater element of last window was the first one which is removed from the window
                max_index = index
            while next_greater[max_index] < index + k:
                max_index = next_greater[max_index]

            res.append(nums[max_index])

        return res


import smbus
import time
import board
import neopixel
import RPi.GPIO as GPIO
bus = smbus.SMBus(1)

addr = 0x10

#Write registers
als_conf_0 = 0x00
als_WH = 0x01
als_WL = 0x02
pow_sav = 0x03

#Read registers
als = 0x04
white = 0x05
interrupt = 0x06

# These settings will provide the range for the sensor: (0 - 15099 lx)
#
# LSB MSB
confValues = [0x00, 0x18] # 1/4 gain, 100ms IT (Integration Time)

#Reference data sheet Table 1 for configuration settings
#MSB = 00011000 = 18 in hexadecimal ( als gain = 1/4, bits 12:11 = 11 )
#LSB = 00000000 = 00 ( integration time = 100ms, bits 9:6 = 0000 )

interrupt_high = [0x00, 0x00] # Clear values
#Reference data sheet Table 2 for High Threshold

interrupt_low = [0x00, 0x00] # Clear values
#Reference data sheet Table 3 for Low Threshold

power_save_mode = [0x00, 0x00] # Clear values
#Reference data sheet Table 4 for Power Saving Modes

bus.write_i2c_block_data(addr, als_conf_0, confValues)
bus.write_i2c_block_data(addr, als_WH, interrupt_high)
bus.write_i2c_block_data(addr, als_WL, interrupt_low)
bus.write_i2c_block_data(addr, pow_sav, power_save_mode)

pixel_pin = board.D18

# On a Raspberry pi, use this instead, not all pins are supported
#pixel_pin = board.D18

# The number of NeoPixels
num_pixels = 60

# The order of the pixel colors - RGB or GRB. Some NeoPixels have red and green reversed!
# For RGBW NeoPixels, simply change the ORDER to RGBW or GRBW.
ORDER = neopixel.GRB

pixels = neopixel.NeoPixel(pixel_pin, num_pixels, brightness=0.2, auto_write=False,
                           pixel_order=ORDER)

def Strobe(red,green,blue, StrobeCount,FlashDelay, EndPause):
  for i in range(StrobeCount):
    pixels.fill((red,green,blue))
    pixels.show()
    time.sleep(FlashDelay)
    pixels.fill((0,0,0))
    pixels.show()
    time.sleep(FlashDelay)

    time.sleep(EndPause)

def wheel(pos):
    # Input a value 0 to 255 to get a color value.
    # The colours are a transition r - g - b - back to r.
    if pos < 0 or pos > 255:
        r = g = b = 0
    elif pos < 85:
        r = int(pos * 3)
        g = int(255 - pos*3)
        b = 0
    elif pos < 170:
        pos -= 85
        r = int(255 - pos*3)
        g = 0
        b = int(pos*3)
    else:
        pos -= 170
        r = 0
        g = int(pos*3)
        b = int(255 - pos*3)
    return (r, g, b) if ORDER == neopixel.RGB or ORDER == neopixel.GRB else (r, g, b, 0)

def rainbow_cycle(wait):
    for j in range(255):
        for i in range(num_pixels):
            pixel_index = (i * 256 // num_pixels) + j
            pixels[i] = wheel(pixel_index & 255)
        pixels.show()
        time.sleep(wait)

buttonPin = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(buttonPin,GPIO.IN, pull_up_down=GPIO.PUD_UP)

prev_input = 0

while True:
#The frequency to read the sensor should be set greater than
# the integration time (and the power saving delay if set).
# Reading at a faster frequency will not cause an error, but
# will result in reading the previous data
	time.sleep(1) # 40ms

	word = bus.read_word_data(addr,als)
# wordIR = bus.read_word_data(addr,white)

	gain = 0.2304 # gain=1/4 and int time=100ms, max lux=15099 lux

#Reference www.vishay.com/docs/84367/designingveml6030.pdf
# 'Calculating the LUX Level'

	val = word * gain
#valIR = wordIR * gain
#val = round(val,1)
#valIR = round(valIR,1)

#Reference www.vishay.com/docs/84367/designingveml6030.pdf
# 'Calculating the LUX Level'

	valcorr = (6.0135E-13*val**4)-(9.392E-9*val**3)+(8.1488E-5*val**2)+(1.0023E0*val)
	valcorr = round(valcorr) #Round corrected value for presentation
	button_input = GPIO.input(17)
	if button_input == False:
		if prev_input == 1:
			prev_input = 0
		else:
			prev_input = 1

		time.sleep(0.5)

	if prev_input == 1:

		if valcorr < 100:
			Strobe(255,255,255,5,0.05,0.001)
			Strobe(255,0,255,5,0.05,0.001)
			Strobe(255,192,203,5,0.05,0.001)
		else:
			pixels.fill((0,0,0))
			pixels.show()

	else:
		pixels.fill((0,0,0))
		pixels.show()


#!/usr/bin/python
# -*- coding: utf-8 -*-

import asyncio
import functools

def greeting(welcome):  # no async declare here
    print(welcome)

async def main(loop):
    loop.call_soon_threadsafe(functools.partial(greeting, "hello asyncio"))
    loop.call_soon(functools.partial(greeting, "hello asyncio"))

    # Most asyncio functions don't accept keyword. If you want to pass keywords
    # to your callback, use functions.partial(). For example,
    # loop.call_soon(functions.partial(print, "Hello", flush=True))
    # will call print("Hello, flush=True")

    # Note: functools.partial() is better than lambda functions, because
    # asyncio can inspect functions.partial() object to display parameters
    # in debug mode, whereas lambda functions have a poor representation.

loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
loop.close()

# https://docs.python.org/3/library/asyncio-eventloop.html#calls


#!/usr/bin/python3
import os
import re
import json
from sys import argv

with open(argv[1]) as fd:
    content = fd.read()
    content = re.sub(r'\n', '', content)
    obj = json.loads(content)
    for cell in obj['cells']:
        if cell['cell_type'] == 'code':
            cell['execution_count'] = None
            cell['outputs'] = []
            if (len(cell['source']) > 0 and cell['source'][0].startswith('##keep')):
                continue
            cell['source'] = []
    print(json.dumps(obj))


# -*- coding: utf-8 -*-
####################################################
# Class Activity
# author: Craig Shaffer
# date revision: 1/12/21
# course: CPSC 242
#
# code to compute cumulative sum of integers
#
# input - integers
# output - the sum of these integers
#
####################################################

#initial value of the sum
sum=0

#infinite loop to continue to accept user input
while(True):
    numVal = input("enter an integer or 'done' >> ")
    if(numVal == "done"): #checks if user input "done"
        print("sum is: ", sum)
        break #ends infinite loop
    sum = sum + int(numVal) #adds integer to cumulative sum


''' We shall define a twopal to be a palindromic tuple having at least one
element with a value of 2. It should also be noted that elements are not
restricted to single digits. Let t(n) be the number of twopals whose elements
sum to n. Find the least value of n such that t(n) is divisible by one
million '''

def main():
    ''' 't_n' = t(n) mod 10^6. At most, 3 consecutive values of the g function
    described in the above link need to be stored at any given time. These
    values are stored in 'g' in ascending order. Values of t(n) are generated
    until a value divisible by one million is found. 'n' is then printed.

    My equation (technically two, one for each parity) for t(n) uses the
    recursive function g described here, with k=2 (unrelated to below k):
        https://math.stackexchange.com/a/2086747/530956
    For even n:
        t(n) = g((n-2)/2) + (sum 2^((n-2m-2)/2)-g((n-2m)/2) for m=0 to n/2)
    For odd n:
        t(n) = sum 2^((n-2m-3)/2)-g((n-2m-1)/2) for m=0 to (n-1)/2
    A given k-length twopal, p, can be equivalently expressed using its first
    floor(k/2) elements (call them h) and middle element, m (0 if k is even).
    The sum of h, s = (n-m)/2. The problem is thus equal to the sum of the
    number of compositions of s containing 2 for all possible values of s.  The
    g recurrence relation described in the above link outputs the number of
    compositions that don't contain a 2, which one can subtract from 2^(x-1),
    the number of compositions of x, to get the correct value. When m=2 (only
    possible for even n as m = n (mod 2)) all compositions make valid twopals.
    The summation doesn't take this into account, so g((n-2)/2) needs to be
    added. The relationship between successive values of t(n) used below can
    easily be derived from the above equation(s) '''
    n = 6
    mod = 10**6
    t_n = 4
    g = [1, 2, 4]
    while t_n != 0:
        n += 1
        if n % 2 == 1:
            t_n -= g[0]
        else:
            t_n = (t_n + g[1] - g[2] + pow(2, (n-2)//2, mod)) % mod
            g = [g[1], g[2], (2*g[2]-g[1]+g[0]) % mod]
    print(n)

if __name__ == "__main__":
    main()


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

import argparse
import os
import shutil
import sys

from mozbuild.util import ensureParentDir

def main(argv):
    parser = argparse.ArgumentParser(description="Merge l10n files.")
    parser.add_argument("--output", help="Path to write merged output")
    parser.add_argument("--ref-file", help="Path to reference file (en-US)")
    parser.add_argument("--l10n-file", help="Path to locale file")

    args = parser.parse_args(argv)

    from compare_locales.compare import ContentComparer, Observer
    from compare_locales.paths import File

    cc = ContentComparer([Observer()])
    cc.compare(
        File(args.ref_file, args.ref_file, ""),
        File(args.l10n_file, args.l10n_file, ""),
        args.output,
    )

    ensureParentDir(args.output)
    if not os.path.exists(args.output):
        src = args.l10n_file
        if not os.path.exists(args.l10n_file):
            src = args.ref_file
        shutil.copy(src, args.output)

    return 0

if __name__ == "__main__":
    main(sys.argv[1:])


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

__author__ = 'sobolevn'

from utils import get_input_function

class Storage(object):  # storage = Storage()
    obj = None

    items = None

    done = None

    @classmethod
    def __new__(cls, *args):
        if cls.obj is None:
            cls.obj = object.__new__(cls)
            cls.items = []
            cls.done = None
        return cls.obj

class BaseItem(object):
    def __init__(self, heading, done=''):
        self.heading = heading
        self.done = done

    def __repr__(self):
        return self.__class__

    @classmethod
    def construct(cls):
        raise NotImplemented()

class ToDoItem(BaseItem):
    def __str__(self):
        return 'ToDo: {}{}'.format(
            self.heading,
            self.done,
        )

    @classmethod
    def construct(cls):
        input_function = get_input_function()
        heading = input_function('Input heading: ')
        done = ' -'
        return ToDoItem(heading, done)

class ToBuyItem(BaseItem):
    def __init__(self, heading, price, done=''):
        super(ToBuyItem, self).__init__(heading)
        self.price = price
        self.done = done

    def __str__(self):
        return 'ToBuy: {} for {}{}'.format(
            self.heading,
            self.price,
            self.done,
        )

    @classmethod
    def construct(cls):
        input_function = get_input_function()
        heading = input_function('Input heading: ')
        price = input_function('Input price: ')
        done = ' -'
        return ToBuyItem(heading, price, done)

class ToReadItem(BaseItem):
    def __init__(self, heading, url, done=''):
        super(ToReadItem, self).__init__(heading)
        self.url = url
        self.done = done

    def __str__(self):
        return 'ToRead: {} for {}{}'.format(
            self.heading,
            self.url,
            self.done
        )

    @classmethod
    def construct(cls):
        input_function = get_input_function()
        heading = input_function('Input heading: ')
        url = input_function('Input URL: ')
        done = ' -'
        return ToReadItem(heading, url, done)


import sys
import glob

infiles = sorted(glob.glob('epitope_MHV/*.tsv'))
for infile in infiles:
  outfile = infile.replace('.tsv','.fasta')
  inhandle = open(infile)
  outhandle = open(outfile,'w')
  header = inhandle.readline()
  for line in inhandle:
    #if ':' in line: continue #discrete epitope
    line = line.rstrip().rsplit('\t')
    name = line[1]+'_'+line[10]
    seq = line[2]
    outhandle.write('>'+name+'\n'+seq+'\n')
  inhandle.close()
  outhandle.close()