#!/usr/bin/env python
# -*- coding: utf-8 -*-
import piradio.graphics as graphics
import freetype
import logging

class Bitmap(object):
    """A 2D bitmap image represented as a list of byte values.
    Each byte indicates the state of a single pixel in the bitmap.
    A value of 0 indicates that the pixel is `off` and any other value
    indicates that it is `on`.
    """
    def __init__(self, width, height, pixels=None):
        self.width = width
        self.height = height
        self.pixels = pixels or bytearray(width * height)

    def __repr__(self):
        """Return a string representation of the bitmap's pixels."""
        rows = ''
        for y in range(self.height):
            for x in range(self.width):
                rows += '*' if self.pixels[y * self.width + x] else '.'
            rows += '\n'
        return rows

    def bitblt(self, src, x, y):
        """Copy all pixels from `src` into this bitmap"""
        srcpixel = 0
        dstpixel = y * self.width + x
        row_offset = self.width - src.width

        for _ in xrange(src.height):
            for _ in xrange(src.width):
                # Perform an OR operation on the destination pixel and
                # the source pixel because glyph bitmaps may overlap if
                # character kerning is applied, e.g. in the string
                # "AVA", the "A" and "V" glyphs must be rendered with
                # overlapping bounding boxes.
                self.pixels[dstpixel] = (self.pixels[dstpixel] or
                                         src.pixels[srcpixel])
                srcpixel += 1
                dstpixel += 1
            dstpixel += row_offset

class Glyph(object):
    def __init__(self, pixels, width, height, top, advance_x):
        self.bitmap = Bitmap(width, height, pixels)

        # The glyph bitmap's top-side bearing, i.e. the vertical
        # distance from the baseline to the bitmap's top-most scanline.
        self.top = top

        self.descent = max(0, self.height - self.top)
        self.ascent = max(0, max(self.top, self.height) - self.descent)

        # The glyph's advance width in pixels.
        self.advance_x = advance_x

    @property
    def width(self):
        return self.bitmap.width

    @property
    def height(self):
        return self.bitmap.height

    @staticmethod
    def from_glyphslot(slot):
        """Construct and return a Glyph object from a FreeType GlyphSlot."""
        pixels = Glyph.unpack_mono_bitmap(slot.bitmap)
        width, height = slot.bitmap.width, slot.bitmap.rows
        top = slot.bitmap_top

        # The advance width is given in FreeType's 26.6 fixed point format,
        # which means that the pixel values are multiples of 64.
        advance_x = slot.advance.x / 64

        return Glyph(pixels, width, height, top, advance_x)

    @staticmethod
    def unpack_mono_bitmap(bitmap):
        """Unpack a freetype FT_LOAD_TARGET_MONO glyph bitmap into a
        bytearray where each pixel is represented by a single byte.
        """
        # Allocate a bytearray of sufficient size to hold the glyph bitmap.
        data = bytearray(bitmap.rows * bitmap.width)

        # Iterate over every byte in the glyph bitmap. Note that we're not
        # iterating over every pixel in the resulting unpacked bitmap --
        # we're iterating over the packed bytes in the input bitmap.
        for y in range(bitmap.rows):
            for byte_index in range(bitmap.pitch):

                # Read the byte that contains the packed pixel data.
                byte_value = bitmap.buffer[y * bitmap.pitch + byte_index]

                # We've processed this many bits (=pixels) so far.
                # This determines where we'll read the next batch
                # of pixels from.
                num_bits_done = byte_index * 8

                # Pre-compute where to write the pixels that we're going
                # to unpack from the current byte in the glyph bitmap.
                rowstart = y * bitmap.width + byte_index * 8

                # Iterate over every bit (=pixel) that's still a part
                # of the output bitmap. Sometimes we're only unpacking
                # a fraction of a byte because glyphs may not always fit
                # on a byte boundary. So we make sure to stop if we
                # unpack past the current row of pixels.
                for bit_index in range(min(8, bitmap.width - num_bits_done)):

                    # Unpack the next pixel from the current glyph byte.
                    bit = byte_value & (1 << (7 - bit_index))

                    # Write the pixel to the output bytearray. We ensure
                    # that `off` pixels have a value of 0 and `on`
                    # pixels have a value of 1.
                    data[rowstart + bit_index] = 1 if bit else 0

        return data

class Font(object):
    def __init__(self, filename, size):
        self.face = freetype.Face(filename)
        self.face.set_pixel_sizes(0, size)
        self.glyphcache = {}

    def glyph_for_character(self, char):
        # Let FreeType load the glyph for the given character and tell
        # it to render a monochromatic bitmap representation.
        if char in self.glyphcache:
            return self.glyphcache[char]

        self.face.load_char(char, freetype.FT_LOAD_RENDER |
                            freetype.FT_LOAD_TARGET_MONO)
        glyph = Glyph.from_glyphslot(self.face.glyph)
        self.glyphcache[char] = glyph

        return glyph

    def render_character(self, char):
        glyph = self.glyph_for_character(char)
        return glyph.bitmap

    def kerning_offset(self, previous_char, char):
        """Return the horizontal kerning offset in pixels when rendering
        `char` after `previous_char`.

        Use the resulting offset to adjust the glyph's drawing position
        to reduces extra diagonal whitespace, for example in the string
        "AV" the bitmaps for "A" and "V" may overlap slightly with some
        fonts. In this case the glyph for "V" has a negative horizontal
        kerning offset as it is moved slightly towards the "A".
        """
        kerning = self.face.get_kerning(previous_char, char)

        # The kerning offset is given in FreeType's 26.6 fixed point
        # format, which means that the pixel values are multiples of 64.
        return kerning.x / 64

    def text_dimensions(self, text):
        """Return (width, height, baseline) of `text` rendered in the
        current font.
        """
        width, height, baseline = 0, 0, 0
        previous_char = None

        ascent = 0
        descent = 0

        # For each character in the text string we load its glyph bitmap
        # and update TODO
        for char in text:
            glyph = self.glyph_for_character(char)

            # Update the overall height and baseline.
            ascent = max(ascent, glyph.ascent)
            descent = max(descent, glyph.descent)
            baseline = max(baseline, glyph.descent)

            kerning_x = self.kerning_offset(previous_char, char)

            # The advance width may be less than the width of the
            # glyph's bitmap. Make sure we compute the total width so
            # that all of the glyph's pixels fit into the returned
            # dimensions.
            width += max(glyph.advance_x + kerning_x, glyph.width + kerning_x)

            previous_char = char

        height = ascent + descent
        return (width, height, baseline)

    def render_text(self, text, width=None, height=None, baseline=None):
        """Render the given `text` into a Bitmap and return it.

        If `width`, `height`, and `baseline` are not specified they are
        computed using the `text_extents' function.
        """
        if None in (width, height, baseline):
            width, height, baseline = self.text_dimensions(text)

        x, y = 0, 0
        previous_char = None
        outbuffer = Bitmap(width, height)

        for char in text:
            # Adjust the glyph's drawing position if kerning information
            # in the font tells us so. This reduces extra diagonal
            # whitespace, for example in the string "AV" the bitmaps for
            # "A" and "V" overlap slightly.
            x += self.kerning_offset(previous_char, char)

            glyph = self.glyph_for_character(char)
            y = height - glyph.ascent - baseline

            outbuffer.bitblt(glyph.bitmap, x, y)

            x += glyph.advance_x

            previous_char = char

        return outbuffer

    def text_extents(self, text):
        return self.text_dimensions(text)

    def render(self, text, width=None, height=None, baseline=None):
        bmp = self.render_text(text, width, height, baseline)
        return graphics.Surface(bmp.width, bmp.height, pixels=bmp.pixels)

_registered_fonts = {}
_loaded_fonts = {}

def register(name, path):
    _registered_fonts[name] = path
    logging.info('Registered font %s --> %s', name, path)

def get(name, size):
    if not name in _registered_fonts:
        raise KeyError('Unknown font name %s' % name)

    path = _registered_fonts[name]
    hashedname = '%s-%i' % (path, size)

    if hashedname in _loaded_fonts:
        return _loaded_fonts[hashedname]

    logging.info('Loading font %s-%i', name, size)

    fnt = Font(_registered_fonts[name], size)
    _loaded_fonts[hashedname] = fnt

    return fnt


#!/usr/bin/env python3

import fileinput
import os
import json
import shutil
import errno

def parse_input(str1,str2):
    filename = str1
    lines = [line.rstrip("\n") for line in open(filename)]
    paths = [lines[i].split("=")[1].strip() for i in range(len(lines))]
    basenames = [os.path.basename(os.path.normpath(paths)[i]) for i in range(len(paths))]
    return(dict(zip(paths,basenames)))

def rw_dat(str1,var,option):
    if(option == 'w'):
        with open(str1, 'w') as fptxt:
            json.dump(var,fptxt)
    elif(option == 'r'):
        lines = [line.rstrip('\n') for line in open(str1)]
        with open(str1) as json_file:
            data = json.load(json_file)
    else:
        print("No correct option selected")


from time import process_time

from msmtools.estimation import transition_matrix as _tm
import math
from ldshmm.util.util_functionality import *
from ldshmm.util.util_math import Utility
from ldshmm.util.variable_holder import Variable_Holder
from ldshmm.util.spectral_mm import SpectralMM
from ldshmm.util.mm_class import MMMScaled

