import pytest

@pytest.allure.CRITICAL
@pytest.allure.feature('SELENIUM.Smoke - nomenclature - Navigate')
@pytest.mark.navigate
@pytest.mark.selenium
@pytest.mark.smoke
class TestSeleniumSmokeNomenclatureNavigate:
    # Background #######################################################################################################
    @pytest.fixture()
    @pytest.allure.step('Background')
    def background(self, frontend):
        frontend.general.button_click('Свернуть меню', None, type_web_element='min_menu')

    # Scenario 0 #######################################################################################################
    @pytest.allure.story("""Section Nomenclature""")
    @pytest.mark.navigate_0
    @pytest.mark.case_0
    @pytest.mark.parametrize(
        ('section', 'subsection', 'name'),
        [
            ('Номенклатура', 'Блюда', 'warehouse.nomenclature.dish'),
            ('Номенклатура', 'Модификаторы', 'warehouse.nomenclature.mods'),
            ('Номенклатура', 'Ингредиенты', 'warehouse.nomenclature.singleproduct'),
            ('Номенклатура', 'Полуфабрикаты', 'warehouse.nomenclature.semiproduct')
        ]
    )
    def test_case_selenium_smoke_navigate_0(self, frontend, section, subsection, name):
        frontend.navigate.go_to_module(section, subsection, checking_time=True)
        frontend.navigate.opened_module_with_url(name)

    # Scenario 1 #######################################################################################################
    @pytest.allure.story("""Section Orders""")
    @pytest.mark.navigate_1
    @pytest.mark.case_1
    @pytest.mark.parametrize(
        ('section', 'subsection', 'name'),
        [
            ('Продажи', 'Чеки', 'front.orders'),
            ('Продажи', 'Пречеки', 'front.preorders'),
            ('Продажи', 'Отмены', 'front.cancellations'),
            ('Продажи', 'Внесения/инкассации', 'front.encashment'),
            ('Продажи', 'Кассовые смены', 'front.zreport')

        ]
    )
    def test_case_selenium_smoke_navigate_1(self, frontend, section, subsection, name):
        frontend.navigate.go_to_module(section, subsection, checking_time=True)
        frontend.navigate.opened_module_with_url(name)

    # Scenario 2 #######################################################################################################
    @pytest.allure.story("""Section Documents""")
    @pytest.mark.navigate_2
    @pytest.mark.case_2
    @pytest.mark.parametrize(
        ('section', 'subsection', 'name'),
        [
            ('Склад', 'Приходные накладные', 'warehouse.documents.incoming'),
            ('Склад', 'Расходные накладные', 'warehouse.documents.outgoing'),
            ('Склад', 'Внутренние перемещения', 'warehouse.documents.exchange'),
            ('Склад', 'Акты списания', 'warehouse.documents.discard'),
            ('Склад', 'Акты приготовления', 'warehouse.documents.cooking'),
            ('Склад', 'Акты разбора', 'warehouse.documents.decomposition'),
            ('Склад', 'Акты переработки', 'warehouse.documents.processing'),
            ('Склад', 'Акты инвентаризации', 'warehouse.inventory.document')
        ]
    )
    def test_case_selenium_smoke_navigate_2(self, frontend, section, subsection, name):
        frontend.navigate.go_to_module(section, subsection, checking_time=True)
        frontend.navigate.opened_module_with_url(name)

    # Scenario 3 #######################################################################################################
    @pytest.allure.story("""Section Core Dictionaries""")
    @pytest.mark.navigate_3
    @pytest.mark.case_3
    @pytest.mark.parametrize(
        ('section', 'subsection', 'name', 'tmp'),
        [
            ('Справочники', 'Единицы измерения', 'core.dictionaries.measureunits', 'Единицы измерения'),
            ('Справочники', 'Тэги', 'core.dictionaries.storeitemtag', 'Тэги'),
            ('Справочники', 'Контрагенты', 'warehouse.providers', 'Контрагенты'),
            ('Справочники', 'Причины списания', 'core.dictionaries.orderdiscardreasons', 'Причины отмены заказа'),
            ('Справочники', 'Типы оплат', 'core.dictionaries.paymenttypes', 'Типы оплат'),
            ('Справочники', 'Фасовки', 'core.dictionaries.packingunits', 'Фасовки товаров')
        ]
    )
    def test_case_selenium_smoke_navigate_3(self, frontend, section, subsection, name, tmp):
        frontend.navigate.go_to_module(section, subsection, checking_time=True)
        frontend.navigate.opened_module_with_url(name)

    # Scenario 4 #######################################################################################################
    @pytest.allure.story("""Section Personnel""")
    @pytest.mark.navigate_4
    @pytest.mark.case_4
    @pytest.mark.parametrize(
        ('section', 'subsection', 'name'),
        [
            ('Персонал', 'Сотрудники', 'personnel.employee'),
            ('Персонал', 'Должности', 'users.role')
        ]
    )
    def test_case_selenium_smoke_navigate_4(self, frontend, section, subsection, name):
        frontend.navigate.go_to_module(section, subsection, checking_time=True)
        frontend.navigate.opened_module_with_url(name)

    # Scenario 5 #######################################################################################################
    @pytest.allure.story("""Section CRM""")
    @pytest.mark.navigate_5
    @pytest.mark.case_5
    @pytest.mark.parametrize(
        ('section', 'subsection', 'name', 'tmp'),
        [
            ('CRM', 'Клиенты', 'crm.customer', 'Клиенты CRM'),
            ('CRM', 'Группы клиентов', 'crm.customer.group', 'Группы клиентов CRM'),
            ('CRM', 'Фиксированные скидки', 'crm.settings.fixed', 'Фиксированные скидки'),
            ('CRM', 'Скидки по расписанию', 'crm.settings.scheduled', 'Скидки по расписанию'),
            ('CRM', 'Типы бонусных счетов', 'crm.accounting.account.type', 'Типы бонусных счетов'),
            ('CRM', 'Бонусные программы', 'crm.settings.bonus', 'Бонусные программы'),
            ('CRM', 'Надбавки', 'crm.settings.markup', 'Надбавки')
        ]
    )
    def test_case_selenium_smoke_navigate_5(self, frontend, section, subsection, name, tmp):
        frontend.navigate.go_to_module(section, subsection, checking_time=True)
        frontend.navigate.opened_module_with_url(name)

    # Scenario 6 #######################################################################################################
    @pytest.allure.story("""Section Company""")
    @pytest.mark.navigate_6
    @pytest.mark.case_6
    @pytest.mark.parametrize(
        ('section', 'subsection', 'name'),
        [
            ('Предприятие', 'Настройки', 'core.company'),
            ('Предприятие', 'Организации', 'core.company.businesses'),
            ('Предприятие', 'Склады', 'warehouse.store'),
            ('Предприятие', 'Места приготовления', 'warehouse.nomenclature.cooking_place'),
            ('Предприятие', 'Места реализации', 'warehouse.nomenclature.sale_place'),
            ('Предприятие', 'Заведения', 'front.tablemanagement')
        ]
    )
    def test_case_selenium_smoke_navigate_6(self, frontend, section, subsection, name):
        frontend.navigate.go_to_module(section, subsection, checking_time=True)
        frontend.navigate.opened_module_with_url(name)

    # Scenario 7 #######################################################################################################
    @pytest.allure.story("""Section Devices""")
    @pytest.mark.navigate_7
    @pytest.mark.case_7
    @pytest.mark.parametrize(
        ('section', 'subsection', 'name'),
        [
            ('Устройства', 'Фискальные регистраторы', 'front.terminals.kkm'),
            ('Устройства', 'Банковские терминалы', 'front.terminals.pos'),
            ('Устройства', 'Принтеры', 'front.terminals.ticketdevices'),
            ('Устройства', 'QR Box', 'front.terminals.raspberry')

        ]
    )
    def test_case_selenium_smoke_navigate_7(self, frontend, section, subsection, name):
        frontend.navigate.go_to_module(section, subsection, checking_time=True)
        frontend.navigate.opened_module_with_url(name)

# # Scenario 11 ######################################################################################################
# @pytest.allure.story("""Проверка даты и названия""")
# @pytest.mark.navigate_11
# @pytest.mark.case_11
# def test_case_selenium_smoke_navigate_11(self, frontend, rest_api, psql, couchdb, background):
#     pass


#неведомая ебаная хуйня
p = int(input())
c = 1
b = 0
while p != 0:
    v = int(input())
    p, v = v, p
    if v == p:
        c += 1
    if c > b:
        b = c
    if p != v:
        c = 1
print(b)

#более понятное решение

