import os
import numpy as np
from PIL import Image

# 图片转换为txt
def ChangeData():
    source_dir = 'C:\\Users\\HP\\Desktop\\1\\'
    target_dir = 'C:\\Users\\HP\\Desktop\\2\\'
    for name in os.listdir(source_dir):
        file_dir = source_dir + '{}/'.format(name)
        for img_name in os.listdir(file_dir):
            # 读取图片
            img_path = file_dir + img_name
            im = Image.open(os.path.expanduser(img_path)).convert("L")  # 将RGB转化为灰度图像，L代表灰度图像，像素值在0~255之间
            im = im.resize((64, 64), Image.ANTIALIAS)
            size = im.size
            print(size)

            # 计算图像im裁剪比例
            im_nu = np.array(im).reshape(64, 64).astype(np.int)  # 返回新形状的数组,把它变成一个 numpy 数组以匹配数据馈送格式
            raw_top, raw_down, col_top, col_down = corp_margin(im_nu)

            # 准备将图片切割
            weight, height = size[0], size[1]
            # left：与左边界的距离 up：与上边界的距离 right：还是与右边界的距离 below：还是与下边界的距离
            box = (int(weight * col_top), int(height * raw_top), int(weight * col_down), int(height * raw_down))
            im = im.crop(box)
            im = im.resize((64, 64), Image.ANTIALIAS)
            im = np.array(im).reshape(64, 64).astype(np.int)
            # 0/1修改
            for i in range(0, 64):
                for j in range(0, 64):
                    if im[i][j] > 50:
                        im[i][j] = 0
                    else:
                        im[i][j] = 1
            # 保存txt
            s1 = img_name.split('.')
            if not os.path.exists(target_dir):
                os.mkdir(target_dir)
            txt_path = target_dir + name
            txtFile_path = target_dir + name + '/' + s1[0] + '.txt'
            if not os.path.exists(txt_path):
                os.mkdir(txt_path)
            np.savetxt(txtFile_path, im, fmt='%s', delimiter='', newline='\n')
    return 0

def corp_margin(img):
    (row, col) = img.shape
    bias = 50
    raw_top, raw_down, col_top, col_down = 0, 0, 0, 0
    for r in range(0, row):
        if img[r].sum() < 255 * col - bias:
            raw_top = r
            break

    for r in range(row - 1, 0, -1):
        if img[r].sum() < 255 * col - bias:
            raw_down = r
            break

    for c in range(0, col):
        if img[:, c].sum() < 255 * col - bias:
            col_top = c
            break

    for c in range(col - 1, 0, -1):
        if img[:, c].sum() < 255 * col - bias:
            col_down = c
            break

    # 保持图像方形
    ch = (col_down - col_top) - (raw_down - raw_top)
    if ch > 0:
        raw_top -= int(ch / 2) + 1
        if raw_top < 0:
            raw_top = 0
        raw_down += int(ch / 2)
        if raw_down > 64:
            raw_down = 64
    elif ch < 0:
        ch = abs(ch)
        col_top -= int(ch / 2) + 1
        if col_top < 0:
            col_top = 0
        col_down += int(ch / 2)
        if col_down > 64:
            col_down = 64

    return raw_top/64, raw_down/64, col_top/64, col_down/64

if __name__ == '__main__':
    re = ChangeData()


import openpyxl
import time
def appendToXL(headers, data_tuplee, path, title):
	wb = openpyxl.load_workbook(path)
	if 'Sheet1' in wb.sheetnames:
		wb.remove_sheet(wb['Sheet1'])
	try:
		ws = wb[title]
	except:
		ws = wb.create_sheet(title)

	# creates the headers
	for header in headers:
		col = headers.index(header) + 1
		ws.cell(row = 1, column = col, value = header)

	# find new row
	empty = False
	empty_row = 2
	while not empty:
		if ws.cell(row = empty_row, column = 1).value == None or ws.cell(row = empty_row, column = 1).value == '':
			empty = True
		else:
			empty_row += 1
	# print(f'empty row is {empty_row}')
	# checks if its a repeat data
	above_row = empty_row - 1
	if ws.cell(row = above_row, column = 2).value == data_tuplee[1]:
		# print(f'this is being tripped accidentally, {ws.cell(row = above_row, column = 2).value} equals {data_tuplee[1]}')
		print('no new data found')
	else:
		# appends the data
		for data in data_tuplee:
			col = data_tuplee.index(data) + 1
			ws.cell(row = empty_row, column = col, value = data)

	# saves the data
	try:
		wb.save(path)
	except PermissionError:
		input('Cannot save to excel file because the file is open. Please close the excel file and re-run this program.')


# Advent of Code 2019 - Day 13

# Author:   Rachael Judy
# Date:     12/5/2020
# Purpose:  Game cabinet - break the blocks by bouncing ball on paddle
#               Check the comments with MOD to add the cheat wall for phase 2
#
# 0 - empty tile - white
# 1 - industructable wall - black
# 2 - block -  vermilion
# 3 - paddle - purple
# 4 - ball - green
#

import os
import queue
import sys

import intcodecomputer
import numpy as np
import pygame

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import parseMod

# set this for part 1 or 2
phase = 2

# constants for displaying the game board
#                 R    G    B
BLACK =         (  0,   0,   0)
WHITE =         (255, 255, 255)
PURPLE =        (128,   0, 128)
VERMILION =     (227,  66,  51)
GREEN =         (  0, 204,   0)

colorDict = {0: WHITE, 1: BLACK, 2: VERMILION, 3: PURPLE, 4: GREEN}

# Create the constants for
BOARDWIDTH = 42  # number of columns in the board
BOARDHEIGHT = 24 # number of rows in the board
TILESIZE = 20
WINDOWWIDTH = 960
WINDOWHEIGHT = 640
FPS = 30

XMARGIN = int((WINDOWWIDTH - (TILESIZE * BOARDWIDTH + (BOARDWIDTH - 1))) / 2)
YMARGIN = int((WINDOWHEIGHT - (TILESIZE * BOARDHEIGHT + (BOARDHEIGHT - 1))) / 2)
global DISPLAYSURF

def drawBoard(board):
    DISPLAYSURF.fill(WHITE)

    for tilex in range(len(board)):
        for tiley in range(len(board[0])):
            if board[tilex][tiley]:
                drawTile(tilex, tiley, board[tilex][tiley])

def getLeftTopOfTile(tileX, tileY):
    left = XMARGIN + (tileX * TILESIZE) + (tileX - 1)
    top = YMARGIN + (tileY * TILESIZE) + (tileY - 1)
    return (left, top)

def drawTile(tilex, tiley, number, adjx=0, adjy=0):
    # draw a tile at board coordinates tilex and tiley, optionally a few
    # pixels over (determined by adjx and adjy)
    TILECOLOR = colorDict[number]
    left, top = getLeftTopOfTile(tilex, tiley)
    pygame.draw.rect(DISPLAYSURF, TILECOLOR, (left + adjx, top + adjy, TILESIZE, TILESIZE))

# input
instructions = parseMod.readCSVInts('data/13game.csv')  # MODIFY TO 13gameMOD.csv for MOD VERSION

pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('Arcade Game')

# phase 1
if phase == 1:
    # create computer
    arcade = intcodecomputer.Computer(instructions)

    # run program and show gameboard
    count = 0
    inputQ = queue.SimpleQueue()
    gameboard = np.zeros((42, 24))
    output = arcade.processInput(inputQ)

    # process the output to show the board and occupied_count the block tiles
    for i in range(0, len(output), 3):
        gameboard[output[i], output[i+1]] = int(output[i+2])
        if output[i+2] == 2:  # occupied_count block tiles
            count += 1

    print("Block tiles: ", count)
    while True:
        drawBoard(gameboard)
        pygame.display.update()

# phase 2
else:
    bestScore = 0
    instructions[0] = 2
    # create computer
    arcade = intcodecomputer.Computer(instructions)

    # run program and show gameboard
    inputQ = queue.SimpleQueue()
    gameboard = np.zeros((44, 26))
    while not arcade.isDone():
        output = arcade.processInput(inputQ)

        # process the output to show the board
        for i in range(0, len(output), 3):
            if output[i] == -1 and output[i+1] == 0:
                print("Current Score: ", output[i+2])  # COMMENT IN TO SEE PROGRESS OF SCORE AS YOU GO
                bestScore = max(bestScore, output[i+2])
                break
            gameboard[output[i], output[i+1]] = int(output[i + 2])

        drawBoard(gameboard)

        # get input
        for event in pygame.event.get(): # event handling loop
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    inputQ.put(1)
                elif event.key == pygame.K_LEFT:
                    inputQ.put(-1)
                elif event.key == pygame.K_DOWN:
                    inputQ.put(0)
#        inputQ.put(0)  # COMMENT IN FOR MODIFIED WALL VERSION

        pygame.display.update()
        FPSCLOCK.tick(FPS)

    print("Best score: ", bestScore)


import config
import PyRSS2Gen
import http.server
import socketserver
import core
from datetime import datetime
from threading import Thread

# Our rss generator
rss = PyRSS2Gen.RSS2(
    title="Satellite station images",
    link="",
    description="Images from the station",
    lastBuildDate=datetime.now(),
    items=[]
    )

# Http server
httpd = 0
server_thread = 0

# We need to set out directory
class HTTPHandler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=config.output_dir, **kwargs)

# Function for adding passes
def addRSSPass(satellite, filename, date, passobj):

    # Generate item content, here being images
    image = ""
    if satellite.downlink == "APT":
        image = "Visible + Infrared : <\p>" + ""
    elif satellite.downlink == "LRPT":
        image = "Visible : <\p>" + "" + "<\p>" + "Infrared : <\p>" + ""

    # Add it to the feed
    rss.items.append(PyRSS2Gen.RSSItem(
        title = satellite.name + " on " + date.strftime('%H:%-M %d, %b %Y') + " (" + str(passobj.max_elevation_deg) + "°)",
        link = "",
        description = image,
        guid = PyRSS2Gen.Guid(""),
        pubDate = date)
    )

    # Write the file to push the update
    rss.write_xml(open(config.output_dir + "/rss.xml", "w"))

# Used for the startup procedure
def startServer():
    global rss, httpd, server_thread

    if config.rss_webserver:
        # Configure the http server
        httpd = socketserver.TCPServer(("", config.rss_port), HTTPHandler)
        print("Starting http server at " + str(config.rss_port))
        print("\n")

        # Start it in a thread
        server_thread = Thread(target = httpd.serve_forever)
        server_thread.start()

    # Write the file to make the feed readable
    rss.write_xml(open(config.output_dir + "/rss.xml", "w"))


import logging

import wrapt
from opencensus.trace import execution_context
from opencensus.trace.blank_span import BlankSpan
from opencensus.trace.span_context import SpanContext
from opencensus.trace.tracers.base import Tracer as BaseTracer
from opencensus.trace.tracestate import Tracestate

from opentelemetry import context, trace
from opentelemetry.shim.opencensus._shim_span import ShimSpan

_logger = logging.getLogger(__name__)

_SHIM_SPAN_KEY = context.create_key("opencensus-shim-span-key")
_SAMPLED = trace.TraceFlags(trace.TraceFlags.SAMPLED)

def set_shim_span_in_context(
    span: ShimSpan, ctx: context.Context
) -> context.Context:
    return context.set_value(_SHIM_SPAN_KEY, span, ctx)

def get_shim_span_in_context() -> ShimSpan:
    return context.get_value(_SHIM_SPAN_KEY)

def set_oc_span_in_context(
    oc_span_context: SpanContext, ctx: context.Context
) -> context.Context:
    """Returns a new OTel context based on ctx with oc_span_context set as the current span"""

    # If no SpanContext is passed to the opencensus.trace.tracer.Tracer, it creates a new one
    # with a random trace ID and a None span ID to be the parent:
    # https://github.com/census-instrumentation/opencensus-python/blob/2e08df591b507612b3968be8c2538dedbf8fab37/opencensus/trace/tracer.py#L47.
    #
    # OpenTelemetry considers this an invalid SpanContext and will ignore it, so we can just
    # return early
    if oc_span_context.span_id is None:
        return ctx

    trace_id = int(oc_span_context.trace_id, 16)
    span_id = int(oc_span_context.span_id, 16)
    is_remote = oc_span_context.from_header
    trace_flags = (
        _SAMPLED if oc_span_context.trace_options.get_enabled() else None
    )
    trace_state = (
        trace.TraceState(tuple(oc_span_context.tracestate.items()))
        # OC SpanContext does not validate this type
        if isinstance(oc_span_context.tracestate, Tracestate)
        else None
    )

    return trace.set_span_in_context(
        trace.NonRecordingSpan(
            trace.SpanContext(
                trace_id=trace_id,
                span_id=span_id,
                is_remote=is_remote,
                trace_flags=trace_flags,
                trace_state=trace_state,
            )
        )
    )