class Evaluation_Holder():
    """
    Class holding all evaluation functions used for a MMMScaled.
    See util_evaluation.py - The evaluation functions are similar except for the underlying model.
    """

    def error_function(m1, model):
        return np.linalg.norm(m1 - model.trans)

    def __init__(self, model, variable_config, error_function=error_function, evaluate_method="both", simulate=True,
                 filename="mm", init_run=False, log_values=True, heatmap=True, avg_values=True):
        """
        Info: This constructor reads simualted data from a previously created file simulated_data_mm ...

        :param model: MMMScaled (for instance obtained by sampling the MMFamily1)
        :param variable_holder: Variable_Holder objects that holds all configurations
        :param simulate: bool (default=True) - decide whether data should be simulated in the constructor
        :param init_run: bool (default=True)
        """
        if init_run:
            # ToDo Check which data to use for init run
            estimate_via_sliding_windows(data=[], num_states=Variable_Holder.num_states)

        self.model = model
        if simulate:
            # ToDO filename??
            self.simulated_data = simulate_and_store(model, filename)
        self.variable_config = variable_config
        self.error_function = error_function
        self.evaluate_method = evaluate_method
        self.log_values = log_values
        self.heatmap = heatmap
        self.avg_values = avg_values

    def evaluate(self, model=None, tauquasi=Variable_Holder.tauquasi, simulated_data=None, print_intermediate_values=False):
        self.tauquasi = tauquasi
        if model is not None:
            self.model = model
        if simulated_data is not None:
            self.simulated_data = simulated_data
        avg_errs_bayes, avg_errs_naive, avg_times_bayes, avg_times_naive = init_time_and_error_arrays(
            self.variable_config.heatmap_size)

        for one, values1 in enumerate(self.variable_config.iter_values1):
            for two, values2 in enumerate(self.variable_config.iter_values2):
                if self.variable_config.taumeta is None:
                    self.taumeta = values1
                else:
                    self.taumeta = self.variable_config.taumeta
                if self.variable_config.eta is None:
                    self.eta = values2
                else:
                    self.eta = self.variable_config.eta

                if self.variable_config.scale_window is None:
                    self.scale_window = values2
                else:
                    self.scale_window = self.variable_config.scale_window

                if self.variable_config.num_trajectories is None:
                    self.num_trajectories = values2
                    self.len_trajectory = int(
                        Variable_Holder.num_trajectories_num_transitions_max / self.num_trajectories) + 1
                else:
                    self.num_trajectories = self.variable_config.num_trajectories
                    self.len_trajectory = self.variable_config.len_trajectory

                if type(self.model) is not MMMScaled:
                    self.model_scaled = self.model.eval(self.taumeta, self.tauquasi)
                else:
                    self.model_scaled = self.model.eval(self.taumeta)

                self.shift = self.eta * self.taumeta
                self.window_size = self.scale_window * self.shift

                self.num_estimations = Utility.calc_num_estimations(self.len_trajectory,
                                                                    self.window_size, self.shift)
                self.r = (self.window_size - self.shift) / self.window_size

                if print_intermediate_values:
                    self.print_param_values(self.taumeta, self.shift, self.window_size, self.num_estimations,
                                            self.len_trajectory, self.num_trajectories, self.eta,
                                            self.scale_window)
                dataarray = np.asarray(self.simulated_data)

                log_total_time_naive, log_avg_err_naive, log_total_time_bayes, log_avg_err_bayes = self.performance_and_error_calculation(
                    dataarray)

                if not self.heatmap:
                    return log_total_time_naive, log_avg_err_naive, log_total_time_bayes, log_avg_err_bayes, None, None

                avg_times_bayes[two][one] = log_total_time_bayes
                avg_errs_bayes[two][one] = log_avg_err_bayes
                avg_times_naive[two][one] = log_total_time_naive
                avg_errs_naive[two][one] = log_avg_err_naive

        return avg_times_naive, avg_errs_naive, avg_times_bayes, avg_errs_bayes, self.variable_config.iter_values1, self.variable_config.iter_values2

    """
    ######
    ### Performance and Error Utility Calculation Methods
    ######
    """

    def performance_and_error_calculation(self, dataarray):
        """
        calculation of both performance and error for naive and bayes

        :param dataarray:
        :return:
        """

        if self.evaluate_method == "bayes":
            time_bayes, error_bayes = self.performance_and_error_calculation_bayes(dataarray)
            if self.log_values:
                time_bayes, error_bayes = self.calc_log_values(time_bayes, error_bayes)
            if self.avg_values:
                time_bayes, error_bayes = self.calc_avg_values(time_bayes, error_bayes)
            return None, None, time_bayes, error_bayes

        elif self.evaluate_method == "naive":
            time_naive, error_naive = self.performance_and_error_calculation_naive(dataarray)
            if self.log_values:
                time_naive, error_naive = self.calc_log_values(time_naive, error_naive)
            if self.avg_values:
                time_naive, error_naive = self.calc_avg_values(time_naive, error_naive)
            return time_naive, error_naive, None, None

        elif self.evaluate_method == "both":
            time_bayes, error_bayes = self.performance_and_error_calculation_bayes(dataarray)
            time_naive, error_naive = self.performance_and_error_calculation_naive(dataarray)

            if self.log_values:
                time_bayes, error_bayes = self.calc_log_values(time_bayes, error_bayes)
                time_naive, error_naive = self.calc_log_values(time_naive, error_naive)
            if self.avg_values:
                time_bayes, error_bayes = self.calc_avg_values(time_bayes, error_bayes)
                time_naive, error_naive = self.calc_avg_values(time_naive, error_naive)
            return time_naive, error_naive, time_bayes, error_bayes

    def performance_and_error_calculation_naive(self, dataarray):
        """
        performance and error calculation for naive only

        :param dataarray:
        :return:
        """
        lag = int(Variable_Holder.max_taumeta / self.taumeta)
        etimenaive = np.zeros(self.num_estimations + 2, dtype=float)
        etimenaive[0] = 0
        err = np.zeros(self.num_estimations + 1, dtype=float)
        self.estimation_time_naive = []
        for k in range(0, self.num_estimations + 1):
            current_time = self.window_size + k * self.shift - 1
            assert (current_time < np.shape(dataarray)[1])
            t0 = process_time()
            data0 = dataarray[:, current_time - self.window_size + 1: (current_time + 1)]

            dataslice0 = convert_2d_to_list_of_rows(data0)

            C0 = estimate_via_sliding_windows(data=dataslice0,
                                              num_states=Variable_Holder.num_states, initial=True,
                                              lag=lag)  # count matrix for whole window
            A0 = _tm(C0)
            t1 = process_time()
            etimenaive[k + 1] = t1 - t0 + etimenaive[k]
            dk = int((self.window_size - 1) / 2)
            estimation_time = current_time - dk
            self.estimation_time_naive.append(estimation_time)
            if type(self.model_scaled) == SpectralMM:
                # stationary
                err[k] = self.error_function(m1=A0, model=self.model_scaled)
            else:
                # non-stationary
                # print(A0)
                # print(self.model_scaled.eval(k).trans)
                err[k] = self.error_function(m1=A0, model=self.model_scaled.eval(estimation_time))

        return etimenaive, err

    def performance_and_error_calculation_bayes(self, dataarray):
        """
        performance and error calculation for bayes only

        :param dataarray:
        :return:
        """
        self.estimation_times_bayes = []
        lag = int(Variable_Holder.max_taumeta / self.taumeta)
        etimebayes = np.zeros(self.num_estimations + 2, dtype=float)
        errbayes = np.zeros(self.num_estimations + 1, dtype=float)
        for k in range(0, self.num_estimations + 1):
            current_time = self.window_size + k * self.shift - 1
            assert (current_time < np.shape(dataarray)[1])
            dk = int(self.window_size - (self.shift + 1) / 2 - self.window_size * math.pow(self.r, k + 1) / 2)
            estimation_time = current_time - dk
            self.estimation_times_bayes.append(estimation_time)
            if k == 0:
                ##### Bayes approach: Calculate C0 separately
                t0 = process_time()
                data0 = dataarray[:, 0 * self.shift: (self.window_size + 0 * self.shift)]
                dataslice0 = convert_2d_to_list_of_rows(data0)

                C_old = estimate_via_sliding_windows(data=dataslice0, num_states=Variable_Holder.num_states,
                                                     initial=True, lag=lag)
                A0 = _tm(C_old)
                etimebayes[1] = process_time() - t0
                if type(self.model_scaled) == SpectralMM:
                    # stationary
                    errbayes[0] = self.error_function(m1=A0, model=self.model_scaled)
                    print("Calculated Error", errbayes[0])
                else:
                    # non-stationary
                    errbayes[0] = self.error_function(m1=A0, model=self.model_scaled.eval(estimation_time))
                    print("Transition Matrix Error Calc:", self.model_scaled.eval(estimation_time).trans)

            if k >= 1:
                ##### Bayes approach: Calculate C1 (and any following) usind C0 usind discounting
                t0 = process_time()
                data1new = dataarray[:, self.window_size + (k - 1) * self.shift - 1: (current_time + 1)]
                dataslice1new = convert_2d_to_list_of_rows(data1new)

                C_new = estimate_via_sliding_windows(data=dataslice1new,
                                                     num_states=Variable_Holder.num_states,
                                                     lag=lag)  # count matrix for just new transitions

                weight0 = self.r
                weight1 = 1.0

                C1bayes = weight0 * C_old + weight1 * C_new
                C_old = C1bayes

                A1bayes = _tm(C1bayes)
                t1 = process_time()
                etimebayes[k + 1] = t1 - t0 + etimebayes[k]
                if type(self.model_scaled) == SpectralMM:
                    errbayes[k] = self.error_function(m1=A1bayes, model=self.model_scaled)
                else:
                    # print(A1bayes)
                    # print(self.model_scaled.eval(k).trans)
                    errbayes[k] = self.error_function(m1=A1bayes, model=self.model_scaled.eval(estimation_time))
        return etimebayes, errbayes

    def print_param_values(self, taumeta, shift, window_size, num_estimations, len_trajectory,
                           num_trajectories, eta, scale_window):
        print("Parameter Overview:")
        print("taumeta:\t", taumeta)
        print("lag:\t", int(Variable_Holder.max_taumeta / self.taumeta))
        if type(self.model) is not MMMScaled:
            print("tauquasi:\t", self.tauquasi)
        print("eta:\t", eta)
        print("scale_window\t:", scale_window)
        print("shift:\t", shift)
        print("window_size:\t", window_size)
        print("num_estimations:\t", num_estimations)
        print("len_trajectory:\t", len_trajectory)
        print("num_trajectories:\t", num_trajectories)
        print("num_trajectories*len_trajectory:\t", num_trajectories * len_trajectory)
        print("NAIVE window_size * num_estimations\t", window_size * (num_estimations + 1))
        print("BAYES window_size + num_estimations*shift\t", window_size + num_estimations * shift)
        print("\n")

    def calc_log_values(self, times, errors):
        log_times = Utility.log_value(times)
        log_errs = Utility.log_value(errors)
        return log_times, log_errs

    def calc_avg_values(self, times, errors):
        total_time = times[-1]
        avg_error = sum(errors) / len(errors)
        return total_time, avg_error


import cv2
import numpy as np
import click
import time

from yolov3 import Detector

import ai2thor.controller

controller = ai2thor.controller.Controller()
controller.start(player_screen_width=500, player_screen_height=400)

# Kitchens: FloorPlan1 - FloorPlan30
# Living rooms: FloorPlan201 - FloorPlan230
# Bedrooms: FloorPlan301 - FloorPlan330
# Bathrooms: FloorPLan401 - FloorPlan430

controller.reset('FloorPlan1')
event = controller.step(dict(action='Initialize', gridSize=0.25, rotation=0, horizon=0))

moves = {'Q': 'MoveLeft', 'R': 'MoveAhead', 'S': 'MoveRight', 'T': 'MoveBack'}
rotates = {'a': -10, 'd': 10}
looks = {'w': -10, 's': 10}

