import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy.stats import binom
from sklearn.calibration import calibration_curve
from sklearn.metrics import r2_score, confusion_matrix

def true_vs_estimated(theta_true, theta_est, param_names, dpi=300,
                      figsize=(20, 4), show=True, filename=None, font_size=12):
    """ Plots a scatter plot with abline of the estimated posterior means vs true values.

    Parameters
    ----------
    theta_true: np.array
        Array of true parameters.
    theta_est: np.array
        Array of estimated parameters.
    param_names: list(str)
        List of parameter names for plotting.
    dpi: int, default:300
        Dots per inch (dpi) for the plot.
    figsize: tuple(int, int), default: (20,4)
        Figure size.
    show: boolean, default: True
        Controls if the plot will be shown
    filename: str, default: None
        Filename if plot shall be saved
    font_size: int, default: 12
        Font size

    """

    # Plot settings
    plt.rcParams['font.size'] = font_size

    # Determine n_subplots dynamically
    n_row = int(np.ceil(len(param_names) / 6))
    n_col = int(np.ceil(len(param_names) / n_row))

    # Initialize figure
    f, axarr = plt.subplots(n_row, n_col, figsize=figsize)
    if n_row > 1:
        axarr = axarr.flat

    # --- Plot true vs estimated posterior means on a single row --- #
    for j in range(len(param_names)):

        # Plot analytic vs estimated
        axarr[j].scatter(theta_est[:, j], theta_true[:, j], color='black', alpha=0.4)

        # get axis limits and set equal x and y limits
        lower_lim = min(axarr[j].get_xlim()[0], axarr[j].get_ylim()[0])
        upper_lim = max(axarr[j].get_xlim()[1], axarr[j].get_ylim()[1])
        axarr[j].set_xlim((lower_lim, upper_lim))
        axarr[j].set_ylim((lower_lim, upper_lim))
        axarr[j].plot(axarr[j].get_xlim(), axarr[j].get_xlim(), '--', color='black')

        # Compute NRMSE
        rmse = np.sqrt(np.mean( (theta_est[:, j] - theta_true[:, j])**2 ))
        nrmse = rmse / (theta_true[:, j].max() - theta_true[:, j].min())
        axarr[j].text(0.1, 0.9, 'NRMSE={:.3f}'.format(nrmse),
                     horizontalalignment='left',
                     verticalalignment='center',
                     transform=axarr[j].transAxes,
                     size=10)

        # Compute R2
        r2 = r2_score(theta_true[:, j], theta_est[:, j])
        axarr[j].text(0.1, 0.8, '$R^2$={:.3f}'.format(r2),
                     horizontalalignment='left',
                     verticalalignment='center',
                     transform=axarr[j].transAxes,
                     size=10)

        if j == 0:
            # Label plot
            axarr[j].set_xlabel('Estimated')
            axarr[j].set_ylabel('True')
        axarr[j].set_title(param_names[j])
        axarr[j].spines['right'].set_visible(False)
        axarr[j].spines['top'].set_visible(False)

    # Adjust spaces
    f.tight_layout()

    if show:
        plt.show()

    if filename is not None:
        f.savefig(filename)

def plot_sbc(theta_samples, theta_test, param_names, bins=25, dpi=300,
            figsize=(24, 12), interval=0.99, show=True, font_size=12):
    """ Plots the simulation-based posterior checking histograms as advocated by Talts et al. (2018).

    Parameters
    ----------
    theta_samples: np.array
        Array of sampled parameters
    theta_test: np.array
        Array of test parameters
    param_names: list(str)
        List of parameter names for plotting.
    bins: int, default: 25
        Bins for histogram plot
    dpi: int, default: 300
        Dots per inch (dpi) for plot
    figsize: tuple(int, int), default: (24, 12)
        Figure size
    interval: float, default: 0.99
        Interval to plot
    show: bool, default: True
        Controls whether the plot shall be printed
    font_size: int, default:12
        Font size

    """

    # Plot settings
    plt.rcParams['font.size'] = font_size
    N = int(theta_test.shape[0])

    # Determine n_subplots dynamically
    n_row = int(np.ceil(len(param_names) / 6))
    n_col = int(np.ceil(len(param_names) / n_row))

    # Initialize figure
    f, axarr = plt.subplots(n_row, n_col, figsize=figsize)
    if n_row > 1:
        axarr = axarr.flat

    # Compute ranks (using broadcasting)
    ranks = np.sum(theta_samples < theta_test, axis=0)

    # Compute interval
    endpoints = binom.interval(interval, N, 1 / (bins+1))

    # Plot histograms
    for j in range(len(param_names)):

        # Add interval
        axarr[j].axhspan(endpoints[0], endpoints[1], facecolor='gray', alpha=0.3)
        axarr[j].axhline(np.mean(endpoints), color='gray', zorder=0, alpha=0.5)

        sns.histplot(ranks[:, j], kde=False, ax=axarr[j], color='#a34f4f', bins=bins, alpha=0.95)

        axarr[j].set_title(param_names[j])
        axarr[j].spines['right'].set_visible(False)
        axarr[j].spines['top'].set_visible(False)
        if j == 0:
            axarr[j].set_xlabel('Rank statistic')
        axarr[j].get_yaxis().set_ticks([])
        axarr[j].set_ylabel('')

    f.tight_layout()

    # Show, if specified
    if show:
        plt.show()
    return f

def plot_confusion_matrix(m_true, m_pred, model_names, normalize=False,
                          cmap=plt.cm.Blues, figsize=(14, 8), annotate=True, show=True):
    """A function to print and plots the confusion matrix. Normalization can be applied by setting `normalize=True`.

    Parameters
    ----------
    m_true: np.array
        Array of true model indices
    m_pred: np.array
        Array of predicted model indices
    model_names: list(str)
        List of model names for plotting
    normalize: bool, default: False
        Controls whether normalization shall be applied
    cmap: matplotlib.pyplot.cm.*, default: plt.cm.Blues
        Colormap
    figsize: tuple(int, int), default: (14, 8)
        Figure size
    annotate: bool, default: True
        Controls if the plot shall be annotated
    show: bool, default: True
        Controls if the plot shall be printed

    """

    # Take argmax of test
    m_true = np.argmax(m_true.numpy(), axis=1).astype(np.int32)

    # Compute confusion matrix
    cm = confusion_matrix(m_true, m_pred)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]

    fig, ax = plt.subplots(figsize=figsize)
    im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
    ax.figure.colorbar(im, ax=ax)
    # We want to show all ticks...
    ax.set(xticks=np.arange(cm.shape[1]),
           yticks=np.arange(cm.shape[0]),
           xticklabels=model_names, yticklabels=model_names,
           ylabel='True Model',
           xlabel='Predicted Model')

    # Rotate the tick labels and set their alignment.
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
             rotation_mode="anchor")

    # Loop over data dimensions and create text annotations.

    if annotate:
        fmt = '.2f' if normalize else 'd'
        thresh = cm.max() / 2.
        for i in range(cm.shape[0]):
            for j in range(cm.shape[1]):
                ax.text(j, i, format(cm[i, j], fmt),
                        ha="center", va="center",
                        color="white" if cm[i, j] > thresh else "black")
    fig.tight_layout()

    if show:
        plt.show()
    return fig

def plot_expected_calibration_error(m_true, m_pred, n_bins=15):
    """Estimates the calibration error of a model comparison neural network.

    Important
    ---------
    Make sure that ``m_true`` are **one-hot encoded** classes!

    Parameters
    ----------
    m_true: np.array or list
        True model indices
    m_pred: np.array or list
        Predicted model indices
    n_bins: int, default: 15
        Number of bins for plot
    """

    # Convert tf.Tensors to numpy, if passed
    if type(m_true) is not np.ndarray:
        m_true = m_true.numpy()
    if type(m_pred) is not np.ndarray:
        m_pred = m_pred.numpy()

    # Extract number of models and prepare containers
    n_models = m_true.shape[1]
    cal_errs = []
    probs = []

    # Loop for each model and compute calibration errs per bin
    for k in range(n_models):

        y_true = (m_true.argmax(axis=1) == k).astype(np.float32)
        y_prob = m_pred[:, k]
        prob_true, prob_pred = calibration_curve(y_true, y_prob, n_bins=n_bins)

        cal_err = np.mean(np.abs(prob_true - prob_pred))
        cal_errs.append(cal_err)
        probs.append((prob_true, prob_pred))

    return np.array(cal_errs), np.array(probs)

def plot_calibration_curves(cal_probs, cal_errs, model_names, font_size=12, figsize=(12, 4)):
    """Plots the calibration curves for a model comparison problem.

    Parameters
    ----------
    cal_probs: np.array
        Currently not used
    cal_errs: np.array or list
        Array of calibration curve data
    model_names: list(str)
        List of model names for plotting
    font_size: int, default: 12
        Font size
    figsize: tuple(int, int), default: (12, 4)
        Figure size for plot layout

    """

    plt.rcParams['font.size'] = 12
    n_models = len(model_names)

    # Determine figure layout
    if n_models >= 6:
        n_col = int(np.sqrt(n_models))
        n_row = int(np.sqrt(n_models)) + 1
    else:
        n_col = n_models
        n_row = 1

    # Initialize figure
    f, axarr = plt.subplots(n_row, n_col, figsize=figsize)
    if n_row > 1:
        axarr = axarr.flat

    # Loop through models
    for i, ax in enumerate(axarr.flat):

        # Plot calibration curve
        ax.plot(cal_errs[i, 0, :], cal_errs[i, 1, :])

        # Plot AB line
        ax.plot(ax.get_xlim(), ax.get_xlim(), '--', color='black')

        # Tweak plot
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.set_xlim([0, 1])
        ax.set_ylim([0, 1])
        ax.set_xlabel('Accuracy')
        ax.set_ylabel('Confidence')
        ax.set_xticks([0.2, 0.4, 0.6, 0.8, 1.0])
        ax.set_yticks([0.2, 0.4, 0.6, 0.8, 1.0])
        ax.text(0.1, 0.9, r'$\widehat{ECE}$ = {0:.3f}'.format(cal_errs[i]),
                        horizontalalignment='left',
                        verticalalignment='center',
                        transform=ax.transAxes,
                        size=12)

        # Set title
        ax.set_title(model_names[i])
    f.tight_layout()
    return f


