# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file,
# You can obtain one at https://mozilla.org/MPL/2.0/.
# This file is part of NF Compose
# [2019] - [2023] © NeuroForge GmbH & Co. KG

from typing import Any
from django.http.response import HttpResponse

from django.shortcuts import render
from rest_framework.decorators import permission_classes
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth.decorators import login_required

from skipper.settings import LOGIN_URL

version: str
with open('skipper/static-private/version.txt') as version_file:
    version = version_file.read().replace('\n', '')

licenses: str
with open('skipper/static-private/OPENSOURCE_LICENSES.html') as licenses_file:
    licenses = licenses_file.read().replace('\n', '')

@permission_classes([IsAuthenticated])
@login_required(login_url='/' + LOGIN_URL)
def licensing_view(request: Any) -> Any:
    if request.method == 'GET':
        return render(request, 'skipper/licensing.html', {
            'name': 'Licensing',
            'version': version
        })

@permission_classes([IsAuthenticated])
@login_required(login_url='/' + LOGIN_URL)
def licensing_oss_view(request: Any) -> Any:
    return HttpResponse(content=licenses, content_type='text/html')


import configs
import datasets
import numpy as np
from torchvision import datasets as Datasets

__all__ = ['MNIST']

class MNIST(datasets.BaseDataset):

    def __init__(self, cfg, **kwargs):
        super(MNIST, self).__init__(cfg, **kwargs)

    @staticmethod
    def more(cfg):
        cfg.path = configs.env.getdir(cfg.path)
        cfg.source.elements = cfg.source.width * cfg.source.height * cfg.source.time
        out = dict()
        out['elements'] = 1
        cfg.out = configs.BaseConfig(out)
        cfg.cross_folder = 0
        cfg.index_cross = 0
        return cfg

    def load(self):
        train = Datasets.MNIST(self.cfg.path, train=True, download=True)
        test = Datasets.MNIST(self.cfg.path, train=False, download=True)

        source_train, source_test = train.data.numpy()[:, np.newaxis, :, :], test.data.numpy()[:, np.newaxis, :, :]
        source_train, source_test = source_train.astype(np.float32), source_test.astype(np.float32)
        target_train, target_test = train.targets.numpy()[:, np.newaxis], test.targets.numpy()[:, np.newaxis]
        count_train, count_test = len(train), len(test)
        count = count_train + count_test

        return {'source_train': source_train, 'target_train': target_train,
                'source_test': source_test, 'target_test': target_test}, \
               {'count_train': count_train, 'count_test': count_test, 'count': count}

    def __getitem__(self, index):
        if index < self.cfg.data_count['count_train']:
            source, target = self.data['source_train'][index], self.data['target_train'][index]
        else:
            index = index - self.cfg.data_count['count_train']
            source, target = self.data['source_test'][index], self.data['target_test'][index]
        return {'source': source, 'target': target}, index

    def split(self, index_cross=None):
        self._reset_norm(split_items=[['source_train', 'target_train'], ['source_test', 'target_test']])

        trainset = datasets.BaseSplit(self, [[0, self.cfg.data_count['count_train']]])
        testset = datasets.BaseSplit(self, [[self.cfg.data_count['count_train'], self.cfg.data_count['count']]])

        return trainset, testset

if __name__ == "__main__":
    datasets.BaseTest(MNIST).run()


from datetime import timedelta, date

from django.contrib.auth.models import User
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from django.utils.crypto import get_random_string
from activity.models import Activity
from member.models import Club, Membership
from note.models import NoteUser

class TestPermissionDenied(TestCase):
    """
    Load some protected pages and check that we have 403 errors.
    """
    fixtures = ('initial',)

    def setUp(self) -> None:
        # Create sample user with no rights
        self.user = User.objects.create(
            username="toto",
        )
        NoteUser.objects.create(user=self.user)
        self.client.force_login(self.user)

    def test_consos(self):
        response = self.client.get(reverse("note:consos"))
        self.assertEqual(response.status_code, 403)

    def test_create_activity(self):
        response = self.client.get(reverse("activity:activity_create"))
        self.assertEqual(response.status_code, 403)

    def test_activity_entries(self):
        activity = Activity.objects.create(
            name="",
            description="",
            creater=self.user,
            activity_type_id=4,
            organizer_id=1,
            attendees_club_id=1,
            date_start=timezone.now(),
            date_end=timezone.now(),
        )
        response = self.client.get(reverse("activity:activity_entry", kwargs=dict(pk=activity.pk)))
        self.assertEqual(response.status_code, 403)

    def test_invite_activity(self):
        activity = Activity.objects.create(
            name="",
            description="",
            creater=self.user,
            activity_type_id=4,
            organizer_id=1,
            attendees_club_id=1,
            date_start=timezone.now(),
            date_end=timezone.now(),
        )
        response = self.client.get(reverse("activity:activity_invite", kwargs=dict(pk=activity.pk)))
        self.assertEqual(response.status_code, 403)

    def test_create_club(self):
        response = self.client.get(reverse("member:club_create"))
        self.assertEqual(response.status_code, 403)

    def test_add_member_club(self):
        club = Club.objects.create(name=get_random_string(127))
        response = self.client.get(reverse("member:club_add_member", kwargs=dict(club_pk=club.pk)))
        self.assertEqual(response.status_code, 403)

    def test_renew_membership(self):
        club = Club.objects.create(name=get_random_string(127))
        membership = Membership.objects.create(user=self.user, club=club)
        response = self.client.get(reverse("member:club_renew_membership", kwargs=dict(pk=membership.pk)))
        self.assertEqual(response.status_code, 403)

    def test_create_invoice(self):
        response = self.client.get(reverse("treasury:invoice_create"))
        self.assertEqual(response.status_code, 403)

    def test_list_invoices(self):
        response = self.client.get(reverse("treasury:invoice_list"))
        self.assertEqual(response.status_code, 403)

    def test_create_remittance(self):
        response = self.client.get(reverse("treasury:remittance_create"))
        self.assertEqual(response.status_code, 403)

    def test_list_remittance(self):
        response = self.client.get(reverse("treasury:remittance_list"))
        self.assertEqual(response.status_code, 403)

class TestLoginRedirect(TestCase):
    def test_consos_page(self):
        response = self.client.get(reverse("note:consos"))
        self.assertRedirects(response, reverse("login") + "?next=" + reverse("note:consos"), 302, 200)


import openpyxl
from work_on_OS import date_picker
from openpyxl.styles import PatternFill
from tkinter import Tk
from tkinter.filedialog import askopenfilename

Tk().withdraw()
file_mame = askopenfilename(title="Выбор файла", filetypes=[("Excel - файлы", ".xlsx")])

def open_file():
    name = file_mame
    wb = openpyxl.load_workbook(name)
    sheet = wb.active
    return sheet

def validation_of_excel_file():
    sheet = open_file()
    for i in range(len(sheet['1'])):
        if "Я подтверждаю, что являюсь совершеннолетним гражданином " \
           "РФ и потребителем никотинсодержащей продукции" in str(sheet['1'][i].value):
            return 0
    return 1