rotate = 0
horizon = 0

detect = Detector()

while True:

    img = event.cv2img

    # Detect edge
    # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # blur = cv2.GaussianBlur(gray, (5,5), 0)
    # edges = cv2.Canny(blur, 50,30)
    # cv2.imshow('Detect Edge', edges)

    st = time.time()
    # object detection
    dst = detect.detect(img)
    print("Time:", time.time() - st)
    cv2.imshow('Detect Object', dst)

    key = cv2.waitKey(0)
    key = chr(key)

    if key == 'q':
        break
    elif key in moves:
        event = controller.step(dict(action=moves[key]))
    elif key in rotates:
        rotate += rotates[key]
        event = controller.step(action=dict(action='Rotate', rotation=rotate))

    elif key in looks:
        horizon += looks[key]
        event = controller.step(action=dict(action='Look', horizon=horizon))

cv2.destroyAllWindows()


import requests
import json
import os
from dotenv import load_dotenv
from bs4 import BeautifulSoup, SoupStrainer
from datetime import datetime as dt
from datetime import timedelta

load_dotenv()
SLACK_URL = 'https://slack.com/api/chat.postMessage'
CHANNEL = os.getenv('SLACK_CHANNEL')
print(str(CHANNEL))
TOKEN = os.getenv('SLACK_TOKEN')
HEADERS = {
    'content-type': 'application/json',
    'authorization': f'Bearer {TOKEN}'
}

URLS = {
    'Knitter': "https://www.lounaat.info/lounas/knitter/espoo",
    'Bluebell': "https://www.lounaat.info/lounas/bluebell/espoo",
    'Happy Friends': "https://www.lounaat.info/lounas/happy-friends/espoo",
    'Sodexo Täyttymys': "https://www.lounaat.info/lounas/sodexo-tyttymys/espoo",
    'Amica Sinitähti': "https://www.lounaat.info/lounas/amica-ravintola-sinitahti/espoo"
}

WEEKDAYS = [
    "maanantai",
    "tiistai",
    "keskiviikko",
    "torstai",
    "perjantai",
    "lauantai",
    "sunnuntai"
]

def weekday_str():
    return WEEKDAYS[dt.today().weekday()]

def weekday_int():
    return dt.today().weekday()

def parse(html_txt, weekday, restaurant):
    try:
        amica_tags = SoupStrainer(id='menu')
        tag = amica_tags        # Default to lounaat.info
        if (restaurant == 'Factory'):
            # Load whole page since Factory has no good ids to parse into
            soup = BeautifulSoup(html_txt, 'html.parser')
            # Find parent of lounaslista text, which holds whole week in
            # multiple <p>'s (*sigh :( )
            s = soup.find(lambda tag: tag.name == "h2" and tag.text.lower(
            ).startswith("lounaslista")).parent.text
            # Find today and tomorrow from the huge string which has whole week
            # lunch and some bloat text
            s = (s[s.lower().find(weekday) +
                   len(weekday):s.lower().find(WEEKDAYS[(dt.today() +
                                                         timedelta(days=1)).weekday()])])
            # Get rid of date text that is following the weekday and return the
            # text
            s = (s[s.find("\n") + len("\n"):])
            return s
        else:       # lounaat.info parse
            soup = BeautifulSoup(html_txt, 'html.parser', parse_only=tag)
            raw_html = soup.find(lambda tag: tag.name == "h3" and tag.text.lower(
            ).startswith(weekday)).parent.parent
            lst = []
            for elem in raw_html.find_all("p"):
                if not elem.text.startswith("Mixed lunch:")\
                        and not elem.text.startswith("Kaikki lounaspakettimme sisältävät")\
                        and not elem.text.startswith("All of our lunch options"):
                    lst.append(" ".join(elem.text.split()))
            return '\n'.join(lst)
    except Exception:
        return ""       # Default failed parse

def main():
    wd = weekday_str()
    ret = json.loads(requests.post(SLACK_URL, data=json.dumps(
        {
            'token': TOKEN,
            'channel': CHANNEL,
            'text': f'Lounaat {wd}',
            'charset': 'utf8'
        }
    ), headers=HEADERS).text)
    print(str(ret))
    thread_id = ret['ts']
    for (restaurant, url) in URLS.items():
        try:
            resp = requests.get(url)
            print("{0}: {1}".format(restaurant, resp.status_code))
            text = parse(resp.text, wd, restaurant)
            bolded_header = "*{0}:*\n".format(restaurant)
            data = {
                'text': bolded_header + text,
                'channel': CHANNEL,
                'thread_ts': thread_id,
            }
            ret = json.loads(
                requests.post(
                    SLACK_URL,
                    data=json.dumps(data),
                    headers=HEADERS).text)
        except Exception as ex:
            print(ex)
            requests.post(SLACK_URL, data=json.dumps(
                {'text': ex}), headers=HEADERS)

main()


"""Serializers module will handle all the object serialization for all the models."""

from rest_framework import serializers

from . import models

# noqa: D212,D204,D404

class ProductsAdsSerializers(serializers.ModelSerializer):
    """
    Serializes and deserializes python objects to JSON data.
    """

    class Meta:
        """
        Get models and fields defined to be serialized.
        """

        model = models.ProductsAds
        fields = ("ads_id", "pricing_id", "category_id", "user_id",
                  "Ads_content", "activity", "Ads_title")

    def update(self, instance, validated_data):
        """Update method updates the products objects and save then to the DB."""
        self.instance.Ads_content = validated_data.get("Ads_content", self.instance.Ads_content)
        self.instance.activity = validated_data.get("activity", self.instance.activity)
        self.instance.Ads_title = validated_data.get("Ads_title", self.instance.Ads_title)
        self.instance.save()

        return self.instance


#Dynamic programming for super sequence

def supersequence(a,b):
	m=len(a)
	n=len(b)

	l=lcs(a,b)
	return (m+n-l)

def lcs(a,b):
	m=len(a)
	n=len(b)

	val=[[0]*(n+2) for _ in range(m+2)]

	for i in range(1,m+1):
		for j in range(n+1):

			if i==0 or j==0:
				val[i][j]=0
			elif a[i-1]==b[j-1]:
				val[i][j]=val[i-1][j-1]+1
			else:
				val[i][j]=max(val[i-1][j],val[i][j-1])

	return val[m][n]

# Driver code
X = "AGGTAB"
Y = "GXTXAYB"

print("Length of the shortest supersequence is %d"
                      % supersequence(X, Y))


#! /usr/bin/python
import cv2
import time
'''
def diffinframes(x,y,z):
	img1=cv2.absdiff(x,y)
	img2=cv2.absdiff(y,z)
	comm_diff=cv2.bitwise_and(img1,img2)
	return comm_diff
'''
#enabling camera
cap=cv2.VideoCapture(0)

#capturing 3 consistent frames
frame1=cap.read()[1]
frame2=cap.read()[1]
frame3=cap.read()[1]

#converting to grayscale
gray1=cv2.cvtColor(frame1,0)
gray2=cv2.cvtColor(frame2,0)
gray3=cv2.cvtColor(frame3,0)

while cap.isOpened():
	img1=cv2.absdiff(gray1,gray2)
	img2=cv2.absdiff(gray2,gray3)
	comm_diff=cv2.bitwise_and(img1,img2)
	#show motion detected frames
	cv2.imshow("camera",comm_diff)
	#capture more frames for further processing
	status,frame=cap.read()
	gray1=gray2
	gray2=gray3
	gray3=cv2.cvtColor(frame,0)
	if cv2.waitKey(1) & 0xFF==ord('q'):
		break

cv2.destroyAllWindows()
cap.release()


import numpy as np
import pylab as plt
import matplotlib

massLoss = np.array([2.98e-4, 4.88e-4, 6.56e-4, 8.3e-4, 8.96e-4])
temps = np.array([323,333,348,363,368])
massLossMg = np.array([8.975e-4, 8.253e-4,7.638e-4])

M = 0.018
R = 8315

Mconst = (M/(2*np.pi*R*temps))**0.5

T = np.arange(273,374,1)

pPart = np.array(np.exp(77.3450 + 0.0057*temps - 7235/temps)/(temps**8.2))

n = 10
rHPart = np.array([np.zeros(5) for _ in range(n)])
deltaP = np.array([np.zeros(5) for _ in range(n)])
mDot = np.array([np.zeros(5) for _ in range(n)])
epsilon = np.array([np.zeros(5) for _ in range(n)])

a = 0
hum = 0.9
while a < 10:
    (rHPart[a]) = hum * pPart
    hum +=0.01

    a+=1

Tc = temps - 273

pVap= 1000*(0.61121*np.exp((18.678 - (Tc/234.5))*(Tc/(257.14+Tc))))

print(pVap,pPart, pVap-pPart)
a = 0
i = 0

"""
while a < 10:
    deltaP[a] = pVap - rHPart[a]

    while i < 5:
        epsilon = massLoss[i]/(deltaP[a][i]*Mconst[i])
        print(massLoss[i],deltaP[a][i], epsilon)
        i+=1

    i=0
    a+=1

"""

"""
mDot = deltaP * epsilon * (M/(2*np.pi*R*T))**0.5

print(epsilon)

massLoss[a]/(deltaP[a]*(M/2*np.pi*R*temps)**0.5)

"""

"""

a = 0
while a < 10:

    plt.plot(temps, deltaP[a], alpha = 0.5, label = a+1)
    a+=1

plt.xlabel('Temperature (K)')
plt.ylabel('Mass Loss')
plt.legend(fontsize = 8)
plt.xlim(273,373)

plt.show()

"""


# Binary search: O(nlogn) time, O(1) space:
# Consider an array that has n distinct numbers in the range [1,n]. For example: [1,2,3,4,5][1,2,3,4,5].
# If we pick any one of these 5 numbers and count how many numbers are less than or equal to it,
# the answer will be equal to that number. So in [1,2,3,4,5], if you pick the number 4,
# there's exactly 4 numbers that are less than or equal to 4.
# If you pick 3, there's exactly 3 numbers that are less than or equal to 3, and so on.
# However, when you have duplicates in the array,
# this count will exceed the number at some point.
# For example: in [4,3,4,5,2,4,1], 3 has 3 numbers less than or equal to it.
# However, the duplicate number will have a count of numbers less than or equal to itself,
# that is greater than itself (in this example, 4, which is the duplicate,
# has 6 numbers that are less than or equal to it).
# Hence, the smallest number that satisfies this property is the duplicate number.
class Solution(object):
    def findDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
       # 'low' and 'high' represent the range of values of the target
        low = 1
        high = len(nums) - 1

        while low <= high:
            cur = (low + high) // 2
            count = 0

            # Count how many numbers are less than or equal to 'cur'
            count = sum(num <= cur for num in nums)
            if count > cur:
                duplicate = cur
                high = cur - 1
            else:
                low = cur + 1

        return duplicate