# pylint: disable=abstract-method
class ShimTracer(wrapt.ObjectProxy):
    def __init__(
        self,
        wrapped: BaseTracer,
        *,
        oc_span_context: SpanContext,
        otel_tracer: trace.Tracer
    ) -> None:
        super().__init__(wrapped)
        self._self_oc_span_context = oc_span_context
        self._self_otel_tracer = otel_tracer

    # For now, finish() is not implemented by the shim. It would require keeping a list of all
    # spans created so they can all be finished.
    # def finish(self):
    #    """End spans and send to reporter."""

    def span(self, name="span"):
        return self.start_span(name=name)

    def start_span(self, name="span"):
        parent_ctx = context.get_current()
        # If there is no current span in context, use the one provided to the OC Tracer at
        # creation time
        if trace.get_current_span(parent_ctx) is trace.INVALID_SPAN:
            parent_ctx = set_oc_span_in_context(
                self._self_oc_span_context, parent_ctx
            )

        span = self._self_otel_tracer.start_span(name, context=parent_ctx)
        shim_span = ShimSpan(
            BlankSpan(name=name, context_tracer=self),
            otel_span=span,
            shim_tracer=self,
        )

        ctx = trace.set_span_in_context(span)
        ctx = set_shim_span_in_context(shim_span, ctx)

        # OpenCensus's ContextTracer calls execution_context.set_current_span(span) which is
        # equivalent to the below. This can cause context to leak but is equivalent.
        # pylint: disable=protected-access
        shim_span._self_token = context.attach(ctx)
        # Also set it in OC's context, equivalent to
        # https://github.com/census-instrumentation/opencensus-python/blob/2e08df591b507612b3968be8c2538dedbf8fab37/opencensus/trace/tracers/context_tracer.py#L94
        execution_context.set_current_span(shim_span)
        return shim_span

    def end_span(self):
        """Finishes the current span in the context and restores the context from before the
        span was started.
        """
        span = self.current_span()
        if not span:
            _logger.warning("No active span, cannot do end_span.")
            return

        span.finish()

        # pylint: disable=protected-access
        context.detach(span._self_token)
        # Also reset the OC execution_context, equivalent to
        # https://github.com/census-instrumentation/opencensus-python/blob/2e08df591b507612b3968be8c2538dedbf8fab37/opencensus/trace/tracers/context_tracer.py#L114-L117
        execution_context.set_current_span(self.current_span())

    # pylint: disable=no-self-use
    def current_span(self):
        return get_shim_span_in_context()

    def add_attribute_to_current_span(self, attribute_key, attribute_value):
        self.current_span().add_attribute(attribute_key, attribute_value)


import os
import unittest

import matplotlib.pyplot as plt
import numpy as np
import numpy.testing as npt
from scipy.io.matlab import loadmat
from scipy.io.wavfile import read, write
from scipy.signal import resample
from time import time

from tqwt_tools.tqwt import synthesis_filter_bank, analysis_filter_bank
from tqwt_tools import tqwt, itqwt
from tqwt_tools.util import get_package_path
from tqwt_tools.util.test_signal import speech_signal

# these output values of the afb and sfb were generated from the Matlab toolbox ([V0, V1] = afb((0:19), 16, 12))
EXPECTEDV0 = np.array([0, 1, 2, 3, 4, 4.85268414962686, 4.24264068711929, 1.68666974424811, 0, 3.13238666788935,
                       9.89949493661167, 14.5580524488806, 16, 17, 18, 19])
EXPECTEDV1 = np.array([0, 1.20476410303436, 4.24264068711929, 6.79375780947761, 8, 9, 10, 11, 12,
                       12.6169787890298, 9.89949493661167, 3.61429230910309])
EXPECTEDY = np.array([0, 1, 2, 3, 4, 5, 9.283601844998817, 17.507536716885582, 23.775413799563122, 25.131037888449338,
                      25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37.296444516289142, 37.790891865207485,
                      31.014025662207025, 20.061288372791118, 15, 16, 17, 18, 19], dtype=np.complex)

class TestTQWT(unittest.TestCase):

    def test_afb(self):
        """Check the analysis filter bank function in a simple case against hard-coded Matlab results"""
        v0, v1 = analysis_filter_bank(np.arange(20).astype(np.float), 16, 12)
        npt.assert_allclose(EXPECTEDV0, v0)
        npt.assert_allclose(EXPECTEDV1, v1)

    def test_tqwt(self):
        """Test the tqwt main function with random numbers"""
        sine = np.cos(2 * np.pi * 2 / 10 * np.arange(48))
        w = tqwt(sine, 3, 3, 3)
        w_matlab = loadmat(os.path.join(get_package_path().replace('/tqwt_tools/', '/'),
                                        'tests', 'resources', 'w_sine'))['w']
        for subband, subband_matlab in zip(w, np.squeeze(w_matlab)):
            npt.assert_allclose(np.imag(subband), 0, atol=1e-14)
            npt.assert_allclose(np.real_if_close(subband).astype(np.float32), np.squeeze(subband_matlab))

    def test_tqwt_with_audio(self) -> None:
        """Test the TQWT with audio material"""

        #sine = np.cos(2 * np.pi * 1000 / 16000 * np.arange(48000))
        #wAudio = tqwt.tqwt(sine, 8, 2, 32)

        #start = time()
        #wAudio = tqwt.tqwt(self.audio, 10, 1.5, 67)
        #print("Runtime: ", time()-start)

        # # plot the resulting spectrogram by resampling each subband
        # spectrogram = np.zeros((wAudio.shape[0], self.audio.shape[0]), dtype=np.complex)
        # for idx, subband in enumerate(wAudio):
        #     spectrogram[idx, :] = resample(subband, self.audio.shape[0])
        # plt.imshow(20*np.log10(1e-8+np.abs(spectrogram)), aspect='auto')
        # plt.yticks([]); plt.xticks([])
        # plt.show()

class TestITQWT(unittest.TestCase):

    def test_sfb(self) -> None:
        """Test the synthesis filter bank used in the itqwt against results from the original Matlab implementation"""
        y = synthesis_filter_bank(np.arange(20), np.arange(start=20, stop=40), 30)
        npt.assert_allclose(EXPECTEDY, y)

class TestPerfectReconstruction(unittest.TestCase):

    def test_perfect_reconstruction(self) -> None:
        q = 2; r = 2; j = 8
        x = speech_signal()
        n = speech_signal().shape[0]
        w = tqwt(x, q, r, j)                      # wavelet transform
        y = itqwt(w, q, r, n)                     # inverse wavelet transform
        reconstruction_error_lin = max(abs(x - y))
        reconstruction_error_db = 20 * np.log10(reconstruction_error_lin)
        self.assertLess(reconstruction_error_db,  -290)
        print("[TestPerfectReconstruction] Reconstrucion Error: ", reconstruction_error_db, "dB")

if __name__ == '__main__':
    unittest.main()


import bpy
from . import fx_map
from . import default_fx
from bpy.props import *

# /!\ building - tasks are untested
# /!\ do not tie this into the main process

## NOTE: this "creator" is for creating and effect data stored in the "map"
##  - the "maker" is for applying effects to create text
##  - see TODO.md for namespace issues

class TextEffectsCreator:
    def __init__(self, mapper):
        self.fx_mapper = mapper
        return

    def is_axes_list(self, axes):
        """Check if a list contains valid axes"""
        compared_axes = ['x', 'y', 'z']
        valid_axes = [compared_axes.pop(axis) for axis in axes if axis in compared_axes]
        return (type(axes) is not list or len(valid_axes) != len(axes))

    def list_effects(self):
        """Get the names of all known effects - alias for fx_map.keys"""
        return self.mapper.keys()

    def create(self, fx_name, attr='', frame_arc=[], value_arc=[], axis=['x', 'y', 'z'], relative=False, compound=False, effects=[]):
        """Create a new effect with configured properties"""
        if not compound and (len(keyframe_arc) != len(value_arc) or not self.is_axes_list(axis)):
            return
        if compound:
            if type(effects) is not list:
                return
            effect = self.fx_mapper.create_compound_fx(fx_name, effects)
        else:
            kf_arc = []
            for i in range(len(frame_arc)):
                kf_arc.append([frame_arc[i], value_arc[i]])
            effect = self.fx_mapper.create_fx(fx_name, attr, kf_arc)
        return effect

fx_mapper = fx_map.TextEffectsMap()
fx_creator = TextEffectsCreator(fx_mapper)

# ui

# TODO instantiate props
prop_names = [
    'fx_name',
    'attr',
    'kf_arc_frames',
    'kf_arc_values',
    'axis',
    'relative',
    'compound',
    'effects'
]

class EffectsCreatorProperties(bpy.types.PropertyGroup):
    # TODO names, incrementing appended index, overwriting
    fx_name = StringProperty(name="Name", description="Name for the new effect", default="My Effect")
    attr = EnumProperty(
        name = "Transform",
        description = "Attribute to set during effect",
        items = [
            ("location", "Location", "Move letters"),
            ("rotation_euler", "Rotation", "Rotate letters"),
            ("scale", "Scale", "Scale letters")
        ],
        default='location'
    )
    # TODO variable list length
    kf_arc_frames = FloatVectorProperty(name="Arc frames", size=4, description="Percent of total frames to advance between each keyframe", default=(0.2, 0.3, 0.25, 0.25))
    kf_arc_values = FloatVectorProperty(name="Arc values", size=4, description="Percent of total value to set at each keyframe", default=(0.0, 0.5, 1.1, 1.0))
    # TODO pull in known effect names
    effects = EnumProperty(name="Effects", description="List of effects to compound",
        items = [
            ("Display name", "FX_NAME", "Effect description"),
        ]
    )
    relative = BoolProperty(name="Relative", description="Transform each letter using relative (each letter to/from its point) or fixed (all letters to/from same point) values", default=False)
    compound = BoolProperty(name="Compound", description="Toggle whether effect applies multiple other effects", default=False)
    axis = EnumProperty(
        name = "Axis",
        description = "Transform axis for effect",
        items = [
            ("z", "Z", "Transform along the z axis"),
            ("y", "Y", "Transform along the y axis"),
            ("x", "X", "Transform along the x axis"),
            ("xyz", "XYZ", "Transform along all axes"),
        ],
        default='xyz'
    )

class EffectsCreator(bpy.types.Operator):
    bl_label = "Text FX Creator"
    bl_idname = "object.text_fx_creator"
    bl_description = "Create and configure text effect"

    def execute(self, ctx):
        prop_src = scene.text_fx_creator
        # NOTE can wrap create call to pass in only prop_src
        fx_creator.create(prop_src.fx_name, attr=prop_src.attr, frame_arc=prop_src.kf_arc_frames, value_arc=prop_src.kf_arc_values, relative=prop_src.relative, compound=prop_src.compound, effects=prop_src.effects)
        return {'FINISHED'}

class EffectsCreatorPanel(bpy.types.Panel):
    bl_label = "Text FX Creator"
    bl_idname = "object.text_fx_creator_panel"
    bl_category = "TextFX Creator"
    bl_context = "objectmode"
    bl_space_type = "VIEW_3D"
    bl_region_type = "TOOLS"

    def draw(self, ctx):
        scene = ctx.scene
        layout = self.layout
        prop_src = scene.text_fx_creator
        is_compound = getattr(scene, 'compound')
        for prop_name in prop_names:
            if not is_compound and prop_name == 'effect':
                continue
            elif is_compound and prop_name in ['kf_arc_frames', 'kf_arc_values', 'axis', 'relative']:
                continue
            else:
                layout.row().prop(prop_src, prop_name)
        layout.operator('text_fx_creator', text="Store effect")


from beanie import PydanticObjectId
from fastapi import APIRouter, HTTPException
from typing import List

from server.models.prod_review import ProdReview, UpdateReview

router = APIRouter()

