# -*- coding: utf-8 -*-
from flask import Flask, render_template, jsonify, Response
from dht import Sensor
import logging
import pigpio
import json
import redis
import time
import ast
import os
import re
import itertools
import datetime
from collections import namedtuple

app = Flask(__name__)
app.debug = True
r = redis.StrictRedis(host='localhost', port=6379, db=0)
Conditions = namedtuple('Conditions', 'temperature humidity message')
logging.basicConfig(level=logging.DEBUG)

pi = pigpio.pi()
CACHE_TIME = 5

@app.route("/")
def home():
    return render_template('main.html')

@app.route("/history")
def history():
    cached_json = r.get('history_cache')
    if cached_json:
        return Response(cached_json, mimetype='application/json')

    samples = r.hgetall('tempsamples')
    if samples:
        samples = ast.literal_eval(samples['samples'])
        logging.debug(type(samples))
        samples = sorted(samples, key=lambda item: datetime.datetime.strptime(
            item['datetime'], '%Y-%m-%d %H:%M:%S'))
        output = {
            'temp': [{
                'x': time.mktime(datetime.datetime.strptime(d['datetime'], '%Y-%m-%d %H:%M:%S').timetuple()),
                'y': float(d['temperature'])
            } for d in samples],
            'humidity': [{
                'x': time.mktime(datetime.datetime.strptime(d['datetime'], '%Y-%m-%d %H:%M:%S').timetuple()),
                'y': float(d['humidity'])
            } for d in samples]
        }
        cache_json = json.dumps(output)
        r.set('history_cache', cache_json, ex=500)
        return jsonify(output)
    else:
        return "Data not available"

@app.route("/current")
def conditions():
    last_reading_str = r.get('last_reading')
    if last_reading_str:
        try:
            last_reading = ast.literal_eval(last_reading_str)
        except:
            logging.warn(
                "Last info from redis was bad. Ignoring and discarding")
            last_reading = None
            r.delete('last_reading')
    else:
        last_reading = None
    if not last_reading or time.time() - last_reading[3] > CACHE_TIME:
        logging.debug("Getting new readings")
        sensor = Sensor(pi, 25)
        sensor.read()
        RETRIES = 4
        sleep = 0.1
        time.sleep(sleep)
        times = 0
        while times < RETRIES and sensor.temperature == -999:
            sleep = sleep * 2
            time.sleep(sleep)
            times += 1
        r.set('last_reading', (sensor.temperature,
                               sensor.humidity, sensor.message, time.time()))
        conditions = Conditions(
            sensor.temperature, sensor.humidity, sensor.message)
        sensor.cancel()
    else:
        logging.debug("Using cached readings")
        conditions = Conditions(
            last_reading[0], last_reading[1], last_reading[2])
    d = {'temperature': str(round(conditions.temperature, 1)),
         'humidity': str(round(conditions.humidity, 1)),
         'message': conditions.message}

    return jsonify(d)

if __name__ == "__main__":
    app.run(host='0.0.0.0')


"""Mambu Value Objects

.. autosummary::
   :nosignatures:
   :toctree: _autosummary
"""

from .mambustruct import MambuStruct

class MambuValueObject(MambuStruct):
    """A Mambu object with some schema but that you won't interact directly
    with in Mambu web, but through some entity."""

class MambuDocument(MambuValueObject):
    """Attached document"""

class MambuAddress(MambuValueObject):
    """Address"""

class MambuIDDocument(MambuValueObject):
    """ID Document"""
    _ownerType = "ID_DOCUMENT"
    """owner type of this entity"""

class MambuComment(MambuValueObject):
    """Comment"""

class MambuDisbursementDetails(MambuValueObject):
    """Disbursement Details"""

class MambuUserRole(MambuValueObject):
    """User Role"""

class MambuGroupMember(MambuValueObject):
    """Group member"""
    _vos = [("roles", "MambuGroupRole")]
    """2-tuples of elements and Value Objects"""

    _entities = [("clientKey", "mambuclient.MambuClient", "client")]
    """3-tuples of elements and Mambu Entities"""

class MambuGroupRole(MambuValueObject):
    """Group member role"""

class MambuDisbursementLoanTransactionInput(MambuValueObject):
    """Disbursment Loan Transaction body"""
    _schema_fields = [
        "amount",
        "bookingDate",
        "externalId",
        "firstRepaymentDate",
        "notes",
        "originalCurrencyCode",
        "shiftAdjustableInterestPeriods",
        "valueDate",
    ]
    """List of schema fields for a loan disbursement transaction."""

class MambuRepaymentLoanTransactionInput(MambuValueObject):
    """Repayment Loan Transaction body"""
    _schema_fields = [
        "amount",
        "bookingDate",
        "externalId",
        "installmentEncodedKey",
        "notes",
        "originalCurrencyCode",
        "prepaymentRecalculationMethod",
        "valueDate",
    ]
    """List of schema fields for a loan repayment transaction."""


import RandomGraph as rg
import plotGraph as pg
import des
import numpy as np
import matplotlib.pyplot as plt
import random

def random_color():
    rgbl = [255, 0, 0]
    random.shuffle(rgbl)
    return tuple(rgbl)

n = 10
m = 1
scheduleTimeout = 5
collectorTimeout = 5
knowledgeTimeout = 10
iteratorTimeout = 15
distance = 1
seed = 6
loss_probability = 1
regenGraphTimeout = 15000
deltaValue = 10
terminationError = 0.01

values = []

Y = list()
Z = list()
X = range(4, 20)
H = list()

for i in X:
    res = []
    missess = []
    exchange = []
    snap = i
    for _ in range(m):
        graph = rg.RandomGraph(i)
        graph.create_graph()
        graph.add_connections()
        nodes = graph.nodes_list()
        edges = graph.edges_dic(distance)
        simulation = des.Sim(nodes, edges, loss_probability, regenGraphTimeout,
                             collectorTimeout, knowledgeTimeout,
                             scheduleTimeout, iteratorTimeout,
                             distance, deltaValue, rg.Types.AVERAGE,
                             terminationError, snap)
        simulation.start()
        des.printNodes(simulation.nodes)
        values.append(simulation.getValues())
        res.append(simulation.time)
        exchange.append(simulation.exchange)
        missess.append(simulation.missess)
    Y.append(np.average(res))
    Z.append(np.average(missess))
    H.append(np.average(exchange))

pg.generateRoundsGraph(X, Y)
pg.generateMissessGraph(X, Z)
pg.generateExchangeGraph(X, H)

snapshot = simulation.snapshot

plt.figure(1)
for key in snapshot.keys():
    if key != 'time':
        plt.plot(snapshot['time'], snapshot[key], "r")

plt.show()

print(values)


print("\n----------------------------------------------------\nExercise 1:")
def classify(input_tuple):
    """Classify people's health status by comparing their age,
    smoking habits and diet."""
    smoker, age, diet = input_tuple
    if smoker == 'yes':
        if int(age) <  29.5:
            return 'less'
        else:
            return 'more'
    else:
        if diet == 'good':
            return 'less'
        else:
            return 'more'

test = classify(('yes', 31, 'good'))
assert test == 'more'
print(test)

print("\n----------------------------------------------------\nExercise 2:")

file_test = 'health-test.txt'
health_test = []

with open(file_test, 'r') as con:
    for line in con:
        extention = line.strip().split(',')
        health_test.append(tuple(extention))
print(health_test)
print("\n----------------------------------------------------\nExercise 3:")

health_tree = []
for subject in health_test:
    health_tree.append(classify(subject))

more_perc = float(health_tree.count('more')) / len(health_tree)
print("predictions: %s" % health_tree)
print("percentage of 'more': %s" % more_perc)

print("\n----------------------------------------------------\nExercise 4:")

file_train = 'health-train.txt'
health_train = []
with open(file_train) as con:
    for line in con:
        content = line.strip().split(',')
        health_train.append((tuple(content[:3]), content[-1]))

print("train-set:\n", health_train)
print("\n----------------------------------------------------\nExercise 5:")
def d(a, b):
    """Calculate distance metric."""
    return (a[0]!=b[0]) + ((float(a[1])-float(b[1]))/50)**2 + (a[2]!=b[2])

def get_nearest_neighbor(target, train_set):
    dist = [d(target, x[0]) for x in train_set]
    return train_set[dist.index(min(dist))]

neighborino = get_nearest_neighbor(('yes', 31, 'good'), health_train)
print(neighborino)

health_neighbor = []

for subject in health_test:
    extention = get_nearest_neighbor(subject, health_train)
    health_neighbor.append(extention[1])

print("Predictions by Decision Tree:\n%s" % health_tree)
print("Predictions by Nearest Neighbor Algorithm:\n%s" % health_neighbor)

indices = []
different = []