t = Solution()
print(t.findDuplicate([4,3,1,4,2]))

# Brute force: O(n2) time, O(1) space: TEL
class Solution(object):
    def findDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        for num1 in nums:
            ct = 0
            for num2 in nums:
                if num2 == num1:
                    ct += 1
                if ct == 2:
                    return num1


import os
import selenium
from selenium import webdriver
import time
currentDirectory = os.path.dirname(__file__)
soundDirectory = currentDirectory + r"/sounds//"
chromedriverPath = currentDirectory + "/setup/chromedriver.exe"
driver = webdriver.Chrome(chromedriverPath)

driver.get("https://youtube.com")
input("enter")
num = 0
scroll = str(270)
while True:
    input("enter")
    try:
        print("window.scrollTo(0, " + scroll + ");")
        driver.execute_script("window.scrollTo(0, " + scroll + ");")
    except Exception as e:
        print(e)
    num += 270
    scroll = str(num)


from collections import namedtuple as nt
from gspread_formatting import *
from gspread.utils import rowcol_to_a1
import numpy as np
import pandas as pd
import pickle as pkl

dpath = 'config/data/'

def get_dict(filename):
    with open(filename, 'rb') as f:
        return pkl.load(f)

def get_dict_value(filename, key):
    return get_dict(dpath + filename).get(key)

def update_dictionary(filename, key, value):
    tmp = get_dict(filename)
    tmp[key] = value
    put_dict(filename, tmp)

attribution = get_dict_value('attribution.pkl', 2)
outlay = get_dict(dpath + 'outlay3.pkl')

def filter_na(df):
    mask = pd.Series(x is not np.nan for x in df.index.values)
    df = df[mask.values].reset_index().append(pd.Series(), ignore_index=True)
    return df.set_index(df.columns[0])

def append_campaign(df, channel, trigger, triggers, attribution):
    """Extends dataframe for each channel's new campaign
        -> df - dataframe of either email/wp/seasonal/sms
        -> channel - string representation of channel
        -> trigger -> new campaign name
    """
    campaign = triggers[channel].get(trigger)
    df = df.append(pd.Series(name = campaign))
    for key, attr in attribution.items():
        df = df.append(pd.Series(name = attr))
    df = df.reset_index().append(pd.Series(), ignore_index=True)
    return df.set_index(df.columns[0])

def get_new_name(name, channel, triggers):
    print("Нажмите только 'Enter', если название компании Вас устраивает:\nВведите новое название для отображения в Google Sheets")
    new_name = input()
    if new_name == '':
        triggers[channel].update({name:name})
    else:
        triggers[channel].update({name:new_name})

def check_new_groups(new_campaigns,
                     main, email, wp,
                     seasonal, sms,
                     triggers, type_):
    maxlen = len(new_campaigns)
    print("Определите категорию кампании для {n} новых:\n".format(n=maxlen))

    i = 0
    while(i != maxlen):
        print("Нажмите 'Enter' для Email\n\t'1' для Web-push\n\t'2' для сезонной\n\t'3' для SMS\n")
        v = input('-> ' + new_campaigns[i] + ': \n')
        if v == '':
            get_new_name(new_campaigns[i], 'email', triggers); i+=1;
            email = append_campaign(email, 'email', new_campaigns[i-1],
                                    triggers, attribution)
        elif v == '1':
            get_new_name(new_campaigns[i], 'wp', triggers); i+=1;
            wp = append_campaign(wp, 'wp', new_campaigns[i-1],
                                 triggers, attribution)
        elif v == '2':
            get_new_name(new_campaigns[i], 'seasonal', triggers); i+=1;
            seasonal = append_campaign(seasonal, 'seasonal', new_campaigns[i-1],
                                       triggers, attribution)
        elif v == '3':
            get_new_name(new_campaigns[i], 'sms', triggers); i+=1;
            sms = append_campaign(sms, 'sms', new_campaigns[i-1],
                                  triggers, attribution)
        else:
            print("Повторите ввод в согласии с инструкцией\n")
    update_dictionary(dpath + '/triggers.pkl', type_, triggers)
    return main.append([email, wp, seasonal, sms])

def reindex_outlay(df, triggers):
    """Update start indices for each channel email/wp/seasonal/sms
    -> df: dataframe from gspread get_as_dataframe
    """
    tmp = df.index.values
    for channel in triggers.keys():
        trigger = list(triggers[channel].values())[0]
        outlay[channel] = np.where(tmp == trigger)[0][0]
    put_dictionary(dpath+'outlay3.pkl', outlay)

def update_campaigns(df, gdf, max_cols,
                     triggers, attribution):
    """Assigns new campaign's attribution values to dataframe
    -> df: dataframe from MindBox report
    -> gdf: dataframe gspread get_as_dataframe
    -> max_cols: period column
    """
    def get_campaign_info(df, name, column):
        """Locates specific value for named campaign"""
        try: res = df.loc[df.name == name, column].values[0]
        except: res = 0
        return res

    gdf = gdf.reset_index()
    for channel in triggers.keys():
        for trigger, campaign in triggers[channel].items():
            try:
                campaign_index = gdf[gdf.columns[0]].loc[gdf[gdf.columns[0]] == campaign].index[0]
                for index, row in gdf.iloc[campaign_index:].iterrows():
                    if pd.isnull(row[0]):
                        break
                    for attr_mb, attr_gsh in attribution.items():
                        if attr_gsh == row[0]:
                            gdf.iloc[index, max_cols] = get_campaign_info(df, trigger, attr_mb)
            except:
                continue
    return gdf

def get_attr_sum(gdf, channel, max_cols, attr):
    outlay = get_dict(dpath + 'outlay3.pkl')
    df = pd.DataFrame()
    if channel == 'Email':
        df = gdf.iloc[outlay['email']:outlay['wp']]
    elif channel == 'Web-push':
        df = gdf.iloc[outlay['wp']:outlay['seasonal']]
    elif channel == 'Сезонные триггеры':
        df = gdf.iloc[outlay['seasonal']:outlay['sms']]
    indices = df.iloc[:, 0].loc[df.iloc[:, 0].where(df.iloc[:, 0] == attr).notna()].index.values
    return sum(gdf.iloc[indices, max_cols])

class mainStats():
    def __init__(self, gdf, max_cols, channel, traffic):
        self.delivered = get_attr_sum(gdf, channel, max_cols, 'Доставлено')
        self.opened = get_attr_sum(gdf, channel, max_cols, 'Открытия')
        self.clicked = get_attr_sum(gdf, channel, max_cols, 'Кликов')
        self.revenue = get_attr_sum(gdf, channel, max_cols, 'Доход по атрибуции MB')
        self.orders = get_attr_sum(gdf, channel, max_cols, 'Покупок по атрибуции MB')
        self.openr = self.opened/self.delivered
        self.clickr = self.clicked/self.opened
        self.ord_traffic = self.orders/traffic
        self.ord_conversion = self.orders/self.delivered

    def switch(self, attr):
        d = {'Доставлено':         self.delivered,
             'OR':                 self.openr,
             'CR':                 self.clickr,
             'Выручка':            self.revenue,
             'Заказов':            self.orders,
             'Заказов от трафика': self.ord_traffic,
             'Конверсия в заказы': self.ord_conversion}
        return d[attr]

def fill_main(gdf, max_cols):
    """
    -> gdf: dataframe of main table
    """
    channels = ['Email', 'Web-push', 'Сезонные триггеры']

    def get_value_index(series, value):
        series = series.where(series == value)
        return series.loc[series.notnull()].index[0]

    for channel in channels:
        idx = get_value_index(gdf.iloc[:, 0], channel)+1
        stats = mainStats(gdf, max_cols, channel, 1)
        for ind, row in gdf.loc[idx:].iterrows():
            if pd.isnull(row[0]):
                break
            gdf.iloc[ind, max_cols] = stats.switch(row[0])
    return gdf

def build_format_patch(df, limit):
    """Returns new formats for gspread worksheet"""
    def create_format_dict(*args):
        fmt = nt('fmt', ['bold',
                         'italic',
                         'alignment',
                         'background'])
        return fmt(*args)

    main = create_format_dict(True, False, 'left', color(244/255, 204/255, 204/255))
    email = create_format_dict(True, True, 'left', color(255/255, 242/255, 204/255))
    wp = create_format_dict(True, True, 'left', color(208/255, 224/255, 227/255))
    seasonal = create_format_dict(True, True, 'left', color(217/255, 210/255, 233/255))
    sms = create_format_dict(True, True, 'left', color(201/255, 218/255, 248/255))

    main_idx = ['Email', 'Web-push', 'Сезонные триггеры']
    email_idx = get_dict_value('triggers.pkl', 2)['email'].values()
    wp_idx = get_dict_value('triggers.pkl', 2)['wp'].values()
    seasonal_idx = get_dict_value('triggers.pkl', 2)['seasonal'].values()
    sms_idx = get_dict_value('triggers.pkl', 2)['sms'].values()

    formats = [(main,     main_idx),
               (email,    email_idx),
               (wp,       wp_idx),
               (seasonal, seasonal_idx),
               (sms,      sms_idx),]

    def get_format_patch(fmt_, df, limit, ranges):
        def get_cell_format(_fmt):
            return cellFormat(backgroundColor=_fmt.background,
                   textFormat=textFormat(bold=_fmt.bold, italic=_fmt.italic),
                              horizontalAlignment=_fmt.alignment.upper())

        def get_fmt_ranges(df, row_vals, max_cols):
            def get_rows_to_a1(df, values, col):
                def locate_formats(series, row_val):
                    print(row_val)
                    return np.where(series == row_val)[0][0] + 2
                indices = [locate_formats(df.iloc[:, 0], x) for x in values]
                return [rowcol_to_a1(x, col) for x in indices]

            minr = get_rows_to_a1(df, row_vals, 1)
            maxr = get_rows_to_a1(df, row_vals, max_cols)
            ranges = []
            for x, y in zip(minr, maxr):
                ranges.append(x + ':' + y)
            return ranges

        (key, val) = fmt_
        _fmt = get_cell_format(key)
        new_ranges = get_fmt_ranges(df, val, limit)
        for range in new_ranges:
            ranges.append((range, _fmt))
    ranges = []
    for fmt in formats:
        get_format_patch(fmt, df, limit, ranges)
    return ranges


import logging
import sys
import os
import socket
import logging.handlers
import subprocess
import logging.config as lc

from autohdl.lib.decorator import decorator