from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
import urlparse
from .base import ParserCommand
from registry import register_parser

def pretty_iso_duration(iso_duration):
    dd = {}
    num = 0
    timesplit = False
    duration = []
    iso_tags = (('Y', 'year'), ('M', 'month'), ('W', 'week'), ('D', 'day'))

    for s in iso_duration:
        if s.isdigit():
            num = num*10 + int(s)
            continue
        if s == 'P':
            continue
        if s == 'T':
            timesplit = True
            continue
        if timesplit and s == 'M':
            s = 'MM'
        dd[s] = num
        num = 0

    for tag, name in iso_tags:
        if tag in dd and dd[tag]:
            duration.append('%s %s%s ' % (dd[tag], name, 's' if dd[tag] > 1 else ''))
    if 'H' in dd: duration.append('%s:' % dd['H'])
    duration.append('%02d:%02d' % (dd.get('MM', 0), dd.get('S', 0)))
    duration = ''.join(duration)
    return duration

@register_parser
class YoutubeParser(ParserCommand):
    def parse(self, msg):
        lines = []
        for word in msg['msg'].split():
            vid = None
            try:
                url = urlparse.urlparse(word)
                if 'youtube' in url.netloc:
                    qs = urlparse.parse_qs(url.query)
                    vid = qs.get('v')[0] if 'v' in qs else None
                    if not vid:
                        split = url.path.split('/')
                        if split[1] == 'v':
                            vid = split[2]
                if 'youtu.be' == url.netloc:
                    vid = url.path.strip('/')
            except:
                continue

            if not vid:
                continue

            youtube = build("youtube", "v3", developerKey=self.config['youtube_key'])
            video_response = youtube.videos().list(id=vid, part='snippet, contentDetails').execute()
            video = video_response.get('items')
            if video:
                video = video[0]
            else:
                continue

            title = video["snippet"]["title"]
            duration = pretty_iso_duration(video['contentDetails']['duration'])
            lines.append("YOUTUBE: %s [%s]" % (title, duration))
        return lines


from collections.abc import Mapping

def extract_attr(obj, *, keys):
    if isinstance(obj, Mapping):
        for key in keys:
            if key in obj:
                return obj[key]
        raise TypeError("%s not found in obj %s" % (keys, obj))
    return obj

def extract_pattern(obj):
    """Extract pattern from str or re.compile object

    Returns:
        str: Extracted pattern
    """
    if obj is not None:
        return getattr(obj, 'pattern', obj)
    return obj


# =============== day and input ===============
day = "11"

import sys
if len(sys.argv) > 1:
    ex = "." + sys.argv[1]
else:
    ex = "." + "in"

filename = "data_" + day + ex

# =============== imports ===============
import numpy as np
import itertools as it
import collections as col

# =============== preparation ===============
with open(filename) as f:
  data = f.read().splitlines()

data = [list(e) for e in data]
np_data = np.array(data).astype(int)

# print(np_data)

# =============== part 1 ===============

def neighbours(i,j):
    return set([(i+x, j+y) for x,y in it.product([-1,0,1], [-1, 0, 1]) if 0 <= i+x < np_data.shape[0] and 0 <= j+y < np_data.shape[1]]) - {(i,j)}

res1 = 0
res2 = 0

synchron = False
hundred = False
counter = 0
while not synchron or not hundred:
    counter += 1
    flashed = set()
    np_data += 1
    q = col.deque(zip(*np.where(np_data > 9)))
    while len(q) > 0:
        e = q.popleft()
        flashed.add(e)
        for n in neighbours(*e):
            np_data[n] += 1
            if n not in flashed and n not in q and np_data[n] > 9:
                q.append(n)

    for e in flashed:
        np_data[e] = 0

    if not hundred:
        res1 += len(flashed)
    if counter == 100:
        hundred = True

    if len(flashed) == len(np_data.ravel()):
        synchron = True#
        res2 = counter

print(res1)
print(res2)

# =============== part 2 ===============


# -*- coding: utf-8 -*-
# @Time    : 2017/7/12 下午2:23
# @Author  : play4fun
# @File    : 一个重要的事.py
# @Software: PyCharm

"""
一个重要的事.py:
当我们可以  参 数 -1 来 定 出图像的深度 数据类型 与原图像保持一致
但是我们在代 码中使用的却是 cv2.CV_64F。 是为什么呢 ？
想象一下一个从黑到白的边界的导数是整数，而一个从白到黑的边界点导数却是负数。
如果原图像的深度是 np.int8 时 所有的负值 会 截断变成 0
 换句话就是把边界丢失掉。
所以如果 两种边界你 想检测到
最好的的办法就是将输出的数据类型 设置的更高
  比如 cv2.CV_16S cv2.CV_64F 等。
  取绝对值然后再把它 回 到 cv2.CV_8U。
  下 的示例演示了输出图片的深度不同造成的不同效果。
"""

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('../data/box.jpg', 0)

# Output dtype = cv2.CV_8U
sobelx8u = cv2.Sobel(img, cv2.CV_8U, 1, 0, ksize=5)
# Output dtype = cv2.CV_64F. Then take its absolute and convert to cv2.CV_8U
sobelx64f = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=5)

abs_sobel64f = np.absolute(sobelx64f)
sobel_8u = np.uint8(abs_sobel64f)

plt.subplot(1, 3, 1), plt.imshow(img, cmap='gray')
plt.title('Original'), plt.xticks([]), plt.yticks([])
plt.subplot(1, 3, 2), plt.imshow(sobelx8u, cmap='gray')
plt.title('Sobel CV_8U'), plt.xticks([]), plt.yticks([])
plt.subplot(1, 3, 3), plt.imshow(sobel_8u, cmap='gray')
plt.title('Sobel abs(CV_64F)'), plt.xticks([]), plt.yticks([])

plt.show()

ch18-图像梯度/一个重要的事.py


from flask import Flask, request, render_template, jsonify, redirect

from core.elements import Room
from core.simulator import Simulation
from core.controllers import BasicController, LightRegressorController, PersonalController

app = Flask(__name__, static_url_path='/static')

# ------------------------------
# Create simulation
# ------------------------------
sim = Simulation()

# ------------------------------
# Add rooms
# ------------------------------
sim.add_room(Room(0, 0, 200, 200, 'Room 01', room_id='r101'))
sim.add_room(Room(200, 0, 200, 200, 'Room 02', room_id='r102'))
sim.add_room(Room(400, 0, 200, 200, 'Room 03', room_id='r103'))
sim.add_room(Room(600, 0, 200, 200, 'Room 04', room_id='r104'))
sim.add_room(Room(800, 0, 200, 200, 'Room 05', room_id='r105'))
sim.add_room(Room(1000, 0, 200, 200, 'Room 06', room_id='r106'))

sim.add_room(Room(0, 200, 200, 200, 'Room 14', room_id='r114'))
sim.add_room(Room(1000, 200, 200, 200, 'Room 07', room_id='r107'))
sim.add_room(Room(600, 200, 400, 200, 'Meeting', room_id='m101'))

sim.add_room(Room(0, 400, 200, 200, 'Room 13', room_id='r113'))
sim.add_room(Room(200, 400, 200, 200, 'Room 12', room_id='r112'))
sim.add_room(Room(400, 400, 200, 200, 'Room 11', room_id='r111'))
sim.add_room(Room(600, 400, 200, 200, 'Room 10', room_id='r110'))
sim.add_room(Room(800, 400, 200, 200, 'Room 09', room_id='r109'))
sim.add_room(Room(1000, 400, 200, 200, 'Room 08', room_id='r108'))

# ------------------------------
# Add controllers
# ------------------------------
basic_controller = BasicController()
basic_controller.set_rooms({
    'r103', 'r104', 'r105', 'r106', 'r107', 'r108', 'r109', 'r110',
    'r111', 'r112', 'r113', 'r114', 'm101'
})
sim.add_controller(basic_controller)

regressor_controller = LightRegressorController()
regressor_controller.set_rooms({'r101', 'r102'})
sim.add_controller(regressor_controller)

personal_controller = PersonalController()
personal_controller.set_rooms({'r113'})
sim.add_controller(personal_controller)

@app.route('/')
def serve_dashboard():
    context = {}
    return render_template('main.html', context=context)

@app.route('/update/power')
def update_power():

    room_id = request.args.get('id', None)
    lamp_power = int(request.args.get('power', 0))
    data = {
        'status': 'nop'
    }
    for r in sim.rooms:
        if r.room_id == room_id and lamp_power is not None:
            r.lamp_power = min(max(lamp_power, 0), 100)
            data['status'] = 'done'

    return jsonify(data), 200

@app.route('/update/user')
def update_user():
    user_x = float(request.args.get('x', None))
    user_y = float(request.args.get('y', None))
    a = request.args.get('a', None)
    if a == 'add':
        sim.add_person(user_x, user_y)
    else:
        sim.del_person(user_x, user_y)

    data = {'status': 'done'}
    return jsonify(data), 200