@router.post("/", response_description="Review added ðŸ‘Œ")
async def add_product_review(review: ProdReview) -> dict:
    await review.create()
    return {"message": "Review added successfully"}

@router.get("/{id}", response_description="Review record retrieved")
async def get_review_record(id: PydanticObjectId) -> ProdReview:
    review = await ProdReview.get(id)
    return review

@router.get("/", response_description="Review records retrieved")
async def get_reviews() -> List[ProdReview]:
    reviews = await ProdReview.find_all().to_list()
    return reviews

@router.put("/{id}", response_description="Review record updated")
async def update_data(id: PydanticObjectId, request: UpdateReview):
    req = {key: value for key, value in request.dict().items() if value is not None}
    update_query = {
                    "$set": req
                }

    review = await ProdReview.get(id)
    if not review:
        raise HTTPException(
            status_code=404,
            detail="Record not found"
        )

    await review.update(update_query)
    return review

@router.delete("/{id}", response_description="Record deleted")
async def delete_student_data(id: PydanticObjectId) -> dict:
    record = await ProdReview.get(id)

    if not record:
        raise HTTPException(
            status_code=404,
            detail="Record not found!"
        )

    await record.delete()
    return {
        "message": "Record deleted successfully"
    }


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image

df = pd.read_csv('sport25.csv', header=None, sep=';')
df = df.transpose()
df[2] = df[2].astype(int)

lata = df[1].unique()
etykiety = np.arange(len(lata))
sporty = df[0].unique()
width = 0.20
colors = ['red', 'blue', 'green', 'orange']

for i in range(len(sporty)):
    sport = df[df[0] == sporty[i]]
    plt.bar(etykiety + i*width, sport[2], width=width, color=colors[i])
plt.xticks(etykiety, lata)
plt.show()


"""add comments_count field to post

Revision ID: 87dacfac1903
Revises: 31bed7ca951f
Create Date: 2018-07-02 15:29:16.208262

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '87dacfac1903'
down_revision = '31bed7ca951f'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('post', sa.Column('comments_count', sa.Integer(), nullable=False))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('post', 'comments_count')
    # ### end Alembic commands ###


import time
from sched import scheduler
import winsound as ws

alarm_time = input('Enter target time:')

def set_alarm(alarm_time,sound,message):
    s = scheduler(time.time,time.sleep)
    s.enterabs(alarm_time,1,print,argument=(message))
    s.enterabs(alarm_time,1,ws.PlaySound,argument=(sound,ws.SND_FILENAME))
    print(f'Alarm set for {time.asctime(time.localtime(alarm_time))}')
    s.run()


import numpy as np
import cv2

import gym
import torch
import torch.nn as nn

from models import Agent

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

def rgb2gray(rgb, norm=True):
    gray = np.dot(rgb[..., :], [0.299, 0.587, 0.114])
    if norm:
        # normalize
        gray = gray / 128. - 1.
    return gray

def preprocess_state(state):
    img_gray = rgb2gray(state)
    img_rs = cv2.resize(img_gray, dsize=(state_shape, state_shape), interpolation=cv2.INTER_CUBIC)
    stack = [img_rs] * img_stack

    return np.array(stack)

img_stack = 1
state_shape = 128

if __name__ == "__main__":
    agent = Agent()
    agent.load_param()
    env = gym.make('CarRacing-v0')
    state = env.reset()
    state = preprocess_state(state)

    # state = env.reset()
    score = 0

    for t in range(100000):
        env.render()
        action, _ = agent.select_action(state)
        state_, reward, done, die = env.step(action * np.array([2., 1., 1.]) + np.array([-1., 0., 0.]))
        score += reward
        state = preprocess_state(state_)
        if done or die:
            break

    print('Score: {:.2f}\t'.format(score))


#!/usr/bin/env python3

import logging
import math
import os
import random
import threading
import time
from datetime import datetime, timedelta

import LightSchedule
import PCA9685
import PCA9685_dummy
import Pid
import Settings
from WeatherType import WeatherType

# Initialise the PCA9685, if cant use a dummy (for testing on machine that is not pi)
try:
    pwm = PCA9685.PCA9685()
    # Alternatively specify a different address and/or bus:
    #pwm = Adafruit_PCA9685.PCA9685(address=0x41, busnum=2)
except:
    msg = "WARNING - unable to load PWM chip... no values will set!"
    logging.info(msg)
    print(msg)
    pwm = PCA9685_dummy.PCA9685()

# Configure min and max, initial weather pattern
LED_MAX = 4095  # Max Brightness
LED_MIN = 0     # Min Brightness (off)
RUN = True
WEATHER = WeatherType.normal

# Set frequency to 1000hz... LEDS.
pwm.set_pwm_freq(1000)
pwm.set_all(LED_MIN)
time.sleep(1)

try:
    i = 0
    j = 0
    while RUN:

        while j < LED_MAX:
            pwm.set_all(j)
            j += 1
        while j > LED_MIN:
            pwm.set_all(j)
            j -= 1
        time.sleep(1)

        for c in range(0,5):
            while i < LED_MAX:
                pwm.set_s(c, min(LED_MAX,i))
                i += 1
                #time.sleep(.5)
                print(i)
            time.sleep(1)
            while i > LED_MIN:
                pwm.set_s(c, i)
                i -= 1
                print(i)
            print("bottom" + str(i))
            time.sleep(1)
finally:
    logging.info(datetime.now().strftime('%H:%M:%S') + ' : finally Quit')
    RUN = False
    pwm.set_all(LED_MIN)


# Обращаемся к странице и парсим ее
# результаты складываем в файлы
#

import requests
import re
import json

def write_to_file(file, data, mode='w'):
    print('Writing to {}\n'.format(file))
    with open(file, mode) as newfile:
        newfile.write(data)

def read_file_data(file):
    print('Reading from {}\n'.format(file))
    try:
        opened_file = open(file)
        data = opened_file.read()
    finally:
        opened_file.close()

    return data

def get_service_data(url):
    result = requests.get(url)
    if result.status_code == 200:
        return result
    else:
        raise RuntimeError("Request from url = '{}' ended with code {}".format(url, result.status_code))

def get_web_data(links):
    r = requests.get(links)
    """ get data from WEB-page """
    print(r.status_code)
    print(r.headers)
    print(r.content)

def get_data_to_json(link):
    """get data from site and save to file (json format) """
    response = get_service_data(link)
    dict_for_json = {}
    for hdr, value in response.headers.items():
        dict_for_json[hdr] = value
        print('{}:{}\n'.format(hdr, value))

    print('JSON response saved in file site_response.json')
    write_to_file('site_response.json', json.dumps(dict_for_json, sort_keys=True, indent=4))

def get_links(links):
    """ get all links from WEB-page """
    response = requests.get(links)
    if response.status_code == 200:
        link_pattern = r'<a[^><]*href=[\'"]([^><\'"]*)[\'"][^><]*>'
        print('Links from {} saved in file site_links.txt'.format(links))
        write_to_file('site_links.txt', '')
        for link_string in re.findall(link_pattern, response.text):
            write_to_file('site_links.txt', link_string + '\n', mode = 'a')
            print(link_string)
    return

if __name__ == "__main__":
    link_1 = 'http://habrahabr.ru/'
    link_2 = 'https://jsonplaceholder.typicode.com/'

    print ('get web data from ', link_1)
    #get_web_data(link_1)
    print ('get all links from web-site & save to file')
    #get_links(link_1)
    print ('get data from web-site & save to file')
    #get_data_to_json(link_2)


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

import paddle
from paddle import nn
import paddle.nn.functional as F

from paddlex.paddleseg.cvlibs import manager

@manager.LOSSES.add_component
class DiceLoss(nn.Layer):
    """
    Implements the dice loss function.

    Args:
        ignore_index (int64): Specifies a target value that is ignored
            and does not contribute to the input gradient. Default ``255``.
    """

    def __init__(self, ignore_index=255, smooth=0.):
        super(DiceLoss, self).__init__()
        self.ignore_index = ignore_index
        self.eps = 1e-5
        self.smooth = smooth  # Laplace smoothing, https://github.com/pytorch/pytorch/issues/1249#issuecomment-337999895

    def forward(self, logits, labels):
        if len(labels.shape) != len(logits.shape):
            labels = paddle.unsqueeze(labels, 1)
        num_classes = logits.shape[1]

        labels = paddle.cast(labels, dtype='int32')
        single_label_lists = []
        for c in range(num_classes):
            single_label = paddle.cast((labels == c), dtype='int32')
            single_label = paddle.squeeze(single_label, axis=1)
            if c == self.ignore_index:
                single_label = paddle.zeros_like(single_label)
            single_label_lists.append(single_label)

        labels_one_hot = paddle.stack(tuple(single_label_lists), axis=1)
        logits = F.softmax(logits, axis=1)

        mask = (labels != self.ignore_index)
        logits = logits * mask

        labels_one_hot = paddle.cast(labels_one_hot, dtype='float32')
        dims = (0, ) + tuple(range(2, labels.ndimension()))
        intersection = paddle.sum(logits * labels_one_hot, dims)
        cardinality = paddle.sum(logits + labels_one_hot, dims)
        dice_loss = ((2. * intersection + self.smooth) /
                     (cardinality + self.eps + self.smooth)).mean()
        return 1 - dice_loss


# 2667 단지번호붙이기
# https://www.acmicpc.net/problem/2667
from collections import deque

dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

def bfs(i, j):
    global num
    q = deque()
    q.append((i, j))
    visited[i][j] = num

    # 같은 단지 수를 셀 변수
    cnt = 1
    while q:
        x, y = q.popleft()

        for d in range(4):
            mx = x + dx[d]
            my = y + dy[d]

            if 0 <= mx < N and 0 <= my < N and arr[mx][my] == 1 and not visited[mx][my]:
                visited[mx][my] = num
                q.append((mx, my))
                cnt += 1
    ans.append(cnt)
    num += 1

N = int(input())
arr = [list(map(int, list(input()))) for _ in range(N)]
visited = [[0] * N for _ in range(N)]

# 단지 번호 붙일 변수
num = 1
ans = []
for i in range(N):
    for j in range(N):
        if arr[i][j] == 1 and not visited[i][j]:
            bfs(i, j)

print(num - 1)
for i in sorted(ans):
    print(i)


import telebot
from telebot import types

bot = telebot.TeleBot("5532472004:AAH74-qByrleRayEA6a2LqQy0fyfzx_YSNU")

START_TEXT = """Hello! I am simple locker bot.\nYou can write /lock to lock me or /unlock to unlock me.\n
Where can i be helpful? If you share some resource with your friends (netflix account for example), you can manage\
 usage of this resource with help of me.\nIf you start using resource - write /lock and you friends must do the same.\