LOGGING = {
  'version': 1,
  'disable_existing_loggers': True,
  'formatters': {
    'verbose': {
      'format': '%(asctime)s:%(filename)s:%(lineno)d:%(levelname)s:%(message)s'
    },
    'simple': {
      'format': '%(levelname)s: %(message)s'
    },
    },
  'handlers': {
    'consoleDebug': {
      'level': 'DEBUG',
      'class': 'logging.StreamHandler',
      'formatter': 'verbose'
    },
    'consoleInfo': {
      'level': 'INFO',
      'class': 'logging.StreamHandler',
      'formatter': 'simple'
    },
    'socket': {
      'level': 'DEBUG',
      'class': 'logging.handlers.SocketHandler',
      'host': 'localhost',
      'port': logging.handlers.DEFAULT_TCP_LOGGING_PORT,
    },
    },
  'loggers': {
    '': {
      'handlers': ['consoleInfo', 'socket'],
      'level': 'DEBUG',
      },
    }
}

lc.dictConfig(LOGGING)

s = socket.socket()  #socket.AF_INET, socket.SOCK_STREAM
# check if logging server up, else - run
if s.connect_ex(('localhost', logging.handlers.DEFAULT_TCP_LOGGING_PORT)): #9020
  path = os.path.dirname(__file__) + '/log_server.py'
  p = subprocess.Popen('pythonw '+ path)

class MyLogger(logging._loggerClass):
  def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
    """Let the caller modify any of the parameters"""
    record = logging.LogRecord(name, level, fn, lno, msg, args, exc_info, func)
    if extra:
      for key in extra:
        record.__dict__[key] = extra[key]
    return record

logging.setLoggerClass(MyLogger)

@decorator
def log_call(fn, *args, **kw):
  """Log calls to fn, reporting caller, args, and return value"""
  logger = logging.getLogger(fn.__module__)
  try:
    frame = sys._getframe(2)
    varnames = fn.func_code.co_varnames
    arglist = ', '.join([i[1]+'='+str(i[0]) for i in zip(args, varnames)])
    if kw:
      arglist += ', '.join(['{0}={1}'.format(k, v) for k, v in kw.viewitems()])

    logger.debug("%(func)s IN (%(args)s)" % (
        {'func': fn.__name__,
         'args': arglist,
         }),
                 extra={
                   'filename': os.path.split(frame.f_code.co_filename)[-1],
                   'pathname': frame.f_code.co_filename,
                   'lineno': frame.f_lineno,
                   'module': fn.__module__,
                   'funcName': fn.__name__})

    result = fn(*args, **kw)

  except Exception as e:
    logger.exception(e)
    logger.debug('crashed')
    raise
  else:
    logger.debug("%(func)s OUT %(ret)s" % (
        {'func': fn.__name__,
         'ret': str(result),
         }),
                 extra={
                   'filename': os.path.split(frame.f_code.co_filename)[-1],
                   'pathname': frame.f_code.co_filename,
                   'lineno': frame.f_lineno,
                   'module': fn.__module__,
                   'funcName': fn.__name__})

  return result


from curl.train import run_task
from softgym.registered_env import env_arg_dict
reward_scales = {
    'PassWater': 20.0,
    'PourWater': 20.0,
    'ClothFold': 50.0,
    'ClothFlatten': 50.0,
    'ClothDrop': 50.0,
    'RopeFlatten': 50.0,
}

clip_obs = {
    'PassWater': None,
    'PourWater': None,
    'ClothFold': (-3, 3),
    'ClothFlatten': (-2, 2),
    'ClothDrop': None,
    'RopeFlatten': None,
}

def get_lr_decay(env_name, obs_mode):
    if env_name == 'RopeFlatten' or (env_name == 'ClothFlatten' and obs_mode == 'cam_rgb'):
        return 0.01
    elif obs_mode == 'point_cloud':
        return 0.01
    else:
        return None

def get_actor_critic_lr(env_name, obs_mode):
    if env_name == 'ClothFold' or (env_name == 'RopeFlatten' and obs_mode == 'point_cloud'):
        if obs_mode == 'cam_rgb':
            return 1e-4
        else:
            return 5e-4
    if obs_mode == 'cam_rgb':
        return 3e-4
    else:
        return 1e-3

def get_alpha_lr(env_name, obs_mode):
    if env_name == 'ClothFold':
        return 2e-5
    else:
        return 1e-3

def main():
    import argparse
    parser = argparse.ArgumentParser()
    # Experiment
    parser.add_argument('--exp_name', default='CURL_SAC', type=str)
    parser.add_argument('--env_name', default='ClothFlatten')
    parser.add_argument('--log_dir', default='./data/curl/')
    parser.add_argument('--test_episodes', default=10, type=int)
    parser.add_argument('--seed', default=100, type=int)
    parser.add_argument('--save_tb', default=False)  # Save stats to tensorbard
    parser.add_argument('--save_video', default=True)
    parser.add_argument('--save_model', default=True)  # Save trained models

    # CURL
    parser.add_argument('--alpha_fixed', default=False, type=bool)  # Automatic tuning of alpha
    parser.add_argument('--init_temperature', default=0.1, type=float)
    parser.add_argument('--replay_buffer_capacity', default=100000)
    parser.add_argument('--batch_size', default=128)

    # Override environment arguments
    parser.add_argument('--env_kwargs_render', default=True, type=bool)  # Turn off rendering can speed up training
    parser.add_argument('--env_kwargs_camera_name', default='default_camera', type=str)
    parser.add_argument('--env_kwargs_observation_mode', default='key_point', type=str)  # Should be in ['key_point', 'cam_rgb', 'point_cloud']
    parser.add_argument('--env_kwargs_num_variations', default=1, type=int)

    args = parser.parse_args()

    args.algorithm = 'CURL'

    # Set env_specific parameters

    env_name = args.env_name
    obs_mode = args.env_kwargs_observation_mode
    args.actor_lr = args.critic_lr = get_actor_critic_lr(env_name, obs_mode)
    args.lr_decay = get_lr_decay(env_name, obs_mode)
    args.scale_reward = reward_scales[env_name]
    args.clip_obs = clip_obs[env_name] if obs_mode == 'key_point' else None
    args.env_kwargs = env_arg_dict[env_name]

    run_task(args.__dict__, args.log_dir, args.exp_name)

if __name__ == '__main__':
    main()


import torch
from utils.funcs import one_iter_joint_training_sim_fix_stoch_encoder, one_iter_rx_meta_tx_joint_sim_fix_stoch_encoder
from data_gen.data_set import channel_set_gen_AR
from utils.basic_funcs import reset_randomness

def multi_task_learning(args, tx_net,rx_net, h_list_meta, writer_meta_training, Noise, Noise_relax, Noise_feedback, PATH_before_adapt_rx_intermediate, PATH_before_adapt_tx_intermediate):
    meta_optimiser_tx = torch.optim.Adam(tx_net.parameters(), args.lr_meta_update)
    meta_optimiser_rx = torch.optim.Adam(rx_net.parameters(), args.lr_meta_update)
    h_list_train = h_list_meta[:args.num_channels_meta]

    if args.if_fix_random_seed:
        random_seed_init = args.random_seed + 99999
    else:
        pass
    previous_channel = None

    for epochs in range(args.num_epochs_meta_train):
        if epochs % 100 == 0:
            curr_path_rx = PATH_before_adapt_rx_intermediate + str(epochs)
            curr_path_tx = PATH_before_adapt_tx_intermediate + str(epochs)
            torch.save(rx_net.state_dict(), curr_path_rx)
            torch.save(tx_net.state_dict(), curr_path_tx)
            print('stochactic meta-learning epoch', epochs)
        first_loss_rx = 0
        second_loss_rx = 0
        first_loss_tx = 0
        second_loss_tx = 0
        iter_in_sampled_device = 0  # for averaging meta-devices
        for ind_meta_dev in range(args.tasks_per_metaupdate):
            if args.if_always_generate_new_meta_training_channels:
                if args.if_fix_random_seed:
                    reset_randomness(random_seed_init) # to make noise same as much as possible for joint and meta
                    random_seed_init += 1
                else:
                    pass
                if args.if_Rayleigh_channel_model_AR:
                    if epochs % args.keep_AR_period == 0:
                        h_var_dist = torch.distributions.uniform.Uniform(torch.FloatTensor([args.mul_h_var_min]), torch.FloatTensor([args.mul_h_var_max]))
                        mul_h_var = h_var_dist.sample()
                        if_reset_AR = True
                    else:
                        if_reset_AR = False
                    current_channel = channel_set_gen_AR(args.tap_num, previous_channel, args.rho, mul_h_var, if_reset_AR)  # num_channels = 1 since we are generating per channel
                    previous_channel = current_channel
                else:
                    raise NotImplementedError
            else:
                if args.if_fix_random_seed:
                    reset_randomness(random_seed_init) # to make noise same as much as possible for joint and meta
                    random_seed_init += 1
                else:
                    pass
                # during this, meta-gradients are accumulated
                channel_list_total = torch.randperm(len(h_list_train))  # sampling with replacement
                current_channel_ind = channel_list_total[
                    ind_meta_dev]  # randomly sample meta-batches (no rep. inside meta-batch)
                current_channel = h_list_train[current_channel_ind]

            if args.if_joint_training:
                iter_in_sampled_device, first_loss_curr_rx, first_loss_curr_tx, second_loss_curr_rx, second_loss_curr_tx = joint_training(args, iter_in_sampled_device,
                                                                                tx_net, rx_net,
                                                                                current_channel, Noise, Noise_relax, Noise_feedback)
            elif args.if_joint_training_tx_meta_training_rx:
                iter_in_sampled_device, first_loss_curr_rx, first_loss_curr_tx, second_loss_curr_rx, second_loss_curr_tx = maml_for_rx_joint_for_tx(
                    args, iter_in_sampled_device,
                    tx_net, rx_net,
                    current_channel, Noise, Noise_relax, Noise_feedback)
            else:  # maml
                raise NotImplementedError
            first_loss_rx = first_loss_rx + first_loss_curr_rx
            second_loss_rx = second_loss_rx + second_loss_curr_rx
            first_loss_tx = first_loss_tx + first_loss_curr_tx
            second_loss_tx = second_loss_tx + second_loss_curr_tx
        first_loss_tx = first_loss_tx / args.tasks_per_metaupdate
        second_loss_tx = second_loss_tx / args.tasks_per_metaupdate
        first_loss_rx = first_loss_rx / args.tasks_per_metaupdate
        second_loss_rx = second_loss_rx / args.tasks_per_metaupdate
        writer_meta_training.add_scalar('first rx loss', first_loss_rx, epochs)
        writer_meta_training.add_scalar('first tx loss', first_loss_tx, epochs)
        writer_meta_training.add_scalar('second rx loss', second_loss_rx, epochs)
        writer_meta_training.add_scalar('second tx loss', second_loss_tx, epochs)
        meta_optimiser_rx.zero_grad()
        meta_optimiser_tx.zero_grad()
        for f in rx_net.parameters():
            f.grad = f.total_grad.clone() / args.tasks_per_metaupdate
        for f in tx_net.parameters():
            f.grad = f.total_grad.clone() / args.tasks_per_metaupdate
        meta_optimiser_rx.step()  # Adam
        meta_optimiser_tx.step()  # Adam