prev = -1
curr_rep_len = 0
max_rep_len = 0
element = int(input())
while element != 0:
    if prev == element:
        curr_rep_len += 1
    else:
        prev = element
        max_rep_len = max(max_rep_len, curr_rep_len) #сравнивает два числа =>
        # В результате она возвращает список, в котором попался бОльший элемент при сравнении
        curr_rep_len = 1
    element = int(input())
max_rep_len = max(max_rep_len, curr_rep_len)
print(max_rep_len)

Максимальное число подряд идущих равных.py


#!/usr/bin/python3
import sqlite3
import os

class database:

    # Initialise the database
    def __init__(self):
        self.conn = sqlite3.connect("events.db")
        self.c = self.conn.cursor()

    # Connect to the database. If the file doesn't exist, it creates it.
    def db_connect(self):

        # Thanks to stackoverflow for help with this one.
        # https://stackoverflow.com/a/1604121
        database_exists = self.c.execute("SELECT name FROM sqlite_master WHERE name='downloads'").fetchone()

        if not database_exists:
            # id = DiceVideoId
            # name = the name of event/episode
            # quality = bitrate
            # date = timestamp
            self.c.execute("CREATE TABLE downloads (id integer unique, name text, quality text, date integer)")
            self.conn.commit()

    # Insert download into the database
    def db_ins(self, video_id, video_name, video_qual, timestamp):
        try:
            self.c.execute("INSERT INTO downloads VALUES ('{}', '{}', '{}', '{}')".format(video_id, video_name, video_qual, timestamp))
            self.conn.commit()
        except sqlite3.IntegrityError:
            print("Error: Couldn't add {} to the database. ID already exists.".format(video_id))

    # Update download information in the database
    def db_upd(self, video_id, video_name, video_qual, timestamp):
        self.c.execute("UPDATE downloads SET name = '{}', quality = '{}', date = '{}' WHERE id = {}".format(video_name, video_qual, timestamp, video_id))
        print("UPDATE downloads SET name = '{}', quality = '{}', date = '{}' WHERE id = {}".format(video_name, video_qual, timestamp, video_id))
        self.conn.commit()

    # Query the database for previously downloaded episode
    def db_query(self, video_id):
        #self.c.execute("INSERT INTO downloads VALUES ('{}', '{}', '{}', '{}')".format(video_id, video_name, video_qual, timestamp))
        result = self.c.execute("SELECT date FROM downloads WHERE id = '{}'".format(video_id))
        if result.fetchone():
            return True
        else:
            return False

    # Close the database, and commit any final changes
    def db_close(self):
        self.conn.commit()
        self.conn.close()

if __name__ == "__main__":
    print("Please run python main.py instead.")
    pass


from discord.ext import commands as u_MiscCMDs
import discord.utils

import sys
import unicodedata

from Servo import bot
from Servo import general_channel, sims_legacies_channel,announcements_channel, labratory_channel

class MemberChanges:
    """Checks for when changes to members occure."""

    def __init__(self, bot):
        self.bot = bot

    @bot.event
    async def on_member_join(self, member):
        """When a member joins, the bot will welcome them
           to the server with a mention.

           The user will then be added to the user files."""
        server = member.server
        fmt = 'Welcome {0.mention} to the **{1.name} Chat Server**! \U0001F604'
        await self.bot.send_message(server, fmt.format(member, server))
        name = str(member.name)
        newName = unicodedata.normalize('NFKD', names).encode('ascii','ignore')
        with open('C:\\Users\\harpe\\Documents\\Discord\\Bots\\USERS\\' + 'Points.SimsVIP.txt', "a") as p:
            if str(newName) not in p:
                p.write('\n{} (#{}) | POINTS: 500'.format(newName, member.discriminator))
        with open('C:\\Users\\harpe\\Documents\\Discord\\Bots\\USERS\\' + 'Members.SimsVIP.txt', "a") as m:
            if str(newNames) not in p:
                m.write('\n{} (#{}) | {}'.format(newNames, member.discriminator, member.id))

    @bot.event
    async def on_member_remove(self, member):
        server = member.server
        fmt = '{0.mention} has left the server. \U0001F626'
        await self.bot.send_message(server, fmt.format(member))
        name = str(member.name)
        newName = unicodedata.normalize('NFKD', names).encode('ascii','ignore')
        with open('C:\\Users\\harpe\\Documents\\Discord\\Bots\\USERS\\' + 'Points.SimsVIP.txt', "a") as p:
            for line in p:
                if str(newName) not in line:
                    p.write('\n{} (#{}) | POINTS: 500'.format(newName, member.discriminator))
        with open('C:\\Users\\harpe\\Documents\\Discord\\Bots\\USERS\\' + 'Members.SimsVIP.txt', "a") as m:
            for line in m:
                if str(newNames) not in line:
                    m.write('\n{} (#{}) | {}'.format(newNames, member.discriminator, member.id))
    @bot.event
    async def on_member_update(self, before, after):
        if after.name != before.name:
            await self.bot.send_message(general_channel, '**{}** has changed their username to **{}**.'.format(before.name, after.name))
            beforenames = str(before.name)
            afternames = str(after.name)
            newBeforeNames = unicodedata.normalize('NFKD', beforenames).encode('ascii','ignore')
            newAfterNames = unicodedata.normalize('NFKD', afternames).encode('ascii','ignore')
            m = open('C:\\Users\\harpe\\Documents\\Discord\\Bots\\USERS\\' + 'Members.SimsVIP.txt','r')
            filedata = m.read()
            m.close()
            p = open('C:\\Users\\harpe\\Documents\\Discord\\Bots\\USERS\\' + 'Points.SimsVIP.txt','r')
            filedata = p.read()
            p.close()

            newdata = filedata.replace(str(newBeforeNames),str(newAfterNames))

            m = open('C:\\Users\\harpe\\Documents\\Discord\\Bots\\USERS\\' + 'Members.SimsVIP.txt','w')
            m.write(newdata)
            m.close()
            p = open('C:\\Users\\harpe\\Documents\\Discord\\Bots\\USERS\\' + 'Points.SimsVIP.txt','w')
            p.write(newdata)
            p.close()
        if after.nick != before.nick:
            if after.nick is None:
                await self.bot.send_message(general_channel, '**{}** has cleared their nickname.'.format(before.name))
            else:
                await self.bot.send_message(general_channel, '**{}** has changed their nickname to **{}**.'.format(before.name, after.nick))

def setup(bot):
    MemChngs = MemberChanges(bot)
    bot.add_cog(MemChngs)


from threading import Thread
from time import sleep

count = 0;

def gcd(x, y, n):
    x1 = y;
    y1 = x % y;

    if(y1 == 0):
        return (y, n);
    else:
        return gcd(x1, y1, n + 1);

def E(x, y):
    ret_val = gcd(x, y, 1);
    return ret_val[1];

def S(n1, n2):
    global count;
    for x in range(n1, n2 + 1):
        for y in range(n1, n2 + 1):
            count += E(x, y);
    return count;

print(S(1, 100));


def getMiddleThreeChars(sampleStr):
    middleIndex = int(len(sampleStr) / 2)
    print("Original String is", sampleStr)
    middleThree = sampleStr[middleIndex - 1:middleIndex + 2]
    print("Middle three chars ", middleThree)

getMiddleThreeChars("JhonDipPeta")
getMiddleThreeChars("Jasonay")

def appendMiddle(s1, s2):
  middleIndex = int(len(s1) /2)
  print("Original Strings are", s1, s2)
  middleThree = s1[:middleIndex:]+ s2 +s1[middleIndex:]
  print("After appending new string in middle", middleThree)

appendMiddle("Aut", "Kelly")
def mix_string(s1, s2):
    first_char = s1[:1] + s2[:1]
    middle_char = s1[int(len(s1) / 2):int(len(s1) / 2) + 1] + s2[int(len(s2) / 2):int(len(s2) / 2) + 1]
    last_char = s1[len(s1) - 1] + s2[len(s2) - 1]
    res = first_char + middle_char + last_char
    print("Mix String is ", res)

s1 = "Ameri"
s2 = "Japan"
mix_string(s1, s2)

def findDigitsCharsSymbols(inputString):
  charCount = 0
  digitCount = 0
  symbolCount = 0
  for char in inputString:
      if char.islower() or char.isupper():
          charCount += 1
      elif char.isnumeric():
          digitCount += 1
      else:
          symbolCount += 1
  print("Chars = ", charCount, "Digits = ", digitCount, "Symbol = ", symbolCount)
inputString = "P@#yn26at^&i5v"
print("total counts of chars, digits,and symbols \n")
findDigitsCharsSymbols(inputString)