If resource is already locked by someone, there is no opportunity to lock it again until the user locked it enters /unlock command.
If user writes /lock, when resource is locked, I will write error message.\n
Common process:\n[UserA, UserB] - share netflix account\n1. UserA enters /lock (mutex is locked - means he/she uses netflix)\n2. UserB enters /lock (gets error because mutex is locked already)
3. UserA enters /unlock (mutex unlocked - he/she does not uses netflix)\n4. UserB enter /lock (mutex locked - UserB uses netflix account)"""

"""
* Contains chat locks.
* syntax: {chat_id: {"locker": True|False}}
"""
lockers = {}

def init_locker(message):
	"""
	* inits locker for chat if it is not inited.
	"""
	if message.chat.id not in lockers:
		lockers[message.chat.id] = {"locker": False}

@bot.message_handler(commands=["start", "help"])
def start_cmd_handler(message):
	init_locker(message)
	bot.send_message(message.chat.id, START_TEXT)

@bot.message_handler(commands=["lock"])
def start_cmd_handler(message):
	init_locker(message)
	if lockers[message.chat.id]["locker"] == True:
		bot.send_message(message.chat.id, "I can not lock mutex. It is already locked by someone! Try again later")
	else:
		lockers[message.chat.id]["locker"] = True
		bot.send_message(message.chat.id, "Mutex is locked!")

@bot.message_handler(commands=["unlock"])
def start_cmd_handler(message):
	init_locker(message)
	if lockers[message.chat.id]["locker"] == False:
		bot.send_message(message.chat.id, "Mutex is already unlocked!")
	else:
		lockers[message.chat.id]["locker"] = False
		bot.send_message(message.chat.id, "Mutex is unlocked now")

bot.polling()


## pip install selenium
## pip install selenium-stealth
## sudo apt install chromium-chromedriver

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time
from selenium_stealth import stealth

## init ##
service = Service(executable_path='/usr/bin/chromedriver')
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument("--single-process")
options.add_argument("--disable-gpu")
options.add_argument("--disable-dev-shm-usage")

## Define Function ##
def get_selenium(url) :
    browser = webdriver.Chrome(service=service, options=options)

    # Bypass Cloudflare Detection
    # https://stackoverflow.com/questions/68289474/selenium-headless-how-to-bypass-cloudflare-detection-using-selenium
    stealth(browser,
        languages=["en-US", "en"],
        vendor="Google Inc.",
        platform="Win64",
        webgl_vendor="Intel Inc.",
        renderer="Intel Iris OpenGL Engine",
        fix_hairline=True,
    )

    browser.get(url)

    result = browser.page_source

    browser.quit()

    return result


from PyQt5 import QtWidgets,QtGui
import sys
#from PIL import Image
def pencere():
    app = QtWidgets.QApplication(sys.argv)
    window=QtWidgets.QWidget()

    window .setWindowTitle("Ataberk")

    Buton=QtWidgets.QPushButton("Okey")
    Buton.setShortcut("Return")
    Buton2=QtWidgets.QPushButton("Cancel")
    h_box=QtWidgets.QHBoxLayout()
    h_box.addStretch()
    h_box.addWidget(Buton)
    h_box.addWidget(Buton2)
    v_box=QtWidgets.QVBoxLayout()
    v_box.addStretch()
    v_box.addLayout(h_box)
    window.setLayout(v_box)
    etiket1=QtWidgets.QLabel(window)
    etiket1.setText("BADEM IS STUPID...")
    etiket1.move(400,10)
    #image=Image.open("Badem.jpeg")
    #kırpılacak_alan=(100,0,700,1000)
    #image.crop(kırpılacak_alan).save("Badem2.jpeg")
    etiket2=QtWidgets.QLabel(window)
    etiket2.setPixmap(QtGui.QPixmap("Badem2.jpeg"))
    etiket2.move(300,100)
    window.setGeometry(100,100,500,500)
    window.show()
    sys.exit(app.exec())
pencere()


import re
from functools import reduce

f=open('ASTGenSuite.py','r')
o=open('result.txt','w')
list_lines=f.readlines()
start=300
number=0
tempexpect=''
for i in list_lines:
    if (i.find('def')!=-1 and i.find('self')!=-1 ):
        o.write(i)

    elif (i.find('expect')!=-1 and i.find('=')!=-1 ):
        pass
    elif (i.find('self.assertTrue')!=-1):
        number=int(re.findall(r'\d+',i)[-1])
        try:
            ftemp=open('./solutions/'+str(number)+'.txt','r')
            temptab=i[0:i.find('self.assertTrue')]
            o.write(temptab+"expect="+ reduce(lambda x,y:x+y,ftemp.readlines(),'')+'\n')
            ftemp.close()
            o.write(i)
        except FileNotFoundError:
            o.write(i)
            print('Không tìm thấy file solution số:'+str(number))
    else:
        o.write(i)

f.close()
o.close()

f=open('ASTGenSuite.py','w')
o=open('result.txt','r')

for i in o.readlines():
    f.write(i)
f.close()
o.close()


import pygame
from random import randint

#colors
BLACK = [  0,   0,   0]
WHITE = [255, 255, 255]
RED = [255, 0 , 0]
BLUE = [0, 0, 255]
YELLOW = [255, 255, 0]
GREEN = [ 0 , 255 , 0 ]
#values
size = [1000,644]
screen = pygame.display.set_mode(size)
done = False
clock = pygame.time.Clock()
player_x = 0
enemy_x = 800
hit_enemy = False
fireball_x = 275
draw_fireball_trigger = False
move_forward_trigger = False
move_backward_trigger = False
player_text ="100/100"
enemy_text = "125/125"
player_mana_text = "100/100"
enemy_mana_text = "100/100"
#game values
player_mana = 80
player_physical_damage = 20
player_magic_damage = randint(20,40)
player_magic_mana_usage = 30
player_ultimate_damage = randint(30,50)
player_ultimate_mana_usage = 50
game_over = False
enemy_p_damage = 15
atk_trigger = True

#draw
def draw_player(x,y):
    pygame.draw.polygon(screen,BLUE, [[ 100 + x, 0 + y ], [0 + x, 50 + y], [200 + x, 50 + y]], 0)
    pygame.draw.circle(screen,BLUE, [100 + x, 75 + y], 50)
    pygame.draw.rect(screen, BLUE, [50 + x, 120 + y, 100, 200])
    pygame.draw.rect(screen, BLUE, [50 + x, 320 + y, 30, 100])
    pygame.draw.rect(screen, BLUE, [120 + x, 320 + y, 30, 100])
    #arm
    pygame.draw.rect(screen, BLUE, [150 + x, 150 + y, 50, 50])
    #wand
    pygame.draw.polygon(screen,BLACK, [[ 255 + x, 55 + y ], [275 + x, 75 + y], [200 + x, 150+ y], [150 + x, 150 + y]], 0)
    pygame.draw.circle(screen,YELLOW, [275 + x, 50 + y], 25)

def draw_enemy(a,b):
    pygame.draw.polygon(screen,BLACK, [[ 10 + a, 150 + b ], [20 + a, 20 + b], [30 + a, 150 + b]], 0)
    pygame.draw.circle(screen,RED, [100 + a, 75 + b], 50)
    pygame.draw.rect(screen, RED, [50 + a, 120 + b, 100, 200])
    pygame.draw.rect(screen, RED, [50 + a, 320 + b, 30, 100])
    pygame.draw.rect(screen, RED, [120 + a, 320 + b, 30, 100])
    pygame.draw.rect(screen, RED, [0 + a, 150 + b, 50, 50])
    pygame.draw.rect(screen, BLACK, [10 + a, 200 + b, 20, 20])

def draw_fireball(x):
    pygame.draw.circle(screen,RED, [x, 250],int((fireball_x - 275)/3.0))

#font
def draw_hp_font(player_hp,enemy_hp):
    player_text = str(player_hp) + "/100"
    myfont = pygame.font.SysFont("monospace", 20, True)
    label = myfont.render(player_text, 1, RED)
    screen.blit(label, (5, 50))

    enemy_text = str(enemy_hp) + "/125"
    label2 = myfont.render(enemy_text, 1, RED)
    screen.blit(label2, (840, 50))

    label3 = myfont.render(player_mana_text, 1, BLUE)
    screen.blit(label3, (5, 150))

    label4 = myfont.render(enemy_mana_text, 1, BLUE)
    screen.blit(label4, (840, 150))

def draw_game_msg_font(damage,atk_type):
    myfont = pygame.font.SysFont("monospace", 20, True)
    message = "Enemy dealt " + str(damage) + " damage to you " + atk_type
    label5 = myfont.render(message, 1, RED)
    screen.blit(label5, (300, 50))


from django.forms import ModelForm, fields
from .models import *

class CreateMealsForm(ModelForm):
    class Meta:
        model = Meal
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request')
        # user_chef = User.objects.filter(is_chef=True)
        super(CreateMealsForm, self).__init__(*args, **kwargs)
        self.fields['user_chef'].queryset = User.objects.filter(username=self.request.user.username)
        self.fields['user_chef'].empty_label = None


import pandas as pd
base = pd.read_csv('credit-data.csv')
base.describe()

""" Localiza valores abaixo de 0 """

base.loc[base['age'] < 0 ]

""" Apagar a Coluna"""

base.drop('age', 1, inplace=True)
"""         |     |       |
            |     |       └─ Não Salvar em nenhuma variável o retorn
            |     └─ Vamos apagar 1 coluna
            └─ Qual coluna iremos apagar