def calculating_the_number_of_items():
    list_of_purchased_products = []
    list_of_presented_products = []
    capsules = "Капсулы"
    capsules_present = "Сменные капсулы Logic Compact"
    count_of_capsules_buy = 0
    count_of_capsules_present = 0
    device = "Logic Compact девайс"
    device_present = "Электронный испаритель Logic Compact"
    count_of_device_buy = 0
    count_of_device_present = 0
    case_present = "Чехол"
    count_of_case_present = 0
    sheet = open_file()
    acc = 1
    while str(sheet['1'][acc].value).find("Подарки") == -1:
        acc = acc + 1
    zero_point = acc - 14
    for i in range(len(sheet['A'])):
        print(f"Проверка {i+1} строки из {len(sheet['A'])}...")
        for j in range(32+zero_point, len(sheet[i + 1])):
            if str(sheet[i + 2][j].value).find(capsules) != -1:
                count_of_capsules_buy += int(sheet[i + 2][j+1].value)
            if str(sheet[i + 2][j].value).find(device) != -1:
                count_of_device_buy += int(sheet[i + 2][j+1].value)
        for j in range(acc, 31+zero_point):
            if str(sheet[i + 2][j].value).find(capsules_present) != -1:
                count_of_capsules_present += int(sheet[i + 2][j+1].value)
            if str(sheet[i + 2][j].value).find(device_present) != -1:
                count_of_device_present += int(sheet[i + 2][j+1].value)
            if str(sheet[i + 2][j].value).find(case_present) != -1:
                count_of_case_present += int(sheet[i + 2][j+1].value)
        one_action_buy = []
        one_action_present = []
        one_action_buy.append(count_of_capsules_buy)
        one_action_buy.append(count_of_device_buy)
        one_action_present.append(count_of_capsules_present)
        one_action_present.append(count_of_device_present)
        one_action_present.append(count_of_case_present)
        count_of_capsules_buy = 0
        count_of_device_buy = 0
        count_of_capsules_present = 0
        count_of_device_present = 0
        count_of_case_present = 0
        list_of_purchased_products.append(one_action_buy)
        list_of_presented_products.append(one_action_present)
    return list_of_purchased_products, list_of_presented_products, zero_point

def paint_a_cell(cell, color):
    cell.fill = PatternFill(start_color= color,
                            end_color= color,
                            fill_type='solid')

def main_function():
    date = date_picker()
    acc = 0
    four_capsules = 0
    core_device = 0
    one_capsules = 0
    two_capsules = 0
    three_capsules = 0
    case = 0
    name = file_mame
    wb = openpyxl.load_workbook(name)
    sheet = wb.active
    items_and_presents = calculating_the_number_of_items()
    items = items_and_presents[0]
    presents = items_and_presents[1]
    zero_point = items_and_presents[2]
    print("Завершение...")
    for i in range(len(items)-1):
        if items[i][1] == 1:  # Уст обычное + 4 пачке капсул
            if presents[i][0] == 4:
                paint_a_cell(sheet[i + 2][24+zero_point], "0000FF00")
                four_capsules += 1
            else:
                paint_a_cell(sheet[i + 2][24+zero_point], "FFFF0000")
                acc += 1
        elif items[i][0] == 2:  # 2+1
            if presents[i][0] == 1:
                paint_a_cell(sheet[i + 2][24+zero_point], "0000FF00")
                one_capsules += 1
            else:
                paint_a_cell(sheet[i + 2][24+zero_point], "FFFF0000")
                acc += 1
        elif items[i][0] == 3:  # 3 пачке капсул + уст обычное
            if presents[i][1] == 1:
                paint_a_cell(sheet[i + 2][24+zero_point], "0000FF00")
                core_device += 1
            else:
                paint_a_cell(sheet[i + 2][24+zero_point], "FFFF0000")
                acc += 1
        elif items[i][0] == 6:  # 6+3
            if presents[i][0] == 3:
                paint_a_cell(sheet[i + 2][24+zero_point], "0000FF00")
                three_capsules += 1
            else:
                paint_a_cell(sheet[i + 2][24+zero_point], "FFFF0000")
                acc += 1
        elif items[i][0] == 4:  # 4+2
            if presents[i][0] == 2:
                paint_a_cell(sheet[i + 2][24+zero_point], "0000FF00")
                two_capsules += 1
            elif presents[i][2] == 1:
                paint_a_cell(sheet[i + 2][24 + zero_point], "0000FF00")
                case += 1
            else:
                paint_a_cell(sheet[i + 2][24+zero_point], "FFFF0000")
                acc += 1
        elif items[i][0] == 0 and items[i][1] == 0:
            if presents[i][0] == 0 and presents[i][1] == 0:
                pass
            else:
                pass
        else:
            paint_a_cell(sheet[i + 2][24+zero_point], "FFFF0000")
            acc += 1
    for i in range(len(sheet['AG'])-1):
        if str(sheet[i+2][32+zero_point].value).find("NEW Кардхол") != -1:
            paint_a_cell(sheet[i + 2][24+zero_point], "FFFFFF00")

    wb.save("Reports/" + date + '_report.xlsx')
    return four_capsules, core_device, one_capsules, two_capsules, three_capsules, date, acc, case


import random
import laspy as lp
import numpy as np

def one_hot_encode(labels):
    targets = np.array(list(map(label_mapper, labels)))
    nb_classes = 5
    one_hot_targets = np.eye(nb_classes)[targets]
    return one_hot_targets

def group_into_grids(points, grid_dim):
    pt_cloud_grids = []
    sorted_by_x = points[np.argsort(points[:, 0])]
    splits_along_x = np.array_split(sorted_by_x, grid_dim)
    for split in splits_along_x:
        sorted_by_y = split[np.argsort(split[:, 1])]
        splits_along_y = np.array_split(sorted_by_y, grid_dim)
        pt_cloud_grids.extend(splits_along_y)
    return pt_cloud_grids

def label_mapper(label):
    """
    for dales
    Args:
        label:

    Returns:

    """
    label_map = {1.0: 0, 2.0: 1, 6.0: 2, 9.0: 3, 26.0: 4}
    return label_map[label]

def norm_pts(x):
    """
    Normalise points to a
    Unit Sphere
    Args:
        x: input arr

    Returns: points normalised
    to Unit Sphere

    """
    x = x / 1000
    x -= np.mean(x, axis=0)
    dists = np.linalg.norm(x, axis=1)
    return x / np.max(dists)

def normalise_intensities(intensities):
    intensities = np.clip(intensities, a_min=1, a_max=600)
    intensities = (intensities - 1)/600
    return intensities

def generate_samples(points, sample_size):
    inputs = []
    labels = []
    for i in range(10):
        indices = np.random.randint(points.shape[0], size=sample_size)
        sample = points[indices, :]
        inp = sample[:, :-1]
        label = one_hot_encode(sample[:, -1])
        inputs.append(inp)
        labels.append(label)
    return inputs, labels