def mixString(s1, s2):
  s2 = s2[::-1]
  lengthS1 = len(s1)
  lengthS2 = len(s2)
  length  = lengthS1 if lengthS1 > lengthS2 else lengthS2
  resultString=""
  for i in range(length):
      if (i < lengthS1):
          resultString = resultString + s1[i]
      if (i < lengthS2):
          resultString = resultString + s2[i]
  print(resultString)
s1 = "Abc"
s2 = "Xyz"
mixString(s1, s2)


from bs4 import BeautifulSoup
import requests

url = 'http://www.tripadvisor.cn/Attractions-g60763-Activities-New_York_City_New_York.html'
wb_data = requests.get(url)
soup = BeautifulSoup(wb_data.text,'lxml')
titles = soup.select(' div.property_title > a[target="_blank"]')
imgs = soup.select('img[width="160"]')
tags = soup.select(' div.p13n_reasoning_v2' )

for title,img,tag in zip(titles,imgs,tags):
    data = {
            'title' :title.get_text(),
            'img' :img.get('src'),
            'tag' :list(tag.stripped_strings),
     }
    print(data)


from django.shortcuts import render
from django.db.models import Q,Count
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from relatedLaw.models import RelatedLaw,LawText
from exam.models import ExamHistory

import simplejson as json

# Create your views here.
def index(request):
    examTypes = ExamHistory.examType
    return render(request,'theory/index.html',{'examTypes':examTypes})

@csrf_exempt
def step2(request):
    datas = request.POST.getlist('data[]')
    q_objects = Q()
    for data in datas:
        q_objects |= Q(**{'examTypeCode': data})

    exam = ExamHistory.objects.filter(q_objects) \
        .values('idexam').annotate(count=Count('idexam'))

    q_objects = Q()
    for data in exam:
        q_objects |= Q(**{'idexam': data['idexam']})

    law = RelatedLaw.objects.filter(q_objects).values('lawNameCode').annotate(Count('lawNameCode'))
    list = []
    for query in law:
        tt = {}
        tt['code'] = query['lawNameCode']
        tt['codeName'] = law.model(lawNameCode=query['lawNameCode']).get_lawNameCode_display()
        list.append(tt)
    context = {
        'data':list
    }
    return HttpResponse(json.dumps(context),content_type="application/json")

@csrf_exempt
def step3(request):
    step2 = request.POST.get('step2')
    step3 = request.POST.get('step3')
    theory = LawText.objects.filter(lawNameCode=step2, lawCategory=step3).extra(
        select={'lawContent_jo0': 'CAST(lawContent_jo AS SIGNED)' \
            , 'lawContent_hang0': 'CAST(lawContent_hang AS SIGNED)' \
            , 'lawContent_ho0': 'CAST(lawContent_ho AS SIGNED)' \
            , 'lawContent_mok0': 'CAST(lawContent_mok AS SIGNED)'}) \
        .order_by('lawContent_jo0', 'lawContent_hang0', 'lawContent_ho0', 'lawContent_mok0').values('idlaw_text','lawText')
    list = []
    print(theory.query)
    for query in theory:
        list.append(query['lawText'])

    context = {
        'data':list
    }
    return HttpResponse(json.dumps(context),content_type="application/json")


from ._optuna import execute_optuna

def execute(
    problem,
    timeout,
    max_evals,
    random_state,
    log_dir,
    cache_dir,
    pruning_strategy,
    **kwargs,
):
    """Execute the TPE algorithm with HB."""
    execute_optuna(
        problem=problem,
        timeout=timeout,
        max_evals=max_evals,
        random_state=random_state,
        log_dir=log_dir,
        cache_dir=cache_dir,
        method="NSGAII",
        pruning_strategy=pruning_strategy,
        **kwargs,
    )


r"""

Definition
----------
This model provides the form factor for a circular cylinder with a core-shell
scattering length density profile. Thus this is a variation of a core-shell cylinder
or disc where the shell on the walls and ends may be of different thicknesses and scattering
length densities. The form factor is normalized by the particle volume.

.. _core-shell-bicelle-geometry:

.. figure:: img/core_shell_bicelle_geometry.png

    (Graphic from DOI: 10.1039/C0NP00002G, note however that the model here calculates for rectangular, not curved, rims.)

The output of the 1D scattering intensity function for randomly oriented
cylinders is then given by the equation above.

The *theta* and *phi* parameters are not used for the 1D output.
Our implementation of the scattering kernel and the 1D scattering intensity
use the c-library from NIST.

.. figure:: img/cylinder_angle_definition.jpg

    Definition of the angles for the oriented core shell bicelle tmodel.

.. figure:: img/cylinder_angle_projection.jpg

    Examples of the angles for oriented pp against the detector plane.

References
----------

L A Feigin and D I Svergun,
*Structure Analysis by Small-Angle X-Ray and Neutron Scattering,*
Plenum Press, New York, (1987)

"""

from numpy import inf, sin, cos

name = "core_shell_bicelle"
title = "Circular cylinder with a core-shell scattering length density profile.."
description = """
    P(q,alpha)= scale/Vs*f(q)^(2) + bkg,  where: f(q)= 2(sld_core
    - solvant_sld)* Vc*sin[qLcos(alpha/2)]
    /[qLcos(alpha/2)]*J1(qRsin(alpha))
    /[qRsin(alpha)]+2(shell_sld-sld_solvent)
    *Vs*sin[q(L+T)cos(alpha/2)][[q(L+T)
    *cos(alpha/2)]*J1(q(R+T)sin(alpha))
    /q(R+T)sin(alpha)]

    alpha:is the angle between the axis of
    the cylinder and the q-vector
    Vs: the volume of the outer shell
    Vc: the volume of the core
    L: the length of the core
    shell_sld: the scattering length density
    of the shell
    sld_solvent: the scattering length density
    of the solvent
    bkg: the background
    T: the thickness
    R+T: is the outer radius
    L+2T: The total length of the outershell
    J1: the first order Bessel function
    theta: axis_theta of the cylinder
    phi: the axis_phi of the cylinder...
        """
category = "shape:cylinder"

# pylint: disable=bad-whitespace, line-too-long
#             ["name", "units", default, [lower, upper], "type", "description"],
parameters = [
    ["radius",         "Ang",       20, [0, inf],    "volume",      "Cylinder core radius"],
    ["rim_thickness",  "Ang",       10, [0, inf],    "volume",      "Rim shell thickness"],
    ["face_thickness", "Ang",       10, [0, inf],    "volume",      "Cylinder face thickness"],
    ["length",         "Ang",      400, [0, inf],    "volume",      "Cylinder length"],
    ["sld_core",       "1e-6/Ang^2", 1, [-inf, inf], "",            "Cylinder core scattering length density"],
    ["sld_face",       "1e-6/Ang^2", 4, [-inf, inf], "",            "Cylinder face scattering length density"],
    ["sld_rim",        "1e-6/Ang^2", 4, [-inf, inf], "",            "Cylinder rim scattering length density"],
    ["sld_solvent",    "1e-6/Ang^2", 1, [-inf, inf], "",            "Solvent scattering length density"],
    ["theta",          "degrees",   90, [-inf, inf], "orientation", "In plane angle"],
    ["phi",            "degrees",    0, [-inf, inf], "orientation", "Out of plane angle"],
    ]

# pylint: enable=bad-whitespace, line-too-long

source = ["lib/Si.c","lib/polevl.c", "lib/sas_J1.c", "lib/gauss76.c", "core_shell_bicelle.c"]

demo = dict(scale=1, background=0,
            radius=20.0,
            rim_thickness=10.0,
            face_thickness=10.0,
            length=400.0,
            sld_core=1.0,
            sld_face=4.0,
            sld_rim=4.0,
            sld_solvent=1.0,
            theta=90,
            phi=0)

qx, qy = 0.4 * cos(90), 0.5 * sin(0)
tests = [
    # Accuracy tests based on content in test/utest_other_models.py
    [{'radius': 20.0,
      'rim_thickness': 10.0,
      'face_thickness': 10.0,
      'length': 400.0,
      'sld_core': 1.0,
      'sld_face': 4.0,
      'sld_rim': 4.0,
      'sld_solvent': 1.0,
      'background': 0.0,
     }, 0.001, 353.550],

    [{'radius': 20.0,
      'rim_thickness': 10.0,
      'face_thickness': 10.0,
      'length': 400.0,
      'sld_core': 1.0,
      'sld_face': 4.0,
      'sld_rim': 4.0,
      'sld_solvent': 1.0,
      'theta': 90.0,
      'phi': 0.0,
      'background': 0.00,
     }, (qx, qy), 24.9167],

    # Additional tests with larger range of parameters
    [{'radius': 3.0,
      'rim_thickness': 100.0,
      'face_thickness': 100.0,
      'length': 1200.0,
      'sld_core': 5.0,
      'sld_face': 41.0,
      'sld_rim': 42.0,
      'sld_solvent': 21.0,
     }, 0.05, 1670.1828],
    ]