for i in range(len(health_tree)):
    if health_tree[i] != health_neighbor[i]:
        indices.append(i)
        different.append(health_test[i])

difference_prob = float(len(different)) / len(health_tree)

print("Index: %s\nDatapoint: %s" % (indices, different))
print("Probability: %s" % difference_prob)
# stay consistent with problem sheet.
print((different, difference_prob))

print("\n----------------------------------------------------\nExercise 6:")

class NearestMeanClassifier(object):
    """Training Method that takes a dataset as input and produces two internal
    vectors corresponding to the mean of each class."""
    def train(self, dataset):
        # Data preparation
        self.classes = []
        data = []
        for line in dataset:
            if line[1] not in self.classes:
                self.classes.append(line[1])

            X, y = line
            smoker, age, diet = X
            numeric_tuple = ((int(smoker == 'yes'),
                              int(age),
                              int(diet == 'poor')), y)
            data.append(numeric_tuple)

        self.class_averages = []

        for classes in self.classes:
            dict_content = [tuples for tuples in data if tuples[1] == classes]
            smoker_list = [tuples[0][0] for tuples in data if tuples[1] == classes]
            age_list = [tuples[0][1] for tuples in data if tuples[1] == classes]
            diet_list = [tuples[0][2] for tuples in data if tuples[1] == classes]

            mean_tuple = ((float(sum(smoker_list)) / len(smoker_list),
                           float(sum(age_list)) / len(age_list),
                           float(sum(diet_list)) / len(diet_list)), classes)
            self.class_averages.append(mean_tuple)

    def predict(self, dataset):
        # Define Distance-Metric
        def d(a, b):
            return (a[0] - b[0])**2 + ((a[1] - b[1])/50)**2 + (a[2] - b[2])**2

        def get_nearest_neighbor(target, train_set):
            dist = [d(target, x[0]) for x in train_set]
            return train_set[dist.index(min(dist))][1]

        self.predictions = []
        for line in dataset:
            smoker, age, diet = line
            line_numeric = (int(smoker == 'yes'),
                            int(age),
                            int(diet == 'poor'))

            prediction = get_nearest_neighbor(line_numeric, self.class_averages)
            self.predictions.append(prediction)

avg_neighbor = NearestMeanClassifier()
avg_neighbor.train(health_train)
avg_neighbor.predict(health_test)

health_avg_neighbor = avg_neighbor.predictions

same_prediction_ind = []
for i in range(len(health_test)):
    is_same = health_tree[i] == health_neighbor[i] == health_avg_neighbor[i]
    same_prediction_ind.append(is_same)

print("Coinciding Predictions:")
for line in same_prediction_ind:
    print(health_test[line])


import math

class Factorial:
    '''
    Factorial is the product of an integer and all the integers below.
    It is represented also by '!'
        Example: Factorial of 5 or 5! = 5 * 4 * 3 * 2 * 1
                                      = 120
    '''

    def __init__(self, number=5):
        self.number = number

    def method_one(self):
        '''
        Using while loop
        '''

        get_factorial = 1
        nums = self.number

        while nums != 1:
            get_factorial *= nums
            nums -= 1

        return f'{self.number}! = {get_factorial}'

    def method_two(self):
        '''
        Using for loop
        '''

        get_factorial = 1

        for num in range(1, self.number + 1):
            get_factorial *= num

        return f'{self.number}! = {get_factorial}'

    def method_three(self):
        '''
        Using built-in "math" module
        '''

        get_factorial = math.factorial(self.number)
        return f'{self.number}! = {get_factorial}'

    def method_four(self, number):
        '''
        Using recursive method
        '''

        if number == 1:
            return number

        return number * self.method_four(number - 1)

if __name__ == '__main__':
    factorial = Factorial()

    print('\nMethod One')
    print(factorial.method_one())

    print('\nMethod Two')
    print(factorial.method_two())

    print('\nMethod Three')
    print(factorial.method_three())

    print('\nMethod Four')
    print(factorial.method_four(factorial.number))


def iswall(x, y):
    magicnum = 1364
    #magicnum = 10
    r = bin(((x * x) + (3 * x) + (2 * x * y) + y + (y * y)) + magicnum)
    #print(r, r[2:])
    cnt = 0
    for c in r[2:]:
        if c == '1': cnt += 1
    #print(r)
    return cnt % 2 != 0

def canmove(x, y, dir):
    if x < 0:
        print("Outside x", dir, x, y)
        return False
    if y < 0:
        print("Outside y", dir, x, y)
        return False

    beenbefore = board[y][x] != 0
    if beenbefore: print("Been before", dir, x, y, board[y][x])
    coordiswall = iswall(x, y) #board[y][x][0]
    if coordiswall: print("Is wall", dir, x, y)
    return not beenbefore and not coordiswall

targetx = 31
targety = 39
#targetx = 7
#targety = 11

def findpath(x, y, path, dir):
    #print("At", x, y, "steps:", len(path), path)

    if (x == targetx) and (y == targety):
        print("Done. On ", x, y, "length", len(path))
        return True

    if not canmove(x, y, "here"): return False
    board[y][x] = 1
    print(dir, "Visiting: ", x, y, "Steps:", len(path))

    path.append([(x, y)])
    if findpath(x+1, y, path, "east") or \
        findpath(x, y+1, path, "south") or \
        findpath(x-1, y, path, "west") or \
        findpath(x, y-1, path, "north"): return True

    print ("XX STUCK!!", x, y)
    return False

#print(iswall(1, 1))
#exit()
board = []
for y in range(1000):
    r = []
    for x in range(1000):
        r.append(0)
    board.append(r)

path = []
findpath(1, 1, path, "here")
print(len(path))

#print(board)


import datetime
import decimal
import uuid

import pytest

import typesystem
import typesystem.formats

class Person(typesystem.Schema):
    name = typesystem.String(max_length=100, allow_blank=False)
    age = typesystem.Integer()

class Product(typesystem.Schema):
    name = typesystem.String(max_length=100, allow_blank=False)
    rating = typesystem.Integer(default=None)

def test_required():
    class Example(typesystem.Schema):
        field = typesystem.Integer()

    value, error = Example.validate_or_error({})
    assert dict(error) == {"field": "This field is required."}

    class Example(typesystem.Schema):
        field = typesystem.Integer(allow_null=True)

    value, error = Example.validate_or_error({})
    assert dict(value) == {"field": None}

    class Example(typesystem.Schema):
        field = typesystem.Integer(default=0)

    value, error = Example.validate_or_error({})
    assert dict(value) == {"field": 0}

    class Example(typesystem.Schema):
        field = typesystem.Integer(allow_null=True, default=0)

    value, error = Example.validate_or_error({})
    assert dict(value) == {"field": 0}

    class Example(typesystem.Schema):
        field = typesystem.String()

    value, error = Example.validate_or_error({})
    assert dict(error) == {"field": "This field is required."}

    class Example(typesystem.Schema):
        field = typesystem.String(allow_blank=True)

    value, error = Example.validate_or_error({})
    assert dict(value) == {"field": ""}

    class Example(typesystem.Schema):
        field = typesystem.String(allow_null=True, allow_blank=True)

    value, error = Example.validate_or_error({})
    assert dict(value) == {"field": None}

def test_schema_validation():
    value, error = Person.validate_or_error({"name": "Tom", "age": "123"})
    assert not error
    assert value == Person(name="Tom", age=123)

    value, error = Person.validate_or_error({"name": "Tom", "age": "123"})
    assert not error
    assert value == Person(name="Tom", age=123)

    value, error = Person.validate_or_error({"name": "Tom", "age": "abc"})
    assert dict(error) == {"age": "Must be a number."}

    value, error = Person.validate_or_error({"name": "Tom"})
    assert dict(error) == {"age": "This field is required."}

def test_schema_eq():
    tom = Person(name="Tom", age=123)
    lucy = Person(name="Lucy", age=123)
    assert tom != lucy

    tom = Person(name="Tom", age=123)
    tshirt = Product(name="T-Shirt")
    assert tom != tshirt

def test_schema_repr():
    tom = Person(name="Tom", age=123)
    assert repr(tom) == "Person(name='Tom', age=123)"

    tom = Person(name="Tom")
    assert repr(tom) == "Person(name='Tom') [sparse]"

def test_schema_instantiation():
    tshirt = Product(name="T-Shirt")
    assert tshirt.name == "T-Shirt"
    assert tshirt.rating == None

    empty = Product()
    assert not hasattr(empty, "name")

    with pytest.raises(TypeError):
        Product(name="T-Shirt", other="Invalid")

    with pytest.raises(TypeError):
        Product(name="x" * 1000)

    tshirt = Product(name="T-Shirt")
    assert Product(tshirt) == tshirt

def test_schema_subclass():
    class DetailedProduct(Product):
        info = typesystem.Text()

    assert set(DetailedProduct.fields.keys()) == {"name", "rating", "info"}