orig_point_cloud = lp.read('C_37EZ1.las')
orig_data = np.vstack((orig_point_cloud.x, orig_point_cloud.y, orig_point_cloud.z, orig_point_cloud.intensity,
                  orig_point_cloud.classification)).transpose()

# globally normalise intensities
orig_data[:, 3] = normalise_intensities(orig_data[:, 3])

orig_grids = group_into_grids(orig_data, 10)

orig_grids = random.sample(orig_grids, 30)

input_samples = []
label_samples = []
count = 0
for orig_grid in orig_grids:

    grids = group_into_grids(orig_grid, 10)
    for grid in grids:
        grid[:, :3] = norm_pts(grid[:, :3])
        inputs, labels = generate_samples(grid, 2048)
        input_samples.extend(inputs)
        label_samples.extend(labels)
    count += 1
    print(f'{count} files processed')

np.save('inputs.npy', np.asarray(input_samples))
np.save('labels.npy', np.asarray(label_samples))


import jwt

from django.urls import reverse
from django.contrib.sites.shortcuts import get_current_site

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny

from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

from watchLuxuryAPI.settings import SECRET_KEY, SIMPLE_JWT
from watchLuxuryAPI.utils import response_code as rescode

from users.serializers import UserSerializer
from users.models import User

from .serializers import LoginSerializer
from .utils import EmailUtil

class LoginView(TokenObtainPairView):
    permission_classes = (AllowAny, )
    serializer_class = LoginSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        try:
            serializer.is_valid()
        except Exception:
            return Response({
                'code': rescode.API_INVALID_LOGIN,
                'msg': 'Invalid login info',
            }, status=status.HTTP_401_UNAUTHORIZED)

        return Response({
            'code': rescode.API_SUCCESS,
            'msg': 'User authenticated',
            'data': serializer.validated_data,
        }, status=status.HTTP_200_OK)

class RefreshView(TokenRefreshView):
    permission_classes = (AllowAny, )

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        try:
            serializer.is_valid()
        except Exception:
            return Response({
                'code': rescode.API_GENERIC_ERROR,
                'msg': 'Request failed',
            }, status=status.HTTP_400_BAD_REQUEST)

        return Response({
            'code': rescode.API_SUCCESS,
            'msg': 'Access token refreshed',
            'data': serializer.validated_data,
        }, status=status.HTTP_200_OK)

class RegisterView(APIView):
    permission_classes = (AllowAny, )

    def post(self, request):
        print(request.data)

        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.save()

            token = RefreshToken.for_user(user).access_token
            current_site = get_current_site(request).domain
            relative_link = reverse('verify_email')
            EmailUtil.send_email(
                'Verify your email',
                f"""Hi {user.username}. Use the link below to verify your email \n
                http://{current_site}{relative_link}?token={str(token)}
                """,
                user.email
            )

            return Response({
                'code': rescode.API_SUCCESS,
                'msg': f'Created user',
                'data': serializer.data
            }, status=status.HTTP_201_CREATED)

        print(serializer.errors)
        return Response({
            'code': rescode.API_GENERIC_ERROR,
            'msg': 'Request failed',
        }, status=status.HTTP_400_BAD_REQUEST)