@app.route('/run/json')
def get_run():

    sim.step_run()

    data = {
        'state_data': sim.get_state()
    }
    return jsonify(data), 200

if __name__ == "__main__":
    app.run(debug=True, port=5000)


from django.urls import path, include
from rest_framework.routers import DefaultRouter

from cookiecutter.users.views import UsersViewSet, GroupsViewSet, MyProfileView

router = DefaultRouter()
router.register("groups", GroupsViewSet)
router.register("", UsersViewSet)

urlpatterns = [
    path("my-profile/", MyProfileView.as_view()),
    path("", include(router.urls)),
]


import json
import re
from collections import Counter

def find_errors(bus_info):
    error_dict = {
        "bus_id": 0,
        "stop_id": 0,
        "stop_name": 0,
        "next_stop": 0,
        "stop_type": 0,
        "a_time": 0
    }
    stop_type_options = ["S", "O", "F", ""]
    stop_name_pattern = re.compile(r"[A-Z][a-z]+\s?\w+?\s?(Road|Avenue|Boulevard|Street)$")
    a_time_pattern = re.compile(r"[0-2][0-9]:[0-5][0-9]$")

    for dict in bus_info:
        bus_id = dict["bus_id"]
        stop_id = dict["stop_id"]
        stop_name = dict["stop_name"]
        next_stop = dict["next_stop"]
        stop_type = dict["stop_type"]
        a_time = dict["a_time"]

        if not bus_id or type(bus_id) != int:
            error_dict["bus_id"] += 1

        if not stop_id or type(stop_id) != int:
            error_dict["stop_id"] += 1

        if not stop_name or not re.match(stop_name_pattern, stop_name):
            error_dict["stop_name"] += 1

        if (not next_stop and next_stop != 0) or type(next_stop) != int:
            error_dict["next_stop"] += 1

        if stop_type not in stop_type_options:
            error_dict["stop_type"] += 1

        if not a_time or not re.match(a_time_pattern, a_time):
            error_dict["a_time"] += 1

    total_errors = sum([error_dict['stop_name'], error_dict['stop_type'], error_dict['a_time']])
    print(f"Format validation: {total_errors} errors")
    print(f"stop_name: {error_dict['stop_name']}")
    print(f"stop_type: {error_dict['stop_type']}")
    print(f"a_time: {error_dict['a_time']}")

def get_line_info(bus_info):
    line_info = {}
    for dict in bus_info:
        bus_id = dict["bus_id"]
        if bus_id in line_info.keys():
            line_info[bus_id] += 1
        else:
            line_info[bus_id] = 1
    print("Line names and number of stops:")
    for key, value in line_info.items():
        print(f"bus_id: {key}, stops: {value}")

def verify_stops(bus_info):
    stops = {}
    for dict in bus_info:
        bus_id = dict["bus_id"]
        stop_type = dict["stop_type"]
        if bus_id in stops.keys():
            stops[bus_id].append(stop_type)
        else:
            stops[bus_id] = [stop_type]
    for line, stop in stops.items():
        if stop.count("S") != 1 or stop.count("F") != 1:
            print(f"There is no start or end stop for the line: {line}.")
            return False
    return True

def count_stops(bus_info):
    start_stops = set()
    finish_stops = set()
    transfer_stops = []
    line_stops = {}

    for dict in bus_info:
        bus_id = dict["bus_id"]
        stop_name = dict["stop_name"]
        stop_type = dict["stop_type"]

        if stop_type == "S":
            start_stops.add(stop_name)
        elif stop_type == "F":
            finish_stops.add(stop_name)

    # Find transfer stops (stops shared by at least 2 bus lines)
        if bus_id in line_stops.keys():
            line_stops[bus_id].add(stop_name)
        else:
            line_stops[bus_id] = {stop_name}
    all_stops = []
    for stop in line_stops.values():
        all_stops += stop
    stop_freq_dict = Counter(all_stops)
    for stop, freq in stop_freq_dict.items():
        if freq > 1:
            transfer_stops.append(stop)

    print(f"Start stops: {len(start_stops)} {sorted(list(start_stops))}")
    print(f"Transfer stops: {len(transfer_stops)} {sorted(transfer_stops)}")
    print(f"Finish stops: {len(finish_stops)} {sorted(list(finish_stops))}")

def check_arrival_times(bus_info):
    curr_line = 0
    curr_time = ""
    error_lines = []
    print("Arrival time test:")
    for dict in bus_info:
        bus_id = dict["bus_id"]
        a_time = dict["a_time"]
        stop_name = dict["stop_name"]
        if bus_id == curr_line and bus_id not in error_lines:
            if a_time < curr_time:
                print(f"bus_id line {bus_id}: wrong time on station {stop_name}")
                error_lines.append(bus_id)
            curr_time = a_time
        else:
            curr_line = bus_id
            curr_time = a_time
    if len(error_lines) == 0:
        print("OK")

def check_on_demand_stops(bus_info):
    start_stops = set()
    finish_stops = set()
    transfer_stops = []
    on_demand_stops = set()
    line_stops = {}
    error_stops = []

    print("On demand stops test:")

    for dict in bus_info:
        bus_id = dict["bus_id"]
        stop_name = dict["stop_name"]
        stop_type = dict["stop_type"]

        if stop_type == "S":
            start_stops.add(stop_name)
        elif stop_type == "F":
            finish_stops.add(stop_name)
        elif stop_type == "O":
            on_demand_stops.add(stop_name)

    # Find transfer stops (stops shared by at least 2 bus lines)
        if bus_id in line_stops.keys():
            line_stops[bus_id].add(stop_name)
        else:
            line_stops[bus_id] = {stop_name}
    all_stops = []
    for stop in line_stops.values():
        all_stops += stop
    stop_freq_dict = Counter(all_stops)
    for stop, freq in stop_freq_dict.items():
        if freq > 1:
            transfer_stops.append(stop)

    for stop in on_demand_stops:
        if stop in start_stops or stop in finish_stops or stop in transfer_stops:
            error_stops.append(stop)

    if error_stops:
        print(f"Wrong stop type: {sorted(error_stops)}")
    else:
        print("OK")

def main():
    bus_info = json.loads(input())
    check_on_demand_stops(bus_info)

main()

Easy Rider Bus Company/task/easyrider/easyrider.py


from collections import defaultdict
import sqlite3
import os
from markdownify import markdownify as md

db = sqlite3.connect(f"{os.getenv('HOME')}/Zotero/zotero.sqlite")

# Fetch all papers
data = db.execute(
    """
select I.itemID, f.fieldName, DV.value from itemNotes N
    inner join items I on I.itemID = N.parentItemID
    inner join itemData D on I.itemID = D.itemID
    inner join fields f on D.fieldID = f.fieldID
    inner join itemDataValues DV on D.valueID = DV.valueID
;
"""
)

items = defaultdict(dict)
for (id, key, value) in data:
    items[id][key] = value

# Fetch all notes
data = db.execute(
    """
select I.itemID, N.note from itemNotes N
    inner join items I on I.itemID = N.parentItemID
;
"""
)

for (id, note) in data:
    items[id]["note"] = note

items = list(sorted(items.values(), key=lambda i: i["title"]))
for props in items:
    title = props["title"]
    print(f"## {title}")
    print()

    for k in props:
        if k in ["date", "DOI", "proceedingsTitle", "url", "publicationTitle"]:
            print(f"{k}: {props[k]}")

    # Convert html to markdown
    print()
    print(md(props["note"]).strip())

    print()


"""init

Revision ID: c0a51a6b5702
Revises:
Create Date: 2019-07-25 23:01:25.497512

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'c0a51a6b5702'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('student',
    sa.Column('usn', sa.Text(), nullable=False),
    sa.Column('name', sa.Text(), nullable=True),
    sa.Column('age', sa.Integer(), nullable=True),
    sa.PrimaryKeyConstraint('usn')
    )
    op.create_table('teacher',
    sa.Column('ssn', sa.Text(), nullable=False),
    sa.Column('name', sa.Text(), nullable=True),
    sa.Column('exp', sa.Integer(), nullable=True),
    sa.Column('salary', sa.Float(), nullable=True),
    sa.PrimaryKeyConstraint('ssn')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('teacher')
    op.drop_table('student')
    # ### end Alembic commands ###


from typing import List
from collections import deque

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def get_right_view(root: TreeNode) -> List[int]:

    if not root:
        return []

    node_queue = deque([root])
    right_view = []

    while node_queue:
        count = len(node_queue)

        while count > 0:

            current_node = node_queue.popleft()
            count -= 1
            if count == 0:
                right_view.append(current_node.val)

            if current_node.left:
                node_queue.append(current_node.left)

            if current_node.right:
                node_queue.append(current_node.right)

    return right_view

class Solution:
    def rightSideView(self, root: TreeNode) -> List[int]:
        return get_right_view(root)

def create_tree_from_list(arr: List[int]) -> TreeNode:

    arr = arr[::-1]
    head = TreeNode(arr.pop())
    node_queue = deque([head])

    while arr:
        current = node_queue.popleft()
        left_val = arr.pop()
        if left_val:
            current.left = TreeNode(left_val)
            node_queue.append(current.left)

        if not arr:
            break
        else:
            right_val = arr.pop()
            if right_val:
                current.right = TreeNode(right_val)
                node_queue.append(current.right)

    return head

if __name__ == "__main__":

    tree = create_tree_from_list([1, 2, 3, 4, 5, 6])
    rv = get_right_view(tree)
    print(rv)


from django.urls import path
from musico import views

app_name = 'musico'

urlpatterns = [
    path('listar/', views.MusicoListView.as_view(), name='read'),
    path('criar/', views.MusicoCreateView.as_view(), name='create'),
    path('editar/<int:pk>/', views.MusicoUpdateView.as_view(), name='update'),
    path('excluir/<int:pk>/', views.MusicoDeleteView.as_view(), name='delete'),
]


"""
LetMeDoIt AI Plugin - modify images