def test_schema_serialization():
    tshirt = Product(name="T-Shirt")

    data = dict(tshirt)

    assert data == {"name": "T-Shirt", "rating": None}

def test_schema_null_items_array_serialization():
    class Product(typesystem.Schema):
        names = typesystem.Array()

    tshirt = Product(names=[1, "2", {"nested": 3}])

    data = dict(tshirt)

    assert data == {"names": [1, "2", {"nested": 3}]}

def test_schema_string_array_serialization():
    class Product(typesystem.Schema):
        names = typesystem.Array(typesystem.String())

    tshirt = Product(names=["T-Shirt"])

    data = dict(tshirt)

    assert data == {"names": ["T-Shirt"]}

def test_schema_dates_array_serialization():
    class BlogPost(typesystem.Schema):
        text = typesystem.String()
        modified = typesystem.Array(typesystem.Date())

    post = BlogPost(text="Hi", modified=[datetime.date.today()])

    data = dict(post)

    assert data["text"] == "Hi"
    assert data["modified"] == [datetime.date.today().isoformat()]

def test_schema_positional_array_serialization():
    class NumberName(typesystem.Schema):
        pair = typesystem.Array([typesystem.Integer(), typesystem.String()])

    name = NumberName(pair=[1, "one"])

    data = dict(name)

    assert data == {"pair": [1, "one"]}

def test_schema_len():
    tshirt = Product(name="T-Shirt")

    count = len(tshirt)

    assert count == 2

def test_schema_getattr():
    tshirt = Product(name="T-Shirt")
    assert tshirt["name"] == "T-Shirt"

def test_schema_missing_getattr():
    tshirt = Product(name="T-Shirt")

    with pytest.raises(KeyError):
        assert tshirt["missing"]

def test_schema_date_serialization():
    class BlogPost(typesystem.Schema):
        text = typesystem.String()
        created = typesystem.Date()
        modified = typesystem.Date(allow_null=True)

    post = BlogPost(text="Hi", created=datetime.date.today())

    data = dict(post)

    assert data["text"] == "Hi"
    assert data["created"] == datetime.date.today().isoformat()
    assert data["modified"] is None

def test_schema_time_serialization():
    class MealSchedule(typesystem.Schema):
        guest_id = typesystem.Integer()
        breakfast_at = typesystem.Time()
        dinner_at = typesystem.Time(allow_null=True)

    guest_id = 123
    breakfast_at = datetime.time(hour=10, minute=30)
    schedule = MealSchedule(guest_id=guest_id, breakfast_at=breakfast_at)

    assert typesystem.formats.TIME_REGEX.match(schedule["breakfast_at"])
    assert schedule["guest_id"] == guest_id
    assert schedule["breakfast_at"] == breakfast_at.isoformat()
    assert schedule["dinner_at"] is None

def test_schema_datetime_serialization():
    class Guest(typesystem.Schema):
        id = typesystem.Integer()
        name = typesystem.String()
        check_in = typesystem.DateTime()
        check_out = typesystem.DateTime(allow_null=True)

    guest_id = 123
    guest_name = "Bob"
    check_in = datetime.datetime.now(tz=datetime.timezone.utc)
    guest = Guest(id=guest_id, name=guest_name, check_in=check_in)

    assert typesystem.formats.DATETIME_REGEX.match(guest["check_in"])
    assert guest["id"] == guest_id
    assert guest["name"] == guest_name
    assert guest["check_in"] == check_in.isoformat()[:-6] + "Z"
    assert guest["check_out"] is None

def test_schema_decimal_serialization():
    class InventoryItem(typesystem.Schema):
        name = typesystem.String()
        price = typesystem.Decimal(precision="0.01", allow_null=True)

    item = InventoryItem(name="Example", price=123.45)

    assert item.price == decimal.Decimal("123.45")
    assert item["price"] == 123.45

    item = InventoryItem(name="test")
    assert dict(item) == {"name": "test", "price": None}
    item = InventoryItem(name="test", price=0)
    assert dict(item) == {"name": "test", "price": 0}

def test_schema_uuid_serialization():
    class User(typesystem.Schema):
        id = typesystem.String(format="uuid")
        username = typesystem.String()

    item = User(id="b769df4a-18ec-480f-89ef-8ea961a82269", username="tom")

    assert item.id == uuid.UUID("b769df4a-18ec-480f-89ef-8ea961a82269")
    assert item["id"] == "b769df4a-18ec-480f-89ef-8ea961a82269"

def test_schema_with_callable_default():
    class Example(typesystem.Schema):
        created = typesystem.Date(default=datetime.date.today)

    value, error = Example.validate_or_error({})
    assert value.created == datetime.date.today()

def test_nested_schema():
    class Artist(typesystem.Schema):
        name = typesystem.String(max_length=100)

    class Album(typesystem.Schema):
        title = typesystem.String(max_length=100)
        release_year = typesystem.Integer()
        artist = typesystem.Reference(Artist)

    value = Album.validate(
        {"title": "Double Negative", "release_year": "2018", "artist": {"name": "Low"}}
    )
    assert dict(value) == {
        "title": "Double Negative",
        "release_year": 2018,
        "artist": {"name": "Low"},
    }
    assert value == Album(
        title="Double Negative", release_year=2018, artist=Artist(name="Low")
    )

    value, error = Album.validate_or_error(
        {"title": "Double Negative", "release_year": "2018", "artist": None}
    )
    assert dict(error) == {"artist": "May not be null."}

    value, error = Album.validate_or_error(
        {"title": "Double Negative", "release_year": "2018", "artist": "Low"}
    )
    assert dict(error) == {"artist": "Must be an object."}

    class Album(typesystem.Schema):
        title = typesystem.String(max_length=100)
        release_year = typesystem.Integer()
        artist = typesystem.Reference(Artist, allow_null=True)

    value = Album.validate(
        {"title": "Double Negative", "release_year": "2018", "artist": None}
    )
    assert dict(value) == {
        "title": "Double Negative",
        "release_year": 2018,
        "artist": None,
    }

def test_nested_schema_array():
    class Artist(typesystem.Schema):
        name = typesystem.String(max_length=100)

    class Album(typesystem.Schema):
        title = typesystem.String(max_length=100)
        release_year = typesystem.Integer()
        artists = typesystem.Array(items=typesystem.Reference(Artist))

    value = Album.validate(
        {
            "title": "Double Negative",
            "release_year": "2018",
            "artists": [{"name": "Low"}],
        }
    )
    assert dict(value) == {
        "title": "Double Negative",
        "release_year": 2018,
        "artists": [{"name": "Low"}],
    }
    assert value == Album(
        title="Double Negative", release_year=2018, artists=[Artist(name="Low")]
    )

    value, error = Album.validate_or_error(
        {"title": "Double Negative", "release_year": "2018", "artists": None}
    )
    assert dict(error) == {"artists": "May not be null."}

    value, error = Album.validate_or_error(
        {"title": "Double Negative", "release_year": "2018", "artists": "Low"}
    )
    assert dict(error) == {"artists": "Must be an array."}

    class Album(typesystem.Schema):
        title = typesystem.String(max_length=100)
        release_year = typesystem.Integer()
        artists = typesystem.Array(items=typesystem.Reference(Artist), allow_null=True)

    value = Album.validate(
        {"title": "Double Negative", "release_year": "2018", "artists": None}
    )
    assert dict(value) == {
        "title": "Double Negative",
        "release_year": 2018,
        "artists": None,
    }

def test_nested_schema_to_json_schema():
    class Artist(typesystem.Schema):
        name = typesystem.String(max_length=100)

    class Album(typesystem.Schema):
        title = typesystem.String(max_length=100)
        release_date = typesystem.Date()
        artist = typesystem.Reference(Artist)

    schema = typesystem.to_json_schema(Album)

    assert schema == {
        "type": "object",
        "properties": {
            "title": {"type": "string", "minLength": 1, "maxLength": 100},
            "release_date": {"type": "string", "minLength": 1, "format": "date"},
            "artist": {"$ref": "#/definitions/Artist"},
        },
        "required": ["title", "release_date", "artist"],
        "definitions": {
            "Artist": {
                "type": "object",
                "properties": {
                    "name": {"type": "string", "minLength": 1, "maxLength": 100}
                },
                "required": ["name"],
            }
        },
    }