from yolotr.models import Darknet
from yolotr.utils.datasets import *
from yolotr.utils.utils import *
import torch
import os

current_path = os.path.dirname(__file__)

class  TrafficDetector:
    def __init__(self,
                 img_size=640,
                 cfg_file="yolov4-tiny.cfg",
                 weights_file="yolov4-tiny.pt",
                 names_file="coco.names"):
        self.img_size = img_size
        self.cfg = os.path.join(current_path, F"cfg/{cfg_file}")
        self.weights = os.path.join(current_path, F"cfg/{weights_file}")
        self.names = os.path.join(current_path, F"cfg/{names_file}")
        # 构建模型
        self.model = Darknet(self.cfg, self.img_size)
        # 加载预训练模型
        self.model.load_state_dict(torch.load(self.weights)['model'])
        self.CUDA = torch.cuda.is_available()
        if self.CUDA:
            self.model.cuda()
        # 因为模型中使用了BatchNorm，Dropout等操作，预测的时候需要调用eval屏蔽
        self.model.eval()
        # ------------ 识别类型名
        # 加载类别
        self.names = load_classes(self.names)

    def detect(self, img0):
        img = self.format_img(img0)
        if self.CUDA:
            img = img.cuda()
        # 计算侦测结果
        pred = self.model(img, augment=False)[0]
        pred = pred.cpu()
        # 进行最大化抑制
        pred = non_max_suppression(pred, 0.3, 0.2, merge=False, classes=None, agnostic=False)
        # 解析识别结果
        for det in pred:
            if det is not None and len(det):
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], img0.shape).round()
        if pred[0] is not None:
            return pred[0].cpu().detach().numpy()  # 总长6：目标位置与大小（0:3），目标概率(4)，目标类别[5]
        else:
            return None

    def detect_mark(self, img0):
        # 侦测
        pred = self.detect(img0)
        # 标注
        if pred is not None:
            # 循环标注
            for result in pred:
                x1, y1, x2, y2 = result[0:4]
                prob = result[4]
                clss = int( result[5])
                cls_name = self.get_name(clss)
                # print([x1, y1, x2, y2], prob, clss, cls_name)
                # 备注：这里可以做一个概率阈值过滤（登录成功，可以考虑使用计数规则）
                # 标注
                img0 = cv2.rectangle(img0, (x1,y1),(x2,y2), color=(0, 0, 255), thickness=2)

        return img0, pred

    def get_name(self, idx):
        return self.names[idx]

    def format_img(self, img0):
        img = letterbox(img0, new_shape=self.img_size)[0]
        img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB
        img = np.ascontiguousarray(img)
        img = torch.from_numpy(img)
        img = img.float()
        img /= 255.0  # 0 - 255 to 0.0 - 1.0
        if img.ndimension() == 3:
            img = img.unsqueeze(0)
        return img

    def load_image(self, img_file):
        img0 = cv2.imread(img_file)  # BGR
        return img0


# Copyright 2021 CDPedistas (see AUTHORS.txt)
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# For further info, check  https://github.com/PyAr/CDPedia/

import shutil
from unittest.mock import patch

import pytest
from PIL import Image

from src.images.download import optimize_png, download, FetchingError, optimize_image

@pytest.fixture
def image_config(tmp_path):
    def f(name):
        img_test_name = 'tests/fixtures/image_to_optimize.png'
        test_path = tmp_path / name
        shutil.copy(img_test_name, str(test_path))
        init_size = test_path.stat().st_size
        return test_path, init_size
    yield f

@pytest.mark.parametrize('filename', [
    'image.png',  # simple
    'Image.PNG',  # uppercase
    'moño.png',  # unicode
    'the image.png',  # spaces
])
def test_pngquant_optimize_ok(image_config, filename):
    img_path, init_size = image_config(filename)
    optimize_png(str(img_path), init_size, init_size)
    final_size = img_path.stat().st_size
    assert init_size > final_size

def test_pngquant_optimize_problem(tmp_path, logs):
    # create something that pngquant will not understand
    img_path = tmp_path / 'weird.png'
    weird_content = "this is not really a png"
    img_path.write_text(weird_content)

    # it should not crash, and leave the original content untouched
    optimize_png(str(img_path), 23, 23)
    assert img_path.read_text() == weird_content
    assert "pngquant failed with 25 on '{}'".format(img_path) in logs.debug

def test_download_ok(tmp_path):
    test_path = tmp_path / 'foo' / 'bar' / 'baz.png'

    with patch('src.images.download.optimize_image') as _optimize_mock:
        with patch('src.images.download._download') as _download_mock:
            # real download will be ok, no need to patch RETRIES
            _download_mock.return_value = None

            download(('test-url', str(test_path)))

    # check directory were prepared ok
    assert test_path.parent.exists()

    # download and optimization was called ok
    _download_mock.assert_called_once_with('test-url', str(test_path))
    _optimize_mock.assert_called_once_with(str(test_path))

@pytest.mark.parametrize('extension', [
    '.svg',
    '.gif',
    '.Svg',
    '.Gif',
    '.SVG',
    '.GIF',
])
def test_download_no_optimization(extension, tmp_path):
    test_path = tmp_path / 'foo' / 'bar' / ('baz.' + extension)

    with patch('src.images.download.optimize_image') as _optimize_mock:
        with patch('src.images.download._download') as _download_mock:
            # real download will be ok, no need to patch RETRIES
            _download_mock.return_value = None

            download(('test-url', str(test_path)))

    # optimization was NOT called
    _optimize_mock.assert_not_called()

def test_download_retry_ok(tmp_path):
    test_path = tmp_path / 'foo' / 'bar' / 'baz.png'

    with patch('src.images.download.optimize_image'):
        with patch('src.images.download._download') as _download_mock:
            with patch('src.images.download.RETRIES', [0]):
                # first time ends with error, second ok
                _download_mock.side_effect = [
                    ValueError('pumba'),
                    None,
                ]
                download(('test-url', str(test_path)))

    # check directory were prepared ok
    assert test_path.parent.exists()

    # download was called twice
    assert _download_mock.call_count == 2

def test_download_problems(tmp_path):
    test_path = tmp_path / 'foo' / 'bar' / 'baz.png'

    with patch('src.images.download.optimize_image'):
        with patch('src.images.download._download') as _download_mock:
            with patch('src.images.download.RETRIES', [0]):
                # always in error
                _download_mock.side_effect = [
                    ValueError('pumba'),
                    ValueError('pumba'),
                ]
                with pytest.raises(FetchingError):
                    download(('test-url', str(test_path)))

    # check directory were prepared ok
    assert test_path.parent.exists()

    # download was called twice
    assert _download_mock.call_count == 2

def test_optimize_pil_error_unidentified(tmp_path, logs):
    tmp_image = tmp_path / "foo.png"
    tmp_image.write_text("not really a PNG, this will cause PIL to crash on open")

    optimize_image(str(tmp_image))
    msg = "PIL UnidentifiedImageError: cannot identify image file '.*/foo.png'"
    assert msg in logs.debug

def test_optimize_pil_error_generic(tmp_path, logs):
    tmp_image = tmp_path / "foo.png"
    tmp_image.write_text("stuff")
    with patch.object(Image, 'open') as mock:
        mock.side_effect = ValueError("pumba")
        optimize_image(str(tmp_image))
    msg = r"PIL optimization failed: ValueError\('pumba'.*\) when processing '.*foo.png'"
    assert msg in logs.debug