class VerifyEmailView(APIView):
    permission_classes = (AllowAny, )

    def get(self, request):
        token = request.query_params.get('token')

        if not token:
            return Response({"msg": "Please provide an access token"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            payload = jwt.decode(token, SECRET_KEY, [SIMPLE_JWT["ALGORITHM"]])
            user = User.objects.get(id=payload['user_id'])
            if not user.is_active:
                user.is_active = True
                user.save()
            return Response({"msg": "User account successfully activated!"}, status=status.HTTP_200_OK)
        except jwt.exceptions.ExpiredSignatureError:
            return Response({"msg": "Activation link expired."}, status=status.HTTP_400_BAD_REQUEST)
        except jwt.exceptions.InvalidSignatureError:
            return Response({"msg": "Invalid activation link."}, status=status.HTTP_400_BAD_REQUEST)


import os
import setuptools

short_description = 'LaunchPanel is a simple interface designed to expose LaunchPad Actions to the user in an intuitive way.'
if os.path.exists('README.md'):
    with open('README.md', 'r') as fh:
        long_description = fh.read()

else:
    long_description = short_description

setuptools.setup(
    name='launchpanel',
    version='2.0.1',
    author='Mike Malinowski',
    author_email='mike.malinowski@outlook.com',
    description=short_description,
    long_description=long_description,
    long_description_content_type='text/markdown',
    url='https://github.com/mikemalinowski/launchpad',
    packages=setuptools.find_packages(),
    classifiers=[
        'Programming Language :: Python',
        'License :: OSI Approved :: MIT License',
        'Operating System :: OS Independent',
    ],
    package_data={
        '': ['_resources/*.png', '_resources/*.ui', '_resources/*.qss'],
    },
    install_requires=['qute', 'scribble', 'factories', 'launchpad'],
    keywords="launch launchpad pad action actions launchpanel panel",
)


""" Tasks for the grades app """
import json

from celery import shared_task
from requests.exceptions import HTTPError
from rest_framework.exceptions import ValidationError
from user_tasks.tasks import UserTask

from registrar.apps.core.jobs import post_job_failure, post_job_success
from registrar.apps.core.tasks import get_program

from . import lms_interop as lms
from .constants import GradeReadStatus
from .serializers import serialize_course_run_grades_to_csv

@shared_task(base=UserTask, bind=True)
# pylint: disable=unused-argument
def get_course_run_grades(self, job_id, user_id, file_format, program_key, internal_course_key):
    """
    A user task that reads course run grade data from the LMS, and writes it to
    a JSON- or CSV-formatted result file.
    """
    program = get_program(job_id, program_key)
    if not program:
        return
    try:
        any_successes, any_failures, grades = lms.get_course_run_grades(
            program.discovery_uuid,
            internal_course_key,
        )
    except HTTPError as err:
        post_job_failure(
            job_id,
            f"HTTP error {err.response.status_code} when getting grades at {err.request.url}"
        )
        return
    except ValidationError as err:
        post_job_failure(
            job_id,
            f"Invalid grade data from LMS: {err}",
        )
        return

    if any_successes and any_failures:
        code_str = str(GradeReadStatus.MULTI_STATUS.value)
    elif not any_successes and not any_failures:
        code_str = str(GradeReadStatus.NO_CONTENT.value)
    elif any_successes:
        code_str = str(GradeReadStatus.OK.value)
    else:
        code_str = str(GradeReadStatus.UNPROCESSABLE_ENTITY.value)

    if file_format == 'json':
        serialized = json.dumps(grades, indent=4)
    elif file_format == 'csv':
        serialized = serialize_course_run_grades_to_csv(grades)
    else:
        raise ValueError(f'Invalid file_format: {file_format}')
    post_job_success(job_id, serialized, file_format, text=code_str)


# import standard plotting and animation
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from mpl_toolkits.mplot3d import Axes3D
from IPython.display import clear_output

# import autograd functionality
from autograd import grad as compute_grad   # The only autograd function you may ever need
import autograd.numpy as np
from autograd import hessian as compute_hess
import math
import time
from matplotlib import gridspec
import copy

class Visualizer:
    '''
    Visualize an input cost function based on data.
    '''

    #### initialize ####
    def __init__(self,data):
        # grab input
        data = data.T
        self.x = data[:,:-1]
        self.y = data[:,-1]

    # sigmoid
    def sigmoid(self,t):
        return 1/(1 + np.exp(-t))

    # sigmoid non-convex least squares
    def sigmoid_least_squares(self,w):
        cost = 0
        for p in range(0,len(self.y)):
            x_p = self.x[p,:]
            y_p = self.y[p]
            a_p = w[0] + np.sum([u*v for (u,v) in zip(x_p,w[1:])])
            cost +=(self.sigmoid(a_p) - y_p)**2
        return cost

    ###### function plotting functions #######
    def plot_costs(self,**kwargs):
        # construct figure
        fig, axs = plt.subplots(1, 2, figsize=(6,3))

        # create subplot with 2 panels
        gs = gridspec.GridSpec(1, 2, width_ratios=[.75,1])
        ax1 = plt.subplot(gs[0]);
        self.scatter_pts(ax1)
        ax2 = plt.subplot(gs[1],projection='3d');

        # pull user-defined args
        viewmax = 3
        if 'viewmax' in kwargs:
            viewmax = kwargs['viewmax']
        view = [20,100]
        if 'view' in kwargs:
            view = kwargs['view']
        label_axes = True
        if 'label_axes' in kwargs:
            label_axes = kwargs['label_axes']

        # make contour plot in each panel
        g = self.sigmoid_least_squares
        self.surface_plot(g,ax2,viewmax,view)

        if label_axes == True:
            ax2.set_xlabel(r'$w_0$',fontsize = 12)
            ax2.set_ylabel(r'$w_1$',fontsize = 12,rotation = 0)
        plt.show()

    ### visualize the surface plot of cost function ###
    def surface_plot(self,g,ax,wmax,view):
        ##### Produce cost function surface #####
        r = np.linspace(-wmax,wmax,300)

        # create grid from plotting range
        w1_vals,w2_vals = np.meshgrid(r,r)
        w1_vals.shape = (len(r)**2,1)
        w2_vals.shape = (len(r)**2,1)
        w_ = np.concatenate((w1_vals,w2_vals),axis = 1)
        g_vals = []
        for i in range(len(r)**2):
            g_vals.append(g(w_[i,:]))
        g_vals = np.asarray(g_vals)

        w1_vals.shape = (np.size(r),np.size(r))
        w2_vals.shape = (np.size(r),np.size(r))

        ### is this a counting cost?  if so re-calculate ###
        levels = np.unique(g_vals)
        if np.size(levels) < 30:
            # plot each level of the counting cost
            levels = np.unique(g_vals)
            for u in levels:
                # make copy of cost and nan out all non level entries
                z = g_vals.copy()
                ind = np.argwhere(z != u)
                ind = [v[0] for v in ind]
                z[ind] = np.nan

                # plot the current level
                z.shape = (len(r),len(r))
                ax.plot_surface(w1_vals,w2_vals,z,alpha = 1,color = '#696969',zorder = 0,shade = True,linewidth=0)

        else: # smooth cost function, plot usual
            # reshape and plot the surface, as well as where the zero-plane is
            g_vals.shape = (np.size(r),np.size(r))

            # plot cost surface
            ax.plot_surface(w1_vals,w2_vals,g_vals,alpha = 1,color = 'w',rstride=25, cstride=25,linewidth=1,edgecolor = 'k',zorder = 2)

        ### clean up panel ###
        ax.xaxis.pane.fill = False
        ax.yaxis.pane.fill = False
        ax.zaxis.pane.fill = False

        ax.xaxis.pane.set_edgecolor('white')
        ax.yaxis.pane.set_edgecolor('white')
        ax.zaxis.pane.set_edgecolor('white')

        ax.xaxis._axinfo["grid"]['color'] =  (1,1,1,0)
        ax.yaxis._axinfo["grid"]['color'] =  (1,1,1,0)
        ax.zaxis._axinfo["grid"]['color'] =  (1,1,1,0)

        ax.view_init(view[0],view[1])

    # scatter points
    def scatter_pts(self,ax):
        if np.shape(self.x)[1] == 1:
            # set plotting limits
            xmax = max(copy.deepcopy(self.x))
            xmin = min(copy.deepcopy(self.x))
            xgap = (xmax - xmin)*0.4
            xmin -= xgap
            xmax += xgap

            ymax = max(copy.deepcopy(self.y))
            ymin = min(copy.deepcopy(self.y))
            ygap = (ymax - ymin)*0.4
            ymin -= ygap
            ymax += ygap

            # initialize points
            ax.scatter(self.x,self.y,color = 'k', edgecolor = 'w',linewidth = 0.9,s = 40)

            # clean up panel
            ax.set_xlim([xmin,xmax])
            ax.set_ylim([ymin,ymax])

            # label axes
            ax.set_xlabel(r'$x$', fontsize = 12)
            ax.set_ylabel(r'$y$', rotation = 0,fontsize = 12)

            ax.axhline(y=0, color='k',zorder = 0,linewidth = 0.5)
            ax.axvline(x=0, color='k',zorder = 0,linewidth = 0.5)

        if np.shape(self.x)[1] == 2:
            # set plotting limits
            xmax1 = copy.deepcopy(max(self.x[:,0]))
            xmin1 = copy.deepcopy(min(self.x[:,0]))
            xgap1 = (xmax1 - xmin1)*0.35
            xmin1 -= xgap1
            xmax1 += xgap1

            xmax2 = copy.deepcopy(max(self.x[:,0]))
            xmin2 = copy.deepcopy(min(self.x[:,0]))
            xgap2 = (xmax2 - xmin2)*0.35
            xmin2 -= xgap2
            xmax2 += xgap2

            ymax = max(self.y)
            ymin = min(self.y)
            ygap = (ymax - ymin)*0.2
            ymin -= ygap
            ymax += ygap

            # initialize points
            ax.scatter(self.x[:,0],self.x[:,1],self.y,s = 40,color = 'k', edgecolor = 'w',linewidth = 0.9)

            # clean up panel
            ax.set_xlim([xmin1,xmax1])
            ax.set_ylim([xmin2,xmax2])
            ax.set_zlim([ymin,ymax])

            ax.set_xticks(np.arange(round(xmin1) +1, round(xmax1), 1.0))
            ax.set_yticks(np.arange(round(xmin2) +1, round(xmax2), 1.0))

            # label axes
            ax.set_xlabel(r'$x_1$', fontsize = 12,labelpad = 5)
            ax.set_ylabel(r'$x_2$', rotation = 0,fontsize = 12,labelpad = 5)
            ax.set_zlabel(r'$y$', rotation = 0,fontsize = 12,labelpad = -3)

            # clean up panel
            ax.xaxis.pane.fill = False
            ax.yaxis.pane.fill = False
            ax.zaxis.pane.fill = False

            ax.xaxis.pane.set_edgecolor('white')
            ax.yaxis.pane.set_edgecolor('white')
            ax.zaxis.pane.set_edgecolor('white')

            ax.xaxis._axinfo["grid"]['color'] =  (1,1,1,0)
            ax.yaxis._axinfo["grid"]['color'] =  (1,1,1,0)
            ax.zaxis._axinfo["grid"]['color'] =  (1,1,1,0)


import numpy as np
import os
import nibabel
import torch
import pandas as pd
from sklearn.base import BaseEstimator
from sklearn.base import TransformerMixin
from collections import OrderedDict
from nilearn.masking import unmask

def bin_age(age_real: torch.Tensor):
    bins = [i for i in range(4, 92, 2)]
    age_binned = age_real.clone()
    for value in bins[::-1]:
        age_binned[age_real <= value] = value
    return age_binned.long()

def read_data(path, dataset, fast):
    print(f"Read {dataset.upper()}")
    df = pd.read_csv(os.path.join(path, dataset + ".tsv"), sep="\t")
    df.loc[df["split"] == "external_test", "site"] = np.nan

    y_arr = df[["age", "site"]].values

    x_arr = np.zeros((10, 3659572))
    if not fast:
        x_arr = np.load(os.path.join(path, dataset + ".npy"), mmap_mode="r")

    print("- y size [original]:", y_arr.shape)
    print("- x size [original]:", x_arr.shape)
    return x_arr, y_arr

class OpenBHB(torch.utils.data.Dataset):
    def __init__(self, root, train=True, internal=True, transform=None,
                 label="cont", fast=False, load_feats=None):
        self.root = root

        if train and not internal:
            raise ValueError("Invalid configuration train=True and internal=False")

        self.train = train
        self.internal = internal

        dataset = "train"
        if not train:
            if internal:
                dataset = "internal_test"
            else:
                dataset = "external_test"

        self.X, self.y = read_data(root, dataset, fast)
        self.T = transform
        self.label = label
        self.fast = fast

        self.bias_feats = None
        if load_feats:
            print("Loading biased features", load_feats)
            self.bias_feats = torch.load(load_feats, map_location="cpu")

        print(f"Read {len(self.X)} records")

    def __len__(self):
        return len(self.y)

    def __getitem__(self, index):
        if not self.fast:
            x = self.X[index]
        else:
            x = self.X[0]

        y = self.y[index]

        if self.T is not None:
            x = self.T(x)

        # sample, age, site
        age, site = y[0], y[1]
        if self.label == "bin":
            age = bin_age(torch.tensor(age))

        if self.bias_feats is not None:
            return x, age, self.bias_feats[index]
        else:
            return x, age, site

class FeatureExtractor(BaseEstimator, TransformerMixin):
    """ Select only the requested data associatedd features from the the
    input buffered data.
    """
    MODALITIES = OrderedDict([
        ("vbm", {
            "shape": (1, 121, 145, 121),
            "size": 519945}),
        ("quasiraw", {
            "shape": (1, 182, 218, 182),
            "size": 1827095}),
        ("xhemi", {
            "shape": (8, 163842),
            "size": 1310736}),
        ("vbm_roi", {
            "shape": (1, 284),
            "size": 284}),
        ("desikan_roi", {
            "shape": (7, 68),
            "size": 476}),
        ("destrieux_roi", {
            "shape": (7, 148),
            "size": 1036})
    ])
    MASKS = {
        "vbm": {
            "path": None,
            "thr": 0.05},
        "quasiraw": {
            "path": None,
            "thr": 0}
    }

    def __init__(self, dtype, mock=False):
        """ Init class.
        Parameters
        ----------
        dtype: str
            the requested data: 'vbm', 'quasiraw', 'vbm_roi', 'desikan_roi',
            'destrieux_roi' or 'xhemi'.
        """
        if dtype not in self.MODALITIES:
            raise ValueError("Invalid input data type.")
        self.dtype = dtype

        data_types = list(self.MODALITIES.keys())
        index = data_types.index(dtype)

        cumsum = np.cumsum([item["size"] for item in self.MODALITIES.values()])

        if index > 0:
            self.start = cumsum[index - 1]
        else:
            self.start = 0
        self.stop = cumsum[index]

        self.masks = dict((key, val["path"]) for key, val in self.MASKS.items())
        self.masks["vbm"] = "./data/masks/cat12vbm_space-MNI152_desc-gm_TPM.nii.gz"
        self.masks["quasiraw"] = "./data/masks/quasiraw_space-MNI152_desc-brain_T1w.nii.gz"

        self.mock = mock
        if mock:
            return

        for key in self.masks:
            if self.masks[key] is None or not os.path.isfile(self.masks[key]):
                raise ValueError("Impossible to find mask:", key, self.masks[key])
            arr = nibabel.load(self.masks[key]).get_fdata()
            thr = self.MASKS[key]["thr"]
            arr[arr <= thr] = 0
            arr[arr > thr] = 1
            self.masks[key] = nibabel.Nifti1Image(arr.astype(int), np.eye(4))

    def fit(self, X, y):
        return self

    def transform(self, X):
        if self.mock:
            #print("transforming", X.shape)
            data = X.reshape(self.MODALITIES[self.dtype]["shape"])
            #print("mock data:", data.shape)
            return data

        # print(X.shape)
        select_X = X[self.start:self.stop]
        if self.dtype in ("vbm", "quasiraw"):
            im = unmask(select_X, self.masks[self.dtype])
            select_X = im.get_fdata()
            select_X = select_X.transpose(2, 0, 1)
        select_X = select_X.reshape(self.MODALITIES[self.dtype]["shape"])
        # print('transformed.shape', select_X.shape)
        return select_X

if __name__ == '__main__':
    import sys
    from torchvision import transforms
    from .transforms import Crop, Pad

    selector = FeatureExtractor("vbm")

    T_pre = transforms.Lambda(lambda x: selector.transform(x))
    T_train = transforms.Compose([
        T_pre,
        Crop((1, 121, 128, 121), type="random"),
        Pad((1, 128, 128, 128)),
        transforms.Lambda(lambda x: torch.from_numpy(x)),
        transforms.Normalize(mean=0.0, std=1.0)
    ])

    train_loader = torch.utils.data.DataLoader(OpenBHB(sys.argv[1], train=True, internal=True, transform=T_train),
                                               batch_size=3, shuffle=True, num_workers=8,
                                               persistent_workers=True)

    x, y1, y2 = next(iter(train_loader))
    print(x.shape, y1, y2)


from django.shortcuts import render
import pickle
import numpy as np
import pandas as pd

## for Ipl
model_path_ipl='model/pipetipl.pkl'
pipe_ipl=pickle.load(open(model_path_ipl,'rb'))
def ipl_pridict(request):
    if request.method=='POST':
       batting_team=request.POST['batting_team']
       bowling_team=request.POST['bowling_team']
       city=request.POST['city']
       current_score=request.POST['current_score']
       overs=request.POST['overs']
       wickets=request.POST['wickets']
       last_five=request.POST['last_five']
       fields=[batting_team,bowling_team,city,current_score,overs,wickets,last_five]
       if batting_team==bowling_team:
           return render(request,'index.html',{'Error':'Batting Team And Bowling Team Can not Be same'})
       if not None in fields:
            overs=float(overs)
            if overs>=5 and overs<=19:
                wickets=float(wickets)
                current_score=float(current_score)
                last_five=float(last_five)
                balls_left=120-(overs*6)
                wickets_left=10-wickets
                crr=current_score/overs
                input=pd.DataFrame([[batting_team,bowling_team,city,current_score,balls_left,wickets_left,crr,last_five]],columns=['batting_team','bowling_team','city','current_score','balls_left','wickets_left','crr','last_five'])
                result=pipe_ipl.predict(input)[0]
                result=np.round(result,0)
                result_dict={'Batting_team':batting_team,
                             'Bowling_team':bowling_team,
                             'Current_Runs':current_score,
                             'overs':overs,
                             'wickets':wickets,
                             'result':result}
            return render(request,'index.html',{'dict':result_dict})
       return render(request,'index.html',{'Error':'Please Type Correct Input'})
    return render(request,'index.html')


import serial
import time
import datetime

list_quality = [
    "160x120",
    "176x144",
    "320x240",
    "352x288",
    "640x480",
    "800x600",
    "1024x768",
    "1280x1024"
]

item_list = []
ser1 = serial.Serial('/dev/ttyUSB0', 921600, timeout=1.5)

class Cameras:
    def __init__(self, num, serial_in, list_items, list_qual):
        self.num = num
        self.serial_in = serial_in
        self.list_items = list_items
        self.list_qual = list_qual

    def take_photo(self):
        data_in = []
        self.serial_in.write(b'1')
        while self.serial_in.inWaiting() == 0:
            pass
        while True:
            try:
                data_in.append(int(self.serial_in.read(1)[-1]).to_bytes(1, 'little'))
            except:
                print("Bytes received = " + str(data_in.__len__()))
                break
        stamp = str(datetime.datetime.time(datetime.datetime.today()))
        stamp = str(stamp[0:2] + "_" + stamp[3:5] + "_" + stamp[6:8])
        photo = open('photos/testing_' + stamp + '.jpg', 'wb')
        for i in range(data_in.__len__()):
            photo.write(data_in[i])
        photo.close()
        data_in.clear()

    def change_q(self, qual_num):
        qual = qual_num + 2
        self.serial_in.write(str(qual).encode())

if __name__ == "__main__":
    cam1 = Cameras(0, ser1, item_list, list_quality)
    cam1.change_q(7)
    time.sleep(3)
    while True:
        cam1.take_photo()
        for i in range(30):
            time.sleep(60)
            print(i+1)


from typing import *
import pastel

class Logger:
  def __init__(self, level:int=1):
    self.level = level
    self.debug = self._make_log_function(
      level=4,
      style_normal='options=dark',
      style_value_primary='options=dark;fg=cyan',
      style_value_secondary='options=dark;fg=blue'
    )
    self.info = self._make_log_function(
      level=3,
      style_normal='fg=default',
      style_value_primary='fg=cyan',
      style_value_secondary='fg=blue'
    )
    self.warn = self._make_log_function(
      level=2,
      style_normal='fg=yellow',
      style_value_primary='fg=default',
      style_value_secondary='options=bold'
    )
    self.error = self._make_log_function(
      level=1,
      style_normal='fg=red',
      style_value_primary='fg=default',
      style_value_secondary='options=bold'
    )
    self.success = self._make_log_function(
      level=3,
      style_normal='fg=green',
      style_value_primary='fg=default',
      style_value_secondary='options=bold'
    )

  def _make_log_function(self, level, style_normal, style_value_primary, style_value_secondary):
    def _function(msg: str, data1=None, data2=None):
      msg = msg.format(
        f'<{style_value_primary}>{data1}</{style_value_primary}>' if data1 is not None else '',
        f'<{style_value_secondary}>{data2}</{style_value_secondary}>' if data2 is not None else ''
      )
      if self.level >= level:
        print(pastel.colorize(f'<{style_normal}>{msg}</{style_normal}>'))
    return _function


"""
<SCRIPTNAME> API TEST </SCRIPTNAME>
<DESCRIPTION>
    完成指定接口的参数测试，运算效率测试
</DESCRIPTION>
<AUTHOR>
    Bingo
</AUTHOR>
<HISTORY>
</HISTORY>
"""
import requests
import json, random, copy
from optparse import OptionParser

def initData(p,typ):

    numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
    character = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
                 'u', 'v', 'w', 's', 'y', 'z']
    special = ['~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '-', '+', '=', '{', '}', '|', '\\', '[',
               ']', '\'', ':', '"', ';', '<', '>', '?', '?', ',', '.', '/', ' ']
    if typ == 'string':
        return random.choice(character)
    if typ == 'integer':
        return int(random.choice(numbers))

def getLog(way,*args):
    if way == True:   #如果方式为0，直接输出到控制台
        for message in args:
            print(message)
    else:
        for message in args:
            with open("Result.txt", "a+") as f:
                f.write(message)
                f.write('\r\n')

def transHttp(ConfigHttp,method):
    global maxtime,resdict
    if method == "get":
        resp = ConfigHttp.get()
    else:
        resp = ConfigHttp.post()
    tim = resp.elapsed.total_seconds() * 1000  # 接口效率
    if int(tim) > maxtime:
        maxtime = int(tim)
        resdict = ConfigHttp.data
    return json.loads(str(resp.content, 'utf-8'))

class ConfigHttp:
    def __init__(self):
        global timeout
        timeout = 2
        self.headers = {}
        self.params = {}
        self.data = {}
        self.host = None
        self.url = None
        self.files = {}
        self.response={}
        self.path = None

    def set_url(self, url):
        self.url = self.host + url

    def set_headers(self, header):
        self.headers = header

    def set_params(self, param):
        self.params = param

    def set_host(self, host):
        self.host = host

    def set_data(self, data):
        self.data = data

    def set_files(self, file):
        self.files = file

        # defined http get method
    def get(self):
        try:
            # response = requests.get(self.url, params=self.params, headers=self.headers, timeout=float(timeout))
            response = requests.get(self.url, params=self.data, headers=self.headers, timeout=float(timeout))

            # response.raise_for_status()

            #return json.loads(str(response.content, 'utf-8'))
            return response  #返回response，提取其中的响应时间，做效率判定
        except TimeoutError:
            # self.logger.error("Time out!")
            return None

    # defined http post method
    def post(self):
        try:
            response = requests.post(self.url, headers=self.headers, data=self.data, files=self.files,
                                     timeout=float(timeout))
            # response.raise_for_status()
            #return json.loads(str(response.content, 'utf-8'))
            return response
        except TimeoutError:
            # self.logger.error("Time out!")
            return None

special = ['~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '-', '+', '=', '{', '}', '|', '\\', '[',
               ']', '\'', ':', '"', ';', '<', '>', '?', '?', ',', '.', '/', ' ']
status = {"success": 2000, "fail":5000,"missarg":4010}
argType = ['string', 'integer']
limiTime = 500  #接口返回效率限制，超过该值将print提醒
geShi = {"tab": "      "}

if __name__ == '__main__':

    optparser = OptionParser()
    #  add the private options here:
    optparser.add_option("-c", action="store_true", dest="way", help="Log打印直接输出到控制台")
    optparser.add_option("-t", action="store_false", dest="way", help="Log打印输入至result.txt")
    optparser.add_option("-p","--path", type=str, dest="path", help="要测试的接口路径，例如：/search/goods")

    (options, args) = optparser.parse_args()
    way = options.way
    path = options.path

    # 需要输入way,path参数，否则退出
    if way == None or path == None:
        optparser.print_help()
        exit()

    API = ConfigHttp()
    url = "http://172.16.31.42:7211/v2/api-docs"
    res_html = requests.get(url)
    res_dict = json.loads(res_html.text)
    host = res_dict["host"]
    API.set_host("http://"+host)
    header = {"x-uc-userdata": "{id:1}"}
    API.set_headers(header)
    paths = res_dict["paths"]
    path_will_test = []
    # path_will_test.append("/search/goods/associativeWords")
    # path_will_test.append("/search/goods")
    path_will_test.append(path)

    for i, j in paths.items():
        if i in path_will_test:
            global maxtime,resdict
            maxtime = 0    #记录接口性能时间，只保留最长时间
            resdict = {}   #记录耗时最长时的请求参数
            API.path = i
            API.set_url(i)  #初始化 url
            api_methods = list(j.keys())[0]
            dict_values = list(j.values())[0]
            getLog(way,dict_values["summary"], "路径："+API.path, "方法："+api_methods)

            API.data = {}

            # 初始化生成正确的data，暂时不处理header参数，并进行正确参数测试
            for parameter in dict_values["parameters"]:
                if parameter['in'] != 'header':
                    API.data[parameter['name']] = initData(parameter, parameter['type'])
            dataRight = copy.deepcopy(API.data) #基准正确参数保留
            res = transHttp(API, api_methods)
            if res['statusCode'] == status["success"]:
                getLog(way, "pass————冒烟测试")

            else:
                getLog(way, "fail————冒烟测试", geShi["tab"]+"错误返回："+json.dumps(res))
                getLog(way, geShi["tab"] + "请求数据：" + str(API.data))

            getLog(way,"<<<<<<<参数类型异常测试>>>>>>")
            for parameter in dict_values["parameters"]:
                if parameter['in'] != 'header':
                    for typ in argType:
                        if typ != parameter['type']:
                            API.data[parameter['name']] = initData(parameter, typ)
                            res = transHttp(API, api_methods)
                            if res['statusCode'] == status["fail"]:
                                getLog(way,"pass————"+ parameter["name"]+"参数要求类型为"+parameter['type']+"，使用"+typ+"类型测试")
                            else:
                                getLog(way,"fail————"+parameter["name"]+"参数要求类型为"+parameter['type']+"，使用"+typ+"类型测试", geShi["tab"]+"错误返回：" + json.dumps(res))
                                getLog(way,geShi["tab"]+"请求数据：" + str(API.data))
                API.data = copy.deepcopy(dataRight)  #重置数据，进行下一个参数修改测试

            getLog(way,"<<<<<<参数必要性测试>>>>>>：")
            for parameter in dict_values["parameters"]:
                if parameter['in'] != 'header':
                    API.data.pop(parameter['name'])
                    res = transHttp(API, api_methods)
                    if parameter['required'] == True:
                        if res['statusCode'] == status["missarg"]:
                            getLog(way,"pass————"+parameter["name"] + "参数要求为必要，缺失类型测试")
                        else:
                            getLog(way,"fail————"+parameter["name"] + "参数要求为必要，缺失类型测试",
                                   geShi["tab"]+"错误返回：" + json.dumps(res))
                            getLog(way,geShi["tab"]+"请求数据：" + str(API.data))
                    else:
                        if res['statusCode'] == status["success"]:
                            getLog(way,"pass————"+parameter["name"] + "参数要求为非必要，缺失类型测试")
                        else:
                            getLog(way,"fail————"+parameter["name"] + "参数要求为非必要，缺失类型测试",
                                   geShi["tab"]+"错误返回：" + json.dumps(res))
                            getLog(way,geShi["tab"]+"请求数据：" + str(API.data))
                API.data = copy.deepcopy(dataRight)  #重置数据，进行下一个参数修改测试
            for parameter in dict_values["parameters"]:
                if parameter['in'] != 'header':
                    if parameter['required'] == False:
                        API.data.pop(parameter['name'])
            res = transHttp(API, api_methods)
            if res['statusCode'] != status["success"]:
                getLog(way,"fail——非必要参数全部缺失测试：",
                       "错误返回：" + json.dumps(res))
                getLog(way,"请求数据：" + str(API.data))
            API.data = copy.deepcopy(dataRight)  # 重置数据，进行下一个参数修改测试

            getLog("<<<<<<参数特殊字符遍历测试>>>>>>") #当参数类型为string则进行该测试
            for parameter in dict_values["parameters"]:
                tag = 0  #作为全部通过标志
                if parameter['in'] != 'header':
                    if parameter['type'] =="string":
                        for c in special:
                            API.data[parameter['name']] = c
                            res = transHttp(API, api_methods)
                            if res['statusCode'] != status["success"]:
                                tag = 1
                                getLog(
                                    way,"fail————"+parameter["name"] + "特殊字符<"+c + ">测试",
                                    geShi["tab"]+"错误返回：" + json.dumps(res))
                                getLog(way,geShi["tab"]+"请求数据：" + str(API.data))
                        if tag == 0:
                            getLog(way,"pass————"+parameter["name"] + "特殊字符测试")
                API.data = copy.deepcopy(dataRight)  # 重置数据，进行下一个参数修改测试

            getLog("<<<<<<接口性能测试>>>>>>")  # 当参数类型为string则进行该测试
            if maxtime > limiTime:
                getLog(
                    way,"fail————接口耗时最长为："+str(maxtime)+"ms,超过设定限定值"+str(limiTime)+"ms",
                    geShi["tab"] + "请求数据：" + json.dumps(resdict))
            else:
                getLog(way,"pass————接口耗时最长为："+str(maxtime)+"ms,小于设定限定值"+str(limiTime)+"ms")


import talib
import numpy as np
from binance.client import Client
import time
from tradingview_ta import TA_Handler, Interval, Exchange
tesla = TA_Handler(
    symbol="TSLA",
    screener="america",
    exchange="NASDAQ",
    interval=Interval.INTERVAL_1_MINUTE
)

api_key = ''
api_secret = ''

client = Client(api_key, api_secret, testnet=True)

symbol = 'BTCUSDT'
quantity = 0.001

def get_indicators(symbol):
    candles = client.get_klines(symbol=symbol, interval=Client.KLINE_INTERVAL_1MINUTE)
    print(candles)
    closes = np.array([float(candle[4]) for candle in candles])
    rsi = talib.RSI(closes, timeperiod=14)
    adx = talib.ADX(closes, closes, closes, timeperiod=14)
    upper, middle, lower = talib.BBANDS(closes, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)
    return rsi[-1], adx[-1], closes[-1], upper[-1], middle[-1], lower[-1]

def place_order(symbol, side, quantity):
    try:
        order = client.create_order(symbol=symbol, side=side, type=Client.ORDER_TYPE_MARKET, quantity=quantity)
        print(order)
    except Exception as e:
        print(e)

while True:
    try:
        rsi, adx, close, upper, middle, lower = get_indicators(symbol)
        print("rsi:", rsi)
        print("adx:", adx)
        print("close:", close)
        print("upper:", upper)
        print("middle:", middle)
        print("lower:", lower)
        if rsi < 30 and adx > 25 and close < lower:
            print('Placing buy order')
            place_order(symbol, Client.SIDE_BUY, quantity)
        elif rsi > 70 and adx > 25 and close > upper:
            print('Placing sell order')
            place_order(symbol, Client.SIDE_SELL, quantity)
    except Exception as e:
        print(e)

    time.sleep(60)


#!/usr/bin/env ipy

##############################################################################
# Written by:  Calen Chen <cachen@novell.com>
#              Ray Wang <rawang@novell.com>
# Date:        03/11/2008
# Description: This is a test application sample for winforms control:
#              TextBox
##############################################################################

import clr

clr.AddReference('System.Windows.Forms')
clr.AddReference('System.Drawing')

from System.Drawing import *
from System.Windows.Forms import *

class TextBoxApp(Form):

    def __init__(self):
        self.Text = "TextBox Control"
        self.Height = 335

        self.label1 = Label()
        self.label1.Text = "Normal TextBox"
        self.label1.AccessibleName = "explicitly set name for label"
        self.label1.Dock = DockStyle.Bottom

        self.textbox1 = TextBox()
        self.textbox1.AcceptsTab = True
        self.textbox1.AcceptsReturn = True
        self.textbox1.Dock = DockStyle.Bottom
        self.textbox1.Name = "self.textbox1"
        self.textbox1.AccessibleName = "explicitly set name for textbox"
        self.textbox1.TextChanged += self.textbox1_enter

        # create a password entry textbox to display asterisks
        # instead of the text typed
        self.label2 = Label()
        self.label2.Text = "Multi-Line TextBox"
        self.label2.Dock = DockStyle.Bottom
        self.label2.Height = 80

        self.textbox2 = TextBox()
        self.textbox2.Dock = DockStyle.Bottom
        self.textbox2.Height = 100
        self.textbox2.Multiline = True
        self.textbox2.ScrollBars = ScrollBars.Both
        self.textbox2.AcceptsTab = True
        self.textbox2.AcceptsReturn = True
        self.textbox2.WordWrap = False
        self.textbox2.TextChanged += self.textbox2_enter

        self.label3 = Label()
        self.label3.Text = "Password TextBox"
        self.label3.Dock = DockStyle.Bottom

        self.textbox3 = TextBox()
        self.textbox3.Dock = DockStyle.Bottom
        self.textbox3.UseSystemPasswordChar = True
        self.textbox3.TextChanged += self.textbox3_enter

        self.label4 = Label()
        self.label4.Text = "non-Editable TextBox"
        self.label4.Dock = DockStyle.Bottom

        self.textbox4 = TextBox()
        self.textbox4.Enabled = False
        self.textbox4.Dock = DockStyle.Bottom

        self.Controls.Add(self.label1)
        self.Controls.Add(self.textbox1)
        self.Controls.Add(self.label2)
        self.Controls.Add(self.textbox2)
        self.Controls.Add(self.label3)
        self.Controls.Add(self.textbox3)
        self.Controls.Add(self.label4)
        self.Controls.Add(self.textbox4)

    def textbox1_enter(self, sender, event):
        self.label1.Text = self.textbox1.Text

    def textbox2_enter(self, sender, event):
        self.label2.Text = self.textbox2.Text

    def textbox3_enter(self, sender, event):
        self.label3.Text = self.textbox3.Text

form = TextBoxApp()
Application.Run(form)


from rest_framework import serializers

from .models import Group, Video, ImageModel

class ImageModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = ImageModel
        fields = '__all__'

    def update(self, instance, validated_data):
        # Delete old image file before setting new one
        if instance.image:
            instance.image.delete()
        return super().update(instance, validated_data)

class VideoReadSerializer(serializers.ModelSerializer):
    aliases = serializers.ListField(source='get_aliases')
    links = serializers.ListField(source='get_links')

    class Meta:
        model = Video
        fields = '__all__'
        extra_kwargs = {
            'alias': {'write_only': True},
            'links_arr': {'write_only': True},
        }

class VideoWriteSerializer(serializers.ModelSerializer):
    aliases = serializers.ListField()
    links = serializers.ListField()

    class Meta:
        model = Video
        fields = '__all__'
        extra_kwargs = {
            'alias': {'read_only': True},
            'links_arr': {'read_only': True},
        }

    def validate(self, attrs):
        attrs['alias'] = Group.build_alias(attrs.pop('aliases'))
        attrs['links_arr'] = Group.build_links(attrs.pop('links'))
        return attrs

    def update(self, instance, validated_data):
        old_order = instance.order
        new_order = validated_data["order"]
        if old_order != new_order:
            instance.reorder(old_order, new_order)
        return super().update(instance, validated_data)

    def create(self, validated_data):
        instance = super().create(validated_data)
        instance.created()
        return instance

    def to_representation(self, instance):
        serializer = GroupReadSerializer(instance=instance.group, context=self.context)
        return serializer.data

class GroupReadSerializer(serializers.ModelSerializer):
    videos = VideoReadSerializer(many=True)
    images = ImageModelSerializer(many=True)
    aliases = serializers.ListField(source='get_aliases')
    links = serializers.ListField(source='get_links')

    class Meta:
        model = Group
        fields = '__all__'
        extra_kwargs = {
            'alias': {'write_only': True},
            'links_arr': {'write_only': True},
        }

class GroupWriteSerializer(serializers.ModelSerializer):
    aliases = serializers.ListField()
    links = serializers.ListField()

    class Meta:
        model = Group
        fields = '__all__'
        extra_kwargs = {
            'alias': {'read_only': True},
            'links_arr': {'read_only': True},
        }

    def validate(self, attrs):
        attrs['alias'] = Group.build_alias(attrs.pop('aliases'))
        attrs['links_arr'] = Group.build_links(attrs.pop('links'))
        return attrs

    def to_representation(self, instance):
        serializer = GroupReadSerializer(instance, context=self.context)
        return serializer.data