def test_definitions_to_json_schema():
    definitions = typesystem.SchemaDefinitions()

    class Artist(typesystem.Schema, definitions=definitions):
        name = typesystem.String(max_length=100)

    class Album(typesystem.Schema, definitions=definitions):
        title = typesystem.String(max_length=100)
        release_date = typesystem.Date()
        artist = typesystem.Reference("Artist")

    schema = typesystem.to_json_schema(definitions)

    assert schema == {
        "definitions": {
            "Artist": {
                "type": "object",
                "properties": {
                    "name": {"type": "string", "minLength": 1, "maxLength": 100}
                },
                "required": ["name"],
            },
            "Album": {
                "type": "object",
                "properties": {
                    "title": {"type": "string", "minLength": 1, "maxLength": 100},
                    "release_date": {
                        "type": "string",
                        "minLength": 1,
                        "format": "date",
                    },
                    "artist": {"$ref": "#/definitions/Artist"},
                },
                "required": ["title", "release_date", "artist"],
            },
        }
    }


""" Pygame base template """

''' Imports '''
import pygame
import random

''' Globals '''
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

SCREEN_WIDTH = 700
SCREEN_HEIGHT = 400

''' Classes '''

class Block(pygame.sprite.Sprite):
    # this class represents a block
    def __init__(self, color):
        super().__init__()                     # super()

        self.image = pygame.Surface([20, 15])
        self.image.fill(color)

        self.rect = self.image.get_rect()

class Player(pygame.sprite.Sprite):
    # this class represents the player
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface([20, 20])
        self.image.fill(RED)

        self.rect = self.image.get_rect()

    def update(self):
        pos = pygame.mouse.get_pos()
        self.rect.x = pos[0]
        self.rect.y = SCREEN_HEIGHT - 30