modify the given images according to changes specified by users

[FUNCTION_CALL]
"""

from letmedoit import config
import openai, os
from openai import OpenAI
from letmedoit.utils.shared_utils import SharedUtil
from letmedoit.utils.terminal_mode_dialogs import TerminalModeDialogs
from pathlib import Path
from base64 import b64decode
from urllib.parse import quote

def modify_images(function_args):
    changes = function_args.get("changes") # required
    files = function_args.get("files") # required
    #print(files)
    if isinstance(files, str):
        if not files.startswith("["):
            files = f'["{files}"]'
        files = eval(files)
    if not files:
        return "[INVALID]"

    filesCopy = files[:]
    for item in filesCopy:
        if os.path.isdir(item):
            for root, _, allfiles in os.walk(item):
                for file in allfiles:
                    file_path = os.path.join(root, file)
                    files.append(file_path)
            files.remove(item)

    for i in files:
        description, filename = get_description(i)
        if description:
            if changes:
                description = f"""Description of the original image:
{description}

Make the following changes:
{changes}"""
            else:
                description = f"Image description:\n{description}"
            if config.developer:
                config.print(description)
            response = create_image(description, filename)
            if response == "[INVALID]" and len(files) == 1:
                return response
    return ""

def get_description(filename):
    content = []
    # validate image path
    if SharedUtil.is_valid_image_url(filename):
        content.append({"type": "image_url", "image_url": {"url": filename,},})
        filename = quote(filename, safe="")
    elif SharedUtil.is_valid_image_file(filename):
        content.append({"type": "image_url", "image_url": SharedUtil.encode_image(filename),})

    if content:
        content.insert(0, {"type": "text", "text": "Describe this image in as much detail as possible, including color patterns, positions and orientations of all objects and backgrounds in the image",})
        #print(content)
        try:
            response = OpenAI().chat.completions.create(
                model="gpt-4-vision-preview",
                messages=[
                    {
                    "role": "user",
                    "content": content,
                    }
                ],
                max_tokens=4096,
            )
            answer = response.choices[0].message.content
            #print(answer)
            return (answer, filename)

        except openai.APIError as e:
            config.print("Error: Issue on OpenAI side.")
            config.print("Solution: Retry your request after a brief wait and contact us if the issue persists.")
        #except openai.Timeout as e:
        #    config.print("Error: Request timed out.")
        #    config.print("Solution: Retry your request after a brief wait and contact us if the issue persists.")
        except openai.RateLimitError as e:
            config.print("Error: You have hit your assigned rate limit.")
            config.print("Solution: Pace your requests. Read more in OpenAI [Rate limit guide](https://platform.openai.com/docs/guides/rate-limits).")
        except openai.APIConnectionError as e:
            config.print("Error: Issue connecting to our services.")
            config.print("Solution: Check your network settings, proxy configuration, SSL certificates, or firewall rules.")
        #except openai.InvalidRequestError as e:
        #    config.print("Error: Your request was malformed or missing some required parameters, such as a token or an input.")
        #    config.print("Solution: The error message should advise you on the specific error made. Check the [documentation](https://platform.openai.com/docs/api-reference/) for the specific API method you are calling and make sure you are sending valid and complete parameters. You may also need to check the encoding, format, or size of your request data.")
        except openai.AuthenticationError as e:
            config.print("Error: Your API key or token was invalid, expired, or revoked.")
            config.print("Solution: Check your API key or token and make sure it is correct and active. You may need to generate a new one from your account dashboard.")
        #except openai.ServiceUnavailableError as e:
        #    config.print("Error: Issue on OpenAI servers. ")
        #    config.print("Solution: Retry your request after a brief wait and contact us if the issue persists. Check the [status page](https://status.openai.com).")
        except:
            SharedUtil.showErrors()

    return ("", "")

def create_image(description, original_filename):
    basename = os.path.basename(original_filename)
    title = f"Modifying '{basename}' ..."
    dialogs = TerminalModeDialogs(None)
    # size selection
    options = ("1024x1024", "1024x1792", "1792x1024")
    size = dialogs.getValidOptions(
        options=options,
        title=title,
        default="1024x1024",
        text="Select size below:"
    )
    if not size:
        config.stopSpinning()
        return "[INVALID]"
    # quality selection
    options = ("standard", "hd")
    quality = dialogs.getValidOptions(
        options=options,
        title=title,
        default="hd",
        text="Select quality below:"
    )
    if not quality:
        config.stopSpinning()
        return "[INVALID]"
    try:
        # get responses
        #https://platform.openai.com/docs/guides/images/introduction
        response = OpenAI().images.generate(
            model="dall-e-3",
            prompt=f"I NEED to test how the tool works with extremely simple prompts. DO NOT add any detail, just use it AS-IS:\n{description}",
            size=size,
            quality=quality, # "hd" or "standard"
            response_format="b64_json",
            n=1,
        )
        # open image
        #imageUrl = response.data[0].url
        #jsonFile = os.path.join(config.letMeDoItAIFolder, "temp", "openai_image.json")
        #with open(jsonFile, mode="w", encoding="utf-8") as fileObj:
        #    json.dump(response.data[0].b64_json, fileObj)
        image_data = b64decode(response.data[0].b64_json)
        imageFile = f"{original_filename}_modified.png"
        with open(imageFile, mode="wb") as pngObj:
            pngObj.write(image_data)
        if config.terminalEnableTermuxAPI:
            config.mainWindow.getCliOutput(f"termux-share {imageFile}")
        else:
            os.system(f"{config.open} {imageFile}")

    except openai.APIError as e:
        config.print("Error: Issue on OpenAI side.")
        config.print("Solution: Retry your request after a brief wait and contact us if the issue persists.")
    #except openai.Timeout as e:
    #    config.print("Error: Request timed out.")
    #    config.print("Solution: Retry your request after a brief wait and contact us if the issue persists.")
    except openai.RateLimitError as e:
        config.print("Error: You have hit your assigned rate limit.")
        config.print("Solution: Pace your requests. Read more in OpenAI [Rate limit guide](https://platform.openai.com/docs/guides/rate-limits).")
    except openai.APIConnectionError as e:
        config.print("Error: Issue connecting to our services.")
        config.print("Solution: Check your network settings, proxy configuration, SSL certificates, or firewall rules.")
    #except openai.InvalidRequestError as e:
    #    config.print("Error: Your request was malformed or missing some required parameters, such as a token or an input.")
    #    config.print("Solution: The error message should advise you on the specific error made. Check the [documentation](https://platform.openai.com/docs/api-reference/) for the specific API method you are calling and make sure you are sending valid and complete parameters. You may also need to check the encoding, format, or size of your request data.")
    except openai.AuthenticationError as e:
        config.print("Error: Your API key or token was invalid, expired, or revoked.")
        config.print("Solution: Check your API key or token and make sure it is correct and active. You may need to generate a new one from your account dashboard.")
    #except openai.ServiceUnavailableError as e:
    #    config.print("Error: Issue on OpenAI servers. ")
    #    config.print("Solution: Retry your request after a brief wait and contact us if the issue persists. Check the [status page](https://status.openai.com).")
    except:
        SharedUtil.showErrors()
    config.stopSpinning()
    return ""

functionSignature = {
    "name": "modify_images",
    "description": "modify the images that I provide",
    "parameters": {
        "type": "object",
        "properties": {
            "changes": {
                "type": "string",
                "description": "The requested changes in as much detail as possible. Return an empty string '' if changes are not specified.",
            },
            "files": {
                "type": "string",
                "description": """Return a list of image paths, e.g. '["image1.png", "/tmp/image2.png"]'. Return '[]' if image path is not provided.""",
            },
        },
        "required": ["changes", "files"],
    },
}

config.pluginsWithFunctionCall.append("modify_images")
config.chatGPTApiFunctionSignatures.append(functionSignature)
config.chatGPTApiAvailableFunctions["modify_images"] = modify_images


import os
import pandas as pd
import numpy as np
from .utils import (
    is_in_word_list
)
from typing import List, Union

ECON_LIST = [
    "economy", "economic", "economics", "business", "commerce", "finance",
    "industry"
]

POLICY_LIST = [
    "government", "governmental", "authorities", "minister", "ministry",
    "parliament", "parliamentary", "tax", "regulation", "legislation",
    "central bank", "imf", "world bank", "international monetary fund",
    "debt"
]

UNCERTAINTY_LIST = [
    "uncertain", "uncertainty", "uncertainties", "unknown", "unstable",
    "unsure", "undetermined", "risky", "risk", "not certain", "non-reliable",
    "fluctuations", "unpredictale"
]

class EPU:
    def __init__(self, filepath,
                 econ_terms: list = ECON_LIST,
                 policy_terms: list = POLICY_LIST,
                 uncertainty_terms: list = UNCERTAINTY_LIST,
                 additional_terms: Union[List, None] = None):
        if not os.path.exists(filepath):
            raise FileNotFoundError(f"Cannot find {filepath}")
        self.filepath = filepath
        self.econ_terms = econ_terms
        self.policy_terms = policy_terms
        self.uncertainty_terms = uncertainty_terms
        self.additional_terms = additional_terms

    @staticmethod
    def process_data(filepath: str, subset_condition: Union[str, None] = None) -> pd.DataFrame:
        """
        Reads a CSV file and processes the data.

        Args:
            filename (str): The name of the CSV file.
            subset_condition (str): The conditions to pass on to df.query(), such as
                        "date >= 'YYYY-MM-DD'"

        Returns:
            pd.DataFrame: Processed DataFrame with the "Unnamed: 0" column dropped,
                        newline characters removed from the "news" column,
                        "date" column converted to datetime, and a new "ym" column added.
        """
        df = pd.read_csv(filepath).drop("Unnamed: 0", axis=1)
        df = df[~df.date.isna()].reset_index(drop=True)
        if subset_condition is not None:
            df = df.query(subset_condition).reset_index(drop=True)

        df["news"] = df["news"].replace("\n", "")
        df["date"] = pd.to_datetime(df["date"], format="mixed")
        df["ym"] = [str(d.year) + "-" + str(d.month) for d in df.date]
        return df

    @staticmethod
    def get_count(data: pd.DataFrame, column: str) -> pd.DataFrame:
        """
        Computes the count of occurrences for a specific column in a DataFrame
        grouped by the year-month ('ym').

        Args:
            data (pd.DataFrame): The input DataFrame.
            column (str): The column for which the count is computed.

        Returns:
            pd.DataFrame: DataFrame with the count of occurrences for the specified column

        """
        try:
            count_df = (data.set_index("date")
                            .groupby("ym")[[str(column)]]
                            .count()
                            .reset_index()
                            .rename({str(column): str(column) + "_count"}, axis=1))
            return count_df
        except KeyError:
            raise KeyError(f"Column '{column}' not found in the DataFrame.")

    def get_epu_category(self, subset_condition=None):
        """
        Reads the csv file that contains news and identifies the Economic/Policy/Uncertainty
        categories.

        Args:
            subset_condition (str): conditionals to pass to EPU().process_data()
        """
        self.raw = self.process_data(
            self.filepath, subset_condition=subset_condition)
        for col, terms in zip(["econ", "policy", "uncertain"], [self.econ_terms, self.policy_terms, self.uncertainty_terms]):
            self.raw[col] = self.raw["news"].str.lower().apply(
                is_in_word_list, terms=terms)

        self.raw["epu"] = (self.raw.econ == True) & (
            self.raw.policy == True) & (self.raw.uncertain == True)

        ##
        if self.additional_terms:
            self.raw["additional"] = self.raw["news"].str.lower().apply(
                is_in_word_list, terms=self.additional_terms)
            self.raw["epu"] = (self.raw.epu == True) & (
                self.raw.additional == True)

    def get_epu_stats(self, cutoff: str = None) -> pd.DataFrame:
        news_count = self.get_count(self.raw, "news")
        epu_count = self.get_count(self.raw[self.raw["epu"] == True], "epu")
        self.epu_stat = news_count.merge(
            epu_count, how="left", on="ym").fillna(0)
        self.epu_stat["date"] = pd.to_datetime(
            self.epu_stat["ym"], format="mixed")

        # Check for date integrity
        self.min_date, self.max_date = self.epu_stat.date.min(), self.epu_stat.date.max()
        self.date_df = pd.DataFrame(pd.date_range(
            self.min_date, self.max_date, freq="MS"), columns=["date"])

        self.epu_stat = (self.date_df.merge(self.epu_stat, how="left", on="date")
                         .fillna(0).drop("ym", axis=1))
        self.epu_stat["ratio"] = self.epu_stat["epu_count"] / \
            self.epu_stat["news_count"]

        if cutoff != None:
            self.std = self.epu_stat[self.epu_stat.date <
                                     cutoff]["ratio"].std()
        else:
            self.std = self.epu_stat["ratio"].std()
        self.epu_stat["z_score"] = self.epu_stat['ratio']/self.std

        return self.epu_stat


#imports
import pygame
import time
from pygame import mixer

#inits
pygame.init()
pygame.font.init()
pygame.mixer.init()

#variáveis
white = (255,255,255)
black = (0,0,0)
largura = 640
altura = 480
happybar = 123
y = 0

#IMAGES LOAD

#icons
lua = pygame.image.load ("images/lua.png")
acai = pygame.image.load ("images/acai.png")
notebook = pygame.image.load ("images/notebook.png")
coraçao = pygame.image.load ('images/coraçao.png')
sleepz =  pygame.image.load ('images/sleepz.png')
stain = pygame.image.load ('images/stain.png')
framebarra = pygame.image.load ('images/framebar.png')

#pai variations
paipqn = pygame.image.load ('images/paipqn.png')
pai = pygame.image.load ("images/pai.png")
happyskin = pygame.image.load ("images/happyskin.png")
skinsuada = pygame.image.load ("images/skinsuada.png")
# pai = pygame.image.load ('images/pai.png')
sadpai = pygame.image.load ('images/sadpai.png')
skindormir =  pygame.image.load ('images/skindormir.png')
bike = pygame.image.load('images/bike.png')
familyphoto = pygame.image.load('images/familyphoto.png')
skindev = pygame.image.load('images/skindev.png')
# fundo variations
fundo = pygame.image.load ("images/fundojogo.png")
fundoazul = pygame.image.load ('images/fundoazul.png')
fundobarra = pygame.image.load ('images/fundobarra.png')

#SOUNDS LOAD

#sounds
sleepsound = mixer.Sound('sounds/sleepsound.wav')
chewsound = mixer.Sound('sounds/chewsound.wav')
clicksound = mixer.Sound('sounds/clicksound.wav')
gameoversound = mixer.Sound('sounds/gameoversound.wav')
typingsound = mixer.Sound('sounds/typingsound.wav')
bikesound = mixer.Sound('sounds/bikesound.wav')
#music
mixer.music.load('sounds/MadonnaHoliday.wav')
mixer.music.play(-1)

#TELA

tela = pygame.display.set_mode((largura,altura))
pygame.display.set_caption("pet.com")

#BUTTON

#button class
class button():
    def __init__(self, x, y, image):
        self.image = image
        self.rect = self.image.get_rect()
        self.rect.topleft = (x, y)
        self.clicked = False

    def draw(self, surface):
        action = False
        #posição do mouse
        pos = pygame.mouse.get_pos()
        #checar se foi o botão foi clicado
        if self.rect.collidepoint(pos):
            if pygame.mouse.get_pressed()[0] == 1 and self.clicked == False: #[0] = botão esquerdo do mouse
                self.clicked = True
                action = True
        if pygame.mouse.get_pressed()[0] == 0:
                self.clicked = False
        #print botão na tela
        surface.blit(self.image, (self.rect.x, self.rect.y))

        return action

#button notebook
notebook_img = pygame.image.load("images/notebook.png").convert_alpha()
notebook_img = button(120, 390, notebook_img)

#button acai
acai_img = pygame.image.load ("images/acai.png").convert_alpha()
acai_img = button(250, 395, acai_img)

#button lua
lua_img = pygame.image.load("images/lua.png").convert_alpha()
lua_img = button(470, 390,lua_img)

#button pai
pai_img = pygame.image.load("images/pai.png").convert_alpha()
pai_img = button(231,142, pai_img)

#button rabo pai
bike_img = pygame.image.load("images/bike.png").convert_alpha()
bike_img = button(342,390, bike_img)

#TELAS

inicio = True
jogo = False
telainicial=True

while telainicial:

    #tela inicio
    if inicio == True:
        for event in pygame.event.get():
            #fechar jogo no x
            if event.type == pygame.QUIT:
                telainicial=False
            #fechar tela inicio e abrir tela jogo quando clicar no espaço
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    clicksound.play()
                    inicio = False
                    jogo = True

        #fundo branco
        tela.fill(white)

        #corações
        if y  >= altura+100:
            y = 0
        y = y + 1

        tela.blit(coraçao,(50,y))
        tela.blit(coraçao,(440,-100 + y))
        tela.blit(coraçao,(550,-40 + y))

        #pai
        tela.blit(paipqn,(270,200))

        #TEXTO

        #texto 1
        txt='Feliz dia dos pais!'
        fontetxt=pygame.font.Font('Minecraftia-Regular.ttf', 30)
        txttela = fontetxt.render(txt, 1, (black))
        tela.blit(txttela,(170,100))
        #texto 2
        txt2='Aperte espaço para jogar'
        fontetxt2=pygame.font.Font('Minecraftia-Regular.ttf', 22)
        txttela2 = fontetxt2.render(txt2, 1, (black))
        tela.blit(txttela2,(150,360))
        pygame.display.update()

    #tela jogo
    elif jogo == True:

        #papel de parede jogo
        tela.blit(fundo,(0,0))

        #barra de felicide
        pygame.draw.rect(tela, (white), (38,happybar,30,230))
        tela.blit(fundobarra,(15, 353))
        tela.blit(framebarra,(25,110))

        #pai image
        tela.blit(pai,(230,142))

        #button images
        tela.blit(notebook,(120, 390))
        tela.blit(acai,(250, 395))
        tela.blit(bike,(342,390))
        tela.blit(lua,(470, 390))

        #enquanto a barra não acaba ela se move
        if happybar<=355:
            #movimento barra de felicidade
            pygame.draw.rect(tela, (white), (38,happybar,30,230))
            happybar = happybar + 0.1                #velocidade
            tela.blit(fundobarra,(15, 353))
            tela.blit(framebarra,(25,110))

        #barra acaba = jogo acaba
        else:
            #gato triste
            tela.blit(fundo,(0,0))
            tela.blit(sadpai,(231,142))
            pygame.display.update()
            #som
            mixer.music.stop()
            gameoversound.play()
            #texto
            txtfim='fim do jogo'
            fontetxt=pygame.font.Font('Minecraftia-Regular.ttf', 40)
            txtfimtela = fontetxt.render(txtfim, 1, (black))
            tela.blit(txtfimtela,(200,800))
            time.sleep(2)
            tela.blit(fundo,(0,0))
            txtfim='Te amamos muito!'
            fontetxt=pygame.font.Font('Minecraftia-Regular.ttf', 40)
            txtfimtela = fontetxt.render(txtfim, 1, (black))
            tela.blit(txtfimtela,(120,60))
            tela.blit(familyphoto,(30,170))

            #fim do jogo
            pygame.display.update()
            time.sleep(6)
            pygame.quit()

        #funcionalid banho
        if (notebook_img.draw(tela)):
            #images
            tela.blit(framebarra,(25,110))
            tela.blit(fundoazul,(107,0))
            tela.blit(skindev,(231,142))
            #sounds
            typingsound.play()
            #wait
            pygame.display.update()
            time.sleep(5)
            #+10 felicidade
            if (happybar - 10 < 123):
                happybar = happybar + (123-happybar)
            else:
                happybar = happybar - 10

        #funcionalid comer
        if (acai_img.draw(tela)):
            #images
            tela.blit(stain,(280, 245))
            #sounds
            chewsound.play()
            #wait
            pygame.display.update()
            time.sleep(3)
            #+10 felicidade
            if (happybar - 10 < 123):
                happybar = happybar + (123-happybar)
            else:
                happybar = happybar - 10

        #funcionalid dormir
        if (lua_img.draw(tela)):
            #images
            tela.blit(framebarra,(25,110))
            tela.blit(fundoazul,(107,0))
            tela.blit(skindormir,(232,142))
            tela.blit(sleepz,(200,140))
            tela.blit(sleepz,(220,100))
            #sounds
            sleepsound.play()
            #wait
            pygame.display.update()
            time.sleep(5)
            #+10 felicidade
            if (happybar - 10 < 123):
                happybar = happybar + (123-happybar)
            else:
                happybar = happybar - 10

        #funcionalid pet
        if (pai_img.draw(tela)):
            #images
            tela.blit(happyskin,(232,142))
            tela.blit(coraçao,(370,120))
            #sounds

            #wait
            pygame.display.update()
            time.sleep(1)
            #+5 felicidade
            if (happybar - 10 < 123):
                happybar = happybar + (123-happybar)
            else:
                happybar = happybar - 5

        #funcionalid bike
        if (bike_img.draw(tela)):
            #images
            tela.blit(skinsuada,(232,142))
            #sounds
            bikesound.play()
            #wait
            pygame.display.update()
            time.sleep(4)
            #-5 felicidade
            happybar = happybar + 5

        #fechar jogo no x
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                telainicial=False

        pygame.display.update()

pygame.quit()


# -*- coding: utf-8 -*-
"""
Created on Wed Feb 17 15:46:01 2021