def joint_training(args, iter_in_sampled_device, tx_net, rx_net, current_channel, Noise, Noise_relax, Noise_feedback):
    tx_net.zero_grad()
    rx_net.zero_grad()
    para_list_from_tx_net = list(map(lambda p: p[0], zip(tx_net.parameters())))
    para_list_from_rx_net = list(map(lambda p: p[0], zip(rx_net.parameters())))
    #### get gradients for joint training
    if_local_update = False
    remove_dependency_to_updated_para = False
    inner_loop = None # no need here, it is only for computing exact score function of tx meta-gradient

    if args.tx_rx_training_mode == 0:
        joint_grad_rx, joint_grad_tx, second_loss_curr_rx, second_loss_curr_tx = one_iter_joint_training_sim_fix_stoch_encoder(args, current_channel, Noise, Noise_relax, Noise_feedback,
                                                                              para_list_from_tx_net,
                                                                              para_list_from_rx_net,
                                                                              para_list_from_tx_net,
                                                                              para_list_from_rx_net,
                                                                              if_local_update,
                                                                              remove_dependency_to_updated_para,
                                                                              inner_loop)
    else:
        raise NotImplementedError

    ##### accumulate gradients for joint training over different channels
    ind_f_para_list = 0
    for f in rx_net.parameters():
        if iter_in_sampled_device == 0:
            f.total_grad = joint_grad_rx[ind_f_para_list].clone().detach()  # f.grad
        else:
            f.total_grad = f.total_grad + joint_grad_rx[ind_f_para_list].clone().detach()  # f.grad
        ind_f_para_list += 1

    ind_f_para_list = 0
    for f in tx_net.parameters():
        if iter_in_sampled_device == 0:
            f.total_grad = joint_grad_tx[ind_f_para_list].clone().detach()  # f.grad
        else:
            f.total_grad = f.total_grad + joint_grad_tx[ind_f_para_list].clone().detach()  # f.grad
        ind_f_para_list += 1
    iter_in_sampled_device = iter_in_sampled_device + 1

    return iter_in_sampled_device, second_loss_curr_rx, second_loss_curr_tx, second_loss_curr_rx, second_loss_curr_tx

def maml_for_rx_joint_for_tx(args, iter_in_sampled_device, tx_net, rx_net, current_channel, Noise, Noise_relax, Noise_feedback):
    tx_net.zero_grad()
    rx_net.zero_grad()
    para_list_from_tx_net = list(map(lambda p: p[0], zip(tx_net.parameters())))
    para_list_from_rx_net = list(map(lambda p: p[0], zip(rx_net.parameters())))

    ####here comes from ftn.
    if args.tx_rx_training_mode == 0:
        meta_grad_rx, joint_grad_tx, first_loss_curr_rx, first_loss_curr_tx, second_loss_curr_rx, second_loss_curr_tx = one_iter_rx_meta_tx_joint_sim_fix_stoch_encoder(args, current_channel, Noise, Noise_relax, Noise_feedback,
                                                        para_list_from_tx_net, para_list_from_rx_net)

    else:
        print('we have only 3 modes, 0, 1, 2 currently')
        raise NotImplementedError
    ##### accumulate meta-gradients over different channels (meta-training channels)
    ind_f_para_list = 0
    for f in rx_net.parameters():
        if iter_in_sampled_device == 0:
            f.total_grad = meta_grad_rx[ind_f_para_list].clone().detach()  # f.grad
        else:
            f.total_grad = f.total_grad + meta_grad_rx[ind_f_para_list].clone().detach()  # f.grad
        ind_f_para_list += 1
    ind_f_para_list = 0
    for f in tx_net.parameters():
        if iter_in_sampled_device == 0:
            f.total_grad = joint_grad_tx[ind_f_para_list].clone().detach()  # f.grad
        else:
            f.total_grad = f.total_grad + joint_grad_tx[ind_f_para_list].clone().detach()  # f.grad
        ind_f_para_list += 1
    iter_in_sampled_device = iter_in_sampled_device + 1

    return iter_in_sampled_device, first_loss_curr_rx, first_loss_curr_tx, second_loss_curr_rx, second_loss_curr_tx


# -*- encoding: utf-8 -*-
from django.contrib.auth.models import AbstractUser, Permission, Group
from django.contrib.sites.models import Site
from django.contrib.sites.managers import CurrentSiteManager
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from django.core.exceptions import PermissionDenied
from django.db.models.signals import m2m_changed
from django_countries.fields import CountryField
from django.utils.safestring import mark_safe
from django.utils.text import slugify
from django.conf import settings
from django.urls import reverse
from django.db import models

from localflavor.mx.models import MXRFCField, MXZipCodeField, MXCURPField
from mptt.models import MPTTModel, TreeForeignKey
from imagekit.models import ProcessedImageField
from imagekit.processors import ResizeToFill
from simple_history.models import HistoricalRecords

import datetime

from .vars import *

def permissions(VARS):
	permissions = []
	if not 'EXC_PERM' in VARS:
		VARS['EXC_PERM'] = []
	if not 'ALL' in  VARS['EXC_PERM']:
		if not 'DETAIL' in VARS['EXC_PERM']:
			permissions.append(('Can_Detail__'+VARS['MODEL'],'Ve lista de '+VARS['VERBOSE_NAME_PLURAL'].lower()))
		if not 'CREATE' in VARS['EXC_PERM']:
			permissions.append(('Can_Create__'+VARS['MODEL'],'Crea '+VARS['VERBOSE_NAME_PLURAL'].lower()))
		if not 'UPDATE' in VARS['EXC_PERM']:
			permissions.append(('Can_Update__'+VARS['MODEL'],'Modifica '+VARS['VERBOSE_NAME_PLURAL'].lower()))
		if not 'DELETE' in VARS['EXC_PERM']:
			permissions.append(('Can_Delete__'+VARS['MODEL'],'Elimina '+VARS['VERBOSE_NAME_PLURAL'].lower()))
	if 'EXT_PERM' in VARS:
		for perm in VARS['EXT_PERM']:
			permissions.append(perm)
	return permissions

VARS = {
	'VERBOSE_NAME':'',
	'VERBOSE_NAME_PLURAL':'',
	'MODEL':'',
	'NEW':'',
	'GENDER_NEW':'',
	'GENDER_THIS':'',
	'APP':APP,
	'EXC_PERM': ['ALL'],
	'EXT_PERM': [],
	'QUERY':{
		'query':[
			(
				('pk','self.request.session.get("organization")).get_descendants(include_self=True)'),
			)
		],
	},
	'SERIALIZER': ['field'],
	'RULES': """
		email: {
			required: !0,
			email: !0,
			minlength: 10
		},
		url: {
			required: !0
		},
		digits: {
			required: !0,
			digits: !0
		},
		creditcard: {
			required: !0,
			creditcard: !0
		},
		phone: {
			required: !0,
			phoneUS: !0
		},
		option: {
			required: !0
		},
		options: {
			required: !0,
			minlength: 2,
			maxlength: 4
		},
		memo: {
			required: !0,
			minlength: 10,
			maxlength: 100
		},
		checkbox: {
			required: !0
		},
		checkboxes: {
			required: !0,
			minlength: 1,
			maxlength: 2
		},
		radio: {
			required: !0
		}
	""",
}
class Model_base(models.Model):
	slug = models.SlugField(blank=True, null=True)
	active = models.BooleanField(default=True)
	VARS = VARS
	class Meta:
		default_permissions = ()
		verbose_name = VARS['VERBOSE_NAME']
		verbose_name_plural = VARS['VERBOSE_NAME_PLURAL']
		permissions = permissions(VARS)
		abstract = True
		ordering = ['-id']
	def str_obj(self):
		return str(self)
	def str_select2(self):
		return self.str_obj()
	def add_text(self):
		return self.VARS['NEW']+" "+self.VARS['VERBOSE_NAME'].upper(),"Agregar "+self.VARS['VERBOSE_NAME'].lower(),"Agrega "+self.VARS['GENDER_NEW']+" "+self.VARS['VERBOSE_NAME'].lower()+"al sistema"
	def edit_text(self):
		return "EDITAR "+self.VARS['VERBOSE_NAME'].upper(),"Editar "+self.VARS['VERBOSE_NAME'].lower(),"Edita los datos de "+self.VARS['GENDER_THIS']+" "+self.VARS['VERBOSE_NAME'].lower()+"al sistema"
	def delete_text(self):
		return "ELIMINAR "+ self.VARS['VERBOSE_NAME'].upper(),"Eliminar "+self.VARS['VERBOSE_NAME'].lower(),"Elimina los datos de "+self.VARS['GENDER_THIS']+" "+self.VARS['VERBOSE_NAME'].lower(),"Se eliminará "+self.VARS['GENDER_THIS']+" "+self.VARS['VERBOSE_NAME'].lower()+" y todos sus datos asociados!"
	def url_list(self):
		try:
			return reverse(self.VARS['APP']+':'+self.VARS['MODEL']+'_ListView')
		except:
			return ''
	def url_add(self):
		try:
			return reverse(self.VARS['APP']+':'+self.VARS['MODEL']+'_CreateView')
		except:
			return ''
	def url_update(self):
		try:
			return reverse(self.VARS['APP']+':'+self.VARS['MODEL']+'_UpdateView',kwargs={'pk': self.pk})
		except:
			return ''
	def url_detail(self):
		try:
			return reverse(self.VARS['APP']+':'+self.VARS['MODEL']+'_DetailView',kwargs={'pk': self.pk})
		except:
			return ''
	def url_delete(self):
		try:
			return reverse(self.VARS['APP']+':'+self.VARS['MODEL']+'_DeleteView',kwargs={'pk': self.pk})
		except:
			return ''
	################################
	################################
	def render_boolean(self, field):
		if field:
			return ''
		else:
			return ''
	def render_color_boolean(self, field):
		if field:
			return 'success'
		else:
			return 'danger'
	def render_boolean_del(self, text, attr):
		if not attr:
			return '<s>{0}</s>'.format(text)
		return text
	def render_color(self, field):
		return ''
	def render_list(self, list, attr):
		string = ''
		if not list.all():
			return '-'
		for l in list.all():
			string += getattr(l, attr) + ', '
		return string[0:len(string)-2]
	def render_ifnot(self, attr):
		if not attr:
			return '-'
		return attr
	def render_ifnot_link(self, attr):
		if not attr:
			return '-'
		return str(self.attr)
	def render_date(self, attr):
		return attr.strftime('%d/%m/%Y')
	def get_select2(self):
		return self.name
	def max_string(self, field, value):
		string = getattr(self, field)[0:value]
		if len(getattr(self, field)) > value:
			string += '...'
		return string

	################################
	################################
	def my_organization(self):
		return self.organization