class Bullet(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface([4, 10])
        self.image.fill(BLACK)

        self.rect = self.image.get_rect()

    def update(self):
        self.rect.y -= 6

''' Game Class '''

class Game():
    ''' Attributes '''
    # all the data we need to run the game

    # sprite lists
    block_list = None
    all_sprites_list = None
    player = None
    game_over = False

    ''' methods '''
    # setup the game
    def __init__(self):
        self.score = 0
        self.game_over = False

        # create sprite lists
        self.block_list = pygame.sprite.Group()
        self.all_sprites_list = pygame.sprite.Group()
        self.bullet_list = pygame.sprite.Group()

        # Create the block sprites
        for i in range(5):
            self.block = Block(BLUE)

            self.block.rect.x = random.randrange(SCREEN_WIDTH - 20)
            self.block.rect.y = random.randrange(250)

            self.block_list.add(self.block)
            self.all_sprites_list.add(self.block)

        self.player = Player()
        self.all_sprites_list.add(self.player)

    # closing window and restarting game
    def process_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return True
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.game_over:
                    self.__init__()
                else:
                    # fire a bullet
                    bullet = Bullet()
                    # set the bullet where the player is
                    bullet.rect.x = self.player.rect.x
                    bullet.rect.y = self.player.rect.y
                    self.all_sprites_list.add(bullet)
                    self.bullet_list.add(bullet)

        return False

    # this method is rin each frame. it updates positions and checks for collisions
    def run_logic(self):

        if not self.game_over:
            # move all the sprites
            self.all_sprites_list.update()

            # bullets mechanics
            for bullet in self.bullet_list:
                block_hit_list = pygame.sprite.spritecollide(bullet, self.block_list, True)

                for block in block_hit_list:
                    self.bullet_list.remove(bullet)
                    self.all_sprites_list.remove(bullet)
                    self.score += 1
                    print(self.score)

            if len(self.block_list) == 0:
                self.game_over = True

    def display_frame(self, screen):
        screen.fill(WHITE)

        if self.game_over:
            # display a text in the middle of the screen
            font = pygame.font.SysFont("serif", 45)
            text1 = font.render("Game Over!", True, BLACK)
            x = (SCREEN_WIDTH // 2) - (text1.get_width() // 2)
            y = (SCREEN_HEIGHT // 2) - (text1.get_height() // 2) - 25
            screen.blit(text1, [x, y])

            font = pygame.font.SysFont("serif", 25)
            text2 = font.render("Click to restart", True, BLACK)
            x = (SCREEN_WIDTH / 2) - (text2.get_width() // 2)
            y = (SCREEN_HEIGHT // 2) - (text2.get_height() // 2) + 25
            screen.blit(text2, [x, y])
        # if game is not over
        else:
            self.all_sprites_list.draw(screen)

        pygame.display.flip()

''' Main function '''

def main():

    pygame.init()

    size = [SCREEN_WIDTH, SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("My Game")
    pygame.mouse.set_visible(False)

    # create ort objects and set the data
    done = False
    clock = pygame.time.Clock()
    game = Game()

    ''' Main Loop '''
    while not done:
        # process events#
        done = game.process_events()
        # update objects
        game.run_logic()
        # draw frame
        game.display_frame(screen)
        # pause for next frame
        clock.tick(60)

    # close window and exit
    pygame.quit()

if __name__ == '__main__':
    main()


from http import HTTPStatus

from django.shortcuts import get_object_or_404, get_list_or_404
from rest_framework.decorators import APIView, api_view
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.response import Response
from watchlist.movie.models import Movie, Review, StreamingPlatform

from .permissions import ReviewUserOrReadOnly
from .serializers import MovieSerializer, ReviewSerializer, StreamingPlatformSerializer

@api_view(["GET", "POST"])
def movies(request):
    """
    List create movie.
    """
    if request.method == "GET":
        movies = Movie.objects.all()
        serializer = MovieSerializer(movies, many=True)
        return Response(serializer.data, status=HTTPStatus.OK)
    if request.method == "POST":
        serializer = MovieSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=HTTPStatus.CREATED)
        return Response(serializer.errors, status=HTTPStatus.BAD_REQUEST)

@api_view(["GET", "PUT", "DELETE"])
def movie_detail(request, pk):
    """
    Retrieve, update or delete a movie.
    """
    movie = get_object_or_404(Movie, pk=pk)

    if request.method == "GET":
        serializer = MovieSerializer(movie)
        return Response(serializer.data)

    elif request.method == "PUT":
        serializer = MovieSerializer(movie, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=HTTPStatus.BAD_REQUEST)

    elif request.method == "DELETE":
        movie.delete()
        return Response(status=HTTPStatus.NO_CONTENT)

class Stream(APIView):
    """
    View to list all streaming platforms or create a new one.
    """

    def get(self, request):
        streaming_platforms = StreamingPlatform.objects.all()
        serializer = StreamingPlatformSerializer(streaming_platforms, many=True, context={"request": request})
        return Response(serializer.data)

    def post(self, request):
        serializer = StreamingPlatformSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=HTTPStatus.CREATED)
        return Response(serializer.errors, status=HTTPStatus.BAD_REQUEST)

class StreamDetail(APIView):
    """
    View to retrieve, update or delete a streaming platform.
    """

    def get(self, request, pk):
        streaming_platform = get_object_or_404(StreamingPlatform, pk=pk)
        serializer = StreamingPlatformSerializer(streaming_platform)
        return Response(serializer.data)

    def put(self, request, pk):
        streaming_platform = get_object_or_404(StreamingPlatform, pk=pk)
        serializer = StreamingPlatformSerializer(streaming_platform, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=HTTPStatus.BAD_REQUEST)

    def delete(self, request, pk):
        streaming_platform = get_object_or_404(StreamingPlatform, pk=pk)
        streaming_platform.delete()
        return Response(status=HTTPStatus.NO_CONTENT)

class UserReviews(APIView):
    """
    View to list all user reviews.
    """

    def get(self, request, username):
        user_reviews = get_list_or_404(Review, user__username=username)
        serializer = ReviewSerializer(user_reviews, many=True)
        return Response(serializer.data)

class QueryUserReviews(APIView):
    """
    View to query user reviews.
    """

    def get(self, request):
        username = request.query_params.get("username")
        if username is not None:
            user_reviews = get_list_or_404(Review, user__username=username)
            serializer = ReviewSerializer(user_reviews, many=True)
            return Response(serializer.data)

class ReviewList(APIView):
    """
    View to list all reviews or create a new one.
    """

    permission_classes = [IsAuthenticatedOrReadOnly]

    def get(self, request):
        reviews = Review.objects.all()
        serializer = ReviewSerializer(reviews, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = ReviewSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=HTTPStatus.CREATED)
        return Response(serializer.errors, status=HTTPStatus.BAD_REQUEST)

class ReviewDetail(APIView):
    """
    View to retrieve, update or delete a review.
    """

    permission_classes = [ReviewUserOrReadOnly]

    def get(self, request, pk):
        review = get_object_or_404(Review, pk=pk)
        serializer = ReviewSerializer(review)
        return Response(serializer.data)

    def put(self, request, pk):
        review = get_object_or_404(Review, pk=pk)
        serializer = ReviewSerializer(review, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=HTTPStatus.BAD_REQUEST)

    def delete(self, request, pk):
        review = get_object_or_404(Review, pk=pk)
        review.delete()
        return Response(status=HTTPStatus.NO_CONTENT)

class MovieReview(APIView):
    """
    Movie review list and create.
    """

    permission_classes = [IsAuthenticated]

    def get(self, request, pk):
        movie = get_object_or_404(Movie, pk=pk)
        reviews = Review.objects.filter(movie=movie)
        serializer = ReviewSerializer(reviews, many=True)
        return Response(serializer.data, status=HTTPStatus.OK)

    def post(self, request, pk):
        """ "
        create a new review for a movie with the given pk in the url.
        """
        movie = get_object_or_404(Movie, pk=pk)
        review_user = request.user
        review_queryset = Review.objects.filter(movie=movie, user=review_user)
        serializer = ReviewSerializer(data=request.data)

        if review_queryset.exists():
            return Response({"message": "You have already reviewed this movie."}, status=HTTPStatus.BAD_REQUEST)

        print(serializer.is_valid())

        if serializer.is_valid():
            if movie.number_ratings == 0:
                movie.average_rating = serializer.validated_data["rating"]
            else:
                movie.average_rating = (movie.average_rating + serializer.validated_data["rating"]) / 2
            movie.number_ratings = movie.number_ratings + 1
            movie.save()
            print(movie)
            serializer.save(movie=movie, user=review_user)
            return Response(serializer.data, status=HTTPStatus.CREATED)
        return Response(serializer.errors, status=HTTPStatus.BAD_REQUEST)


# coding: utf-8

from math import log

n = int(input())

if n == 1:
    print(n)
else:
    digit = int(log(n, 2))
    std = 2 ** (digit+1)
    if std//2 == n:
        print(n)
    else:
        gap = std - n
        result = std - 2 * gap
        print(result)


import cv2
import mediapipe as mp
import numpy as np

from recognition.hand_detector import hand_detector

class body_detector():

    def __init__(self, mode=False, complex=1, smooth_landmarks=True, segmentation=True, smooth_segmentation=True,
                 detectionCon=0.5, trackCon=0.5):
        # save the input variables in local ones
        self.mode = mode
        self.complex = complex
        self.smooth_landmarks = smooth_landmarks
        self.segmentation = segmentation
        self.smooth_segmentation = smooth_segmentation
        self.detectionCon = detectionCon
        self.trackCon = trackCon

        # save the drawing information (from mediapipe)
        self.mpDraw = mp.solutions.drawing_utils
        self.mpDrawStyle = mp.solutions.drawing_styles
        self.mpPose = mp.solutions.pose
        self.pose = self.mpPose.Pose(self.mode, self.complex, self.smooth_landmarks, self.segmentation,
                                     self.smooth_segmentation, self.detectionCon, self.trackCon)
        # create hand detector
        self.hd = hand_detector()

    def findPose(self, img, draw=True):
        # convert to RGB
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        # position and sizeof camera stream
        self.results = self.pose.process(imgRGB)
        # Window size
        width = 1280
        height = 750
        # Black screen to draw the landmarks on
        black_image = np.zeros((height, width, 3), np.uint8)
        black_image= self.hd.findHandsAB(img, black_image)

        # draw silhouette only if landmarks are not null
        if self.results.pose_landmarks:
            if draw:
                self.mpDraw.draw_landmarks(black_image, self.results.pose_landmarks,
                                           self.mpPose.POSE_CONNECTIONS,
                                           # Farbe und Dicke sowie die Punktenradius zeichnen und festlegen, für Linien und anschließend für die Punkte
                                           self.mpDraw.DrawingSpec(color=(245, 117, 66), thickness=5, circle_radius=2),
                                           self.mpDraw.DrawingSpec(color=(245, 66, 230), thickness=5, circle_radius=2))
        return black_image


class Solution:
    def letterCasePermutation(self, S: str) -> List[str]:
        '''
        permutation with case changing using susets method
        copy list -> modify case -> append[i]
        '''

        result = [S]

        for i in range(len(S)):
            if S[i].isalpha() == False:
                continue

            size = len(result)

            #copy list -> modify -> append
            for j in range(size):
                copy = list(result[j])

                #modify only index i
                copy[i] = self.switchCase(S[i])

                #append[i]
                val = "".join(copy)
                result.append(val)

        return result

    def switchCase(self, c):
        if c.isupper() == True:
            return c.lower()
        else:
            return c.upper()


import os
import unittest

import numpy as np
import torch
import torch.nn as nn

from metal.end_model import EndModel, LogisticRegression
from metal.end_model.identity_module import IdentityModule
from metal.metrics import METRICS

class EndModelTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # Set seed
        np.random.seed(1)

        n = 2000

        X = np.random.random((n, 2)) * 2 - 1
        Y = (X[:, 0] > X[:, 1] + 0.25).astype(int) + 1

        X = torch.tensor(X, dtype=torch.float)
        Y = torch.tensor(Y, dtype=torch.long)

        Xs = [X[:1000], X[1000:1500], X[1500:]]
        Ys = [Y[:1000], Y[1000:1500], Y[1500:]]
        cls.single_problem = (Xs, Ys)

    def test_logreg(self):
        em = LogisticRegression(seed=1, input_dim=2, verbose=False)
        Xs, Ys = self.single_problem
        em.train_model(
            (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=5, checkpoint=False
        )
        score = em.score((Xs[2], Ys[2]), verbose=False)
        self.assertGreater(score, 0.95)

    def test_softmax(self):
        em = LogisticRegression(seed=1, input_dim=2, output_dim=3, verbose=False)
        Xs, _ = self.single_problem
        Ys = []
        for X in Xs:
            class1 = X[:, 0] < X[:, 1]
            class2 = X[:, 0] > X[:, 1] + 0.5
            class3 = X[:, 0] > X[:, 1]
            Y = torch.argmax(torch.stack([class1, class2, class3], dim=1), dim=1) + 1
            Ys.append(Y)
        em.train_model(
            (Xs[0], Ys[0]),
            valid_data=(Xs[1], Ys[1]),
            lr=0.1,
            n_epochs=10,
            checkpoint=False,
        )
        score = em.score((Xs[2], Ys[2]), verbose=False)
        self.assertGreater(score, 0.95)

    def test_singletask(self):
        """Test basic single-task end model"""
        em = EndModel(
            seed=1,
            input_batchnorm=False,
            middle_batchnorm=False,
            input_dropout=0.0,
            middle_dropout=0.0,
            layer_out_dims=[2, 10, 2],
            verbose=False,
        )
        Xs, Ys = self.single_problem
        em.train_model(
            (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=5, checkpoint=False
        )
        score = em.score((Xs[2], Ys[2]), verbose=False)
        self.assertGreater(score, 0.95)

    def test_singletask_extras(self):
        """Test batchnorm and dropout"""
        em = EndModel(
            seed=1,
            input_batchnorm=True,
            middle_batchnorm=True,
            input_dropout=0.01,
            middle_dropout=0.01,
            layer_out_dims=[2, 10, 2],
            verbose=False,
        )
        Xs, Ys = self.single_problem
        em.train_model(
            (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=5, checkpoint=False
        )
        score = em.score((Xs[2], Ys[2]), verbose=False)
        self.assertGreater(score, 0.95)

    def test_custom_modules(self):
        """Test custom input/head modules"""
        input_module = nn.Sequential(IdentityModule(), nn.Linear(2, 10))
        middle_modules = [nn.Linear(10, 8), IdentityModule()]
        head_module = nn.Sequential(nn.Linear(8, 2), IdentityModule())
        em = EndModel(
            seed=1,
            input_module=input_module,
            middle_modules=middle_modules,
            head_module=head_module,
            layer_out_dims=[10, 8, 8],
            verbose=False,
        )
        Xs, Ys = self.single_problem
        em.train_model(
            (Xs[0], Ys[0]),
            valid_data=(Xs[1], Ys[1]),
            n_epochs=5,
            verbose=False,
            checkpoint=False,
            show_plots=False,
        )
        score = em.score((Xs[2], Ys[2]), verbose=False)
        self.assertGreater(score, 0.95)

    def test_scoring(self):
        """Test the metrics whole way through"""
        em = EndModel(
            seed=1,
            batchnorm=False,
            dropout=0.0,
            layer_out_dims=[2, 10, 2],
            verbose=False,
        )
        Xs, Ys = self.single_problem
        em.train_model(
            (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=5, checkpoint=False
        )
        metrics = list(METRICS.keys())
        scores = em.score((Xs[2], Ys[2]), metric=metrics, verbose=False)
        for i, metric in enumerate(metrics):
            self.assertGreater(scores[i], 0.95)

    def test_determinism(self):
        """Test whether training and scoring is deterministic given seed"""
        em = EndModel(
            seed=123,
            batchnorm=True,
            dropout=0.1,
            layer_out_dims=[2, 10, 2],
            verbose=False,
        )
        Xs, Ys = self.single_problem
        em.train_model(
            (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=1, checkpoint=False
        )
        score_1 = em.score((Xs[2], Ys[2]), verbose=False)

        # Test scoring determinism
        score_2 = em.score((Xs[2], Ys[2]), verbose=False)
        self.assertEqual(score_1, score_2)

        # Test training determinism
        em_2 = EndModel(
            seed=123,
            batchnorm=True,
            dropout=0.1,
            layer_out_dims=[2, 10, 2],
            verbose=False,
        )
        em_2.train_model(
            (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=1, checkpoint=False
        )
        score_3 = em_2.score((Xs[2], Ys[2]), verbose=False)
        self.assertEqual(score_1, score_3)

    def test_save_and_load(self):
        """Test basic saving and loading"""
        em = EndModel(
            seed=1337,
            input_batchnorm=False,
            middle_batchnorm=False,
            input_dropout=0.0,
            middle_dropout=0.0,
            layer_out_dims=[2, 10, 2],
            verbose=False,
        )
        Xs, Ys = self.single_problem
        em.train_model(
            (Xs[0], Ys[0]), valid_data=(Xs[1], Ys[1]), n_epochs=3, checkpoint=False
        )
        score = em.score((Xs[2], Ys[2]), verbose=False)

        # Save model
        SAVE_PATH = "test_save_model.pkl"
        em.save(SAVE_PATH)

        # Reload and make sure (a) score and (b) non-buffer, non-Parameter
        # attributes are the same
        em_2 = EndModel.load(SAVE_PATH)
        self.assertEqual(em.seed, em_2.seed)
        score_2 = em_2.score((Xs[2], Ys[2]), verbose=False)
        self.assertEqual(score, score_2)

        # Clean up
        os.remove(SAVE_PATH)

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


import requests
import json
import tabulate

def pin_me(pincode):
    url="https://api.postalpincode.in/pincode/"+pincode
    x = requests.get(url)
    print(x.status_code)
    val1=x.text
    val2=json.loads(val1)[0]['PostOffice']
    header=val2[0].keys()
    rows =  [x.values() for x in val2]

    print(tabulate.tabulate(rows,header))

pincode=str(input("Enter pincode:"))
pin_me(pincode)


from threading import Lock
import os
from termcolor import colored

class Logger():
    def __init__(self):
        self.__loading = "|/-\\"
        self.__step = 0
        self.__lock = Lock()

    class Level():
        SUCCESS = ('+', 'green')
        INFO = ('!', 'yellow')
        FAIL = ('-', 'red')
        IMPORTANT = ('!', 'magenta')

    def __clear_line(self):
        (width, _) = os.get_terminal_size()
        print(f"\r" + width * " ", end = "")

    def display_loadbar(self, message:str):
        self.__lock.acquire()
        self.__clear_line()
        self.__step += 1
        print(f"\r[{self.__loading[self.__step%len(self.__loading)]}] {message}", end="")
        self.__lock.release()

    def log(self, message:str, level:Level = Level.SUCCESS):
        self.__lock.acquire()
        self.__clear_line()
        print(colored(f"\r[{level[0]}] {message}", level[1]))
        self.__lock.release()


# A collection of functions to create displays of different
# AVHRR RGB products

# AVHRR Night Microphysics RGB
def AVHRRNightMicrophysicsRGB(b3T, b4T, b5T):
    # red = band5 - band4; -4K to 2K rescalled to 0 to 255
    # grn = band4 - band3; -4K to 6K rescalled to 0 to 255
    # blu = band4; 243K to 293K rescalled to 0 to 255
    m3 = b3T.getMetadataMap()
    b3TM = mask(b3T, '>', 0, 1) * b3T
    b3TM.setMetadataMap(m3)
    red = rescale(b5T-b4T, -4, 2, 0, 255)
    grn = rescale(b4T-b3TM, -4, 6, 0, 255)
    blu = rescale(b4T, 243, 293, 0, 255)
    return combineRGB(red, grn, blu)

# AVHRR Day Microphysics RGB
def AVHRRDayMicrophysicsRGB(b2R, b4T, b6R):
    # red = band2; 0% to 100% reflectance rescalled to 0 to 255
    # grn = band6; 0% to 70% reflectance rescalled to 0 to 255
    # blu = band4; 203K to 323K rescalled to 0 to 255
    red = rescale(b2R, 0, 100, 0, 255)
    grn = rescale(b6R, 0, 70, 0, 255)
    blu = rescale(b4T, 203, 323, 0, 255)
    return combineRGB(red, grn, blu)

# AVHRR Day Microphysics RGB
def AVHRRNaturalColorRGB(b1R, b2R, b6R):
    # red = band6; 0% to 100% reflectance rescalled to 0 to 255
    # grn = band2; 0% to 100% reflectance rescalled to 0 to 255
    # blu = band1; 0% to 100% reflectance rescalled to 0 to 255
    red = rescale(b6R, 0, 100, 0, 255)
    grn = rescale(b2R, 0, 100, 0, 255)
    blu = rescale(b1R, 0, 100, 0, 255)
    return combineRGB(red, grn, blu)

# AVHRR Cloud RGB
def AVHRRCloudRGB(b1R, b2R, b4T):
    # red = band1; 0% to 100% reflectance rescalled to 0 to 255
    # grn = band2; 0% to 100% reflectance rescalled to 0 to 255
    # blu = band4 inverted; 323K to 203K rescalled to 0 to 255
    red = rescale(b1R, 0, 100, 0, 255)
    grn = rescale(b2R, 0, 100, 0, 255)
    blu = rescale(b4T, 323, 203, 0, 255)
    return combineRGB(red, grn, blu)


from click.testing import CliRunner
import click
import importlib
from sqlite_utils import cli, Database, hookimpl, plugins

def test_register_commands():
    importlib.reload(cli)
    assert plugins.get_plugins() == []

    class HelloWorldPlugin:
        __name__ = "HelloWorldPlugin"

        @hookimpl
        def register_commands(self, cli):
            @cli.command(name="hello-world")
            def hello_world():
                "Print hello world"
                click.echo("Hello world!")

    try:
        plugins.pm.register(HelloWorldPlugin(), name="HelloWorldPlugin")
        importlib.reload(cli)

        assert plugins.get_plugins() == [
            {"name": "HelloWorldPlugin", "hooks": ["register_commands"]}
        ]

        runner = CliRunner()
        result = runner.invoke(cli.cli, ["hello-world"])
        assert result.exit_code == 0
        assert result.output == "Hello world!\n"

    finally:
        plugins.pm.unregister(name="HelloWorldPlugin")
        importlib.reload(cli)
        assert plugins.get_plugins() == []

def test_prepare_connection():
    importlib.reload(cli)
    assert plugins.get_plugins() == []

    class HelloFunctionPlugin:
        __name__ = "HelloFunctionPlugin"

        @hookimpl
        def prepare_connection(self, conn):
            conn.create_function("hello", 1, lambda name: f"Hello, {name}!")

    db = Database(memory=True)

    def _functions(db):
        return [
            row[0]
            for row in db.execute(
                "select distinct name from pragma_function_list order by 1"
            ).fetchall()
        ]

    assert "hello" not in _functions(db)

    try:
        plugins.pm.register(HelloFunctionPlugin(), name="HelloFunctionPlugin")

        assert plugins.get_plugins() == [
            {"name": "HelloFunctionPlugin", "hooks": ["prepare_connection"]}
        ]

        db = Database(memory=True)
        assert "hello" in _functions(db)
        result = db.execute('select hello("world")').fetchone()[0]
        assert result == "Hello, world!"

        # Test execute_plugins=False
        db2 = Database(memory=True, execute_plugins=False)
        assert "hello" not in _functions(db2)

    finally:
        plugins.pm.unregister(name="HelloFunctionPlugin")
        assert plugins.get_plugins() == []


# 1. Задайте список. Напишите программу, которая определит, присутствует ли в заданном списке строк некое число.

from typing import List

def have_number(list_number, number):
    have_number = False
    for word in list_number:
        for elem in word:
            if (elem == str(number)):
                have_number = True
                print(f'Такой элемент есть')
                break
    if have_number == False:
        print('Такого элемента нет')

have_number(['gwr5', 'sdGSDH', '8', 'sdHH'], 5)


import arrow
import os
import mimetypes

def datetimeformat(date_str):
    dt = arrow.get(date_str)
    return dt.humanize()

def file_type(key):
    file_info = os.path.splitext(key)
    file_extension = file_info[1].lower()
    try:
        return mimetypes.types_map[file_extension]
    except:
        return 'Unknown'

def sizeof_fmt(num, suffix='B'):
    for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)


import rclpy
from rclpy.node import Node

# Need to add these Dependencies to the package.xml
from std_msgs.msg import String

# This class inherits from Node
class MinimalPublisher(Node):

    # Constructor
    def __init__(self):
        # Call the Node class Constructor and name it
        super().__init__('minimal_publisher')
        # Declares that the node publishes a String over a topic named topic
        # with a queue size of 10
        self.publisher_ = self.create_publisher(String, 'topic', 10)
        # Create a timer that calles timer_callback every 0.5 secs
        timer_period = 0.5  # seconds
        self.timer = self.create_timer(timer_period, self.timer_callback)
        # Counter
        self.i = 0

    def timer_callback(self):
        # Create the message that will be published
        msg = String()
        msg.data = 'Hello World: %d' % self.i
        # Hand the message to the publish that was created in __init__
        self.publisher_.publish(msg)
        # Log to the console that the message was published
        self.get_logger().info('Publishing: "%s"' % msg.data)
        # Increment the counter
        self.i += 1

def main(args=None):
    # Initialize the ros
    rclpy.init(args=args)

    # Create the Publisher
    minimal_publisher = MinimalPublisher()

    # tell ros to spin up the node
    rclpy.spin(minimal_publisher)

    # Destroy the node explicitly
    # (optional - otherwise it will be done automatically
    # when the garbage collector destroys the node object)
    minimal_publisher.destroy_node()
    rclpy.shutdown()

if __name__ == '__main__':
    main()


import cv2
import numpy as np
from scipy.spatial import ConvexHull
from scipy.stats import norm
from scipy.stats import truncnorm

from matplotlib import pyplot as plt

class GroupShapeGeneration(object):

    # This class takes the information from grouping and
    # generates social group shapes.
    # Group shapes are generated by calling the generate_group_shape
    # method after classs initialization.
    #
    # Group shapes are formatted as either a sequence of coordinates
    # in the counter clock direction representing the convex shape blob,
    # or, if an image is given, formatted as drawing the blob on the image.

    def __init__(self, msg):
        # Initialization
        # Inputs:
        # msg: message class object (should have data loaded first)

        if msg.if_processed_data:
            self.video_position_matrix = msg.video_position_matrix
            self.video_velocity_matrix = msg.video_velocity_matrix
            self.video_pedidx_matrix = msg.video_pedidx_matrix
        else:
            raise Exception('Data has not been loaded!')
        if msg.if_processed_group:
            self.video_labels_matrix = msg.video_labels_matrix
        else:
            raise Exception('Grouping has not been performed!')

        if (msg.dataset == 'ucy') and (msg.flag == 2):
            self.const = 0.25
        else:
            self.const = 0.35
        return

    def _find_label_properties(self, frame_idx, label):
        # Given a frame index and a group membership label (group id),
        # find information (positions, velocities, person ids) of
        # all the pedestrians in that group and that frame.
        # Inputs:
        # frame_idx: frame index of the video
        # label: group membership label
        # Outputs:
        # positions: positions of the pedestrians in the given group and frame index.
        # velocities: velocities of the pedestrians in the given group and frame index.
        # pedidx: person ids of the pedestrians in the given group and frame index.

        positions = []
        velocities = []
        pedidx = []
        labels = self.video_labels_matrix[frame_idx]
        for i in range(len(labels)):
            if label == labels[i]:
                positions.append(self.video_position_matrix[frame_idx][i])
                velocities.append(self.video_velocity_matrix[frame_idx][i])
                pedidx.append(self.video_pedidx_matrix[frame_idx][i])
        return positions, velocities, pedidx

    @staticmethod
    def draw_social_shapes(position, velocity, const):
        # This function draws social group shapes
        # given the positions and velocities of the pedestrians.

        # Parameters from Rachel Kirby's thesis
        front_coeff = 1.0
        side_coeff = 2.0 / 3.0
        rear_coeff = 0.5
        safety_dist = 0.5
        total_increments = 20 # controls the resolution of the blobs
        quater_increments = total_increments / 4
        angle_increment = 2 * np.pi / total_increments

        # Draw a personal space for each pedestrian within the group
        contour_points = []
        for i in range(len(position)):
            center_x = position[i][0]
            center_y = position[i][1]
            velocity_x = velocity[i][0]
            velocity_y = velocity[i][1]

            velocity_magnitude = np.sqrt(velocity_x ** 2 + velocity_y ** 2)
            velocity_angle = np.arctan2(velocity_y, velocity_x)
            variance_front = max(0.5, front_coeff * velocity_magnitude)
            variance_side = side_coeff * variance_front
            variance_rear = rear_coeff * variance_front

            # Draw four quater-ovals with the axis determined by front, side and rear "variances"
            # The overall shape contour does not have discontinuities.
            for j in range(total_increments):
                if (j // quater_increments) == 0:
                    prev_variance = variance_front
                    next_variance = variance_side
                elif (j // quater_increments) == 1:
                    prev_variance = variance_rear
                    next_variance = variance_side
                elif (j // quater_increments) == 2:
                    prev_variance = variance_rear
                    next_variance = variance_side
                else:
                    prev_variance = variance_front
                    next_variance = variance_side
                value = np.sqrt(const / ((np.cos(angle_increment * j) ** 2 / (2 * prev_variance)) + (np.sin(angle_increment * j) ** 2 / (2 * next_variance))))
                value = max(safety_dist, value)
                #value = 0.5

                addition_angle = velocity_angle + angle_increment * j
                x = center_x + np.cos(addition_angle) * value
                y = center_y + np.sin(addition_angle) * value
                contour_points.append((x, y))

        #plt.scatter(np.array(contour_points)[:, 0], np.array(contour_points)[:, 1])
        #plt.gca().set_aspect('equal', adjustable='box')
        #plt.draw()
        #plt.show()

        # Get the convex hull of all the personal spaces
        convex_hull_vertices = []
        hull = ConvexHull(np.array(contour_points))
        for i in hull.vertices:
            hull_vertice = (contour_points[i][0], contour_points[i][1])
            convex_hull_vertices.append(hull_vertice)

        return convex_hull_vertices

    def generate_group_shape(self, frame_idx, group_label):
        # Method that generates group shape
        # Inputs
        # frame_idx: frame number
        # group_label: group id
        # frame(optional): an image in numpy array (opencv image format)
        # Outputs
        # If an image frame is not provided
        # vertices: coordinates (in meters) that draws a convex shape blob
        #           in the clockwise direction.
        # If an image frame is provided
        # frame: an updated image with a group shape drawn on it.
        # (Regardless) pedidx: the person ids of the pedestrians in the given group.

        positions, velocities, pedidx = self._find_label_properties(frame_idx, group_label)
        if len(positions) == 0:
            raise Exception('Group does not exist in the given frame!')
        vertices = self.draw_social_shapes(positions, velocities, self.const)
        return vertices, (positions, velocities, pedidx)


# N = no. of rows

def pattern(n):
    x = n * (n + 1) / 2

    for i in range(n):
        for j in range(i + 1):
            print(int(x), end=" ")
            x -= 1
        print()

pattern(5)


from unittest import mock

from . import TestCase, create_environ, get_fixture_file_path

from commissaire_http.authentication import httpbasicauth
from commissaire_http.authentication import httpauthclientcert

class TestHTTPClientCertAuth(TestCase):
    """
    Tests for the HTTPBasicAuthByEtcd class.
    """

    def setUp(self):
        self.cert = {
            "version": 3,
            "notAfter": "Apr 11 08:32:52 2018 GMT",
            "notBefore": "Apr 11 08:32:51 2016 GMT",
            "serialNumber": "07",
            "subject": [
                [["organizationName", "system:master"]],
                [["commonName", "system:master-proxy"]]],
            "issuer": [
                [["commonName", "openshift-signer@1460363571"]]
             ]
        }

    def expect_forbidden(self, data=None, cn=None):
        auth = httpauthclientcert.HTTPClientCertAuth(None, cn=cn)
        environ = create_environ()
        if data is not None:
            environ['SSL_CLIENT_VERIFY'] = data

        self.assertFalse(auth.authenticate(environ, mock.MagicMock()))

    def test_invalid_certs(self):
        """
        Verify authenticate denies when cert is missing or invalid
        """
        self.expect_forbidden()
        self.expect_forbidden(data={"bad": "data"})
        self.expect_forbidden(data={"subject": (("no", "cn"),)})

    def test_valid_certs(self):
        """
        Verify authenticate succeeds when cn matches, fails when it doesn't
        """
        self.expect_forbidden(data=self.cert, cn="other-cn")

        auth = httpauthclientcert.HTTPClientCertAuth(None, cn="system:master-proxy")
        environ = create_environ()
        environ['SSL_CLIENT_VERIFY'] = self.cert
        self.assertTrue(auth.authenticate(environ, mock.MagicMock()))

        # With no cn any is valid
        auth = httpauthclientcert.HTTPClientCertAuth(None)
        self.assertTrue(auth.authenticate(environ, mock.MagicMock()))


__copyright__ = "Copyright 2017 Birkbeck, University of London"
__author__ = "Martin Paul Eve & Andy Byers"
__license__ = "AGPL v3"
__maintainer__ = "Birkbeck Centre for Technology and Publishing"

import errno
import io
import os
import warnings

from django.conf import settings
from django.core.exceptions import SuspiciousFileOperation
from django.template import Origin, TemplateDoesNotExist
from django.template.loaders.base import Loader as BaseLoader
from django.utils._os import safe_join
from django.utils.deprecation import RemovedInDjango20Warning

from utils import setting_handler, function_cache, logic as utils_logic

class Loader(BaseLoader):

    @staticmethod
    @function_cache.cache(120)
    def journal_theme(journal):
        return setting_handler.get_setting('general', 'journal_theme', journal).value

    @staticmethod
    @function_cache.cache(120)
    def base_theme(journal):
        return setting_handler.get_setting('general', 'journal_base_theme', journal).value

    def get_theme_dirs(self):
        from core import models as core_models
        request = utils_logic.get_current_request()
        base_theme, theme_setting = None, None

        if request:
            if request.journal:
                # this is a journal and we should attempt to retrieve any theme settings
                try:
                    theme_setting = self.journal_theme(request.journal)
                except core_models.Setting.DoesNotExist:
                    pass

                try:
                    base_theme = self.base_theme(request.journal)
                except core_models.Setting.DoesNotExist:
                    pass

            elif request.repository:
                # only the material theme supports repositories at the moment.
                theme_setting = 'material'
            else:
                # this is the press site
                theme_setting = request.press.theme

        # allows servers in debug mode to override the theme with ?theme=name in the URL
        if settings.DEBUG and request and request.GET.get('theme'):
            theme_setting = request.GET.get('theme')

        # order up the themes and return them with engine dirs
        themes_in_order = list()

        if theme_setting:
            themes_in_order.append(
                os.path.join(settings.BASE_DIR, 'themes', theme_setting, 'templates')
            )
        if base_theme:
            themes_in_order.append(
                os.path.join(settings.BASE_DIR, 'themes', base_theme, 'templates')
            )

        # if the base_theme and INSTALLATION_BASE_THEME are different,
        # append the INSTALLATION_BASE_THEME.
        if not base_theme == settings.INSTALLATION_BASE_THEME:
            themes_in_order.append(
                os.path.join(settings.BASE_DIR, 'themes', settings.INSTALLATION_BASE_THEME, 'templates')
            )

        return themes_in_order + self.engine.dirs

    def get_dirs(self):
        return self.get_theme_dirs()

    def get_contents(self, origin):
        try:
            with io.open(origin.name, encoding=self.engine.file_charset) as fp:
                return fp.read()
        except IOError as e:
            if e.errno == errno.ENOENT:
                raise TemplateDoesNotExist(origin)
            raise

    def get_template_sources(self, template_name, template_dirs=None):
        """
        Return an Origin object pointing to an absolute path in each directory
        in template_dirs. For security reasons, if a path doesn't lie inside
        one of the template_dirs it is excluded from the result set.
        """
        if not template_dirs:
            template_dirs = self.get_dirs()
        for template_dir in template_dirs:
            try:
                name = safe_join(template_dir, template_name)
            except SuspiciousFileOperation:
                # The joined path was located outside of this template_dir
                # (it might be inside another one, so this isn't fatal).
                continue

            yield Origin(
                name=name,
                template_name=template_name,
                loader=self,
            )

    def load_template_source(self, template_name, template_dirs=None):
        warnings.warn(
            'The load_template_sources() method is deprecated. Use '
            'get_template() or get_contents() instead.',
            RemovedInDjango20Warning,
        )
        for origin in self.get_template_sources(template_name, template_dirs):
            try:
                return self.get_contents(origin), origin.name
            except TemplateDoesNotExist:
                pass
        raise TemplateDoesNotExist(template_name)


from Cryptodome.Cipher import AES
from Cryptodome.Util.Padding import pad, unpad
from Cryptodome.Random import get_random_bytes
from Cryptodome.Hash import SHA3_256
from base64 import b64encode, b64decode

IV_RANDOM_BYTE_COUNT = 8

class CipherHelper:

    def __init__(self, key_file):
        '''
        Creates a new instance of a CipherHelper using the key written in The
        file specified in key_file.
        Uses a AES cipher and uses the file's SHA3 hash to generate a 32 bytes
        key
        '''
        with open(key_file, 'rb') as f:
            self.key = SHA3_256.new().update(f.read()).digest()

    def generate_iv(self, random_bytes):
        '''
        Generates the IV from the key and a byte string

        Returns 16 bytes representing the IV
        '''
        hash = SHA3_256.new().update(random_bytes+self.key).digest()
        # Only return as many bytes as the AES block size
        return hash[0:AES.block_size]

    def encrypt(self, message):
        '''
        Takes a message as a string and returns the encrypted message as a
        string.
        Uses AES in CBC mode together with PKCS7 padding.
        The IV is generated using a number random bytes specified in
        IV_RANDOM_BYTE_COUNT and the key.

        Returns encrypted message
        '''
        random_bytes = get_random_bytes(IV_RANDOM_BYTE_COUNT)
        iv = self.generate_iv(random_bytes)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        padded_msg = pad(message.encode('utf-8'), AES.block_size)
        enc_msg = cipher.encrypt(padded_msg)
        return b64encode(enc_msg + random_bytes).decode('utf-8')

    def decrypt(self, message):
        '''
        Takes an encrypted message and returns the original message as a
        string.

        Returns the original message
        '''
        encrypted_msg = b64decode(message)
        # last bytes are the bytes used to generate the IV
        random_bytes = encrypted_msg[-IV_RANDOM_BYTE_COUNT:]
        encrypted_msg = encrypted_msg[:-IV_RANDOM_BYTE_COUNT]

        iv = self.generate_iv(random_bytes)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        dec_msg = cipher.decrypt(encrypted_msg)
        unpadded_msg = unpad(dec_msg, AES.block_size)
        return unpadded_msg.decode('utf-8')


import pytest
# import requests_mock

from page_analyzer.html import (
    normalize_url,
    validate_url,
    # get_page_data,
)

@pytest.mark.parametrize(
    'url_entered, url_name',
    [
        ('https://ru.hexlet.io/courses/python-basics',
         'https://ru.hexlet.io'),
        ('https://translate.google.com/?hl=ru&sl=ru&tl=en&op=translate',
         'https://translate.google.com'),
    ]
)
def test_normalize_url(url_entered, url_name):
    url_parsed = normalize_url(url_entered)
    assert url_name == url_parsed

class TestValidateUrl:
    urls = [
        ('htp://sorry.jo', 'https://yandex.ru'),
        ('http://benq,ru', 'https://github.com'),
    ]
    empty_url = ''
    not_empty_url = 'https://mail.ru'
    too_long_url = 'o' * 256
    short_url = 'https://itisshorturl.com'

    @pytest.mark.parametrize('url_incorrect, url_correct', urls)
    def test_validate_incorrect_url(self, url_incorrect, url_correct):
        assert ('Некорректный URL', 'danger') in validate_url(url_incorrect)
        assert ('Некорректный URL', 'danger') not in validate_url(url_correct)

    def test_validate_empty_url(self):
        assert ('URL обязателен', 'danger') in validate_url(self.empty_url)
        assert ('URL обязателен', 'danger') not in validate_url(self.not_empty_url)

    def test_validate_too_long_url(self):
        assert ('URL превышает 255 символов', 'danger') in validate_url(self.too_long_url)
        assert ('URL превышает 255 символов', 'danger') not in validate_url(self.short_url)

class TestGetPageData:
    fixture_page = './tests/fixtures/page.html'
    page_url = 'https://ru.hexlet.io'
    expected_page_data = {
        'status_code': 200,
        'h1': 'Test h1',
        'title': 'Test title',
        'description': 'Test content',
    }

    # def test_get_page_data1(self):
    #     with open(self.fixture_page) as fp:
    #         current_page = fp.read()
    #     with requests_mock.Mocker() as mock:
    #         mock.get(
    #             self.page_url,
    #             text=current_page
    #         )
    #         current_data = get_page_data(self.page_url)
    #
    #     assert self.expected_page_data == current_data


from django.urls import path
from . import views

app_name = 'posts'
urlpatterns = [
    path('', views.HomeListView.as_view(), name='home'),
    path('post/<int:pk>/', views.PostDetailView.as_view(), name='detail'),
    path('post/new/', views.PostCreateView.as_view(), name='new'),
    path('post/<int:pk>/delete/', views.DeletePost.as_view(), name='delete'),
    path('post/<int:pk>/edit/', views.EditPost.as_view(), name='edit' ),
    path('home/register/', views.HomeRegister, name='home_register')

]

    # non class based example
    # path('', views.home_view, name='home')