@author: user

yamlex2.py : list를 yaml 문서양식으로 변경하기
"""
import yaml
customer = [
    {"name":"Inseong","age":"24","gender":"man"},
    {"name":"Kildong","age":"22","gender":"man"},
    {"name":"ChunHang","age":"20","gender":"woman"},
    {"name":"HangDan","age":"25","gender":"woman"}
]
#파이썬 데이터(List)를 yaml 문서양식으로 변경하기
# yaml문서 양식에 맞는 문자열 <= yaml.dump(리스트)
yaml_str = yaml.dump(customer)
print(type(yaml_str))
print(yaml_str)

#yaml_str 문서를 리스트형으로 변경하기
data = yaml.load(yaml_str,Loader=yaml.FullLoader)
print(type(data))
print(data)


import typing

import numpy as np
import pandas as pd

from FinMind.schema.data import Dataset
from FinMind.strategies.base import Strategy

class InstitutionalInvestorsFollower(Strategy):
    """
    url: "https://www.finlab.tw/%E8%85%A6%E5%8A%9B%E6%BF%80%E7%9B%AA%E7%9A%84%E5%A4%96%E8%B3%87%E7%AD%96%E7%95%A5%EF%BC%81/"
    summary:
        策略概念: 法人大量買超會導致股價上漲, 賣超反之
        策略規則: 三大法人大量買超隔天就賣，大量賣超就買
    """

    def create_trade_sign(self, stock_price: pd.DataFrame) -> pd.DataFrame:
        stock_price = stock_price.sort_values("date")
        stock_price.index = range(len(stock_price))
        institutional_investors_buy_sell = self.data_loader.get_data(
            dataset=Dataset.TaiwanStockInstitutionalInvestorsBuySell,
            data_id=self.stock_id,
            start_date=self.start_date,
            end_date=self.end_date,
        )
        institutional_investors_buy_sell = (
            institutional_investors_buy_sell.groupby(
                ["date", "stock_id"], as_index=False
            ).agg({"buy": np.sum, "sell": np.sum})
        )
        institutional_investors_buy_sell["diff"] = (
            institutional_investors_buy_sell["buy"]
            - institutional_investors_buy_sell["sell"]
        )
        stock_price = pd.merge(
            stock_price,
            institutional_investors_buy_sell[["stock_id", "date", "diff"]],
            on=["stock_id", "date"],
            how="left",
        ).fillna(0)
        stock_price["signal_info"] = self.detect_Abnormal_Peak(
            y=stock_price["diff"].values,
            lag=10,
            threshold=3,
            influence=0.35,
        )
        stock_price["signal"] = 0
        stock_price.loc[stock_price["signal_info"] == -1, "signal"] = 1
        stock_price.loc[stock_price["signal_info"] == 1, "signal"] = -1
        return stock_price

    def detect_Abnormal_Peak(
        self, y: np.array, lag: int, threshold: float, influence: float
    ) -> typing.List[float]:
        signals = np.zeros(len(y))
        filtered_y = np.array(y)
        avg_filter = [0] * len(y)
        std_filter = [0] * len(y)
        avg_filter[lag - 1] = np.mean(y[0:lag])
        std_filter[lag - 1] = np.std(y[0:lag])
        for i in range(lag, len(y)):
            if abs(y[i] - avg_filter[i - 1]) > threshold * std_filter[i - 1]:
                if y[i] > avg_filter[i - 1]:
                    signals[i] = 1
                else:
                    signals[i] = -1

                filtered_y[i] = (
                    influence * y[i] + (1 - influence) * filtered_y[i - 1]
                )
                avg_filter[i] = np.mean(filtered_y[(i - lag + 1) : i + 1])
                std_filter[i] = np.std(filtered_y[(i - lag + 1) : i + 1])
            else:
                signals[i] = 0
                filtered_y[i] = y[i]
                avg_filter[i] = np.mean(filtered_y[(i - lag + 1) : i + 1])
                std_filter[i] = np.std(filtered_y[(i - lag + 1) : i + 1])
        return list(signals)


from rest_framework import viewsets, mixins
from boxing_console.permissions import IsSuperAdminPermission
from biz.models import User
from boxing_console.serializers import AdminSerializer

class AdminViewSet(viewsets.GenericViewSet,
                   mixins.ListModelMixin,
                   mixins.CreateModelMixin,
                   mixins.DestroyModelMixin):
    permission_classes = (IsSuperAdminPermission,)
    queryset = User.objects.filter(is_active=True, is_staff=True).order_by("-date_joined")
    serializer_class = AdminSerializer

    def perform_destroy(self, instance):
        instance.is_staff = False
        instance.save()


import numpy as np
import math
import time
import sys

np.set_printoptions(threshold=np.inf, linewidth=np.inf)
test = np.load('/users/user2/Desktop/AIDC/model/features.npy').reshape(-1, 64)
# print(test.shape)

# data = test[383]
# data = data.astype(np.uint16)
# print(len(data))
# print(data)
N = 64
M = 16
datatype = 'uint16'

# decimal int number to binary numpy array
def toBinary(value, wid):
    value_bin = np.binary_repr(value, width = wid)
    # width가 자릿수, value가 바꿀 정수

    value_bin = np.array(list(value_bin))
    value_bin = value_bin.astype(datatype)
    return value_bin

# a = 2
# print(toBinary(a, 7))

# binary numpy array to decimal int number
def toDecimal(nparr):
    fliarr = np.flip(nparr)
    # 들어온 넘피 어레이의 끝자리부터 2곱해서 더해줄려고 1차원 넘피 어레이를 뒤집어주는 함수
    # ex) [0 0 0 0 0 1] => [1 0 0 0 0 0]

    twoarr = np.array([2**0,2**1,2**2,2**3,2**4,2**5,2**6,2**7,2**8,2**9,2**10,2**11,2**12,2**13,2**14,2**15], dtype = np.uint16)
    valuearr = fliarr * twoarr[0:len(fliarr)]
    value = valuearr.sum()
    return value

# b = np.array([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], dtype = datatype)
# print(toDecimal(b))
# print(b.sum())

def Delta(datablock):
    baseword = datablock[0]
    delta = datablock[1:].astype(np.uint16) - baseword
    delta = delta.astype(datatype)

    return baseword, delta

# baseword, delta= Delta(data)
# print(baseword)
# print(delta)
# print(len(delta))

# change to bit plane
def DBP16(deltablock):
    deltas = np.unpackbits(deltablock.view(np.uint8)).reshape(-1, 16)
    d1 = deltas[:,0:8]
    d2 = deltas[:,8:16]
    deltas = np.hstack((d2, d1))
    deltas = deltas.astype(datatype)

    dbps = np.array(list(zip(*deltas[::]))) ## 2차원 넘피 어레이를 90도 회전시키는 함수
    return dbps

# dbps16 = DBP16(delta)
# print(dbps16)
# print(dbps16.shape)

# calculate to delta-bit plane-xor
def DBX16(dbps):
    x1 = np.delete(dbps, 0, 0).astype(np.uint16)
    x2 = np.delete(dbps, dbps.shape[0] - 1, 0).astype(np.uint16)
    xored = x1 ^ x2
    xored = np.vstack([dbps[0], xored])
    return xored

# dbxs16 = DBX16(dbps16)
# print(dbxs16)
# print(dbxs16.shape)

def Encoder(dbp, dbx):

    global patt0

    # if DBX plane is all 1 or all 0
    if np.all(dbx==0):
        return 3, np.array([0, 0, 1], dtype = datatype)
    elif np.all(dbx==1):
        return 5, np.array([0, 0, 0, 0, 0], dtype = datatype)
    elif np.all(dbp==0):
        return 5, np.array([0, 0, 0, 0, 1], dtype = datatype)

    # plane is not all 1 or all 0
    pos_one = np.where(dbx == 1)[0]

    # single 1
    if len(pos_one) == 1:
        return 5 + 6, np.concatenate((np.array([0, 0, 0, 1, 1], dtype = datatype), toBinary(62 - pos_one[0], 6))) ## len(delta)가 이미 N-1이므로, 바로 log2를 취하면 됩니다

    elif len(pos_one) == 2:
        # Consecutive two 1 연속된 1
        if pos_one[1] - pos_one[0] == 1:
            return 5 + 6, np.concatenate((np.array([0, 0, 0, 1, 0], dtype = datatype), toBinary(62 - pos_one[1], 6))) ## 똑같이 -2가 아니라 -1만 하면 됨

        # 연속되지 않은 1 => not compress
        else:
            return len(delta)+1, np.concatenate((np.array([1], dtype=datatype), dbx))

    else:
        return len(delta)+1, np.concatenate((np.array([1], dtype=datatype), dbx))

# for i in range(M):
#     length, code = Encoder(dbps16[i], dbxs16[i])
#     print(dbxs16[i], "->", length, code)

def BPC(block):
    outputcode = np.array([], dtype=datatype)
    outputlen = 0

    baseword, deltablock = Delta(block)
    dbps = DBP16(deltablock)
    dbxs = DBX16(dbps)
    basesymbol = toBinary(baseword, 16)

    zrl = 0

    for i in range(M):
        length, code = Encoder(dbps[i], dbxs[i])

        if np.array_equal(code, np.array([0, 0, 1], dtype = datatype)): # all-0 DBX 일 경우
            zrl += 1
            continue

        else: # all-0 DBX가 아닐 경우
            if zrl != 0: # 근데 앞에 all-0 DBX가 있었을 경우
                if zrl == 1:
                    outputcode = np.concatenate((outputcode, np.array([0, 0, 1], dtype = datatype)), axis=None)
                    outputlen += 3
                else:
                    runlen = toBinary(zrl-2, 4)
                    outputcode = np.concatenate((outputcode, np.array([0, 1], dtype=datatype), runlen), axis=None)
                    outputlen += 2 + 4
                # 이제 all-0 DBX가 아닌 현재 code를 붙여줘야함
                outputcode = np.concatenate((outputcode, code), axis=None)
                outputlen += length
                zrl = 0
            else: # 앞에 all-0 DBX가 없었을 경우
                outputcode = np.concatenate((outputcode, code), axis=None)
                outputlen += length

    if zrl != 0:
        if zrl == 1:
            outputcode = np.concatenate((outputcode, np.array([0, 0, 1], dtype = datatype)), axis=None)
            outputlen += 3
        else:
            runlen = toBinary(zrl-2, 4)
            outputcode = np.concatenate((outputcode, np.array([0, 1], dtype=datatype), runlen), axis=None)
            outputlen += 2 + 4

    outputlen += 16
    outputcode = np.concatenate((basesymbol, outputcode), axis=None)

    outputlen += 2
    outputcode = np.concatenate((np.array([0, 0], dtype=datatype), outputcode), axis=None)

    # padding
    if outputlen < 512:
        e = 512 - outputlen
        ex = np.zeros(e, dtype=datatype)
        outputcode = np.concatenate((outputcode, ex), axis=None)

    return outputcode, outputlen

# result_bpc, len_bpc = BPC(data)
# print(result_bpc)
# print(len_bpc)
# print(len(result_bpc))

def ZRLE(block):
    outputcode = np.array([], dtype=datatype)
    outputlen = 0
    new_block = block.reshape(-1, 4)
    for idx in range(new_block.shape[0]):
        vec = np.where(new_block[idx] > 0)[0]
        if len(vec) == 0:
            outputcode = np.concatenate((outputcode, np.array([0, 0, 0, 0, 0, 0], dtype=datatype)), axis=None)
            outputlen += 6
        elif len(vec) == 1:
            if vec[0] == 3:
                outputcode = np.concatenate((outputcode, np.array([0, 0, 0, 0, 0, 1], dtype=datatype)), axis=None)
                outputlen += 6
            elif vec[0] == 2:
                outputcode = np.concatenate((outputcode, np.array([0, 0, 0, 0, 1], dtype=datatype)), axis=None)
                outputlen += 5
            elif vec[0] == 1:
                outputcode = np.concatenate((outputcode, np.array([0, 0, 0, 1, 0], dtype=datatype)), axis=None)
                outputlen += 5
            elif vec[0] == 0:
                outputcode = np.concatenate((outputcode, np.array([0, 0, 0, 1, 1], dtype=datatype)), axis=None)
                outputlen += 5
            outputcode = np.concatenate((outputcode, toBinary(new_block[idx][vec[0]], 16)), axis=None)
            outputlen += 16
        elif len(vec) == 2:
            if vec[1] == 3:
                if vec[0] == 2:
                    outputcode = np.concatenate((outputcode, np.array([0, 0, 1, 0], dtype=datatype)), axis=None)
                    outputlen += 4
                elif vec[0] == 1:
                    outputcode = np.concatenate((outputcode, np.array([0, 0, 1, 1], dtype=datatype)), axis=None)
                    outputlen += 4
                elif vec[0] == 0:
                    outputcode = np.concatenate((outputcode, np.array([0, 1, 0, 0], dtype=datatype)), axis=None)
                    outputlen += 4
            elif vec[1] == 2:
                if vec[0] == 1:
                    outputcode = np.concatenate((outputcode, np.array([0, 1, 0, 1], dtype=datatype)), axis=None)
                    outputlen += 4
                elif vec[0] == 0:
                    outputcode = np.concatenate((outputcode, np.array([0, 1, 1, 0], dtype=datatype)), axis=None)
                    outputlen += 4
            elif vec[1] == 1:
                outputcode = np.concatenate((outputcode, np.array([0, 1, 1, 1], dtype=datatype)), axis=None)
                outputlen += 4
            outputcode = np.concatenate((outputcode, toBinary(new_block[idx][vec[0]], 16), toBinary(new_block[idx][vec[1]], 16)), axis=None)
            outputlen += 32
        elif len(vec) == 3:
            sumvec = vec[0] + vec[1] + vec[2]
            if sumvec == 6: #123
                outputcode = np.concatenate((outputcode, np.array([1, 0, 0, 0], dtype=datatype)), axis=None)
                outputlen += 4
            elif sumvec == 5: #023
                outputcode = np.concatenate((outputcode, np.array([1, 0, 0, 1], dtype=datatype)), axis=None)
                outputlen += 4
            elif sumvec == 4: #013
                outputcode = np.concatenate((outputcode, np.array([1, 0, 1, 0], dtype=datatype)), axis=None)
                outputlen += 4
            elif sumvec == 3: #012
                outputcode = np.concatenate((outputcode, np.array([1, 0, 1, 1], dtype=datatype)), axis=None)
                outputlen += 4
            outputcode = np.concatenate((outputcode, toBinary(new_block[idx][vec[0]], 16), toBinary(new_block[idx][vec[1]], 16), toBinary(new_block[idx][vec[2]], 16)), axis=None)
            outputlen += 48
        elif len(vec) == 4:
            outputcode = np.concatenate((outputcode, np.array([1, 1], dtype=datatype)), axis=None)
            outputcode = np.concatenate((outputcode, toBinary(new_block[idx][vec[0]], 16), toBinary(new_block[idx][vec[1]], 16), toBinary(new_block[idx][vec[2]], 16), toBinary(new_block[idx][vec[3]], 16)), axis=None)
            outputlen += 66

    outputcode = np.concatenate((np.array([0, 1], dtype=datatype), outputcode), axis=None)
    outputlen += 2

    # padding
    if outputlen < 512:
        e = 512 - outputlen
        ex = np.zeros(e, dtype=datatype)
        outputcode = np.concatenate((outputcode, ex), axis=None)

    return outputcode, outputlen

# result_zrl, len_zrl = ZRLE(data)
# print(result_zrl)
# print(len_zrl)
# print(len(result_zrl))

def SR(block):
    reduct_block = np.logical_or(block < 128, block > 65407)
    idx_block = np.where(block > 65407)[0]
    dup_block = block.copy()
    outputcode = np.array([], dtype=datatype)
    if np.all(reduct_block == True):
        if (block[0] < 64 or block[0] > 65471):
            ret_flag = 1
        else:
            ret_flag = 0
    else:
        ret_flag = 0

    if (dup_block[0] > 65407):
        dup_block[0] -= 128
    dup_block = dup_block.astype(np.uint8)

    for idx in range(len(dup_block)):
        if idx == 0:
            outputcode = np.concatenate((outputcode, np.array([1], dtype=datatype), toBinary(dup_block[idx], 7)[-7:]), axis=None)
        else:
            outputcode = np.concatenate((outputcode, toBinary(dup_block[idx], 8)), axis=None)

    return outputcode, ret_flag

# result_sr, len_sr = SR(data)
# print(result_sr)
# print(len_sr)
# print(len(result_sr))

# if len_sr == 1:
#     print(result_sr)
# elif len_zrl < 513:
#     print(result_zrl)
# elif len_bpc < 513:
#     print(result_bpc)
# else:
#     print(result_bpc[:512])
import torch

def Comp(x : torch.Tensor):
    x_numpy = x.numpy()
    newarr = np.array([], dtype=np.uint16)
    npline = np.array(list(x_numpy[:-1]), dtype=np.uint16).reshape(-1, 16)
    for i in range(64):
        newarr = np.append(newarr, toDecimal(npline[i]), axis=None)
    bpc_code, bpc_len = BPC(newarr)
    zrl_code, zrl_len = ZRLE(newarr)
    sr_code, sr_flag = SR(newarr)

    if sr_flag == 1:
        result = "".join(sr_code)
    elif zrl_len < 513:
        result = "".join(zrl_code)
    elif bpc_len < 513:
        result = "".join(bpc_code)
    else:
        result = "".join(bpc_code[0:512])


#!/usr/bin/python3

from cmd import Cmd
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import scipy
import scipy.ndimage
import copy

from cmd_parser import gen_parser
from zoom import clipped_zoom

class Prompt(Cmd):
    intro = 'Welcome to lbox. Type help or ? to list commands.\n'
    prompt = '(lbox) '
    def __init__(self, image_filename):
        super(Prompt, self).__init__()
        self.filename = image_filename
        self.img = mpimg.imread(image_filename)
        self.img_array = [copy.copy(self.img)]
        self.ver_idx = 0 #off by one for refresh
        self.row,self.col,self.ch = self.img.shape
        plt.imshow(self.img)
        plt.ion()
        plt.show()
        self.refresh(True)

    def refresh(self, isIndex=False):
        if not isIndex:
            while (len(self.img_array)>self.ver_idx+1):
                self.img_array.pop()
            self.img_array.append(copy.copy(self.img))
            self.ver_idx += 1
        plt.clf()
        plt.imshow(self.img)
        plt.draw()
        plt.pause(0.0001)

    def do_exit(self, inp):
        print("Exiting...")
        return True

    def do_EOF(self, line):
        print("Exiting...")
        return True

    def default(self, inp):
        split = inp.split()
        cmd = split[0]
        inp = ' '.join(split[1:]) if len(split) > 1 else ''

        try:
            f = getattr(self, cmd)
        except:
            print(f"Unknown command '{cmd}'")
            return

        try:
            parse, spec = gen_parser(f)
        except Exception as e:
            print(f"Internal error: {e}")
            return

        try:
            args = parse(inp)
        except Exception as e:
            spec = ' '.join(f"{n} [{t.__name__}]" for n,t in spec)
            print(f"Invalid argument! usage:")
            print(f"  {cmd} {spec}")
            return
        try:
            f(*args)
        except Exception as e:
            print(f"Internal error: {e}")
        return

    #############################################
    ############## Functions Below ##############
    #############################################
    def undo(self):
        if self.ver_idx > 0:
            self.ver_idx -= 1
            self.img = copy.copy(self.img_array[self.ver_idx])
            self.refresh(True)
        else:
            print("No more versions in history")

    def redo(self):
        if self.ver_idx+1 < len(self.img_array):
            self.ver_idx += 1
            self.img = copy.copy(self.img_array[self.ver_idx])
            self.refresh(True)
        else:
            print("Most recent version in history")

    def rotate(self, degrees : float):
        self.img = scipy.ndimage.rotate(self.img, degrees, reshape=False)
        self.refresh()

    def zoom(self, percent : float):
        self.img = clipped_zoom(self.img, 1 + percent / 100)
        self.refresh()

    def imfilter(self, filt : str, filt_size : int = 3):
        filt = filt.upper()
        supported = True
        if filt == "GAUSSIAN":
            filt_func = lambda x: scipy.ndimage.gaussian_filter(x, sigma=3)
        elif filt == "MEDIAN":
            filt_func = lambda x: scipy.ndimage.median_filter(x, size=(filt_size,filt_size))
        else:
            print("Filter type not supported")
            return
        for idx in range(self.ch): #only works for rgb?
            self.img[:,:,idx] = filt_func(self.img[:,:,idx])
        self.refresh()

    def noisy(self, noise: str):
        noise = noise.upper()
        if noise == "GAUSSIAN":
            noise = np.random.normal(0,.05,(self.row,self.col,self.ch))
            temp = np.array(self.img[:,:,:2] + noise[:,:,:2])
            temp[temp > 1] = 1
            temp[temp < 0] = 0
            self.img[:,:,:2] = temp
        elif noise == "S&P":
            svp = 0.5 #amount of salt vs. pepper
            p_val = 0.02 #probability of salt or pepper
            s_coords = [np.random.randint(0, i-1, int(p_val*self.row*self.col*self.ch*svp)) for i in (self.row,self.col,self.ch)]
            p_coords = [np.random.randint(0, i-1, int(p_val*self.row*self.col*self.ch*svp)) for i in (self.row,self.col,self.ch)]
            temp = self.img
            temp[s_coords] = 1
            temp[p_coords] = 0
            self.img[:,:,:2] = temp[:,:,:2]
        else:
            print("Noise type not supported")
            return
        print('success')
        self.refresh()

    #############################################
    ############## Functions Above ##############
    #############################################

import sys
if len(sys.argv) < 2:
  print ("Usage: python lbox.py image.png")
  exit(1)

print("type 'exit' to close")
Prompt(sys.argv[1]).cmdloop()


#!/usr/bin/env python

try:
    from setuptools import setup, find_packages
except ImportError:
    from distribute_setup import use_setuptools
    use_setuptools()
    from setuptools import setup, find_packages

try:
    license = open('LICENSE').read()
except:
    license = None

try:
    readme = open('README').read()
except:
    readme = None

setup(
    name='Rohrpost',
    version='0.0.1',
    author='Pavel Reznikov',
    author_email='pashka.reznikov@gmail.com',
    packages=['rohrpost', 'rohrpost.channels'],
    scripts=[],
    url='https://github.com/troolee/rohrpost',
    license=license,
    description='',
    long_description=readme,
    requires=['tornado', 'unittest2'],
    install_requires=[
    ]
)


import numpy
import scipy.stats
from addict import Dict

import CADETMatch.score as score
import CADETMatch.util as util

name = "dextran_original"
settings = Dict()
settings.adaptive = True
settings.badScore = 0
settings.meta_mask = True
settings.count = 3
settings.failure = (
    [0.0] * settings.count,
    1e6,
    1,
    numpy.array([0.0]),
    numpy.array([0.0]),
    numpy.array([1e6]),
    [1.0] * settings.count,
)

def run(sim_data, feature):
    "special score designed for dextran. This looks at only the front side of the peak up to the maximum slope and pins a value at the elbow in addition to the top"
    selected = feature["origSelected"]
    max_time = feature["max_time"]

    sim_time_values, sim_data_values = util.get_times_values(
        sim_data["simulation"], feature, selected
    )

    exp_time_values = feature["time"][selected]
    exp_data_values = feature["value"][selected]

    sim_spline = util.create_spline(exp_time_values, sim_data_values).derivative(1)
    exp_spline = util.create_spline(exp_time_values, exp_data_values).derivative(1)

    expSelected = selected & (feature["time"] <= max_time)
    expTime = feature["time"][expSelected]
    expValues = feature["value"][expSelected]
    expDerivValues = exp_spline_derivative(expSelected)

    values = sim_spline_derivative(exp_time_values)
    # sim_max_index = numpy.argmax(values)
    # sim_max_time = exp_time_values[sim_max_index]

    simSelected = selected & (feature["time"] <= max_time)

    simTime, simValues = util.get_times_values(
        sim_data["simulation"], feature, simSelected
    )

    simDerivValues = sim_spline_derivative(simSelected)

    score_cross, diff_time = score.cross_correlate(expTime, simValues, expValues)
    scoreDeriv, diff_time_deriv = score.cross_correlate(
        expTime, simDerivValues, expDerivValues
    )

    if score_cross < 0:
        score_cross = 0

    if scoreDeriv < 0:
        scoreDeriv = 0

    temp = [score_cross, scoreDeriv, feature["maxTimeFunction"](diff_time)]

    return (
        temp,
        util.sse(sim_data_values, exp_data_values),
        len(sim_data_values),
        sim_time_values,
        sim_data_values,
        exp_data_values,
        [1.0 - i for i in temp],
    )

def setup(sim, feature, selectedTimes, selectedValues, CV_time, abstol):
    temp = {}
    # change the stop point to be where the max positive slope is along the searched interval
    exp_spline = util.create_spline(selectedTimes, selectedValues).derivative(1)

    values = exp_spline(selectedTimes)
    max_index = numpy.argmax(values)
    max_time = selectedTimes[max_index]

    temp["origSelected"] = temp["selected"]
    temp["selected"] = temp["selected"] & (temp["time"] <= max_time)
    temp["max_time"] = max_time
    temp["maxTimeFunction"] = score.time_function_decay(
        CV_time / 10.0, max_time, diff_input=True
    )
    return temp

def headers(experimentName, feature):
    name = "%s_%s" % (experimentName, feature["name"])
    temp = [
        "%s_Front_Similarity" % name,
        "%s_Derivative_Similarity" % name,
        "%s_Time" % name,
    ]
    return temp