#############################
# 현재 1개의 레시피 추천까지 진행
##############################
"""Example using TF Lite to classify objects with the Raspberry Pi camera."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import io
import time
import threading
import numpy as np
import picamera

from tkinter import *
from tkinter import messagebox

from PIL import Image, ImageTk ###import 추가->mj
from tflite_runtime.interpreter import Interpreter
#import tflite ###import 추가->mj
import pandas as pd

class Camera(threading.Thread):
  m_bPressed = False
  m_rFood ={} ######################카메라 고장으로 잠시 주석하고 테스트했음
  #m_rFood={'onion':1,'tomato':1} ##대신 테스트했던 코드
  m_bExit = False

  def __init__(self):
    super().__init__()

  def Pressed(self, bEnable) :
      self.m_bPressed = bEnable

  def load_labels(self, path):
    with open(path, 'r') as f:
      return {i: line.strip() for i, line in enumerate(f.readlines())}

  def set_input_tensor(self, interpreter, image):
    tensor_index = interpreter.get_input_details()[0]['index']
    input_tensor = interpreter.tensor(tensor_index)()[0]
    input_tensor[:, :] = image

  def result(self):
    s = self.m_rFood.keys()

    return s

  def classify_image(self, interpreter, image, top_k=1):
    """Returns a sorted array of classification results."""
    self.set_input_tensor(interpreter, image)
    interpreter.invoke()
    output_details = interpreter.get_output_details()[0]
    output = np.squeeze(interpreter.get_tensor(output_details['index']))

    # If the model is quantized (uint8 data), then dequantize the results
    if output_details['dtype'] == np.uint8:
      scale, zero_point = output_details['quantization']
      output = scale * (output - zero_point)

    ordered = np.argpartition(-output, top_k)
    return [(i, output[i]) for i in ordered[:top_k]]

  def exit(self):
    self.m_bExit = True

  def run(self):

    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--model', help='File path of .tflite file.', required=True)
    parser.add_argument('--labels', help='File path of labels file.', required=True)
    args = parser.parse_args()

    #labels = self.load_labels('labels.txt')
    #interpreter = Interpreter('model_unquant.tflite')
    labels = self.load_labels(args.labels)
    interpreter = Interpreter(args.model)

    interpreter.allocate_tensors()
    _, height, width, _ = interpreter.get_input_details()[0]['shape']

    with picamera.PiCamera(resolution=(640, 480), framerate=3) as camera:
      camera.start_preview(fullscreen=False, window=(0,0,320,240) )
      try:
        stream = io.BytesIO()
        for _ in camera.capture_continuous(
          stream, format='jpeg', use_video_port=True):

          stream.seek(0)
          image = Image.open(stream).convert('RGB').resize((width, height),Image.ANTIALIAS)
          start_time = time.time()
          results = self.classify_image(interpreter, image)

          elapsed_ms = (time.time() - start_time) * 1000
          label_id, prob = results[0]

          stream.seek(0)
          stream.truncate()
          camera.annotate_text = '%s %.2f\n%.1fms' % (labels[label_id], prob,
                                                        elapsed_ms)

          if self.m_bPressed :
            self.m_rFood[labels[label_id]]=label_id
            #self.m_rFood.append(labels[label_id])
            print ( labels[label_id] )
            self.m_bPressed = False
            camera.annotate_text = '%s added.' % (labels[label_id] )

          if self.m_bExit:
            camera.stop_preview()
            break

      finally:
        camera.stop_preview()

cam = Camera()

def pressed_button() :
    cam.Pressed(True)
    print('button pressed')

def show_result():
    msg = messagebox.showinfo('result',cam.result())
    print('show')
def pressed_recipe(text):
    print(text)

def show_recipe():
    try:
      source = cam.result()
      data= pd.read_csv('food_Ingredients.csv')
      #print(data)

      recipe_ingredient=data['food ingredients']
      ingredients=[]
      count=[0 for _ in range(len(data))]
      #print("data 갯수 %d" %len(data))
      recommend=[]
      for num,i in enumerate(recipe_ingredient):
          ingredients.append(i.split(','))
      for num,a in enumerate(ingredients):
          print(a)
          for s in source:
              if s in a:
                  count[num]+=1 # 나중에 딕셔너리형으로 바꾸는거 고려
      if any(count):
          for num in range(len(count)):
              if count[num]!=0:
                  count[num] = count[num]/len(ingredients[num])
          result=count.index(max(count))
          recommend.append(data['cook'][result])
      else:
          print("해당재료로 만들 수 있는 레시피 없음.")
          msg2 = messagebox.showinfo('no recommend','No recipe for the ingredients')
          raise ValueError('No recipe for the ingredients!')

    #print(max(count))
    # for num,cnt in enumerate(count):
    #     if max(count)==0:
    #         print("해당재료로 만들 수 있는 레시피 없음.")
    #         msg2 = messagebox.showinfo('no recommend','No recipe for the ingredients')
    #         break
    #     if cnt==max(count) :
    #         recommend.append(data['cook'][num])
    # #print(recommend)

      recipe = Tk()
      recipe.configure(bg='white')
      recipe.geometry('750x600+500+500')
      recipe.title('레시피 추천')
      l = Label(recipe, bg="white", text=recommend[0], font=13) #요리제목
      l.place(x=30, y=10)

      image1 = Image.open("image/%s_2.jpg"%recommend[0])
      image2 = Image.open("image/%s_3.jpg"%recommend[0])

      image1 = image1.resize((350,500),Image.ANTIALIAS)
      image2 = image2.resize((350,500),Image.ANTIALIAS)

      img1 = ImageTk.PhotoImage(image1,master=recipe)
      img2 = ImageTk.PhotoImage(image2,master=recipe)

      label1 = Label(recipe, image= img1)
      label2 = Label(recipe, image= img2)

      # # Position image
      label1.place(x=20, y=60)
      label2.place(x=370,y=60)

    # btn={}
    # for num,a in enumerate(recommend):
    #       btn[a] = Button(recipe, width=20, height=1, text=a, bg="yellow", command=lambda: pressed_recipe(a))
    #       btn[a].place(x=130+150*num, y=10)
    #print(btn)
      recommend.clear()
      cam.m_rFood.clear()
      ingredients.clear()
      count.clear()
      recipe.mainloop()
    finally:
      recommend.clear()
      cam.m_rFood.clear()
      ingredients.clear()
      count.clear()
      print("end")

    return recommend

def main():
    try:
        cam.start()
        window = Tk()
        window.geometry('250x250+650+300')
        window.title('AI CHEF')

        l = Label(window, bg="white", text='Capturing the Image', font=13)
        l.place(x=30, y=10)

        b1 = Button(window, width=10, height=2, text='CAPTURE', bg="magenta", command=pressed_button)
        b1.place(x=65, y=60)

        b2 = Button(window, width=10, height=2, text='RESULT', bg="pink", command=show_result)
        b2.place(x=65, y=120)

        b3 = Button(window, width=10, height=2, text='RECIPE', bg="blue", command=show_recipe)
        b3.place(x=65, y=180)

        window.mainloop()

    finally:
        cam.exit()
        cam.join()
        quit()
    return

if __name__ == '__main__':
    main()


#!/usr/bin/env python3
# Dependencies from the Python 3 standard library:
import os
import subprocess as sp
from shutil import copyfile
# Dependencies from the Scipy stack https://www.scipy.org/stackspec.html :
import numpy as np
import matplotlib.pyplot as plt
# Dependencies from https://github.com/AndrewGYork/remote_refocus/figure_generation :
import np_tif

## Set/create directories
input_directory = os.path.abspath(os.path.join(
    os.getcwd(), os.pardir, os.pardir, 'big_data_input', 'SIM_lines_edge'))
temp_directory = os.path.abspath(os.path.join(
    os.getcwd(), os.pardir, os.pardir, 'temp'))
if not os.path.isdir(temp_directory): os.mkdir(temp_directory)
temp_directory = os.path.join(temp_directory, 'SIM_lines_edge')
if not os.path.isdir(temp_directory): os.mkdir(temp_directory)
output_directory = os.path.abspath(os.path.join(
    os.getcwd(), os.pardir, os.pardir, 'big_data_output'))
if not os.path.isdir(output_directory): os.mkdir(output_directory)
output_directory = os.path.join(output_directory, 'SIM_lines_edge')
if not os.path.isdir(output_directory): os.mkdir(output_directory)

## Set input file name and acquisition parameters for processing
mz_step = 5 # microscope z step
num_f = 13 # number of files
num_slices = 17 # number of z slices in a stack
input_filename = ('SpXcyan-dmi8GFPcube_dmi8z_%1s.0.tif')
input_filename_list = num_f*[None]
hyperstack_filename = os.path.splitext(input_filename)[0] + '_hyperstack.tif'
input_filename = os.path.join(input_directory, input_filename)
hyperstack_filename = os.path.join(temp_directory, hyperstack_filename)

## Cropping parameters
left_crop = 1400
right_crop = 100
top_crop = 115
bottom_crop = 1385

## If hyperstack file exists then skip processing
if os.path.exists(hyperstack_filename):
    print('Found hyperstack tif, loading...', end='')
    data = np_tif.tif_to_array(hyperstack_filename)
    data = data.reshape((num_f, num_slices) + data.shape[-2:])
    print('done')

## If no hyperstack file then process original data
else:
    data_list = num_f*[None]
    for fn in range(num_f):
        input_filename_list[fn] = (input_filename
                                   %((fn-int(0.5*(num_f-1)))*mz_step))
        print('Found input files, loading...', end='')
        data_list[fn] = np_tif.tif_to_array(input_filename_list[fn])
        print('done')
    print('Creating np data array...', end='')
    data = np.asarray(data_list)
    data = data.reshape((num_f, num_slices) + data.shape[-2:])
    print('done')
    print('Cropping...', end='', sep='')
    if left_crop or right_crop > 0:
        data = data[:, :, :, left_crop:-right_crop]
    if top_crop or bottom_crop > 0:
        data = data[:, :, top_crop:-bottom_crop, :]
    print('done')
    print("Saving result...", end='')
    np_tif.array_to_tif(
        data.reshape(num_f*num_slices, data.shape[-2], data.shape[-1]),
        hyperstack_filename, slices=num_slices, channels=1, frames=num_f)
    print('done')

print('tif shape (Microsope z, RR z, y, x) =', data.shape)

## Add white scale bar to all images
for t in range(data.shape[0]):
    for z in range(data.shape[1]):
        image = data[t, z, :, :]
        image[20:30, 350:535] = 3000

## Choose parameters for video
current_frame = -1
xmargin = 0.15
ymargin = 0.16
space = 0.03
z_scale = 0.25

## Set output folder and filename for images to make video
output_filename = os.path.join(output_directory, 'img%02i%02i.png')

## Make images for video
fig = plt.figure(figsize=(10,10),dpi=(600))
for fn in range(num_f):
    mz = (fn-int(0.5*(num_f-1)))*mz_step
    print('Microscope z = ', mz)
    for z in range(num_slices):
        rrz = 1.52*mz + z_scale*(z-(num_slices-1)/2)
        current_frame += 1
        print('frame = ', current_frame)
        plt.clf()
        print('RR z = ', rrz)
        plt.imshow(data[fn, z, :, :], cmap='gray', vmin=750, vmax=3000)
        plt.gca().get_xaxis().set_ticks([])
        plt.gca().get_yaxis().set_ticks([])
        plt.figtext(xmargin, ymargin + 22*space,
                    'Diffraction limited resolution',
                    color='yellow', family='monospace')
        plt.figtext(xmargin, ymargin + 2*space, 'RR z=%6s$\mu$m'%('%0.2f'%rrz),
                    color='yellow', family='monospace')
        plt.figtext(xmargin, ymargin + space, 'Microscope z=%6s$\mu$m'%('%0.2f'%mz),
                    color='yellow', family='monospace')
        plt.figtext(xmargin, ymargin, 'Field of view = edge',
                        color='yellow', family='monospace')
        plt.savefig(output_filename%(fn, z), bbox_inches='tight')
plt.close(fig)

## Choose 'poster' image and copy to video location
copyfile(os.path.join(output_directory, 'img0608.png'),
         os.path.join(output_directory, 'default.png'))


class Node:
  def __init__(self):
    self.data = None
    self.next = None
    self.prev = None

class Link:

  def __init__(self, data=()):
    self.head = Node()  # 实利化头节点
    self.tail = self.head  # 指针指向开头
    self.length = 0
    for d in data:
      self.append(d)

  def __find__node_by(self, pos):
    nodeptr = self.head
    while pos:
      nodeptr = nodeptr.next
      pos -= 1
    return nodeptr

  def append(self, data):
    node = Node()
    node.data = data
    self.tail.next = node
    node.prev = self.tail
    self.tail = node
    self.length += 1

  def pop(self, i=-1):
    if len(self) <= 0:
      raise Exception('THE LIST IS EMPTY')
    if i == -1:
      node = self.tail
      self.tail.next = None
      self.length -= 1
      return node.data
    else:
      node = self.__find__node_by(i)
      cur_node = node.next
      third_node = node.next.next
      if third_node is not None:
        third_node.prev = node
      node.next = third_node
      self.length -= 1
      return cur_node.data

  def insert(self, i, data):

    assert i <= len(self) - 1
    nodeptr = self.head
    while i:
      nodeptr = nodeptr.next
      i -= 1
    third_node = nodeptr.next
    node = Node()
    third_node.prev = nodeptr
    node.prev = node
    self.length += 1

  def remove(self, i):
    assert i <= len(self) - 1
    nodeptr = self.__find__node_by(i)
    third_node = nodeptr.next.next
    nodeptr.next = third_node
    third_node.prev = nodeptr
    self.length -= 1

  def __len__(self):
    return self.length

  def __iter__(self):
    return LinkIterator(self)

  def __setitem__(self, key, value):
    assert key <= len(self) - 1
    nodeptr = self.__find__node_by(key)
    nodeptr.next.data = value
    return nodeptr

  def __add__(self, other):
    for i in other:
      self.append(i)
    return self

  def __iadd__(self, other):
    for i in self:
      i = i + other
      self.append(i)
      return self

  def __sub__(self, other):
    pass

  def __isub__(self, other):
    pass

  def __mul__(self, other):
    pass

  def __divmod__(self, other):
    pass

  def __contains__(self, item):
    for d in self:
      if d == item:
        return True
    return False
def recerse(link, m):
  def recursive(node, m):
    first_node = node.next
    if first_node == None:
        return
    n = m -1
    while n:
      nn = first_node.next
      if not nn:
        return
      # 移除当前节点'nn'
      first_node.next = nn.next
      if nn.next:
        nn.next.prev = first_node
      # 将当前节点插入到第一个位置
      nn.next = node.next
      node.next = nn
      nn.prev = node
      n -= 1
    recursive(first_node, m)
  recursive(link.head, m)

class LinkIterator:
  def __init__(self, link):
    self._node_ptr = link.head

  def __next__(self):
    self._node_ptr = self._node_ptr.next
    if self._node_ptr is None:
      raise StopIteration
    data = self._node_ptr.data
    return data

list = Link
x = list()
x.append(1)
x.append(2)
x.append(3)
x.append(4)

x.__iadd__(2)
for i in x:
  print(i)

# print(x.__setitem__(1, 8))
# for i in x:
#   print(i)
#
# print(x.pop(2))
# for i in x:
#   print(i)


from django.contrib import messages
from django.shortcuts import redirect, render
import bcrypt
from .decorators import login_required
from .models import *
from datetime import datetime, time, timedelta
from django.utils import timezone
import re

@login_required
def index(request):
    context = {
        'mensajes': Mensaje.objects.all(),
        'comentarios': Comentario.objects.all(),
    }
    return render(request, 'index.html', context)

@login_required
def mensaje_crear(request):
    print(request.POST)

    errors= Mensaje.objects.validador_basico_mensaje(request.POST)
    print(errors)
    if len(errors) > 0:
        for key, value in errors.items():
            messages.error(request, value)
        return redirect("/")
    else:
        mensaje_creado = request.POST['mensaje']
        user_id_creador = request.session['usuario']['id']

        mensaje = Mensaje.objects.create(
            mensaje = mensaje_creado,
            user = User.objects.get(id = user_id_creador),
        )
        messages.success(request, "Mensaje agregado correctamente")
        return redirect(f"/")

def calculate_minutos(fecha):
    today = timezone.now()
    print(today, "today")
    print(fecha, "fecha")
    print("años", (today.year - fecha.year), (today.year - fecha.year)*365*24*60)
    print("meses", (today.month - fecha.month), (today.month - fecha.month)*30*24*60)
    print("dias", (today.day - fecha.day), (today.day - fecha.day)*24*60)
    print("horas", (today.hour-fecha.hour), (today.hour-fecha.hour)*60)
    print("minutos", (today.minute-fecha.minute))
    resultado = (today.year - fecha.year)*365*24*60 + (today.month - fecha.month)*30*24*60 + (today.day - fecha.day)*24*60 + (today.hour-fecha.hour)*60 + (today.minute-fecha.minute)
    print(resultado)
    return resultado

@login_required
def mensaje_borrar(request, val):
    errors = {}
    print(request.GET, 'Entró a borrar mensaje')
    borr = Mensaje.objects.get(id = val)
    print("Aqui se va a borrar el mensaje ID=", val)
    calc = calculate_minutos(borr.created_at)
    if calc > 30:
        messages.warning(request, "No se borró el mensaje. Tiempo expirado máximo 30 min")
    else:
        print("Autorizado para borrar el mensaje")
        messages.success(request, "Mensaje borrado exitosamente")
        borr.delete()
    return redirect("/")

@login_required
def comentario_crear(request):
    print(request.POST)

    errors= Comentario.objects.validador_basico_comentario(request.POST)
    print(errors)
    if len(errors) > 0:
        for key, value in errors.items():
            messages.error(request, value)
        return redirect("/")
    else:
        comentario_creado = request.POST['comentario']
        id_mensaje = request.POST['id_mensaje_comentario']
        comentario_user_id = request.session['usuario']['id']

        comentario = Comentario.objects.create(
            comentario = comentario_creado,
            user = User.objects.get(id=comentario_user_id),
            mensaje = Mensaje.objects.get(id=id_mensaje),
        )
        messages.success(request, "Comentario agregado correctamente")
        return redirect(f"/")

@login_required
def comentario_borrar(request, val):
    print(request.GET)
    borr = Comentario.objects.get(id = val)
    print("Aqui se va a borrar el comentario ID=", val)
    calc = calculate_minutos(borr.created_at)
    if calc > 30:
        messages.warning(request, "No se borró el comentario. Tiempo expirado máximo 30 min")
    else:
        print("Autorizado para borrar el comentario")
        messages.success(request, "Comentario borrado exitosamente")
        borr.delete()
    return redirect("/")


import shutil
import os
from datetime import datetime
from glob import glob
from django.test import TestCase
from django.contrib.auth import get_user_model

from core.models import Client, Brand, Project, Humans
from file_system.models import ClientFileSystem, ProjectFileSystem, pick_values_by_key, create_dir_tree
from file_system import settings

class PopulateCore(object):
    def __init__(self):
        # create dummy_user
        user_model = get_user_model()
        dummy_user = user_model.objects.create_user(
                'test_user_username',
                'test@email.com',
                'test_password'
        )
        dummy_user.save()
        self.dummy_user = dummy_user

        # create human contact
        dummy_human = Humans()
        dummy_human.user = dummy_user
        dummy_human.department = 'management'
        dummy_human.department = 'general-manager'
        dummy_human.phone = '0123456789'
        dummy_human.address = 'dummy user test address'
        dummy_human.personal_email = 'dummy@personal.em'
        dummy_human.enrolled = datetime.now()
        dummy_human.save()
        self.dummy_human = dummy_human

        # create a dummy client
        dummy_client = Client()
        dummy_client.name = 'test_client_name'
        dummy_client.manager = self.dummy_human
        dummy_client.save()
        self.dummy_client = dummy_client

        # create a dummy brand
        dummy_brand = Brand()
        dummy_brand.name = 'brand_test_name'
        dummy_brand.client = self.dummy_client
        dummy_brand.save()
        self.dummy_brand = dummy_brand

        # create a dummy project
        dummy_project = Project()
        dummy_project.name = 'test_project_name'
        dummy_project.short_code = "test_prj_dir_name"
        dummy_project.client = self.dummy_client
        dummy_project.brand = self.dummy_brand
        self.dummy_project = dummy_project

class TestHelperFunctions(TestCase):
    def setUp(self):
        class Obj(object):
            include_pattern = 'included1'
            not_include = 'not_included1'
            included_safe_pattern_pattern = 'included2'
            not_included_1pattern = 'not_included2'

        tree = dict(
                dir1_level1='dir1_level1',
                dir2_level1='dir2_level1',
                deep1_level1=dict(
                        root='deep1_level1',
                        dir1_level2='dir1_level2',
                        dir2_level2='dir2_level2',
                        deep2_level2=dict(
                                root='deep1_level2',
                                dir1_level3='dir1_level3',
                                dir2_level3='dir2_level3',
                        )
                )
        )
        self.obj = Obj()
        self.pattern = '_pattern'
        self.tree = tree

    def tearDown(self):
        shutil.rmtree(settings.STORAGE_ROOT)
        os.makedirs(settings.STORAGE_ROOT)

    def test_pick_values_by_key(self):
        self.assertEqual({'included1', 'included2'},
                         set(pick_values_by_key(self.obj, self.pattern)))

    def test_create_dir_tree(self):
        create_dir_tree(settings.STORAGE_ROOT, self.tree)
        self.assertTrue(os.path.join(settings.STORAGE_ROOT, 'dir1_level1'))
        self.assertTrue(os.path.isdir(os.path.join(settings.STORAGE_ROOT, 'deep1_level1', 'dir2_level2')))
        self.assertTrue(
                os.path.isdir(os.path.join(settings.STORAGE_ROOT, 'deep1_level1', 'deep1_level2', 'dir1_level3')))

class TestClientFileSystem(TestCase):
    def setUp(self):
        self.core = PopulateCore()
        self.client_filesystem = ClientFileSystem()
        self.client_filesystem.client = self.core.dummy_client

        self.project_filesystem = ProjectFileSystem()
        self.project_filesystem.project = self.core.dummy_project

    def tearDown(self):
        shutil.rmtree(settings.STORAGE_ROOT)
        os.makedirs(settings.STORAGE_ROOT)

    def test_client_filesystem(self):
        client_root = self.client_filesystem.create_filesystem()
        self.assertEqual(client_root, os.path.join(settings.STORAGE_ROOT, self.core.dummy_client.name))
        test_dirs = pick_values_by_key(self.client_filesystem, "_path")
        for test_dir in test_dirs:
            self.assertTrue(os.path.isdir(test_dir))

class TestProjectFileSystem(TestCase):
    def setUp(self):
        self.core = PopulateCore()

        self.client_filesystem = ClientFileSystem()
        self.client_filesystem.client = self.core.dummy_client

        self.project_filesystem = ProjectFileSystem()
        self.project_filesystem.project = self.core.dummy_project

    def tearDown(self):
        shutil.rmtree(settings.STORAGE_ROOT)
        os.makedirs(settings.STORAGE_ROOT)

    def test_project_filesystem(self):
        client_root = self.client_filesystem.create_filesystem()
        expected_project_root = self.project_filesystem.create_filesystem()

        project_root = os.path.join(client_root, settings.PROJECTS_ROOT, self.core.dummy_project.short_code)
        self.assertEqual(project_root, expected_project_root)

        symlinks_dirs = glob(os.path.join(client_root, '*-links'))
        for check_dir in symlinks_dirs:
            link = glob(os.path.join(check_dir, '*'))[0]
            self.assertTrue(os.path.islink(link))
            self.assertEqual(os.path.basename(link), self.project_filesystem.project_dir_name)
            dir_type = os.path.basename(check_dir).split('-')[0]
            dir_target = getattr(self.project_filesystem, dir_type + '_path')
            self.assertEqual(os.path.realpath(link), dir_target)


# Copyright (c) 2015 SUSE Linux GmbH.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from azure.storage.blob.baseblobservice import BaseBlobService
from azure.storage.sharedaccesssignature import SharedAccessSignature

# project
from azurectl.azurectl_exceptions import (
    AzureCannotInit,
    AzureContainerListError,
    AzureContainerListContentError,
    AzureContainerCreateError,
    AzureContainerDeleteError
)

ISO8061_FORMAT = '%Y-%m-%dT%H:%M:%SZ'

class Container(object):
    """
        Information from Azure storage containers
    """
    def __init__(
        self,
        account=None,
        account_name=None,
        key=None,
        blob_service_host_base=None
    ):
        if account:
            self.account_name = account.storage_name()
            self.account_key = account.storage_key()
            self.blob_service_host_base = account.get_blob_service_host_base()
        elif (account_name and key and blob_service_host_base):
            self.account_name = account_name
            self.account_key = key
            self.blob_service_host_base = blob_service_host_base
        else:
            raise AzureCannotInit('''
                Either an account, or account_name, key, and service host base
                are required.
            ''')

    def list(self):
        result = []
        blob_service = BaseBlobService(
            self.account_name,
            self.account_key,
            endpoint_suffix=self.blob_service_host_base
        )
        try:
            for container in blob_service.list_containers():
                result.append(format(container.name))
        except Exception as e:
            raise AzureContainerListError(
                '%s: %s' % (type(e).__name__, format(e))
            )
        return result

    def exists(self, container):
        blob_service = BaseBlobService(
            self.account_name,
            self.account_key,
            endpoint_suffix=self.blob_service_host_base
        )
        try:
            blob_service.get_container_properties(container)
            return True
        except Exception:
            return False

    def create(self, container):
        blob_service = BaseBlobService(
            self.account_name,
            self.account_key,
            endpoint_suffix=self.blob_service_host_base
        )
        try:
            blob_service.create_container(
                container_name=container,
                fail_on_exist=True
            )
        except Exception as e:
            raise AzureContainerCreateError(
                '%s: %s' % (type(e).__name__, format(e))
            )
        return True

    def delete(self, container):
        blob_service = BaseBlobService(
            self.account_name,
            self.account_key,
            endpoint_suffix=self.blob_service_host_base
        )
        try:
            blob_service.delete_container(
                container_name=container,
                fail_not_exist=True
            )
        except Exception as e:
            raise AzureContainerDeleteError(
                '%s: %s' % (type(e).__name__, format(e))
            )
        return True

    def content(self, container):
        result = {container: []}
        blob_service = BaseBlobService(
            self.account_name,
            self.account_key,
            endpoint_suffix=self.blob_service_host_base
        )
        try:
            for blob in blob_service.list_blobs(container):
                result[container].append(format(blob.name))
            return result
        except Exception as e:
            raise AzureContainerListContentError(
                '%s: %s' % (type(e).__name__, format(e))
            )

    def sas(self, container, start, expiry, permissions):
        sas = SharedAccessSignature(
            self.account_name, self.account_key
        )
        signed_query = sas.generate_container(
            container_name=container,
            permission=permissions,
            expiry=expiry.strftime(ISO8061_FORMAT),
            start=start.strftime(ISO8061_FORMAT)
        )
        return 'https://{0}.blob.core.windows.net/{1}?{2}'.format(
            self.account_name, container, signed_query
        )


#Senior Design ECE 1896 Posture Watcher
#Gerald Kiliany

#Read input from Force Sensitive Resistors through ADC (MCP3008)

#import necessary libraries
import spidev
import time
import sys
import RPi.GPIO as GPIO
import csv

#variables
samplePeriod = 1
FSR_channel0 = 0
FSR_channel1 = 1
FSR_channel2 = 2
FSR_channel3 = 3
FSR_channel4 = 4
seatedThresh = 10 #threshold for pressure to consider a user to be seated (1024 range)
timeElapsed = 0
vibMode = False
vibrating = False
vibPinIn = 17 #GPIO pin to read vibration mode input
vibPinOut = 26 #GPIO pin for vibration motor
seatCount = 0
oversittingThresh = 5
notSittingThresh = 2
standCount = 0

#GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(vibPinIn, GPIO.IN)
GPIO.setup(vibPinOut, GPIO.OUT)

#SPI Comm setup
mcp0 = spidev.SpiDev()
mcp0.open(0,0) #open communication between spi bus 0 and mcp device on channel 0
mcp0.max_speed_hz = 1000000

def readADC(adcnum):
    #Read SPI data from ADC, 8 channels
    if adcnum > 7 or adcnum < 0:
        return -1
   # mcp0.open(0,0)
   # mcp0.max_speed_hz = 1000000

    r = mcp0.xfer2([1, (8 + adcnum) << 4, 0])
    data = ((r[1] & 3) << 8) + r[2]

    #spi.close()
    return data

while timeElapsed < 5069: #for debugging don't run forever
        timeElapsed+=1

        vibMode = GPIO.input(17) #read pin 17 for if vibration switch on or off

        FSR_value0 = readADC(FSR_channel0) #0-1023 for 10 bit ADC, sensor 0
        FSR_value1 = readADC(FSR_channel1) #sensor 1
        FSR_value2 = readADC(FSR_channel2) #sensor 2
        FSR_value3 = readADC(FSR_channel3) #sensor 3
        FSR_value4 = readADC(FSR_channel4) #sensor 4
        #adc = MCP3008()
        #FSR_value0 = adc.read(channel = 0)
        #FSR_value1 = adc.read(channel = 1)

        #perform ops on data
        if FSR_value0 > seatedThresh:
            isSeated = True;
        else:
            isSeated = False;
        #for testing

        if isSeated:
            seatCount +=1 #increment time spent seated
            standCount = 0 #reset counter for standing
        else :
            standCount+=1
            if standCount >= notSittingThresh: #sense standing, reset seated count
                seatCount = 0

        print("Time elapsed: ", timeElapsed)
        print("FSR0 value: ", FSR_value0)
        print("FSR1 value: ", FSR_value1)
        print("FSR2 value: ", FSR_value2)
        print("FSR3 value: ", FSR_value3)
        print("FSR4 value: ", FSR_value4)
        print("Seated or not: ", isSeated)

        if (seatCount >= oversittingThresh) & ((seatCount % oversittingThresh) == 0) & (standCount < 1): #compare time sitting to the threshold considered to be too long
            if(vibMode) :
                print("Vibration Mode: Vibrating")
                GPIO.output(vibPinOut, GPIO.HIGH)
            else:
                print("Seated too long")
               # print("Pressure Pad Value: ", FSR_value0)
               # print("Seated or not: ", isSeated)
        #Write to file
        currValues = [FSR_value0, FSR_value1, FSR_value2, FSR_value3, FSR_value4]
        with open('mlData.csv', 'a', newline = '') as csvfile:
            outWriter = csv.writer(csvfile, delimiter = ' ')
            outWriter.writerow(currValues)

        time.sleep(samplePeriod)
        GPIO.output(vibPinOut, GPIO.LOW)
        #end
mcp0.close() #end comms with mcp device


import pickle

from moviepy.editor import *
from moviepy.video.tools.tracking import manual_tracking, Trajectory

clip = VideoFileClip("input/Gorod_2.mp4")

if __name__ == "__main__":
    start_frame = 3
    end_frame = 14
    trjectories_count = 1
    trajectories = manual_tracking(
        clip,
        t1=start_frame,
        t2=end_frame,
        nobjects=trjectories_count,
        fps=3,
        savefile="gorod_track"
    )


from random import randint

class CreditCard:
    DEFAULT = 0000
    IIN = 400000

    def __init__(self):
        self.card = ""
        self.pin = self.DEFAULT
        self.word = ""
        self.n_list = []
        self.checksum = ""

    def generate_card(self):
        self.word = str(randint(000000000, 999999999))
        self.word = str(self.IIN) + "0" * (9 - len(self.word)) + self.word

        self.n_list = [int(x) for x in self.word]

        for _, n in enumerate(self.n_list):
            if self.n_list.index(n, _) % 2 == 0:
                self.n_list[self.n_list.index(n, _)] = n * 2
        for _, n in enumerate(self.n_list):
            if n > 9:
                self.n_list[self.n_list.index(n, _)] = n - 9

        if sum(self.n_list) % 10 == 0:
            self.checksum = "0"
        else:
            self.checksum = str(10 - sum(self.n_list) % 10)

        self.card = self.word + self.checksum
        self.pin = str(randint(0000, 9999))
        self.pin = "0" * (4 - len(self.pin)) + self.pin
        print("Your card has been created")
        return self.card, self.pin

    def show_credentials(self):
        print("Your card number:")
        print(self.card)
        print("Your card PIN:")
        print(self.pin)

cred_dict = {}
loop = True
while loop:
    print("1. Create an account")
    print("2. Log into account")
    print("0. Exit")

    option = input(">")

    if option == "0":
        loop = False
        print("Bye!")

    if option == "1":
        my_card = CreditCard()
        cardID, pinID = my_card.generate_card()
        cred_dict[cardID] = pinID
        my_card.show_credentials()

    if option == "2":
        print("Enter your card number:")
        card_number = input()
        print("Enter your PIN:")
        pin_number = input()

        if card_number in cred_dict.keys():
            if cred_dict[card_number] == pin_number:
                print("You have successfully logged in!")
                new_loop = True
                while new_loop:
                    print("1. Balance")
                    print("2. Log Out")
                    print("0. Exit")

                    new_option = input()
                    if new_option == "1":
                        print("Balance: 0")
                    if new_option == "2":
                        print("You have successfully logged out!")
                        new_loop = False
                    if new_option == "0":
                        new_loop = False
                        loop = False
                        print("Bye!")
            else:
                print("Wrong card number or PIN!")
        else:
            print("Wrong card number or PIN!")


import ipaddress
import string
import random
import os
import shutil
import glob

import natlaslogging

SCAN_ID_LENGTH = 16

utillogger = natlaslogging.getLogger("Utilities")

def validate_target(target, config):
	try:
		iptarget = ipaddress.ip_address(target)
		if iptarget.is_private and not config.scan_local:
			utillogger.error("We're not configured to scan local addresses!")
			return False
	except ipaddress.AddressValueError:
		utillogger.error("%s is not a valid IP Address" % target)
		return False
	return True

def generate_scan_id():
	return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(SCAN_ID_LENGTH))

def cleanup_files(scan_id):
	utillogger.info("Cleaning up files for %s" % scan_id)
	if os.path.isdir("data/aquatone.%s" % scan_id):
		shutil.rmtree("data/aquatone.%s" % scan_id)
	for file in glob.glob("data/natlas."+scan_id+".*"):
		try:
			os.remove(file)
		except Exception:
			utillogger.error("Could not remove file %s" % file)