"""

""" Apagar os registros com problema """

base.drop(base[base.age < 0].index, inplace = True)

""" Preencher os valores manualmente com a média"""

base['age'].mean()
base['age'][base.age > 0].mean()
base.loc[base.age < 0, 'age'] = 40.92

pd.isnull(base['age'])
base.loc[pd.isnull(base['age'])]
previsores = base.iloc[:, 1:4].values
classe = base.iloc[:, 4].values

from sklearn.impute import SimpleImputer
imputer = SimpleImputer()
imputer = imputer.fit(previsores[:, 0:3])
previsores[:, 0:3] = imputer.transform(previsores[:, 0:3])


from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import UnexpectedAlertPresentException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException, UnexpectedAlertPresentException
from selenium import webdriver
import pandas as pd
import os
from os import listdir
import time
from pynput.keyboard import Controller, Key
# from lib import create_folder, downloadImage
options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_argument('--start-maximized')

def downloadImage(url:str, path:str):
    try:
        # url = 'https://image-v4.sinsang.market/?f=https://image-cache.sinsang.market/images/25232/92085305/167655035100655297_1462791657.jpg&w=1500&h=2000'
        # url = 'https://www.searchenginejournal.com/wp-content/uploads/2022/06/image-search-1600-x-840-px-62c6dc4ff1eee-sej-1280x720.png'

        headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'  # A common user agent
                }
        response = requests.get(url=url, headers=headers)
        if response.status_code == 200:
            with open(f'{path}', 'wb') as f:
                f.write(response.content)
            print("Image downloaded successfully.")
        else:
            print("Failed to download image. Status code:", response.status_code)

        # urlretrieve(url, './Products/test.png')

        # image_response = requests.get(url, stream=True)
        # with open('./Products/test.jpg', 'wb') as out_file:
        #     shutil.copyfileobj(image_response.raw, out_file)
        # del image_response
        # print(image_response.status_code)
        # if image_response.status_code == 200:
        #     with  open('./Products/test2.jpg', 'wb') as out_file:
        #         out_file.write(image_response.content)
        #     return HTTPException(
        #      status_code=status.HTTP_200_OK
        #     )

    except Exception as err:
        print(f'Error {err}')

def create_folder(directory):
    try:
        if not os.path.exists(directory):
            os.makedirs(directory)

    except OSError:
        print(f"Error: Creating directory {directory}")

def watermark(images):
   print('test')

def images():

   global driver
   driver = webdriver.Chrome(service=Service(), options=options)
   folder_path = f'{os.getcwd()}/../Products'

   image_list = listdir(folder_path)[:2]
   create_folder('./Watermark')
   for image in image_list:
      driver.get('https://www.watermarkremover.io/upload')
      driver.find_element(By.ID, 'uploadImage').send_keys(f'/Users/jackson/Desktop/elether/sokodress_scraping/Products/{image}')
      time.sleep(20)

      # image_src = driver.find_element(By.CLASS_NAME, 'ImageMagnifier__StyledPixelBinImage-sc-kcdk33-3 kBnRAJ').get_attribute('src')
      # print(f'Image src : {image_src}')
      # image_path = './Watermark/' + image
      # downloadImage(image_src, image_path)

   time.sleep(1999)

   folder_path = f'{os.getcwd()}/../../productImages'
   image_list = listdir(folder_path)[:10]

   for image in image_list:
      print(image)

      # urlretrieve(f'https://sokodress.s3.ap-northeast-2.amazonaws.com/Products/{image}', f'./Products/{image}')

images()


import asyncio
from typing import Any, Dict, List, Optional, TYPE_CHECKING
import random

from bot.сhain_responsibility.receivers.mixins import KeyboardMixin, MenuMixins
from bot.сhain_responsibility.receivers.receivers import ButtonReceiverAbstract
from bot_long_poll.dcs import Update
from vk_api.dcs import Message

if TYPE_CHECKING:
    from bot.state.state import State
    from store.quiz.models import QuestionModel
    from store.quiz.models import AnswerModel
    from store.game.models import GameModel
    from store.player.models import PlayerModel
    from store.player.models import Score

class GuessLetterCommandButtonReceiver(MenuMixins, KeyboardMixin, ButtonReceiverAbstract):
    def __init__(self, update: Update, state: "State"):
        super().__init__(update, state)
        self.answer: Optional["AnswerModel"] = None
        self.letter: str = ""
        self.result = ""
        self.started_game: Optional["GameModel"] = None
        self.question: Optional["QuestionModel"] = None
        self.score: Optional["Score"] = None
        self.word: List[Optional[str]] = []
        self.correct_answer_score: int = 0

    def set_buttons(self):
        if self.result == self.answer:
            self.buttons = self.get_menu()
        elif self.letter in self.answer.title:
            self.buttons = self.get_keyboard()

    async def execute(self) -> Optional[Dict[str, Any]]:
        self.started_game = await self.game_accessor.get_started_game_by_player(self.update)
        self.score = await self.player_accessor.get_score(self.started_game.id, self.update.from_id)
        self.who_next = self.started_game.who_next
        if self.update.from_id != self.who_next[0]:
            self.message = "Не Ваша очередь"
            return await self.send_message(self.update.from_id)
        self.question: "QuestionModel" = self.started_game.question
        self.letter: str = self.update.text
        self.answer: "AnswerModel" = self.question.answer
        if self.started_game:
            if self.letter in self.started_game.word:
                await self.send_unsuccessful_message()
            else:
                self.word = [letter for letter in self.started_game.word]
                indexes = self.find_indexes()
                if indexes:
                    self.refresh_result(indexes)
                    if self.result == self.answer.title:
                        await self.stop_game_player_won()
                    else:
                        await self.send_successful_message()
                else:
                    await self.send_unsuccessful_message()
                    await self.game_accessor.update_game_instance(self.started_game)

    async def stop_game_player_won(self):
        self.started_game.state = "Stoped"
        await asyncio.gather(
            self.send_winner_message(),
            self.game_accessor.update_game_instance(self.started_game))

    async def send_successful_message(self):
        self.set_buttons()
        self.correct_answer_score = random.randint(1, 100)
        self.score.score += self.correct_answer_score
        msgs = self.get_successful_messages()
        await asyncio.gather(
            self.player_accessor.update_score_instanse(self.score),
            self.send_messages(msgs),
            self.game_accessor.update_game_instance(self.started_game))

    def refresh_result(self, indexes):
        for index in indexes:
            self.word[index] = self.letter
        self.result = "".join(self.word)
        self.started_game.word = self.result

    def get_player(self, vk_id) -> "PlayerModel":
        for player in self.started_game.players:
            if player.vk_id == vk_id:
                return player

    async def send_winner_message(self):
        player = self.get_player(self.update.from_id)
        text = f"Победу одержал(а): {player.first_name} {player.last_name}\n Ответ: {self.answer.title}"
        msgs = [Message(vk_api, text, self.get_menu()) for vk_api in self.who_next]
        self.started_game.who_next = []
        await self.send_messages(msgs)

    def get_successful_messages(self):
        text = f"Буква {self.letter} в слове присутствует.\
                \nЗа правильный ответ начислено баллов: {self.correct_answer_score}\
                \nВсего баллов: {self.score.score}\
                \nСлово: {self.started_game.word}\
                \nВаш следующий ход."
        player = self.get_player(self.update.from_id)
        text2 = f"Текущий ход у игрока: {player.first_name} {player.last_name}\
                 Игрок назавал букву {self.letter}.\
                 \nСлово: {self.started_game.word}"
        msg = Message(self.update.from_id, text, self.buttons)
        msgs = [Message(vk_id, text2, "{}") for vk_id in self.who_next[1:]]
        msgs.append(msg)
        return msgs

    async def send_unsuccessful_message(self):
        self.change_player_queue()
        next_player_vk_id = self.who_next[0]
        next_player = self.get_player(next_player_vk_id)
        text = f"Неверный ответ. Ход переходит к игроку: \
{next_player.first_name} {next_player.last_name}."
        text2 = f"Ваш ход. \nСлово: {self.started_game.word}"
        msg = Message(self.update.from_id, text, "{}")
        msg2 = Message(self.who_next[0], text2, self.get_keyboard())
        await self.send_messages([msg, msg2])

    def change_player_queue(self):
        current_player = self.who_next.pop(0)
        self.who_next.append(current_player)

    def find_indexes(self):
        indexes = []
        index = self.answer.title.find(self.letter)
        while index >= 0:
            indexes.append(index)
            index = self.answer.title.find(self.letter, index+1)
        return indexes

    async def run(self):
        await self.execute()


#!/usr/local/bin/python3

import json

DEFENSE = ["anticapitalism", "chasiness", "omniscience", "tenaciousness", "watchfulness"];
PITCHING = ["ruthlessness", "overpowerment", "unthwackability", "shakespearianism", "suppression", "coldness"];
BATTING = ["patheticism", "moxie", "divinity", "musclitude", "thwackability", "buoyancy", "martyrdom"];
BASE_RUNNING = ["base_thirst", "laserlikeness", "continuation", "ground_friction", "indulgence"];

HEADERS = ["name", "team"];

## Primary files
BATTING_FILE = open("../data/s14-batters.csv", "a")
PITCHING_FILE = open("../data/s14-pitching.csv", "a")
DEFENSE_FILE = open("../data/s14-defense.csv", "a")
BASE_RUNNING_FILE = open("../data/s14-base-running.csv", "a")
OFFENSE_FILE = open("../data/s14-offense.csv", "a")

with open('../data/players-20200314.json') as f:
  players = json.load(f)

prefix = "name,team,";
defense = "anticapitalism,chasiness,omniscience,tenaciousness,watchfulness";
pitching = "ruthlessness,overpowerment,unthwackability,shakespearianism,suppression,coldness";
batting = "patheticism,moxie,divinity,musclitude,thwackability,buoyancy,martyrdom";
base_running = "base_thirst,laserlikeness,continuation,ground_friction,indulgence";
offense = batting + "," + base_running;
BATTING_FILE.write(prefix + batting + "\n")
PITCHING_FILE.write(prefix + pitching + "\n")
DEFENSE_FILE.write(prefix + defense + "\n")
BASE_RUNNING_FILE.write(prefix + base_running + "\n")
OFFENSE_FILE.write(prefix + offense + "\n")

for player in players:
    team = player["team"];
    name = player["player_name"];
    if team is None or name is None:
        continue;

    #print(f"player={name}\tteam={team}");
    #print("\tBATTING");
    cur_prefix = name + "," + team;
    cur_batting = "";
    cur_pitching = "";
    cur_defense = "";
    cur_base_running = "";
    cur_offense = "";
    for x in BATTING:
        cur_batting = cur_batting + "," + player[x];
        #print(f"\t\t{x} = {player[x]}");
    for x in PITCHING:
        cur_pitching = cur_pitching + "," + player[x];
        #print(f"\t\t{x} = {player[x]}");
    for x in DEFENSE:
        cur_defense = cur_defense + "," + player[x];
        #print(f"\t\t{x} = {player[x]}");
    for x in BASE_RUNNING:
        cur_base_running = cur_base_running + "," + player[x];
        #print(f"\t\t{x} = {player[x]}");
    cur_offense = cur_batting + cur_base_running;

    BATTING_FILE.write(cur_prefix + cur_batting + "\n")
    PITCHING_FILE.write(cur_prefix + cur_pitching + "\n")
    DEFENSE_FILE.write(cur_prefix + cur_defense + "\n")
    BASE_RUNNING_FILE.write(cur_prefix + cur_base_running + "\n")
    OFFENSE_FILE.write(cur_prefix + cur_offense + "\n")


#!/usr/bin/env python

# Mabel Zhang
# 9 Sep 2015
#
#
#

import numpy as np

from sklearn.neighbors import KernelDensity  # For KDE

# For debugging KDE
import matplotlib.pyplot as plt

def main ():

    '''
    # edgesdd is Python list[] of 3 elements. Each element is a numpy array
    #   with number of elements equal to the number of bins in that dimension
    #   + 1. `.` for b bins, there are b+1 edges.
    # See ret vals of this fn using the 3-line ex on numpy histogramdd() API page.
    histdd, edgesdd = np.histogramdd (data, bins=bins, range=bin_range,
      normed=False)

    #####
    # Find bin centers of histogram, so can feed these bin centers as data
    #   to KDE.
    #####

    nDims = len (edgesdd)

    # You don't need histogram centers. You shouldn't use them. Use bin_range.
    # Wait no, edges ARE already incorporating bin_range, because you pass
    #   bin_range to histogramdd()! So deifnitely need this.
    centersdd = []
    centersdd.append (np.zeros ([bins[0], ]))
    centersdd.append (np.zeros ([bins[1], ]))
    centersdd.append (np.zeros ([bins[2], ]))

    # Get histogram centers from edges. n+1 edges means there are n centers.
    #   Copied from plot_hist_dd.py.
    for i in range (0, nDims):
      centersdd[i][:] = ( \
        edgesdd[i][0:len(edgesdd[i])-1] + edgesdd[i][1:len(edgesdd[i])]) * 0.5

    #####
    # Construct the histogram into data to feed to KDE
    #####

    # Make a (n x d) matrix out of the histogram
    hist_as_data = []

    # For each bin in UNNORMALIZED histogram, append its counts
    # bins[0]
    for x in range (0, len (centersdd [0])):
      # Bin center
      bincx = centersdd [0] [x]

      # bins[1]
      for y in range (0, len (centersdd [1])):
        bincy = centersdd [1] [y]

        # bins[2]
        for z in range (0, len (centersdd [2])):
          bincz = centersdd [2] [z]

          if histdd [x, y, z] > 0:

            # Be careful when use [[]] * n, the inner lists are instances, not
            #   copies. So if you change one, it will change all the others!
            # Make sure histdd is UNNORMALIZED. Here is why, we are copying the
            #   list a (bin count) number of times. So bin count cannot be
            #   floating points!
            hist_as_data.extend ([[bincx, bincy, bincz]] * histdd [x, y, z])
    '''

    histdd = np.array ([[[2, 0], [0, 0]], [[0, 0], [0, 1]]])

    bins = [2, 2, 2]
    hist_as_data = np.array ([[0, 0, 0], [0, 0, 0], [1, 1, 1], [1, 1, 1], [1, 1, 1]])

    #####
    # Fit KDE to histogram
    #####

    # TODO: try different bandwidth variable, see if makes big difference

    #print (np.shape (hist_as_data))
    #print (hist_as_data)

    # Calculate KDE smoothed histograms
    #   Ref: http://scikit-learn.org/stable/auto_examples/neighbors/plot_kde_1d.html#example-neighbors-plot-kde-1d-py
    kde = KernelDensity (kernel='epanechnikov').fit (hist_as_data)

    #####
    # Generate some fine-grained x-values, to request KDE
    #####

    # Increase this increase factor to get more smooth
    factor_detail = 1.0

    nbins_smoothed = np.array (bins) * factor_detail
    nbins_total = int (np.product (nbins_smoothed))

    print (bins)
    print ('Number of bins in KDE smoothed histogram: %d' % nbins_total)

    # Must be 0 min, step 1, `.` I'm using unravel_index()! This makes it easier
    #   to loop through the 3 dimensions and produce a n x 3 array. If manually
    #   do it, will need 3 nested for-loops. Not as clean and prone to mistakes.
    request_X = np.unravel_index (np.arange (0, nbins_total, 1),
      nbins_smoothed)
    request_X = np.asarray (request_X).T

    # Then make the "smoothed bin centers" floating point
    request_X = request_X / float (factor_detail)

    #####
    # Evaluated fitted KDE on the requested indices, to give us a smoothed
    #   histogram.
    #####

    # 1D array. Number of elements is number of bins in 3D histogram. So like
    #   8 * 8 * 9. This is also the number of rows in your request_X.
    density = kde.score_samples (request_X)

    # TODO why? Did I not construct hist_as_data correctly?
    # Flip signs to positive. For some reason KDE always returns negative
    density = -density

    #print ('%d inf elements' % np.sum (np.isinf (density)))

    # If negative infinity, just set to 0
    # Ref np.where: http://stackoverflow.com/questions/4588628/find-indices-of-elements-equal-to-zero-from-numpy-array
    inf_idx = np.where (np.isinf (density))
    if inf_idx:
      density [inf_idx] = 0

    #print ('%d inf elements after setting to zero' % np.sum (np.isinf (density)))
    #print ('%d zero elements' % np.size (np.where (density == 0)))

    print ('%d non-zero elements' % np.size (np.where (density != 0)))

    # Linearize the matrix, write to file
    density_linear = np.reshape (density, [density.size, ]);
    #file_writer.writerow (density_linear.tolist ())

    #####
    # Just plot 3D histogram in 1D anyway, the whole thing, to see if smoothed
    #   resembles original, even though the plot won't look like the actual
    #   histogram, `.` plot is linearized.
    #####

    # Just use linear index
    hist_linear = np.reshape (histdd, [histdd.size, ]);
    plt.plot (range (0, np.product (bins)), hist_linear)
    plt.show ()

    plt.plot (range (0, nbins_total), density)
    plt.show ()

if __name__ == '__main__':
  main ()


import random as rd
import numpy as np
import matplotlib as mlp
import matplotlib.pyplot as plt
import matplotlib.patches as patch
import time
start_time = time.time()
from math import pi

inside = 0
outside = 0
coords = []
# ----Plotting the circle and the rectangle-------
x = np.linspace(0, 1, 200)
y = np.sqrt((0.5 ** 2) - ((x - 0.5) ** 2)) + 0.5  # Upper half of circle
neg_y = -np.sqrt(0.25 - ((x - 0.5) ** 2)) + 0.5  # Lower half of circle
fig, ax = plt.subplots()
ax.plot(x, y, 'blue')
ax.plot(x, neg_y, 'blue')
rect = patch.Rectangle((0, 0), 1, 1, linewidth=1, fill=False)
ax.add_patch(rect)
ax.axis('equal')
ax.axis('off')
# ---------Loop that creates each frame for animation--------
N=100
for i in range(1, N):
    x_rand = rd.random()  # Random x coordinate
    y_rand = rd.random()  # Random y coordinate
    if (x_rand - 0.5) ** 2 + (y_rand - 0.5) ** 2 < (1 / 4):  # If the (x,y) coordinate falls inside the circle
        ax.plot(x_rand, y_rand, 'go', markersize=1)
        inside += 1
    else:
        ax.plot(x_rand, y_rand, 'ko', markersize=1)
        outside += 1
    pi_mc = 4 * (inside / (inside + outside))
    ax.set_title("$\pi$ = " + str(format(pi_mc ,'.7f'))+" "+str(i))  # Show 7 decimal places of Pi

    if i < 10:
        plt.savefig("000000" + str(i))
    if i >= 10 and i <100:
        plt.savefig("00000" + str(i))
    if i >= 100 and i < 1000:
        plt.savefig("0000"+ str(i))
    if i >= 1000 and i < 10000:
        plt.savefig("000"+ str(i))
    if i >= 10000 and i < 100000:
        plt.savefig("00"+ str(i))

    print(i)

import cv2
import numpy as np
import glob

img_array = []
for filename in sorted(glob.glob('C:/Users/jack7/Documents/pi/*.png')):
    img = cv2.imread(filename)
    height, width, layers = img.shape
    size = (width,height)
    img_array.append(img)

out = cv2.VideoWriter('project.mp4',cv2.VideoWriter_fourcc(*'DIVX'), 30, size)

for i in range(len(img_array)):
    out.write(img_array[i])
out.release()

#delete pngs at end

print(time.time() - start_time)

#add subplot for error


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

import os
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.interpolate as interpolate
from skimage import restoration
from PIL import Image
from pylab import *
from sklearn.mixture import BayesianGaussianMixture
import time
import matplotlib as mpl
from scipy import linalg
import itertools

dir = 'Testoversize'                # data directory
multithreshold = 0.25
PSFsize = 200
deconiter = 200

def COGcut(inputdata, cutratio):
    COGdata = inputdata.copy()
    COGx = 0
    COGy = 0
    tot = 0
    COGdata /= np.nanmax(COGdata)
    ver, hor = COGdata.shape
    for j in range(ver):
        for k in range(hor):
            if np.isnan(COGdata[j,k]) == False and COGdata[j,k] > cutratio:
                COGx += COGdata[j,k] * k
                COGy += COGdata[j,k] * j
                tot += COGdata[j,k]
    COGx /= tot
    COGy /= tot
    return COGx, COGy

def plot_results(X, Y_, means, covariances, index, title):
    #splot = plt.subplot(2, 1, 1 + index)
    for i, (mean, covar, color) in enumerate(zip(
            means, covariances, color_iter)):
        #v, w = linalg.eigh(covar)
        #print(v, w)
        v = [covar, covar]
        w = [[1,0],[0,1]]
        v = 2. * np.sqrt(2.) * np.sqrt(v)
        u = w[0] / linalg.norm(w[0])
        # as the DP will not use every component it has access to
        # unless it needs it, we shouldn't plot the redundant
        # components.
        if not np.any(Y_ == i):
            continue
        plt.scatter(X[Y_ == i, 0], X[Y_ == i, 1], .8, color=color,alpha=0.1)

    #plt.xlim(-9., 5.)
    #plt.ylim(-3., 6.)
    #plt.xticks(())
    #plt.yticks(())
    plt.title(title)

# PandaX parameters & initialization
dataInProcess = []
dataoversize = []
datafailed = []
dataasymmetric = []

grid_x, grid_y = np.mgrid[-600:600:1, -600:600:1]
grid_x_mirror, grid_y_mirror = np.mgrid[200:1000:1, -400:400:1]

color_iter = itertools.cycle(['navy', 'c', 'cornflowerblue', 'gold',
                              'darkorange'])

# input data
for file in os.listdir(path = dir):
    dataInProcess.append(file)
for i in range(len(dataInProcess)):
#for i in range(1,2):
    processstarttime = time.time()
    print(dataInProcess[i])
    euler = np.array([[1,0],[0,1]])
    eventtype = ''

    data = pd.read_table(dir + '/' + dataInProcess[i], header = None, names = ['PMTID','x','y','Intensity'])
    zdata = data.iloc[-2,0]
    xCOG = eval(data.iloc[-8,0].split(" = ")[1])
    yCOG = eval(data.iloc[-7,0].split(" = ")[1])
    xTMs = eval(data.iloc[-6,0].split(" = ")[1])
    yTMs = eval(data.iloc[-5,0].split(" = ")[1])
    xPAF = eval(data.iloc[-4,0].split(" = ")[1])
    yPAF = eval(data.iloc[-3,0].split(" = ")[1])
    data = data.dropna()            # Last 8 rows are not raw data, and contain NaNs

    x = data['x'].values.tolist()
    y = data['y'].values.tolist()
    coord = data.loc[:,['x','y']].values.tolist()
    intens = data['Intensity'].values.tolist()

# interpolation
    interp = interpolate.griddata(coord, intens, (grid_x, grid_y), method='cubic')
    interp = interp.T

# preprocess
    preprocess = interp.copy()
    preprocess = np.where(np.isnan(preprocess), 1e-9, preprocess)
    preprocess = np.where(preprocess <= 0, 1e-9, preprocess)        # clear out nan/0/negatives

# estimate approximate position: COG/max
    intensmaxloc = np.nanargmax(preprocess)
    height, width = preprocess.shape
    maxlocy = int(intensmaxloc / height) - 600
    maxlocx = intensmaxloc % height - 600
    #print("max:", maxlocx, maxlocy)
    if maxlocx ** 2 + maxlocy ** 2 < 550 ** 2:
        COGdataslice = preprocess[max(0, maxlocy + 600 - 300) : min(1200, maxlocy + 600 + 300 + 1), max(0, maxlocx + 600 - 300) : min(1200, maxlocx + 600 + 300 + 1)]
        appx, appy = COGcut(COGdataslice, 0.1)

        appx = int(appx)
        appy = int(appy)
        appy += max(0, maxlocy + 600 - 300)
        appy -= 600
        appx += max(0, maxlocx + 600 - 300)
        appx -= 600
        print("approximate:", appx, appy)
        if appx ** 2 + appy ** 2 < 450 ** 2:
            eventtype = 'central'
        else:
            eventtype = 'margin'
    else:
        appx = maxlocx
        appy = maxlocy
        eventtype = 'oversized'
        dataoversize.append(dataInProcess[i])
        '''
        print("Event in " + dataInProcess[i] + " seemed to occur somewhere between the center of the farthest PMT and the wall. No algorithm found valid for this type of event yet. You can refer to x = " + str(appx) +", y = " + str(appy) + ", however, for a single oversized event, by 3 cm radial error\n")

        #visualization skipped
        processendtime = time.time()
        print(str(i + 1) + " finished! elapsed time: " + str(processendtime - processstarttime))
        continue
    '''
    print(eventtype)

    if eventtype != 'central':
        angle = math.degrees(math.atan2(appy, appx))

        rotated = interp.copy()
        #mirror
        im = Image.fromarray(rotated)
        im = im.rotate(angle)
        im = im.crop((800,200,1200,1000))
        im_flipped = im.transpose(Image.FLIP_LEFT_RIGHT)
        im = array(im)
        im_flipped = array(im_flipped)

        rotated = np.append(im, im_flipped, axis = 1)
        coord_mirror = []
        intens_mirror = []
        for j in range(-400,400):
            for k in range(200,1000):
                if np.isnan(rotated[j + 400,k - 200]) == False and rotated[j + 400,k - 200] > 10:
                    coord_mirror.append([j,k])
                    intens_mirror.append(rotated[j + 400,k - 200])
        #interpolation
        interp_mirror = interpolate.griddata(coord_mirror, intens_mirror, (grid_y_mirror, grid_x_mirror), method='linear')
        interp_mirror = interp_mirror.T

        preprocess = interp_mirror.copy()
        preprocess = np.where(np.isnan(preprocess), 1e-9, preprocess)
        preprocess = np.where(preprocess <= 0, 1e-9, preprocess)

# clustering on intensity image, estimates event center location
    dots = np.empty([0,2])
    pointweight = preprocess / np.max(preprocess) * 2

    if eventtype == 'central':
        for j in range(max(0, appy + 600 - 200), min(1200, appy + 600 + 200 + 1)):
            for k in range(max(0, appx + 600 - 200), min(1200, appx + 600 + 200 + 1)):
                if pointweight[j,k] >= 1:
                    dots = np.append(dots, np.tile(np.array([k - 600, j - 600]), (int(pointweight[j,k]), 1)), axis = 0)
        #print(dots[-1:])

        eventnum = 2
        weights = 0
        while eventnum > 0 and np.any(weights < multithreshold):
            dpgmm = BayesianGaussianMixture(n_components=eventnum, covariance_type='spherical', max_iter = 10000,weight_concentration_prior_type='dirichlet_distribution', weight_concentration_prior=1e-3).fit(dots)
            weights = dpgmm.weights_
            print(weights)
            eventnum -= 1

        eventnum += 1
        means = np.swapaxes(dpgmm.means_, 0, 1)

    else:
        for j in range(800):
            for k in range(800):
                if pointweight[j,k] >= 1:
                    dots = np.append(dots, np.tile(np.array([k + 200, j - 400]), (int(pointweight[j,k]), 1)), axis = 0)
            #print(dots[-1:])

        eventnum = 2
        weights = 0
        while eventnum > 0 and np.any(weights < multithreshold / 2):
            dpgmm = BayesianGaussianMixture(n_components=eventnum*2, covariance_type='spherical', n_init=10, max_iter = 10000,weight_concentration_prior_type='dirichlet_distribution', weight_concentration_prior=1e-3).fit(dots)
            weights = dpgmm.weights_
            print(weights)
            eventnum -= 1

        eventnum += 1
        means = dpgmm.means_

        '''
        bgm = BayesianGaussianMixture(n_components=eventnum*2, random_state=0, covariance_type='spherical', max_iter = 2000).fit(dots)
        #bgm = BayesianGaussianMixture(n_components=eventnum*2, random_state=0, max_iter = 2000).fit(dots)
        means = bgm.means_
        weights = bgm.weights_
        #print(means, weights)
        '''
        dellist = []
        for j in range(len(weights)):
            if means[j, 0] ** 2 + means[j, 1] ** 2 > 600 ** 2:
                dellist.append(j)
        means = np.delete(means, dellist, axis = 0)
        weights = np.delete(weights, dellist)
        weights *= 2
        means = np.swapaxes(means, 0, 1)
        meansinmirror = means.copy()

        #rotate to original frame
        angle = math.radians(angle)
        euler = np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])
        means = np.dot(euler, means)

    resultsangle = 0
    if len(weights) != eventnum:
        print("===It seems that a margin event was clustered with asymmetric result.===")

    #bgm = BayesianGaussianMixture(n_components=2, random_state=0, covariance_type='spherical', max_iter = 2000).fit(dots)

# visualization
    #plt.gcf().set_size_inches(6, 12)
    fig = plt.figure(figsize=(16,5.5),dpi=300)
    ax2 = fig.add_subplot(1,3,2)

    plt.subplot(1,3,1)
    plt.imshow(interp, extent=(-600, 600, -600, 600), origin = 'lower', cmap = 'Blues')
    plt.colorbar()

    plt.scatter(x, y, s = 20, alpha = 0.8, c = [intens], cmap = 'gist_heat', label = 'Raw PMT intensity')

    plt.legend(loc = "lower left")
    plt.xlabel('x (mm)')
    plt.ylabel('y (mm)')
    plt.title('Interpolated Intensity')

    plt.text(x = 0, y = -800, s = zdata, ha = 'center')

    plt.subplot(1,3,2)
    textstr = 'BGMMweight:\n' + str(dpgmm.weights_)
    plt.text(0.05,0.9,textstr,size=10,transform=ax2.transAxes,bbox=dict(boxstyle="round",alpha=0.6,ec=(0.5,0.5,1.),fc=(0.8,0.8,1.)))

    if eventtype == 'central':
        plot_results(dots, dpgmm.predict(dots), dpgmm.means_, dpgmm.covariances_, 1,'Bayesian Gaussian Mixture with a Dirichlet process prior')
        plt.imshow(interp[appy + 600 - 200 : appy + 600 + 200, appx + 600 - 200 : appx + 600 + 200], extent=(appx - 200, appx + 200, appy - 200, appy + 200), origin = 'lower', cmap = 'Blues' )
    else:
        plot_results(dots, dpgmm.predict(dots), dpgmm.means_, dpgmm.covariances_, 1,'Bayesian Gaussian Mixture with a Dirichlet process prior')
        plt.imshow(interp_mirror, extent=(200, 1000, -400, 400), origin = 'lower', cmap = 'Blues' )

    # comparison with other algorithms
    ud = [appy + 600 - 200 , appy + 600 + 200]
    lr = [appx + 600 - 200 , appx + 600 + 200]
    if ud[0] < 0:
        ud = [0, 400]
    if ud[1] > 1200:
        ud = [800, 1200]
    if lr[0] < 0:
        lr = [0, 400]
    if lr[1] > 1200:
        lr = [800, 1200]

    plt.subplot(1,3,3)
    plt.scatter(x, y, s = 400, alpha = 0.8, c = [intens], cmap = 'gist_heat')
    plt.scatter(x = xCOG, y = yCOG, s = 150, alpha = 0.6, edgecolors = 'black', marker = '^', label = 'COG')
    plt.scatter(x = xTMs, y = yTMs, s = 150, alpha = 0.6, edgecolors = 'black', marker = 'o', label = 'TMs')
    plt.scatter(x = xPAF, y = yPAF, s = 150, alpha = 0.6, edgecolors = 'black', marker = 's', label = 'PAF')
    plt.scatter(means[0], means[1], s = 300 * weights, alpha = 0.6, edgecolors = 'orange', marker = 'X', label = 'BGMM')
    #plt.scatter(x = RLCOGx, y = RLCOGy, s = 150, alpha = 0.6, edgecolors = 'black', marker = '*', label = 'RL')
    plt.legend(loc = "lower left")
    plt.xlabel('x (mm)')
    plt.ylabel('y (mm)')
    plt.title('Comparison with Other Algorithms')
    plt.imshow(interp[ud[0] : ud[1], lr[0] : lr[1]], extent=(lr[0] - 600, lr[1] - 600, ud[0] - 600, ud[1] - 600), origin = 'lower', cmap = 'Blues')

    plt.suptitle('File Name:' + dataInProcess[i] + '\nEvent Type: ' + eventtype + '    ' + str(eventnum) + ' event(s) occured')

    plt.show()
    # Save plot. Requires folder "result" before running. Replaces '.txt' in output file name.
    #plt.savefig('result/multivalidity/' + dataInProcess[i][:-4] + '.png')

    plt.clf()

    # Save deconvoluted image in values
    #result = pd.DataFrame(decon)
    #result.to_csv("result.csv", index=False)

    processendtime = time.time()
    print(str(i + 1) + " finished! elapsed time: " + str(processendtime - processstarttime))

print("all finished!\nOversize events:\n" + '\n'.join(dataoversize) + "\nAsymmetric clusters:\n" + '\n'.join(dataasymmetric))


import numpy as np
import argparse
import matplotlib
matplotlib.use("Qt5Agg")
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from scipy.stats import wilcoxon
import seaborn as sns
import pandas as pd
import sys

mniroivalues = np.array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11., 12., 13.,
       14., 15., 16., 17., 18., 19., 20., 21., 22., 23., 24., 25., 26.,
       27., 28., 29., 30., 31., 32., 33., 34., 35., 36., 37., 38., 39.,
       40., 41., 42., 43., 44., 45., 46., 47., 48., 49., 50., 51., 52.,
       53., 54., 55., 56., 57., 58., 59., 60., 61., 62., 63., 64., 65.,
       66., 67., 68., 69., 70., 71., 72.])

mniroivalues = np.array([np.int32(v) for v in mniroivalues])

mniroinames = np.array(['3rd Ventricle', '4th Ventricle', 'Accumbens Area',
       'Amygdala', 'Brain Stem', 'Caudate',
       'Cerebellum Exterior',
       'Cerebellum White Matter',
       'Cerebral White Matter', 'Cerebrospinal Fluid',
       'Hippocampus', 'Inferior Lateral Ventricle',
       'Lateral Ventricle', 'Pallidum',
       'Putamen', 'Thalamus Proper',
       'Ventral Diencephalon (DC)', 'Vessel', 'Optic Chiasm',
       'Cerebellar Vermal Lobules I-V',
       'Cerebellar Vermal Lobules VI-VII',
       'Cerebellar Vermal Lobules VIII-X', 'Basal Forebrain',
       'Anterior cingulate gyrus',
       'Anterior insula',
       'Anterior orbital gyrus',
       'Angular gyrus',
       'Calcarine cortex',
       'Central operculum', 'Cuneus',
       'Entorhinal area',
       'Frontal operculum',
       'Frontal pole', 'Fusiform gyrus',
       'Gyrus rectus',
       'Inferior occipital gyrus',
       'Inferior temporal gyrus',
       'Lingual gyrus',
       'Lateral orbital gyrus',
       'Middle cingulate gyrus',
       'Medial frontal cortex',
       'Middle frontal gyrus',
       'Middle occipital gyrus',
       'Medial orbital gyrus',
       'Postcentral gyrus medial segment',
       'Precentral gyrus medial segment',
       'Superior frontal gyrus medial segment',
       'Middle temporal gyrus',
       'Occipital pole',
       'Occipital fusiform gyrus',
       'Opercular part of the inferior frontal gyrus',
       'Obital part of the inferior frontal gyrus',
       'Posterior cingulate gyrus',
       'Precuneus',
       'Parahippocampal gyrus',
       'Posterior insula',
       'Parietal operculum',
       'Postcentral gyrus',
       'Posterior orbital gyrus',
       'Planum polare',
       'Precentral gyrus',
       'Planum temporale',
       'Subcallosal area',
       'Superior frontal gyrus',
       'Supplementary motor cortex',
       'Supramarginal gyrus',
       'Superior occipital gyrus',
       'Superior parietal lobule',
       'Superior temporal gyrus',
       'Temporal pole',
       'Triangular part of the inferior frontal gyrus',
       'Transverse temporal gyrus'])

#mniroinames = np.array([np.str(v) for v in mniroinames])

def read_roi_dice_scores(file):
    with open(file, "r") as f:
        lines = f.readlines()
    return zip(*[(np.int32(np.float32(lines[0].split(" ")[:-1][i])), np.float32(col)) for i, col in enumerate(lines[1].split(" ")[:-1])])

if __name__ == "__main__":
    CLI=argparse.ArgumentParser()
    CLI.add_argument(
        "--rawdices",
        nargs="*",
        help=".txt files containing DICE scores of between pairs of ground truth and raw DSC ROIs",
        type=str,
        default=["mniroisgtrawdice.txt"],
    )
    CLI.add_argument(
        "--cordices",
        nargs="*",
        help=".txt files containing DICE scores of between pairs of ground truth and corrected DSC ROIs",
        type=str,
        default=["mniroisgtepicdice.txt"],
    )
    args = CLI.parse_args()

    assert len(args.rawdices) == len(args.cordices), \
    "Not equal number of rawdice and cordice files passed as argument"

    num_sub = len(args.rawdices)
    num_rois = len(mniroivalues)

    allrawdicescores, allcordicescores = np.empty((num_rois, num_sub)), \
                                         np.empty((num_rois, num_sub))

    allrawdicescores[:], allcordicescores[:] = np.nan, np.nan

    for i in range(num_sub):

        # Read the files
        rawdicerois, rawdicescores = read_roi_dice_scores(args.rawdices[i])
        cordicerois, cordicescores = read_roi_dice_scores(args.cordices[i])

        # Find the common rois
        rois = np.intersect1d(rawdicerois, cordicerois)

        # Remove outside of the brain ROI value (0.0) if exists
        if 0 in rois:
            rois = np.delete(rois, np.where(rois == 0))

        # Find the common medians and dice scores by
        # using the common rois
        rawdicescores_common = [rawdicescores[idx] for idx in [np.where(rawdicerois == roi)[0][0] for roi in rois]]
        cordicescores_common = [cordicescores[idx] for idx in [np.where(cordicerois == roi)[0][0] for roi in rois]]

        assert len(rois) == len(rawdicescores_common) == len(cordicescores_common), \
        "Failed to find common regions for analysis of dice scores"

        allrawdicescores[[np.where(mniroivalues == roi)[0][0] for roi in rois], i] = rawdicescores_common
        allcordicescores[[np.where(mniroivalues == roi)[0][0] for roi in rois], i] = cordicescores_common

    allrawdicescores_nonan = [roisamples[~np.isnan(roisamples)] for roisamples in allrawdicescores]
    allcordicescores_nonan = [roisamples[~np.isnan(roisamples)] for roisamples in allcordicescores]

    wilcoxonresults = np.empty((2, num_rois))
    wilcoxonresults[:] = np.nan

    for i in range(num_rois):
        if len(allrawdicescores_nonan[i]) >= 10 and len(allcordicescores_nonan[i]) >= 10:
            wilcoxonresults[:, i] = wilcoxon(allrawdicescores_nonan[i], allcordicescores_nonan[i])

    #print("HER")
    #print(wilcoxonresults[1,:])

    # How to sort the regions
    # By increaseing p-value
    sortidxbla = np.argsort(wilcoxonresults[1, :])

    # Bonferroni correction
    alpha = 0.05
    num_sub_test = len(wilcoxonresults[1, :][~np.isnan(wilcoxonresults[1, :])])
    cutoff = alpha/num_sub_test
    print("Threshold for significant p-value is %f" % cutoff)

    # Extract number of significant regions
    topbla = np.argwhere(np.sort(wilcoxonresults[1, :]) < cutoff)[-1][0] + 1

    print("Se her!")
    print(topbla)
    print(mniroinames[sortidxbla][:topbla])

    topmedianrawdicescoressortedbla = \
    np.array([np.median(scores) for scores in np.array(allrawdicescores_nonan)[sortidxbla][:topbla]])
    topmediancordicescoressortedbla = \
    np.array([np.median(scores) for scores in np.array(allcordicescores_nonan)[sortidxbla][:topbla]])

    print("before")
    print(topmedianrawdicescoressortedbla)
    print("after")
    print(topmediancordicescoressortedbla)
    print("after-before")
    print(topmediancordicescoressortedbla-topmedianrawdicescoressortedbla)

    top = 72 # 72 or more selects all regions. 71 for TOPUP GE beceause region "vessel" contain only
    # nan . This causes problems.
    #top = 10

    # Then sort significant regions by increasing ground truth Dice score
    medianrawdicescores = np.array([np.median(scores) for scores in np.array(allrawdicescores_nonan)])
    sortidx = np.argsort(medianrawdicescores)
    topmedianrawdicescores = medianrawdicescores[sortidx][:top]

    # The top regions
    topregions = mniroinames[sortidx][:top]
    print("Number of top regions: %i" % top)
    print("The top regions are: ")
    print(topregions)
    print("Top ground truth Dice scores are: ")
    print(topmedianrawdicescores)

    descriptionchoice = 2
    description = ["TOPUP impact on gradient echo DSC Dice", \
                   "TOPUP impact on spin echo DSC Dice", \
                   "EPIC impact on gradient echo DSC Dice", \
                   "EPIC impact on spin echo DSC Dice"]

    fig = plt.figure(figsize=[2*6.4, 6*4.8], tight_layout=True)

    fig.suptitle(description[descriptionchoice])

    gs = gridspec.GridSpec(1, 5)

    ax1 = fig.add_subplot(gs[0, 0:3])
    ax2 = fig.add_subplot(gs[0, 3], sharey=ax1)
    ax3 = fig.add_subplot(gs[0, 4], sharey=ax1)

    # Making split violin kernel density plot
    # Prepare median values for uncorrected Dice
    topdicedata = np.array(allrawdicescores_nonan)[sortidx][:top]
    topdicedatadf = \
    pd.DataFrame({"Dice" : np.array([pd.Series([sample for sample in samples], dtype=float) for samples in topdicedata])}).explode("Dice")
    topcorrectiontypedf = \
    pd.DataFrame({"Comparison" : np.array([pd.Series(["1. GT vs. uncorrected" for num_samples in range(len(samples))], dtype="category") for samples in topdicedata])}).explode("Comparison")
    topregionsdatadf = \
    pd.DataFrame({"Region" : np.array([pd.Series([region for num_samples in range(len(samples))], dtype="category") for region, samples in zip(topregions, topdicedata)])}).explode("Region")
    d1 = pd.concat((topcorrectiontypedf, topregionsdatadf, topdicedatadf), axis=1).astype({"Comparison" : str, "Region" : str, "Dice" : float})

    # --"-- corrected Dice
    topdicedata = np.array(allcordicescores_nonan)[sortidx][:top]
    topdicedatadf = \
    pd.DataFrame({"Dice" : np.array([pd.Series([sample for sample in samples], dtype=float) for samples in topdicedata])}).explode("Dice")
    topcorrectiontypedf = \
    pd.DataFrame({"Comparison" : np.array([pd.Series(["2. GT vs. corrected" for num_samples in range(len(samples))], dtype="category") for samples in topdicedata])}).explode("Comparison")
    topregionsdatadf = \
    pd.DataFrame({"Region" : np.array([pd.Series([region for num_samples in range(len(samples))], dtype="category") for region, samples in zip(topregions, topdicedata)])}).explode("Region")
    d2 = pd.concat((topcorrectiontypedf, topregionsdatadf, topdicedatadf), axis=1).astype({"Comparison" : str, "Region" : str, "Dice" : float})

    # Combine dataframes for uncorrected and corrected Dice
    d = pd.concat((d1, d2))

    #d_xls = "/run/user/1001/gvfs/smb-share:server=desktop-suc40rk,share=onedrive/work/OUS/distortion_correction/article_figures/dsc-space/topsedice.xlsx"

    #d.to_excel(d_xls)

    print("START")

    print(d1)

    print("MIDDLE")

    print(d2)

    print("HERE")

    topmedianrawdicescoressorted = \
    np.array([np.median(scores) for scores in np.array(allrawdicescores_nonan)[sortidx][:top]])
    topmediancordicescoressorted = \
    np.array([np.median(scores) for scores in np.array(allcordicescores_nonan)[sortidx][:top]])

    print(topmedianrawdicescoressorted)
    print(topmediancordicescoressorted)

    print("A")
    print(topmediancordicescoressorted-topmedianrawdicescoressorted)
    print(np.sum(topmediancordicescoressorted-topmedianrawdicescoressorted))

    print("B")
    print(topmedianrawdicescoressorted-topmediancordicescoressorted)
    print(np.sum(topmedianrawdicescoressorted-topmediancordicescoressorted))

    print("END")

    # Plot Dice
    sns.violinplot(x="Dice",
                   y="Region",
                   hue="Comparison",
                   split=True,
                   inner="quart",
                   data=d,
                   ax=ax1)

    # Prepare uncorrected Dice scores for box plot
    topdicedata = np.array(allrawdicescores_nonan)[sortidx][:top]
    topregionsdatadf = \
    pd.DataFrame({"Region" : np.array([pd.Series([region for num_samples in range(len(samples))], dtype="category") for region, samples in zip(topregions, topdicedata)])}).explode("Region")
    topdicedatadf = \
    pd.DataFrame({"1" : np.array([pd.Series([sample for sample in samples], dtype=float) for samples in topdicedata])}).explode("1")
    d = pd.concat((topregionsdatadf, topdicedatadf), axis=1).astype({"Region" : str, "Region" : str, "1" : float})

    # Plot uncorrected Dice
    #sns.barplot(x=toppvalues,
    #            y=topregions,
    #            ax=ax3)
    #ax3.set_xlabel("Corrected Dice")
    sns.boxplot(x="1", y="Region", data=d, ax=ax2)

    plt.setp(ax2.get_yticklabels(), visible=False)
    ax2.set_ylabel("")

    # Prepare corrected Dice scores for box plot
    topdicedata = np.array(allcordicescores_nonan)[sortidx][:top]
    topregionsdatadf = \
    pd.DataFrame({"Region" : np.array([pd.Series([region for num_samples in range(len(samples))], dtype="category") for region, samples in zip(topregions, topdicedata)])}).explode("Region")
    topdicedatadf = \
    pd.DataFrame({"2" : np.array([pd.Series([sample for sample in samples], dtype=float) for samples in topdicedata])}).explode("2")
    d = pd.concat((topregionsdatadf, topdicedatadf), axis=1).astype({"Region" : str, "Region" : str, "2" : float})

    # Plot corrected Dice scores
    sns.boxplot(x="2", y="Region", data=d, ax=ax3)

    plt.setp(ax3.get_yticklabels(), visible=False)
    ax3.set_ylabel("")

    # Make some free space for suptitle
    gs.tight_layout(fig, rect=[0, 0, 1, 0.95])

    plt.show()


import sys
import os

sys.path.append(os.path.abspath("."))
sys.dont_write_bytecode = True

__author__ = "bigfatnoob"

from analysis import arguments
from analysis.helpers import constants as a_consts
from utils import cache
import properties

def get_meta_for_file(dataset, file_path):
  args_meta_data = arguments.parse_file_for_args(file_path, dataset)
  return args_meta_data

def execute(dataset, root_folder):
  for file_path in cache.list_files(root_folder, check_nest=True, is_absolute=True):
    file_name = cache.get_file_name(file_path)
    if file_name == "__init__" or file_name.startswith(a_consts.GENERATED_PREFIX):
      continue
    get_meta_for_file(dataset, file_path)

def execute_dataset(dataset):
  root_folder = os.path.join(properties.PYTHON_PROJECTS_HOME, dataset)
  execute(dataset, root_folder)

def execute_problem(dataset, problem):
  root_folder = os.path.join(properties.PYTHON_PROJECTS_HOME, dataset, problem)
  execute(dataset, root_folder)

if __name__ == "__main__":
  args = sys.argv
  if len(args) < 2:
    print("Use python codejam/file_metadata.py <dataset> <?problem_id>")
    exit(0)
  elif len(args) > 2:
    execute_problem(args[1], args[2])
  else:
    execute_dataset(args[1])


# -*- coding: utf-8 -*-
"""
Created on Sat Sep 19 13:58:36 2020