# AS37

vowels = ["a", "e", "i", "o", "u"]

def code(string):
    for i in range(0, len(string)):
        if string[i] not in vowels:
            string[i] = string[i] + "o" + string[i]
    return string

string = list(input("Input message"))
print(string)
print("".join(code(string)))


##encoding=utf8
##version =py27, py33
##author  =sanhe
##date    =2014-10-15

from __future__ import print_function

from HSH.Data.iterable import cycle_running_windows, cycle_slice
from HSH.DataSci.stat import clear_outlier_onetime
import numpy as np, pandas as pd
import matplotlib.pyplot as plt
from collections import deque
from itertools import count

def fetch_ith(i):
    """return the i th sample
    """
    data = pd.read_csv("raw_data.csv", index_col = 0)
    return data.iloc[i]

def generator_backward_forward_running_average(array, window_size):
    """
    array = [1,2,3,4,5,6,7,8,9,10]
    for value, backward_running_average, forward_running_average in g_b_f_r_a(array, 3):
        yield 1, (8+9+10)/3, (2+3+4)/3
        yield 2, (9+10+1)/3, (3+4+5)/3
        ...
    """
    before, after = deque(array), deque(array)
    before.rotate(window_size)
    after.rotate(-1)
    for value, before_window, after_window in zip(array,
                                                  cycle_running_windows(before, window_size),
                                                  cycle_running_windows(after, window_size)):
        yield value, float(sum(before_window))/window_size, float(sum(after_window))/window_size

def backward_range(start, n, cycle_size):
    """backward generate #n integers start from #start-1.
    from cycle [0, 1, 2, ..., #cycle_size-1]
    e.g.
        backward_range(5, 2, 10) -> [3, 4]
        backward_range(3, 5, 10) -> [8, 9, 0, 1, 2]
    """
    if start >= n:
        return list(range(start - n, start))
    else:
        return list(range(cycle_size + start - n, cycle_size)) + list(range(start))

def forward_range(start, n, cycle_size):
    """forward generate #n integers start from #start+1.
    from cycle [0, 1, 2, ..., #cycle_size-1]
    e.g.
        forward_range(5, 3, 10) -> [6, 7, 8]
        forward_range(7, 5, 10) -> [8, 9, 0, 1, 2]
    """
    if start + n <= cycle_size - 1:
        return range(start + 1, start + 1 + n)
    else:
        return list(range(start + 1, cycle_size)) + list(range(start + 1 + n - cycle_size))

def merge_setpoints(array, k, size):
    """
    Because for every setpoints, it take time to taken effects.
    So we merge setpoints to the earliest one. (backward merge)
    """
    array_set = set(array) # create a set copy. make examing is in faster
    res = list()
    for i in array:
        flag = 1 # 在一开始，总认为这个setpoint是不需要merge的
        for j in backward_range(i, k, size): # 对于i之前的k个setpoint
            if j in array_set: # 只要有1个也是setpoint，那么这个就可以被merge到前面去
                flag = 0
                break
        if flag:
            res.append(i)
    return res

def produce_by_setpoint(setpoint_indices, setpoint_values, length):
    """generate rectangle wave by set points
    e.g. produce_by_setpoint([4, 7], [1.1, 3.3], 10)
    [3.3, 3.3, 3.3, 3.3, ]
    """
    res = deque()
    number_of_setpoints = len(setpoint_indices)
    for i in range(length):
        ind = (sum(np.linspace(i,i,number_of_setpoints) > setpoint_indices ) - 1) % number_of_setpoints
        res.append(setpoint_values[ind])
    res.rotate(-2)
    return list(res)

def main(window_size = 6, k = 8):
    """
    [Parameters]
    ------------
    window_size: running average window size
    k: the second parameters in merge_setpoints(array, k, size)
    """
    ### Initial dataset
    sample = fetch_ith(68).values.tolist() # fetch the ith sample
    e = abs(np.diff(sample)).std()*1 # delta_before criterion
    c = count() # sample index counter
    potential_setpoint_indices_rise = list()

    for value, mean_before, mean_after in generator_backward_forward_running_average(sample, window_size):
        counter = next(c)
        dt_before, dt_after = value - mean_before, mean_after - value

        if abs(dt_before) >= e:
            potential_setpoint_indices_rise.append(counter)

    print("e = %s" % e) # 门限
    print(potential_setpoint_indices_rise)
    setpoint_indices = merge_setpoints(potential_setpoint_indices_rise, k, 96)
    setpoint_values = list()
    for i, j in cycle_running_windows(setpoint_indices, 2): # 计算均值
        setpoint_values.append(
                               np.mean(
                                       clear_outlier_onetime(
                                                             cycle_slice(sample, i, j)
                                                             )
                                       )
                               )

    step_func = produce_by_setpoint(setpoint_indices, setpoint_values, 96)
    print(setpoint_indices, setpoint_values, 96)

    plt.plot(sample)
    plt.plot(step_func)
    plt.show()

if __name__ == "__main__":
    main(window_size = 6, k = 8)


"""
Plotting utilities to visualize training logs.
"""
import torch
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

from pathlib import Path, PurePath

def plot_logs(logs, fields=('class_error', 'loss_bbox_unscaled', 'mAP'), ewm_col=0, log_name='log.txt'):
    '''
    Function to plot specific fields from training log(s). Plots both training and test results.

    :: Inputs - logs = list containing Path objects, each pointing to individual dir with a log file
              - fields = which results to plot from each log file - plots both training and test for each field.
              - ewm_col = optional, which column to use as the exponential weighted smoothing of the plots
              - log_name = optional, name of log file if different than default 'log.txt'.

    :: Outputs - matplotlib plots of results in fields, color coded for each log file.
               - solid lines are training results, dashed lines are test results.

    '''
    func_name = "plot_utils.py::plot_logs"

    # verify logs is a list of Paths (list[Paths]) or single Pathlib object Path,
    # convert single Path to list to avoid 'not iterable' error

    if not isinstance(logs, list):
        if isinstance(logs, PurePath):
            logs = [logs]
            print(f"{func_name} info: logs param expects a list argument, converted to list[Path].")
        else:
            raise ValueError(f"{func_name} - invalid argument for logs parameter.\n \
            Expect list[Path] or single Path obj, received {type(logs)}")

    # Quality checks - verify valid dir(s), that every item in list is Path object, and that log_name exists in each dir
    for i, dir in enumerate(logs):
        if not isinstance(dir, PurePath):
            raise ValueError(f"{func_name} - non-Path object in logs argument of {type(dir)}: \n{dir}")
        if not dir.exists():
            raise ValueError(f"{func_name} - invalid directory in logs argument:\n{dir}")
        # verify log_name exists
        fn = Path(dir / log_name)
        if not fn.exists():
            print(f"-> missing {log_name}.  Have you gotten to Epoch 1 in training?")
            print(f"--> full path of missing log file: {fn}")
            return

    # load log file(s) and plot
    dfs = [pd.read_json(Path(p) / log_name, lines=True) for p in logs]

    fig, axs = plt.subplots(ncols=len(fields), figsize=(16, 5))

    for df, color in zip(dfs, sns.color_palette(n_colors=len(logs))):
        for j, field in enumerate(fields):
            if field == 'mAP':
                coco_eval = pd.DataFrame(
                    np.stack(df.test_coco_eval_bbox.dropna().values)[:, 1]
                ).ewm(com=ewm_col).mean()
                axs[j].plot(coco_eval, c=color)
            else:
                df.interpolate().ewm(com=ewm_col).mean().plot(
                    y=[f'train_{field}', f'test_{field}'],
                    ax=axs[j],
                    color=[color] * 2,
                    style=['-', '--']
                )
    for ax, field in zip(axs, fields):
        ax.legend([Path(p).name for p in logs])
        ax.set_title(field)

def plot_precision_recall(files, naming_scheme='iter'):
    if naming_scheme == 'exp_id':
        # name becomes exp_id
        names = [f.parts[-3] for f in files]
    elif naming_scheme == 'iter':
        names = [f.stem for f in files]
    else:
        raise ValueError(f'not supported {naming_scheme}')
    fig, axs = plt.subplots(ncols=2, figsize=(16, 5))
    for f, color, name in zip(files, sns.color_palette("Blues", n_colors=len(files)), names):
        data = torch.load(f)
        # precision is n_iou, n_points, n_cat, n_area, max_det
        precision = data['precision']
        recall = data['params'].recThrs
        scores = data['scores']
        # take precision for all classes, all areas and 100 detections
        precision = precision[0, :, :, 0, -1].mean(1)
        scores = scores[0, :, :, 0, -1].mean(1)
        prec = precision.mean()
        rec = data['recall'][0, :, 0, -1].mean()
        print(f'{naming_scheme} {name}: mAP@50={prec * 100: 05.1f}, ' +
              f'score={scores.mean():0.3f}, ' +
              f'f1={2 * prec * rec / (prec + rec + 1e-8):0.3f}'
              )
        axs[0].plot(recall, precision, c=color)
        axs[1].plot(recall, scores, c=color)

    axs[0].set_title('Precision / Recall')
    axs[0].legend(names)
    axs[1].set_title('Scores / Recall')
    axs[1].legend(names)
    return fig, axs

# COCO classes
CLASSES_COCO = [
    'N/A', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
    'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A',
    'stop sign', 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse',
    'sheep', 'cow', 'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack',
    'umbrella', 'N/A', 'N/A', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis',
    'snowboard', 'sports ball', 'kite', 'baseball bat', 'baseball glove',
    'skateboard', 'surfboard', 'tennis racket', 'bottle', 'N/A', 'wine glass',
    'cup', 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich',
    'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', 'donut', 'cake',
    'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table', 'N/A',
    'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard',
    'cell phone', 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A',
    'book', 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier',
    'toothbrush'
]

# colors for visualization
COLORS = [[0.000, 0.447, 0.741], [0.850, 0.325, 0.098], [0.929, 0.694, 0.125],
          [0.494, 0.184, 0.556], [0.466, 0.674, 0.188], [0.301, 0.745, 0.933]]