@author: rjnsa
"""

import re
from nltk.corpus import stopwords
import requests

def getUrl(url):
     response=requests.get(url,headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36' })
     if response:
         response=response.text
     else: print ('failed attempt')
     return response

def ProcessData(url):
    freq = {}
    stopLex=set(stopwords.words('english'))
    urlText = getUrl(url)
    text=re.sub('[^a-z]',' ',urlText.lower())
    words=text.split(' ')
    for word in words:
            if word=='' or word in stopLex:continue
            else: freq[word]=freq.get(word,0)+1
    return freq

def fetchWords(url1, url2, url3):
    result = []
    urlText1 = ProcessData(url1)
    urlText2 = ProcessData(url2)
    urlText3 = ProcessData(url3)
    for word in urlText2.keys():
        print(word)
        if word in urlText3.keys() and word in urlText1.keys():
            if (urlText3[word] > urlText2[word] and (urlText2[word] > urlText1[word])):
               result.append(word)
    return set(result)

print(fetchWords
('https://gist.githubusercontent.com/rashmiswaroop10/012403550d28849cea886378801aaa45/raw/9e068f4fadf26aa7c9791ca6ae20cacfb90b6904/text1.txt',
'https://gist.githubusercontent.com/rashmiswaroop10/7ffe171e93071cab8aad9c338c24aea1/raw/74ac846d5c0a8f2b287578ce7862bf006ac05387/text3.txt',
'https://gist.githubusercontent.com/rashmiswaroop10/8086af919f6da231bd458edc6f7ef749/raw/02b7eddfbf778252c613ab50b50258af3bda7554/text2.txt'
))

print(fetchWords
('https://gist.githubusercontent.com/gilgga/193db382232aaeb7763242d39cbc5d72/raw/1aa1457105dd0222bd8cb38f7b980a53bfbe900b/webcounter_testlink1.txt',
'https://gist.githubusercontent.com/gilgga/193db382232aaeb7763242d39cbc5d72/raw/1aa1457105dd0222bd8cb38f7b980a53bfbe900b/webcounter_testlink2.txt',
'https://gist.githubusercontent.com/gilgga/193db382232aaeb7763242d39cbc5d72/raw/1aa1457105dd0222bd8cb38f7b980a53bfbe900b/webcounter_testlink3.txt'
)
)

[Homework 2] Web Counter/frequentwords.py


# Create your views here.
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext,Context, loader
import utils.config as cfg
from utils import cache

from enroll.models import Course,Folder,Season
import logging

def index(request):
    cfg_list=cfg.getConfigList()
    return render_to_response('admin/sys_index.html', RequestContext(request, { 'config_list': cfg_list }))

def config_create(request):
    if request.method == 'POST':
        form = cfg.ConfigForm(request.POST)
        if form.is_valid():
            logging.info('form data' + form.cleaned_data['name'])
            config  = form.save(commit=False)
            config.save()
            logging.info('new config created - id: %s key: %s data: %s' % (config.key().id() , config.key(), config))
            return redirect('/admin/sys/')
    else:
        form = cfg.ConfigForm()
    return render_to_response('admin/sys_config_create.html', RequestContext(request, { 'form': form }))

def config_edit(request, config_id):
    config = cfg.Config.get_by_id(int(config_id))
    if config is None:
        raise Http404
    if request.method == 'POST':
        form = cfg.ConfigForm(request.POST, instance=config)
        if form.is_valid():
            logging.info('edit config before - id: %s key: %s data: %s' % (config.key().id() , config.key(), config))
            form.save(commit=False)
            logging.info('edit config after - id: %s key: %s data: %s' % (config.key().id() , config.key(), config))
            config.save()
            return redirect('/admin/sys/')
    else:
        form = cfg.ConfigForm(instance=config)
    return render_to_response('admin/sys_config_edit.html', RequestContext(request, { 'form': form }) )

def config_setup(request):
    cfg.setupConfig()
    return redirect('/admin/sys/')

def flush_cache(request):
    r = cache.flush_all()
    return HttpResponse('ok %s'%(r))

def all_courses(request):

########## hromadne vypnuti slevy
    course_list=Course.list()
    for c in course_list:
        if c.cost_sale:
            logging.info('course %s sale off'%(c.code))
            c.cost_sale = False
            c.save()
#############

    return HttpResponse('ok')


from threading import Thread

from flask import current_app
from flask import render_template
from flask_mail import Message

from app import utils
from app.extensions import mail

def _send_async(app, msg):
    with app.app_context():
        mail.send(msg)

def send(subject, sender, recipients, text_body, html_body):
    msg = Message(subject, sender=sender, recipients=recipients)
    msg.body = text_body
    msg.html = html_body
    Thread(target=_send_async,
           args=(current_app._get_current_object(), msg)).start()

def send_from_default(subject, recipients, text_body, html_body):
    send(subject,
         current_app._get_current_object().config['MAIL_USERNAME'],
         recipients, text_body, html_body)

def send_verification_email(user_id, user_email, referring_uuid=''):
    payload = {
        'user_id': user_id,
        'referring_uuid': referring_uuid}
    jwt_token = utils.encode_jwt_token(payload)
    send_from_default(subject='Please verify your email address',
                      recipients=[user_email],
                      text_body=render_template(
                          'email/verify_email.txt', token=jwt_token),
                      html_body=render_template(
                          'email/verify_email.html', token=jwt_token))