def plot_bbox_results(pil_img, prob, boxes, savepath=None, id2name=None):
    plt.figure(figsize=(16,10))
    plt.imshow(pil_img)
    ax = plt.gca()
    for p, (xmin, ymin, xmax, ymax), c in zip(prob, boxes.tolist(), COLORS * 100):
        ax.add_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin,
                                   fill=False, color=c, linewidth=3))
        cl = p.argmax()
        if id2name is None:
            text = f'{CLASSES_COCO[cl]}: {p[cl]:0.2f}'
        else:
            cl = cl.item()
            text = f'{id2name[cl]}: {p[cl]:0.2f}'
        ax.text(xmin, ymin, text, fontsize=15,
                bbox=dict(facecolor='yellow', alpha=0.5))
    plt.axis('off')
    if savepath is None:
        plt.show()
    else:
        plt.savefig(savepath)


import pyttsx3
import pyaudio
import speech_recognition as sr
import  sys, os

def takeCommand():
    #it takes microphone input from usre and returnn string output
    r=sr.Recognizer()
    with sr.Microphone() as source:
        print("listening..")
        r.pause_threshold = 1
        audio=r.listen(source)

    try:
         print("Recognizing...")
         query=r.recognize_google(audio,language='en-in')
         print("user said:",query)
    except Exception as e:
          print(e)

          print("Say that again ")
          return "None"
    return query

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
print(voices)
engine.setProperty('voice',voices[0].id)
engine.setProperty('rate', 150)
engine.setProperty('volume', 0.9)

def speak(audio):

    engine.say(audio)

    engine.runAndWait()


"""Event model module"""
from django.db import models

class Event(models.Model):
    """Event database model"""
    gamer = models.ForeignKey("Gamer", on_delete=models.CASCADE)
    description = models.CharField(max_length=75)
    game = models.ForeignKey("Game", on_delete=models.CASCADE)
    date = models.DateField(auto_now=False, auto_now_add=False)
    time = models.TimeField(auto_now=False, auto_now_add=False)


class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        def __dfs(idx, res, pre, nums):
            if not idx:
                res.append(pre[:])
                return
            temp = idx.copy()
            for i in temp:
                pre.append(nums[i])
                idx.remove(i)
                __dfs(idx, res, pre, nums)
                idx.append(i)
                pre.pop()

        idx = []
        res = []
        pre = []
        for i in range(len(nums)):
            idx.append(i)
        __dfs(idx, res, pre, nums)
        return res

from typing import List

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        def dfs(nums, size, depth, path, state, res):
            if depth == size:
                res.append(path)
                return

            for i in range(size):
                if ((state >> i) & 1) == 0:
                    dfs(nums, size, depth + 1, path + [nums[i]], state ^ (1 << i), res)

        size = len(nums)
        if size == 0:
            return []

        state = 0
        res = []
        dfs(nums, size, 0, [], state, res)
        return res


import csv

ADDRESS_CSV_PATH="/home/coder-hex/Desktop/OpenSource/cohort_3/submissions/sm_108_krishna-kant/week_16/day_4/assignment/server/database/address.csv"
USER_CSV_PATH="/home/coder-hex/Desktop/OpenSource/cohort_3/submissions/sm_108_krishna-kant/week_16/day_4/assignment/server/database/users.csv"

def edit_address(user_id,id,line_1,line_2,city,pincode,task_type):
    address_data = read_address()
    updated_address = {"id":id,"user_id":user_id,"line_1":line_1,"line_2":line_2,"city":city,"pincode":pincode}
    for i in range(len(address_data)):
        if address_data[i]['user_id'] == user_id and address_data[i]['id'] == id:
            if task_type == "edit":
                address_data[i] = updated_address
            elif task_type == "delete":
                updated_address = address_data.pop(i)
                break
    with open(ADDRESS_CSV_PATH,"w") as addresscsv:
        fieldsname = ['id','user_id','line_1','line_2','city','pincode']
        writer = csv.DictWriter(addresscsv,fieldnames=fieldsname)
        writer.writeheader()
        for row in address_data:
            writer.writerow(row)
        return updated_address

def edit_user(user_id,name,email,mobile,task_type):
    user_data = read_user()
    updated_user = {"id":user_id,"name":name,"mobile":mobile,"email":email}
    for i in range(len(user_data)):
        if user_data[i]['id'] == user_id:
            if task_type == 'edit':
                user_data[i] = updated_user
            elif task_type == "delete":
                user_data.pop(i)
                break
    with open(USER_CSV_PATH,"w") as usercsv:
        fieldnames = ['id','name','mobile','email']
        writer = csv.DictWriter(usercsv,fieldnames=fieldnames)
        writer.writeheader()
        for row in user_data:
            writer.writerow(row)
    return updated_user

def get_user(user_id):
    user_data = read_user()
    address = read_address()
    user_details = {}
    for row in user_data:
        if row["id"] == user_id:
            user_details = row
    address_list = []
    for row in address:
        if row["user_id"] == user_id:
            print(row["user_id"])
            address_list.append(row)
    user_details["address"] = address_list
    return user_details

def write_user(id,name,mobile,email):
    user_data = {"id":id,"name":name,"mobile":mobile,"email":email}
    with open(USER_CSV_PATH,'a') as usercsv:
        fieldnames = ['id','name','mobile','email']
        writer = csv.DictWriter(usercsv,fieldnames=fieldnames)
        writer.writerow(user_data)
    return user_data

def write_address(id,user_id,line_1,line_2,city,pincode):
    address_data = {"id":id,"user_id":user_id,"line_1":line_1,"line_2":line_2,"city":city,"pincode":pincode}
    with open(ADDRESS_CSV_PATH , 'a') as addresscsv:
        fieldsname = ['id','user_id','line_1','line_2','city','pincode']
        writer = csv.DictWriter(addresscsv,fieldnames=fieldsname)
        writer.writerow(address_data)
    return address_data

def read_address():
    address = []
    with open(ADDRESS_CSV_PATH) as addresscsv:
        reader = csv.DictReader(addresscsv)
        for row in reader:
            address.append(row)
    return address

def read_user():
    user_data = []
    with open(USER_CSV_PATH) as usercsv:
        reader = csv.DictReader(usercsv)
        for row in reader:
            user_data.append(row)
    return user_data


def seatnum(seatcode):
    bitmul = [64,32,16,8,4,2,1,4,2,1]
    string = [1 if c in ['B','R'] else 0 for c in seatcode]

    result = []
    for char,bit in zip(string, bitmul):
        result.append(char*bit)

    row = sum(result[:7])
    col = sum(result[7:])

    return row * 8 + col

list = []
with open('inputs/day5','r') as f:
    for line in f:
        list.append(line)

seats_taken = []
for line in list:
    seats_taken.append(seatnum(line))

## PART 1
max(seats_taken)

## PART 2
all_seats = range(min(seats_taken), max(seats_taken)+1)
print(sum(all_seats) - sum(seats_taken))


import turtle, math, random
turtle.setup(1000,400)
wn=turtle.Screen()
bird=turtle.Turtle()
t1=turtle.Turtle()
t2=turtle.Turtle()
t1.color("red")
t2.color("red")

def setbird():
    bird.setpos(-400,0)
    bird.dy = 0
def flyingturtlemove():
    fall=bird.ycor() + bird.dy
    bird.goto(bird.xcor(),fall)
    if bird.dy>-4:
        bird.dy -= .1 #gravity
    if bird.ycor()> 190:
        bird.dy=-1

# how the flying turtle moves

def fn_up():
    if bird.dy<3:
        if bird.dy<-2:
            bird.dy += 5 #amount the bird jumps

        if bird.dy>-2:
            bird.dy += 4

# Make turtle jump

def newenemyturtle():
    r=random.randint(-190,90)
    t1.goto(200,r)
    t2.goto(200,r+100)

# spawn 2 new enemy turtles (one 20 above the other
# send turtles to the left at a constant speed
def enemyturtlemove():
    t1.goto(t1.xcor()-5,t1.ycor())
    t2.goto(t2.xcor()-5, t2.ycor())

def gameloop():
    while t1.xcor()> -450:
        flyingturtlemove()
        enemyturtlemove()
    else:
        if bird.ycor()> t1.ycor() and bird.ycor()< t2.ycor(): #if the bird goes through the gate
            newenemyturtle()

        if bird.ycor()< t1.ycor() or bird.ycor()> t2.ycor(): #outside

            wn.bye()
            print("you lose")

    wn.ontimer(gameloop, 10)

# main loop of the game

wn.listen()
wn.onkey(fn_up, "space")
bird.penup()
t1.penup()
t2.penup()
newenemyturtle()
setbird()
wn.ontimer(gameloop,10)
wn.mainloop()

2017-Projects/4e Aquilla Flappy Bird/milestone 3.py


# -*- coding: utf-8 -*-
'''
说明：
对称加密(明文 <==(key)==> 密文)

安装：
pip install cryptography

参考：
https://cryptography.io/en/latest/installation/
https://pythonguidecn.readthedocs.io/zh/latest/scenarios/crypto.html
https://zhuanlan.zhihu.com/p/25278582
'''
from cryptography.fernet import Fernet

# 生成秘钥（bytes）
key = Fernet.generate_key()
# 秘钥类型转文本（bytes->str，一般存储到配置文件）
key_str = key.decode('ascii', 'ignore')

# 文本秘钥转bytes(一般是从配置文件读取，为实例化密码器做准备)
key = key_str.encode('ascii', 'ignore')
# 实例化密码组（密码器）
cipher_suite = Fernet(key)
# --------------------------------------------------------------
# 原始数据(str)
raw_data = '这里是原始数据, Life is short, use Python. 1989,1991'
# 原始数据类型转成bytes，为加密作准备
data = raw_data.encode('utf-8', 'ignore')

# 加密（得到密文，bytes）
cipher_text = cipher_suite.encrypt(data)
# 将密文类型转成str（一般用于网络传输）
cipher_text_str = cipher_text.decode('ascii', 'ignore')
# --------------------------------------------------------------
# 密码从文本转成bytes，为解密做准备
cipher_text = cipher_text_str.encode('ascii', 'ignore')
# 解密（得到明文，bytes）

plain_text = cipher_suite.decrypt(cipher_text)
# 将明文类型转为str（一般用于页面显示、数据库查询参数等）
plain_text_str = plain_text.decode('utf-8', 'ignore')


import numpy as np
import matplotlib.pyplot as plt

def relu_func(x):
	if x <= 0:
		return 0
	else:
		return x

def relu_array(x):
	y = []
	for item in x:
		y.append(relu_func(item))
	return y

x = np.arange(-10., 10., 0.2)
sig = relu_array(x)

plt.plot(x, sig)
plt.show()