# -*- coding: utf-8 -*-

from Catalog import Catalog
from datetime import date,datetime,timedelta

class User:
    def __init__(self, name, location, age, aadhar_id):
        self.name = name
        self.location = location
        self.age = age
        self.aadhar_id = aadhar_id
        #self.catalog = Catalog()  #creating  a catalog object

class Member(User):
    def __init__(self,name, location, age, aadhar_id,student_id):
        super().__init__(name, location, age, aadhar_id)
        self.student_id = student_id
        self.issueLimit = 3
        self.bookIssued = []

    def __repr__(self):
        return self.name + ' ' + self.location + ' ' + str(self.student_id)

    #assume name is unique
    def issueBook(self,catalog,name,barcode,days=10):
        transaction = []  #store the current transaction details
        self.days = days
        book = catalog.searchByName(name) # search in the books objects  # if requested book present
        try:
            #check count of booItem in inventory and   check the member issue limit
            if catalog.inventory.get(name) > 0 and self.issueLimit > 0:
                for bookitem in book.book_item: # search for bookItem of requested barcode
                    if bookitem.barcodeNo == barcode:  # if requested barcode present
                        book.book_item.remove(bookitem) #remove bookItem of that barcode
                        book.total_count-= 1  #decrease total count of bookItems
                        catalog.inventory[name]-= 1  #decrease the count of that book in inventory
                        self.issueLimit-= 1  # reduce the book issue limit of member
                        print('you can issue {} more books'.format(self.issueLimit))
                        returndays = self.returnDays(days) #will return total days from issue date to return date
                        transaction.extend([(datetime.now()),book.name,bookitem.isbn,bookitem.rack,barcode,returndays])  #make a transaction
                        self.bookIssued.append(transaction) #associate the details of transaction with member
                        return transaction
        except:
            print("bookItem of book {} not present".format(book.name))
            return

        print("book of name {} not present in inventory".format(name))

    # issue book return inforamation
    def returnDays(self,days):
        currenttime  = datetime.now()
        returntime   = currenttime + timedelta(days)
        info = returntime - currenttime
        info = int(str(info).split(" ")[0])
        return info #total days from issue date to return date

    #show the whole collection of book and bookItem
    def showInventory(self,catalog):
        return catalog.inventory

    #assume name is unique
    def returnBook(self,catalog,name,rinfo,issuedays,returndays):
        #print(name,issuedays,returndays)
        fineAmt = 0
        bkitem = [bitem for bitem in self.bookIssued if rinfo[-2] in bitem]
        if bkitem:  #check the book is that whick is issued
            #[(datetime.now()),book.name,bookitem.isbn,bookitem.rack,barcode,returndays]
            book = catalog.searchByName(name)
            #book = [bk for bk in catalog.books if bk.name == rinfo[1]][0]
            catalog.addBookItem(book,rinfo[2],rinfo[3],rinfo[4])
            catalog.inventory[book.name]+= 1  #increase the count of that book in inventory
            self.issueLimit+= 1  # update the book issue limit of member
            self.bookIssued.remove(rinfo)  # remove that transaction from member account
            fineAmt = self.payFine(returndays-issuedays)
            print("Return successful")
            print("please pay the fine of {} to librarian".format(fineAmt))
        else:
            print("please bring associated with this library")

    #for paying fine
    def payFine(self,noOfDays):
        fineAmt = 0
        if noOfDays <= 10:  # now we are checking only for 10 days
            return 0
        else:
            fineAmt = (noOfDays-10) * 2 # if greater than 10 days count from 11th day
            return fineAmt

    #for searching all the available book present in catalog by name
    def searchCatalogByName(self,catalog,name):
        result = catalog.searchByName(name) #if book of required name found
        if result:
            print("book of name {} is present".format(name))
            return True
        else:
            print("book of name {} is not present".format(name))
            return False

    #for searching all the available book present in catalog by author
    def searchCatalogByAuthor(self,catalog,author):
        result = catalog.searchByAuthor(author)
        if result:  #if book of required author found
            print("all the books by author {} is/are {}".format(author,result))
        else:
            print("book of author {} not present now".format(author))

class Librarian(User):

    def __init__(self,name, location, age, aadhar_id,emp_id):
        super().__init__(name, location, age, aadhar_id)
        self.emp_id = emp_id

    #string representation of the object
    def __repr__(self):
        return self.name +' '+ self.location +' '+ self.emp_id

    # to add the book in the catalog by the librarian
    def addBook(self,catalog,name,author,publish_date,pages):
        #only librarian can add the book to catalog
        # returning the book object and storing in self.book for later use
        self.book = catalog.addBook(name,author,publish_date,pages)  # returning the book object
        return self.book         # returning book object

    # to display No. of different Books
    def displayDifferentBooks(self,catalog):
        catalog.displayDifferentBooks()

    # to add the bookItem of perticular book
    def addBookItem(self,catalog,book,isbn,rack,barcode):
        #we are calling the already defined function of catalog class
        #only librarian can add the bookItem to catalog
        catalog.addBookItem(self.book,isbn,rack,barcode)

    #display all the book item with different book
    def displayAllBookItems(self,catalog):
        catalog.displayAllBookItems()

    #for removing the book so its bookItem will also deleted
    def removeBook(self,catalog,name):
        self.bookItemslen = 0
        bookobj = catalog.searchByName(name)
        catalog.books.remove(bookobj)  #remove book object from list of books
        catalog.different_book_count-=1  # reduce the different book count
        bookobj.book_item.clear() #clearing the bookItem list of perticular list
        self.bookItemslen = len(bookobj.book_item) #determining total bookitems of book
        bookobj.total_count-=self.bookItemslen #reducing total book count
        catalog.inventory.pop(bookobj.name)

    #to remove the bookItem based on the barcodeNo from inventory
    def removeBookItem(self,catalog,name,barcodeNo):
        books = catalog.searchByName(name)
        for bookItem in books.book_item:
            if bookItem.barcodeNo == barcodeNo:
                books.book_item.remove(bookItem)
                catalog.inventory[books.name]-= 1
                books.total_count-= 1

Project 1- LMS/Library Mgmt System/User.py


from scrapy.shell import inspect_response
import scrapy

class MercadolibreSpider(scrapy.Spider):
    name = 'mercadolibre'
    allowed_domains = ['inmuebles.mercadolibre.com.ar']
    start_urls = ['https://inmuebles.mercadolibre.com.ar/departamentos/alquiler/capital-federal/']

    #Descomentar para mas exactitud. [Tardará mucho más]
    #custom_settings = {
    #    'DOWNLOAD_DELAY':4,
    #    'RETRY_HTTP_CODES':[403],
    #    'RETRY_TIMES':5,
    #    'CONCURRENT_REQUESTS_PER_DOMAIN':4
    #}

    def parse_item(self,response):
        self.logger.info(response.url)
        images_urls=response.xpath('//figure/img/@data-src').extract()
        price = response.xpath('//div[@class="ui-pdp-price__second-line"]//text()').get()
        expenses=response.xpath('//tr//text()[contains(.,"ARS")]').get()
        extras =response.xpath('//div[@class="ui-pdp-highlighted-specs-res"]//text()').extract()
        extras = [extra.strip() for extra in extras if extra.strip()!='']
        location = response.xpath('//li[@class="andes-breadcrumb__item"]//text()').extract()
        location = ', '.join(location[-2:])
        address = response.xpath('//figure/following-sibling::div[@class="ui-pdp-media__body"]/p//text()').get()
        yield {
                'images':images_urls,
                'price':price,
                'url':response.url,
                'expenses':expenses,
                'location':location,
                'address':address,
                'extras':extras
            }

    def parse(self, response):
        for item in response.xpath('//li[@class="ui-search-layout__item"]'):
            url = item.xpath('.//a/@href').get()
            yield scrapy.Request(url=url,callback=self.parse_item,dont_filter=True)

        next_page = response.xpath('//a[@title="Siguiente"]/@href').get()
        if next_page is not None:
            yield response.follow(next_page, self.parse)


import numpy as np
from .sph_source import SPHSource
from ..sph_kernels import _WendlandC2Kernel, find_fwhm
from os.path import join, normpath, sep
import astropy.units as U

class EAGLESource(SPHSource):
    """
    Class abstracting HI sources designed to work with publicly available
    EAGLE snapshot + group data.

    For file access, see http://icc.dur.ac.uk/Eagle/database.php.

    Parameters
    ----------
    snapPath : str
        Directory containing snapshot files. The directory structure unpacked
        from the publicly available tarballs is expected; removing/renaming
        files or directories below this will cause errors.

    snapBase : str
        Filename of snapshot files, omitting portion '.X.hdf5'.

    fof : int
        FOF group number of the target object. Note that all particles in the
        FOF group to which the subhalo belongs are used to construct the data
        cube. This avoids strange "holes" at the locations of other subhaloes
        in the same group, and gives a more realistic treatment of foreground
        and background emission local to the source. In the EAGLE database,
        this is the 'GroupNumber'.

    sub : int
        Subfind subhalo number of the target object. For centrals the subhalo
        number is 0, for satellites >0. In the EAGLE database, this is then
        'SubGroupNumber'.

    db_user : str
        Database username.

    db_key : str, optional
        Database password, or omit for a prompt at runtime. (Default: None.)

    subBoxSize : Quantity, with dimensions of length
        Box half-side length of a region to load around the object of interest,
        in physical (not comoving, no little h) units. Using larger values
        will include more foreground/background, which may be desirable, but
        will also slow down execution and impair the automatic routine used
        to find a disc plane.

    distance : Quantity, with dimensions of length, optional
        Source distance, also used to set the velocity offset via Hubble's law.
        (Default: 3 Mpc.)

    vpeculiar : Quantity, with dimensions of velocity, optional
        Source peculiar velocity, added to the velocity from Hubble's law.
        (Default: 0 km/s.)

    rotation : dict, optional
        Must have a single key, which must be one of `axis_angle`, `rotmat` or
        `L_coords`. Note that the 'y-z' plane will be the one eventually placed in the
        plane of the "sky". The corresponding value must be:

        - `axis_angle` : 2-tuple, first element one of 'x', 'y', 'z' for the \
        axis to rotate about, second element a Quantity with \
        dimensions of angle, indicating the angle to rotate through.
        - `rotmat` : A (3, 3) numpy.array specifying a rotation.
        - `L_coords` : A 2-tuple containing an inclination and an azimuthal \
        angle (both Quantity instances with dimensions of \
        angle). The routine will first attempt to identify a preferred plane \
        based on the angular momenta of the central 1/3 of particles in the \
        source. This plane will then be rotated to lie in the plane of the \
        "sky" ('y-z'), rotated by the azimuthal angle about its angular \
        momentum pole (rotation about 'x'), and inclined (rotation about \
        'y'). A 3-tuple may be provided instead, in which case the third \
        value specifies the position angle on the sky (rotation about 'x'). \
        The default position angle is 270 degrees.

        (Default: identity rotation matrix.)

    ra : Quantity, with dimensions of angle, optional
        Right ascension for the source centroid. (Default: 0 deg.)

    dec : Quantity, with dimensions of angle, optional
        Declination for the source centroid. (Default: 0 deg.)

    print_query : bool, optional
        If True, the SQL query submitted to the EAGLE database is printed.
        (Default: False.)
    """

    def __init__(
        self,
        snapPath=None,
        snapBase=None,
        fof=None,
        sub=None,
        db_user=None,
        db_key=None,
        subBoxSize=50.0 * U.kpc,
        distance=3.0 * U.Mpc,
        vpeculiar=0 * U.km / U.s,
        rotation={"rotmat": np.eye(3)},
        ra=0.0 * U.deg,
        dec=0.0 * U.deg,
        print_query=False,
    ):
        if snapPath is None:
            raise ValueError("Provide snapPath argument to EAGLESource.")
        if snapBase is None:
            raise ValueError("Provide snapBase argument to EAGLESource.")
        if fof is None:
            raise ValueError("Provide fof argument to EAGLESource.")
        if sub is None:
            raise ValueError("Provide sub argument to EAGLESource.")
        if db_user is None:
            raise ValueError("Provide EAGLE database username.")

        # optional dependencies for this source class
        from eagleSqlTools import connect, execute_query
        from pyread_eagle import EagleSnapshot
        from Hdecompose.atomic_frac import atomic_frac
        import h5py

        snapNum = int(snapBase.split("_")[1])
        volCode = normpath(snapPath).split(sep)[-2]
        query = (
            "SELECT "
            "  sh.redshift as redshift, "
            "  sh.CentreOfPotential_x as x, "
            "  sh.CentreOfPotential_y as y, "
            "  sh.CentreOfPotential_z as z, "
            "  sh.Velocity_x as vx, "
            "  sh.Velocity_y as vy, "
            "  sh.Velocity_z as vz "
            "FROM "
            "  {:s}_SubHalo as sh ".format(volCode) + "WHERE "
            "  sh.Snapnum = {:d} ".format(snapNum)
            + "  and sh.GroupNumber = {:d} ".format(fof)
            + "  and sh.SubGroupNumber = {:d}".format(sub)
        )
        if print_query:
            print("-----EAGLE-DB-QUERY-----")
            print(query)
            print("-------QUERY-ENDS-------")
        if db_key is None:
            print("EAGLE database")
        q = execute_query(connect(db_user, db_key), query)
        redshift = q["redshift"]
        a = np.power(1 + redshift, -1)
        cop = np.array([q[coord] for coord in "xyz"]) * a * U.Mpc
        vcent = np.array([q["v" + coord] for coord in "xyz"]) * U.km / U.s

        snapFile = join(snapPath, snapBase + ".0.hdf5")

        with h5py.File(snapFile, "r") as f:
            h = f["RuntimePars"].attrs["HubbleParam"]
            subBoxSize = (subBoxSize * h / a).to(U.Mpc).value
            centre = (cop * h / a).to(U.Mpc).value
            eagle_data = EagleSnapshot(snapFile)
            region = np.vstack((centre - subBoxSize, centre + subBoxSize)).T.flatten()
            eagle_data.select_region(*region)
            lbox = f["/Header"].attrs["BoxSize"] * U.Mpc / h
            fH = f["/RuntimePars"].attrs["InitAbundance_Hydrogen"]
            fHe = f["/RuntimePars"].attrs["InitAbundance_Helium"]
            proton_mass = f["/Constants"].attrs["PROTONMASS"] * U.g
            mu = 1 / (fH + 0.25 * fHe)
            gamma = f["/RuntimePars"].attrs["EOS_Jeans_GammaEffective"]
            T0 = f["/RuntimePars"].attrs["EOS_Jeans_TempNorm_K"] * U.K

            def fetch(att, ptype=0):
                # gas is type 0, only need gas properties
                tmp = eagle_data.read_dataset(ptype, att)
                dset = f["/PartType{:d}/{:s}".format(ptype, att)]
                aexp = dset.attrs.get("aexp-scale-exponent")
                hexp = dset.attrs.get("h-scale-exponent")
                return tmp[()] * np.power(a, aexp) * np.power(h, hexp)

            code_to_g = f["/Units"].attrs["UnitMass_in_g"] * U.g
            code_to_cm = f["/Units"].attrs["UnitLength_in_cm"] * U.cm
            code_to_cm_s = f["/Units"].attrs["UnitVelocity_in_cm_per_s"] * U.cm / U.s
            ng_g = fetch("GroupNumber")
            particles = dict(
                xyz_g=(fetch("Coordinates") * code_to_cm).to(U.kpc),
                vxyz_g=(fetch("Velocity") * code_to_cm_s).to(U.km / U.s),
                T_g=fetch("Temperature") * U.K,
                hsm_g=(fetch("SmoothingLength") * code_to_cm).to(U.kpc)
                * find_fwhm(_WendlandC2Kernel().kernel),
            )
            rho_g = fetch("Density") * U.g * U.cm**-3
            SFR_g = fetch("StarFormationRate")
            Habundance_g = fetch("ElementAbundance/Hydrogen")

        particles["mHI_g"] = (
            atomic_frac(
                redshift,
                rho_g * Habundance_g / (mu * proton_mass),
                particles["T_g"],
                rho_g,
                Habundance_g,
                onlyA1=True,
                EAGLE_corrections=True,
                SFR=SFR_g,
                mu=mu,
                gamma=gamma,
                fH=fH,
                T0=T0,
            )
            * code_to_g
        ).to(U.Msun)

        mask = ng_g == fof
        for k, v in particles.items():
            particles[k] = v[mask]

        particles["xyz_g"] -= cop
        particles["xyz_g"][particles["xyz_g"] > lbox / 2.0] -= lbox.to(U.kpc)
        particles["xyz_g"][particles["xyz_g"] < -lbox / 2.0] += lbox.to(U.kpc)
        particles["vxyz_g"] -= vcent

        super().__init__(
            distance=distance,
            vpeculiar=vpeculiar,
            rotation=rotation,
            ra=ra,
            dec=dec,
            h=h,
            **particles,
        )
        return


import sqlite3

from create_tables import DATABASE_URI

__author__ = 'myidispg'

class Education:

    def __init__(self, _id, course, from_date, till_date, institution, board_university):
        self._id = _id
        self.course = course
        self.from_date = from_date
        self.till_date = till_date
        self.institution = institution
        self.board_university = board_university

    def insert_data(self):
        """
        If a row with the user id already exists, then it updates the row, otherwise inserts the data
        :return: Nothing to return
        """
        connection = sqlite3.connect(DATABASE_URI)
        cursor = connection.cursor()

        query_find_by_id = "SELECT * FROM education WHERE _id=? and course=?"
        result = cursor.execute(query_find_by_id, (self._id, self.course,))
        rows = result.fetchone()

        if rows is not None:
            query = "UPDATE education " \
                    "SET from_date=?, till_date=?, institution = ?, board_university = ? " \
                    "WHERE _id = ? and course = ?"
            cursor.execute(query, (self.from_date, self.till_date,
                                   self.institution, self.board_university, self._id, self.course,))

        else:
            query = "INSERT INTO education values(?,?,?,?,?,?)"
            cursor.execute(query, (self._id, self.course, self.from_date, self.till_date, self.institution,
                                   self.board_university,))

        connection.commit()
        connection.close()

    @classmethod
    def get_by_id(cls, _id):
        connection = sqlite3.connect(DATABASE_URI)
        cursor = connection.cursor()

        query = 'SELECT * FROM education WHERE _id=?'
        result = cursor.execute(query, (_id,))

        row = result.fetchone()

        education = cls(row[0], row[1], row[2], row[3], row[4])
        connection.close()

        return education

    @staticmethod
    def get_all():
        connection = sqlite3.connect(DATABASE_URI)
        cursor = connection.cursor()

        query = "SELECT * from education"
        result = cursor.execute(query)

        rows = result.fetchall()

        list = []

        for row in rows:
            dictionary = {
                'id': row[0],
                'course': row[1],
                'from_date': row[2],
                'till_date': row[3],
                'institution': row[4],
                'board': row[5]
            }
            list.append(dictionary)

        connection.close()
        return list


#!/usr/bin/python3
"""
this file implements all unittests for collector dnsspf
"""

__author__ = "Lukas Reiter"
__license__ = "GPL v3.0"
__copyright__ = """Copyright 2018 Lukas Reiter

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY 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/>.
"""
__version__ = 0.1

import os
import tempfile
from typing import List
from unittests.tests.collectors.kali.modules.dns.core import BaseKaliDnsCollectorTestCase
from collectors.os.modules.dns.dnsspf import CollectorClass as DnsSpfCollector
from unittests.tests.collectors.core import CollectorProducerTestSuite
from database.model import Host
from database.model import Network
from database.model import ScopeType
from database.model import CollectorType

class BaseDnsSpfCollectorTestCase(BaseKaliDnsCollectorTestCase):
    """
    This class implements all unittestss for the given collector
    """
    def __init__(self, test_name: str, **kwargs):
        super().__init__(test_name,
                         collector_name="dnsspf",
                         collector_class=DnsSpfCollector,
                         **kwargs)

    @staticmethod
    def get_command_text_outputs() -> List[str]:
        """
        This method returns example outputs of the respective collectors
        :return:
        """
        return """$ /usr/bin/dig +short -t TXT test.local
"v=spf1 mx include:mail.test.local include:smtp.test.local include:spf.protection.outlook.com a:mail.test1.local a:smtp.test1.local a:mail.test2.local/24 mx:mail.test3.local exists:mail.test4.local -all"
"v=spf1 ip4:192.168.0.0/16 ~all"
"v=spf1 ip4:192.168.0.1/16 ~all"
"v=spf1 ip4:192.168.0.2/32 ~all"
"v=spf1 ip4:192.168.0.3 ~all"
"v=spf1 ip6:fe80::/64 ~all"
"v=spf1 ip6:::1/96 ~all"
"v=spf1 ip6:::2/128 ~all"
"v=spf1 ip6:::3 ~all"
"v=spf1 ip6:1080::8:800:200C:417A/98 ~all"
""".split(os.linesep)

    def _check_existence(self, session, host_name: str):
        self.assertIsNotNone(self.query_hostname(session=session,
                                                 workspace_str=self._workspaces[0],
                                                 host_name=host_name))

    def test_verify_results(self):
        """
        This method checks whether the collector correctly verifies the command output
        :return:
        """
        self.init_db()
        with tempfile.TemporaryDirectory() as temp_dir:
            test_suite = CollectorProducerTestSuite(engine=self._engine,
                                                    arguments={"workspace": self._workspaces[0],
                                                               "output_dir": temp_dir})
            with self._engine.session_scope() as session:
                source = self.create_source(session, source_str=self._collector_name)
                command = self.create_command(session=session,
                                              workspace_str=self._workspaces[0],
                                              command=["dig", "+short", "-t", "TXT", "test.local"],
                                              collector_name_str=self._collector_name,
                                              collector_name_type=CollectorType.host_service,
                                              service_port=53,
                                              scope=ScopeType.all,
                                              output_path=temp_dir)
                command.stdout_output = self.get_command_text_outputs()
                test_suite.verify_results(session=session,
                                          arg_parse_module=self._arg_parse_module,
                                          command=command,
                                          source=source,
                                          report_item=self._report_item)
        # Check database
        with self._engine.session_scope() as session:
            # Check domain names
            self._check_existence(session=session, host_name="test.local")
            self._check_existence(session=session, host_name="mail.test.local")
            self._check_existence(session=session, host_name="smtp.test.local")
            self._check_existence(session=session, host_name="test1.local")
            self._check_existence(session=session, host_name="mail.test1.local")
            self._check_existence(session=session, host_name="smtp.test1.local")
            self._check_existence(session=session, host_name="test2.local")
            self._check_existence(session=session, host_name="mail.test2.local")
            self._check_existence(session=session, host_name="test3.local")
            self._check_existence(session=session, host_name="mail.test3.local")
            self._check_existence(session=session, host_name="outlook.com")
            self._check_existence(session=session, host_name="spf.protection.outlook.com")
            # Check IP addresses
            self.assertIsNotNone(session.query(Host).filter_by(address="::1").one_or_none())
            self.assertIsNotNone(session.query(Host).filter_by(address="::2").one_or_none())
            self.assertIsNotNone(session.query(Host).filter_by(address="::3").one_or_none())
            self.assertIsNotNone(session.query(Host).filter_by(address="192.168.0.1").one_or_none())
            self.assertIsNotNone(session.query(Host).filter_by(address="192.168.0.2").one_or_none())
            self.assertIsNotNone(session.query(Host).filter_by(address="192.168.0.3").one_or_none())
            self.assertIsNotNone(session.query(Host).filter_by(address="1080::8:800:200C:417A").one_or_none())
            # Check IP networks
            self.assertIsNotNone(session.query(Network).filter_by(network="fe80::/64").one_or_none())
            self.assertIsNotNone(session.query(Network).filter_by(network="192.168.0.0/16").one_or_none())


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import logging
import time
from six import wraps, get_method_function, get_method_self

from .exceptions import DoNotReadThisWidget

null_logger = logging.getLogger('widgetastic_null')
null_logger.addHandler(logging.NullHandler())

class PrependParentsAdapter(logging.LoggerAdapter):
    """This class ensures the path to the widget is represented in the log records."""
    def process(self, msg, kwargs):
        return '[{}]: {}'.format(self.extra['widget_path'], msg), kwargs

def create_widget_logger(widget_path, logger=None):
    """Create a logger that prepends the ``widget_path`` to the log records."""
    return PrependParentsAdapter(
        logger or null_logger,
        {'widget_path': widget_path})

def logged(log_args=False, log_result=False):
    def g(f):
        @wraps(f)
        def wrapped(self, *args, **kwargs):
            start_time = time.time()
            if log_args:
                signature = '{}{!r}{!r}'.format(f.__name__, args, kwargs)
            else:
                signature = f.__name__
            self.logger.debug('%s started', signature)
            try:
                result = f(self, *args, **kwargs)
            except DoNotReadThisWidget:
                elapsed_time = (time.time() - start_time) * 1000.0
                self.logger.info(
                    '%s not read on widget\'s request (elapsed %.0f ms)', signature, elapsed_time)
                raise
            else:
                elapsed_time = (time.time() - start_time) * 1000.0
                if log_result:
                    self.logger.info('%s -> %r (elapsed %.0f ms)', signature, result, elapsed_time)
                else:
                    self.logger.info('%s (elapsed %.0f ms)', signature, elapsed_time)
                return result

        wrapped.original_function = f
        return wrapped

    return g

def call_unlogged(method, *args, **kwargs):
    """Calls the original method without logging when ``logged`` is applied.

    In case you pass in an ordinary method that was not decorated, it will work as usual.

    Args:
        method: The method object from the object.
        *args: Args to pass to the method.
        **kwargs: Keyword arguments to pass to the method.

    Returns:
        Whatever that method returns.
    """
    try:
        f = method.original_function
    except AttributeError:
        f = get_method_function(method)

    return f(get_method_self(method), *args, **kwargs)


from django.urls import path

from .views import (
    AuthorListView,
    AuthorDetailView,
    BookListView,
    BookDetailView,
    AuthorCreateView,
    BookCreateView,
    AuthorUpdateView,
    AuthorDeleteView,
    BookUpdateView,
    BookDeleteView,
    GenreListView,
    GenreCreateView,
    GenreUpdateView,
    GenreDeleteView,
)

urlpatterns = [
    path("books/", BookListView.as_view(), name="books-list"),
    path("book/add/", BookCreateView.as_view(), name="book-create"),
    path("book/update/<int:pk>", BookUpdateView.as_view(), name="book-update"),
    path("book/delete/<int:pk>", BookDeleteView.as_view(), name="book-delete"),
    path("book/<int:pk>", BookDetailView.as_view(), name="book-detail"),
    path("authors/", AuthorListView.as_view(), name="authors-list"),
    path("author/<int:pk>", AuthorDetailView.as_view(), name="author-detail"),
    path("author/add/", AuthorCreateView.as_view(), name="author-create"),
    path("author/update/<int:pk>", AuthorUpdateView.as_view(), name="author-update"),
    path("author/delete/<int:pk>", AuthorDeleteView.as_view(), name="author-delete"),
    path("genres/", GenreListView.as_view(), name="genres-list"),
    path("genre/add/", GenreCreateView.as_view(), name="genre-create"),
    path("genre/update/<int:pk>", GenreUpdateView.as_view(), name="genre-update"),
    path("genre/delete/<int:pk>", GenreDeleteView.as_view(), name="genre-delete"),
]


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 17 11:15:57 2018

@author: kazuki.onodera
"""

import gc, os
from tqdm import tqdm
import pandas as pd
import sys
sys.path.append(f'/home/{os.environ.get("USER")}/PythonLibrary')
import lgbextension as ex
import lightgbm as lgb
from multiprocessing import cpu_count, Pool
#from glob import glob
import count
import utils, utils_cat
utils.start(__file__)
#==============================================================================

SEED = 71

HEADS = list(range(500, 2500, 100))

param = {
         'objective': 'binary',
         'metric': 'auc',
         'learning_rate': 0.01,
         'max_depth': 6,
         'num_leaves': 63,
         'max_bin': 255,

         'min_child_weight': 10,
         'min_data_in_leaf': 150,
         'reg_lambda': 0.5,  # L2 regularization term on weights.
         'reg_alpha': 0.5,  # L1 regularization term on weights.

         'colsample_bytree': 0.9,
         'subsample': 0.9,
#         'nthread': 32,
         'nthread': cpu_count(),
         'bagging_freq': 1,
         'verbose':-1,
         'seed': SEED
         }

# =============================================================================
# load
# =============================================================================
imp = pd.read_csv('LOG/imp_801_imp_lgb.py.csv')
imp['split'] /= imp['split'].max()
imp['gain'] /= imp['gain'].max()
imp['total'] = imp['split'] + imp['gain']
imp.sort_values('total', ascending=False, inplace=True)

for HEAD in HEADS:
    imp_ = imp[~imp.feature.str.startswith('Mxw_META_FEATURE_')]
    use_files = (imp_.head(HEAD).feature + '.f').tolist()

    files = utils.get_use_files(use_files, True)

    X = pd.concat([
                    pd.read_feather(f) for f in tqdm(files, mininterval=60)
                   ], axis=1)
    y = utils.read_pickles('../data/label').TARGET

    if X.columns.duplicated().sum()>0:
        raise Exception(f'duplicated!: { X.columns[X.columns.duplicated()] }')
    print('no dup :) ')
    print(f'X.shape {X.shape}')

    gc.collect()

    CAT = list( set(X.columns)&set(utils_cat.ALL))

    # =============================================================================
    # cv
    # =============================================================================
    dtrain = lgb.Dataset(X, y, categorical_feature=CAT )
    gc.collect()

    ret = lgb.cv(param, dtrain, 9999, nfold=5,
                 early_stopping_rounds=100, verbose_eval=50,
                 seed=SEED)

    result = f"CV auc-mean({HEAD}): {ret['auc-mean'][-1]}"
    print(result)

    utils.send_line(result)

# =============================================================================
# train
# =============================================================================
#dtrain = lgb.Dataset(X, y, categorical_feature=CAT )
##model = lgb.train(param, dtrain, len(ret['auc-mean']))
#model = lgb.train(param, dtrain, 1000)
#imp = ex.getImp(model).sort_values(['gain', 'feature'], ascending=[False, True])
#
#
#imp.to_csv(f'LOG/imp_{__file__}.csv', index=False)
#
#"""
#imp = pd.read_csv('LOG/imp_909_cv.py.csv')
#"""

#def multi_touch(arg):
#    os.system(f'touch "../feature_unused/{arg}.f"')
#
#
#col = imp[imp['split']==0]['feature'].tolist()
#pool = Pool(cpu_count())
#pool.map(multi_touch, col)
#pool.close()

#==============================================================================
utils.end(__file__)
#utils.stop_instance()


from copy import deepcopy
from qiskit.execute import execute
from qiskit.providers.basicaer import BasicAer

from qiskit.test import QiskitTestCase

from qiskit.circuit import ClassicalRegister, QuantumRegister, QuantumCircuit

def random_circuit(Data):
    qr = QuantumRegister(3, 'q')
    cr = ClassicalRegister(3, 'c')
    circuit = QuantumCircuit(qr, cr)
    circuit.h(qr[1])
    circuit.cx(qr[1], qr[2])
    circuit.measure(qr, cr)
    return circuit

class FuzzOptmizationLevels(QiskitTestCase):

    def __init__(self, Data):
        self.circuit = random_circuit(Data)
        self.seed_simulator = int.from_bytes(Data.read(1), byteorder='little')
        self.random_bool = self.seed_simulator < 42

    def assertEqualCounts(self, *counts):
        average = {}
        for value in set(counts[0]).intersection(*counts[1:]):
            average[value] = sum([count[value] for count in counts])/len(counts)

        for count in counts:
            for value in count.keys():
                self.assertEqual(count[value], average[value])

    def optmization_levels(self):
        backend = BasicAer.get_backend('qasm_simulator')

        circuit = self.circuit
        seed_simulator = self.seed_simulator
        seed_transpiler = seed_simulator

        counts_0 = execute(deepcopy(circuit),
                           backend, optimization_level=0,
                           seed_simulator=seed_simulator,
                           seed_transpiler=seed_transpiler).result().get_counts()
        counts_1 = execute(deepcopy(circuit),
                           backend, optimization_level=1,
                           seed_simulator=seed_simulator,
                           seed_transpiler=seed_transpiler,
                           ).result().get_counts()
        counts_2 = execute(deepcopy(circuit),
                           backend, optimization_level=2,
                           seed_simulator=seed_simulator,
                           seed_transpiler=seed_transpiler,
                           ).result().get_counts()

        if self.random_bool:
            counts_3 = execute(deepcopy(circuit),
                           backend, optimization_level=3,
                           seed_simulator=seed_simulator,
                           seed_transpiler=seed_transpiler,
                           ).result().get_counts()
        else:
            counts_3 = deepcopy(counts_2)

        self.assertEqualCounts(counts_0, counts_1, counts_2, counts_3)

def optmization_levels(Data):
    test = FuzzOptmizationLevels(Data)
    test.optmization_levels()

if __name__ == '__main__':
    import io
    data = io.BytesIO(b"abcdef")
    optmization_levels(data)


import zipfile
import os
import random
import shutil

train_percent = 0.8

# Archive unpack
unzip_dir = 'VOC_PCB'

if not os.path.exists(unzip_dir):
    path_to = '../VOC_PCB.zip'
    with zipfile.ZipFile(path_to, 'r') as zip_ref:
        zip_ref.extractall()

# Data group
new_dir = 'Dataset_for_YOLO'

if not os.path.exists(new_dir):
    os.mkdir(new_dir)
    os.mkdir(os.path.join(new_dir, 'train'))
    os.mkdir(os.path.join(new_dir, 'val'))
    os.mkdir(os.path.join(new_dir, 'train', 'images'))
    os.mkdir(os.path.join(new_dir, 'train', 'labels'))
    os.mkdir(os.path.join(new_dir, 'val', 'images'))
    os.mkdir(os.path.join(new_dir, 'val', 'labels'))

photo_dir = unzip_dir + '/JPEGImages'
annotation_dir = '../Labels'

for filename in os.listdir(photo_dir):
    rand_num = random.random()

    if rand_num < train_percent:
        target_dir = os.path.join(new_dir, 'train', 'images')
        annotation_target_dir = os.path.join(new_dir, 'train', 'labels')
    else:
        target_dir = os.path.join(new_dir, 'val', 'images')
        annotation_target_dir = os.path.join(new_dir, 'val', 'labels')

    os.makedirs(target_dir, exist_ok=True)
    source_path = os.path.join(photo_dir, filename)

    if os.path.exists(source_path):
        target_path = os.path.join(target_dir, filename)
        shutil.move(source_path, target_path)

        annotation_file = os.path.splitext(filename)[0] + '.txt'
        annotation_source_path = os.path.join(annotation_dir, annotation_file)
        annotation_target_path = os.path.join(annotation_target_dir, annotation_file)

        if os.path.exists(annotation_source_path):
            shutil.move(annotation_source_path, annotation_target_path)
        else:
            print(f"Annotation file not found: {annotation_source_path}")
    else:
        print(f"File is not real: {source_path}")


"""
Module defining variable calculators managing the exact calculation process
of variables on objects.
"""
from __future__ import annotations

import typing as t
from collections import abc
from itertools import repeat

from more_itertools import peekable
from toolz import curry

from lXtractor.core.exceptions import FailedCalculation
from lXtractor.util import apply
from lXtractor.variables.base import (
    AbstractCalculator,
    ERT,
    OT,
    VT,
    MappingT,
    AbstractVariable,
)

M: t.TypeAlias = MappingT | abc.Iterable[MappingT | None] | None
METHODS = ("joblib", "multiprocess")

# TODO: docs

@curry
def _try_calculate(
    inp: tuple[OT, VT, MappingT | None],
    valid_exceptions: abc.Sequence[t.Type[Exception]] | None,
) -> ERT:
    o, v, m = inp
    if valid_exceptions is not None:
        try:
            return True, v.calculate(o, m)
        except tuple(valid_exceptions) as e:
            return False, str(e)
    return True, v.calculate(o, m)

@curry
def _calc_on_object(
    inp: tuple[OT, abc.Iterable[VT], MappingT | None],
    valid_exceptions: abc.Sequence[t.Type[Exception]] | None,
) -> list[ERT]:
    o, vs, m = inp
    return [_try_calculate((o, v, m), valid_exceptions) for v in vs]

def calculate(
    o: abc.Iterable[OT],
    v: abc.Iterable[VT] | abc.Iterable[abc.Iterable[VT]],
    m: MappingT | abc.Iterable[MappingT | None] | None,
    valid_exceptions: abc.Sequence[t.Type[Exception]] | None,
    num_proc: int,
    verbose: bool = False,
    **kwargs,
) -> abc.Generator[abc.Iterator[ERT], None, None]:
    # Unpack o to know the size
    o = list(o)

    # Check variables type
    v = peekable(v)
    fst = v.peek(None)
    if isinstance(fst, AbstractVariable):
        v = repeat(list(v), len(o))

    if m is None:
        m = repeat(None, len(o))
    elif isinstance(m, abc.Mapping):
        m = repeat(m, len(o))

    inputs = zip(o, v, m, strict=True)
    fn = _calc_on_object(valid_exceptions=valid_exceptions)
    yield from apply(fn, inputs, verbose, "Calculating variables", num_proc, **kwargs)

class GenericCalculator(AbstractCalculator):
    """
    Parallel calculator, calculating variables in parallel. Duh.
    """

    __slots__ = ("num_proc", "valid_exceptions", "apply_kwargs", "verbose")

    def __init__(
        self,
        num_proc: int = 1,
        valid_exceptions: abc.Sequence[t.Type[Exception]] = (FailedCalculation,),
        apply_kwargs: dict | None = None,
        verbose: bool = False,
    ):
        self.num_proc = num_proc
        self.valid_exceptions = valid_exceptions
        self.apply_kwargs = apply_kwargs or {}
        self.verbose = verbose

    @t.overload
    def __call__(self, o: OT, v: VT, m: MappingT | None) -> ERT:
        ...

    @t.overload
    def __call__(
        self,
        o: abc.Iterable[OT],
        v: abc.Iterable[VT] | abc.Iterable[abc.Iterable[VT]],
        m: abc.Iterable[MappingT | None] | None,
    ) -> abc.Iterable[abc.Iterable[ERT]]:
        ...

    def __call__(
        self,
        o: OT | abc.Iterable[OT],
        v: VT | abc.Iterable[VT] | abc.Iterable[abc.Iterable[VT]],
        m: MappingT | abc.Iterable[MappingT | None] | None,
    ) -> ERT | abc.Iterable[abc.Iterable[ERT]]:
        if isinstance(v, abc.Iterable):
            return calculate(
                o,
                v,
                m,
                self.valid_exceptions,
                self.num_proc,
                self.verbose,
                **self.apply_kwargs,
            )
        assert (
            isinstance(m, abc.Mapping) or m is None
        ), "Mapping must be a single object"

        return _try_calculate((o, v, m), self.valid_exceptions)

    def map(
        self, o: OT, v: abc.Iterable[VT], m: MappingT | None
    ) -> abc.Generator[ERT, None, None]:
        v = list(v)
        inputs = zip(
            repeat(o, len(v)),
            v,
            repeat(m, len(v)),
            strict=True,
        )
        fn = _try_calculate(valid_exceptions=self.valid_exceptions)
        yield from apply(
            fn, inputs, self.verbose, "Calculating variables", self.num_proc
        )

    def vmap(
        self,
        o: abc.Iterable[OT],
        v: VT,
        m: abc.Iterable[MappingT | None] | MappingT | None,
    ) -> abc.Generator[ERT, None, None]:
        o = list(o)
        if m is None or isinstance(m, abc.Mapping):
            m = repeat(m, len(o))
        inputs = zip(o, repeat(v, len(o)), m)
        fn = _try_calculate(valid_exceptions=self.valid_exceptions)
        yield from apply(
            fn, inputs, self.verbose, "Calculating variables", self.num_proc
        )

if __name__ == "__main__":
    raise RuntimeError


from __future__ import print_function
import cv2 as cv
import argparse

# Cada imagen pasa por un ciclo de clasificación (Cascade classifier)
# Cada clasificador examina una singularidad o rasgo de la imagen y responde a la pregunta
# mi imagen posee este singularidad?
# Al terminar el ciclo se podrá responder la pregunta
# mi imagen posee todas las singularidades para ser considerada aquel objeto?

def detectAndDisplay(frame):
    frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    frame_gray = cv.equalizeHist(frame_gray)
    #-- Detectar rostros
    faces = face_cascade.detectMultiScale(frame_gray)
    for (x,y,w,h) in faces:
        center = (x + w//2, y + h//2)
        frame = cv.ellipse(frame, center, (w//2, h//2), 0, 0, 360, (255, 0, 255), 4)
        faceROI = frame_gray[y:y+h,x:x+w]
        #-- Localizar ojos en el rostro
        eyes = eyes_cascade.detectMultiScale(faceROI)
        for (x2,y2,w2,h2) in eyes:
            eye_center = (x + x2 + w2//2, y + y2 + h2//2)
            radius = int(round((w2 + h2)*0.25))
            frame = cv.circle(frame, eye_center, radius, (255, 0, 0 ), 4)
    cv.imshow('Capture - Face detection', frame)

face_cascade = cv.CascadeClassifier()
eyes_cascade = cv.CascadeClassifier()

# Cargar los clasificadores adiestrados
face_cascade.load('haarcascade_frontalface_alt.xml')
eyes_cascade.load('haarcascade_eye_tree_eyeglasses.xml')

frame = cv.imread('carlomagno.jpg')
detectAndDisplay(frame)
cv.waitKey()


import sqlite3
from random import random

# conn = sqlite3.connect('train.db')
# c = conn.cursor()

# speciesToID = {}
# idCounter = 0

# f = open('train.csv')
# items = []
# c.execute('DROP TABLE IF EXISTS train')
# for i, line in enumerate(f):
#   lineArr = line.split(',')[:2]
#   # schema
#   if i == 0:
#     createSchema = 'CREATE TABLE train ('
#     for j in range(2):
#       item = lineArr[j]
#       if j > 0:
#         createSchema += ', '
#       createSchema += item
#     createSchema += ')'
#     c.execute(createSchema)
#   else:
#     for j in range(2):
#       item = lineArr[j]
#       if j == 0:
#         lineArr[j] = int(item)
#       elif j == 1:
#         species = item
#         if species not in speciesToID:
#           speciesToID[species] = idCounter
#           idCounter += 1
#         lineArr[j] = int(speciesToID[species])
#     asTuple = tuple(lineArr)
#     items.append(asTuple)
# c.executemany('INSERT INTO train VALUES (?, ?)', items)
# conn.commit()
# c.execute('DROP TABLE IF EXISTS test')
# conn.commit()
# conn.close()

conn = sqlite3.connect('train.db')
c = conn.cursor()
res = c.execute("SELECT id, species from train where id < 1585")
train_datas = []
train_labels = []
test_datas = []
test_labels = []
for r in res:
  prob = random()
  if prob >= 0.8:
    test_datas.append(str(r[0]))
    test_labels.append(str(r[1]))
  else:
    train_datas.append(str(r[0]))
    train_labels.append(str(r[1]))
training = open("train2.txt", 'a')
training.write(','.join(train_datas) + "\n")
training.write(','.join(train_labels) + "\n")
testing = open("test2.txt", 'a')
testing.write(','.join(test_datas) + "\n")
testing.write(','.join(test_labels) + "\n")
conn.close()


from django.shortcuts import render

# Create your views here.
from django.utils import timezone
from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings
from django.views.generic import ListView, DetailView, View
from .models import Order, CartItem
from gallery.models import painting

@login_required(login_url='/login/')
def OrderSummary(request):
    cart_items,created = CartItem.objects.get_or_create(
        user=request.user, ordered=False)
    context = {'cart_items': cart_items}
    print(cart_items)
    return render(request, 'cart.html', context)

@login_required(login_url='/login/')
def add_to_cart(request, pk):
    item = get_object_or_404(painting, pk=pk)
    ordered_item, created = Order.objects.get_or_create(
        item=item,
        user=request.user,
        ordered=False
    )

    user_cartitem = CartItem.objects.filter(
        user=request.user, ordered=False)

    if user_cartitem.exists():
        cart_item = user_cartitem[0]

        if cart_item.item.filter(item__pk=item.pk).exists():
            ordered_item.quantity += 1
            ordered_item.save()
            messages.success(request, "Added Quantity Item")
            return redirect("cart:order-summary")
        else:
            cart_item.item.add(ordered_item)
            messages.success(request, "Added Item to your cart")
            return redirect("cart:order-summary")

    else:
        ordered_date = timezone.now()
        cart_item = CartItem.objects.create(
            user=request.user, order_date=ordered_date)
        cart_item.item.add(ordered_item)
        messages.success(request, "Added Item to your cart")
        return redirect("cart:order-summary", pk=pk)

@login_required(login_url='/login/')
def remove_from_cart(request, pk):
    item = get_object_or_404(painting,pk=pk)
    user_cartitems = CartItem.objects.filter(user=request.user,
                                             ordered=False
                                             )
    if user_cartitems.exists():
        cart_items = user_cartitems[0]

        if cart_items.item.filter(item__pk=item.pk).exists():
            order_item = Order.objects.filter(user=request.user,
                                              item=item,
                                              ordered=False)[0]
            order_item.delete()
            messages.success(request, "Item \"" +
                             order_item.item.Title+"\" removed from your cart")
            return redirect("cart:order-summary")
        else:
            messages.success(request, "This Item not in your cart")
            return redirect("cart:order-summary")
    else:
        messages.success(request, "You do not have an Order")
        return redirect("cart:order-summary")

@login_required(login_url='/login/')
def remove_single_item_from_cart(request, pk):
    item = get_object_or_404(painting,pk=pk)
    user_cartitems = CartItem.objects.filter(user=request.user,
                                             ordered=False
                                             )
    if user_cartitems.exists():
        cart_items = user_cartitems[0]

        if cart_items.item.filter(item__pk=item.pk).exists():
            order_item = Order.objects.filter(user=request.user,
                                              item=item,
                                              ordered=False)[0]
            if order_item.quantity > 1:
                order_item.quantity -= 1
                order_item.save()
            else:
                order_item.delete()
            messages.success(request, "Cart Updated")
            return redirect("cart:order-summary")

        else:
            messages.success(request, "This Item is not in your cart")
            return redirect("cart:order-summary")
    else:
        messages.success(request, "You do not have an Order")
        return redirect("cart:order-summary")

@login_required(login_url='/login/')
def PlaceOrder(request):
    cart_items = CartItem.objects.get(user=request.user, ordered=False)
    # order = Order.objects.filter(user=request.user, ordered=False)

    order_items = cart_items.item.all()
    order_items.update(ordered=True)
    for item in order_items:
        item.save()

    cart_items.ordered = True
    cart_items.save()
    messages.success(request, "Your Order has been placed")
    return redirect("/")


import cv2

cap=cv2.VideoCapture("http://192.168.1.72:4747/video")
while True:
    ret, frame = cap.read()
    if ret:
        # Отображение кадра с IP-камеры на экране
        cv2.imshow("Camera", frame)

        if cv2.waitKey(1) & 0xFF == 27:
            break
    else:
        print('aaaaaaa')
        break

# Освобождение ресурсов и закрытие окон
cap.release()
cv2.destroyAllWindows()


from datetime import datetime
from pathlib import Path
from more_itertools import powerset
import numpy as np
import pandas as pd
from tqdm import tqdm

from circuitree.models import SimpleNetworkGrammar

def _get_n_motifs_present(
    samples: list[str],
    motif_combination_strings: list[str],
    grammar: SimpleNetworkGrammar,
):
    motif_combinations_counter = np.zeros(len(motif_combination_strings), dtype=int)
    mc_index = {mc: i for i, mc in enumerate(motif_combination_strings)}
    for sample in samples:
        motif_set = [m for m in motifs if grammar.has_pattern(sample, motifs[m])]
        motif_combination_string = "+".join(motif_set) or "(none)"
        motif_combinations_counter[mc_index[motif_combination_string]] += 1
    return motif_combinations_counter

def main(
    results_dir: Path,
    motifs: dict[str, str],
    save_dir: Path = None,
    save: bool = False,
    components=["A", "B", "C"],
    interactions=["activates", "inhibits"],
    step_globstr="*_samples.csv",
    delim="_",
    which_in_split=-2,
):
    grammar = SimpleNetworkGrammar(components=components, interactions=interactions)

    motif_combinations = []
    motif_combination_strings = []
    for ms in powerset(motifs.keys()):
        mc_string = "+".join(ms) or "(none)"
        motif_combinations.append(set(ms))
        motif_combination_strings.append(mc_string)

    results_dir = Path(results_dir)
    replicate_dirs = sorted(d for d in results_dir.iterdir() if d.is_dir())
    replicates = []
    steps = []
    motif_samples = []

    for i, d in enumerate(tqdm(replicate_dirs, desc=f"Loading replicates")):
        step_files = list(d.glob(step_globstr))
        for f in step_files:
            step = int(f.stem.split(delim)[which_in_split])
            replicates.append(i)
            steps.append(step)
            sample_df = pd.read_csv(f)
            if "selected_node" in sample_df.columns:
                # Get the selected node at each step
                step_samples = sample_df["selected_node"].values
            else:
                # Remove header and read the first column as a list of selected states
                step_samples = sample_df.iloc[1:, 0].to_list()

            n_motifs_sampled_at_step = _get_n_motifs_present(
                step_samples, motif_combination_strings, grammar
            )
            motif_samples.append(n_motifs_sampled_at_step)

    motif_samples = np.array(motif_samples)
    df = pd.DataFrame(
        {
            "replicate": replicates,
            "step": steps,
            **{mc: n for mc, n in zip(motif_combination_strings, motif_samples.T)},
        }
    )
    df = df.sort_values(["replicate", "step"]).reset_index(drop=True)

    if save:
        today = datetime.today().strftime("%y%m%d")
        fpath = Path(save_dir).joinpath(f"{today}_motif_counts.csv")
        print(f"Writing to: {fpath.resolve().absolute()}")
        df.to_csv(fpath, index=False)

if __name__ == "__main__":
    # results_dir = Path("data/oscillation/mcts/mcts_bootstrap_short_231020_175449")
    # results_dir = Path("data/oscillation/mcts/mcts_bootstrap_short_231102_111706")
    # results_dir = Path("data/oscillation/mcts/mcts_bootstrap_long_231022_173227")
    results_dir = Path(
        "data/oscillation/mcts/mcts_bootstrap_short_exploration2.00_231103_140501"
    )

    save_dir = results_dir

    motifs = {"AI": "ABa_BAi", "III": "ABi_BCi_CAi"}

    main(
        results_dir=results_dir,
        save_dir=save_dir,
        motifs=motifs,
        save=True,
    )


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import utils.plot as plot
from utils.preprocessing import *
from data.DigitSet import DigitSet
from data.DataSet import DataSet
import os

#%%
folder = os.path.join("files", "dataset")
dataset = DataSet(folder)
dataset.apply(apply_mean_centering)
dataset.apply(apply_unit_distance_normalization)
dataset.apply(lambda x: normalize_pressure_value(x, 512))

#%%
filename = os.path.join(folder, "10.43_23.03.2018_digitset.json")
digitset = DigitSet(filename)
scaled = digitset.copy()
# Apply transformations
scaled.apply(apply_mean_centering)
scaled.apply(apply_unit_distance_normalization)
scaled.apply(lambda x: normalize_pressure_value(x, 512))
if scaled.time_is_dt():
    scaled.convert_dt_to_t()

#%%
digit, label = digitset[6]
plot.show_digit(digit, label=label,
                show_lines=True, show_points=True,
                use_time_as_color=(not digitset.time_is_dt()),
                padding=100)

#%%
# plot random digit
digit, label = scaled[6]
plot.show_digit(digit, label=label,
                show_lines=True, show_points=True,
                use_time_as_color=(not scaled.time_is_dt()),
                padding=0.1)

#%%
#if __name__ == '__main__':
#    filename = "temp/01.15_14.03.2018_digitset.json"
#    digitset = loader.load_digitset(filename)
#    data, labels = loader.extract_data_and_labels(digitset)
#    plot.show_digit(data[-7])

#%%
# convert dt to t
#digit, label = digitset[30]
#digit = digit.copy()
#for i in range(1, len(digit)):
#    digit[i][3] += digit[i-1][3]
#


from time import time
import tweepy
import datetime
from urllib.request import urlopen
from bs4 import BeautifulSoup

#########################################################################################
# Twitter API setup

# reading keys from file

# open keys.txt file
file = open("keys.txt","r")
read = file.readlines()

# create new array for elements
modified = []

# read keys from textfile
for line in read:
    modified.append(line.strip())

# keys
api_key = modified[0]
api_key_secret = modified[1]
access_token = modified[2]
access_token_secret = modified[3]

# basic authentication
authenticator = tweepy.OAuthHandler(api_key, api_key_secret)
authenticator.set_access_token(access_token, access_token_secret)

api = tweepy.API(authenticator, wait_on_rate_limit = True)

# closing file
file.close()

print("auth OK...")
#########################################################################################

# functions

# GET data from Google Finance about indexes
def get_index_data(url):

    print("finding data...")

    # define array for collecting values
    data = []

    # read data from internet
    html = urlopen(url, timeout = 20).read()
    soup = BeautifulSoup(html, "html.parser")

    # GET data from specific elements
    points_now = soup.find("div", attrs = {"class" : "YMlKec fxKbKc"}) # get index point data
    points_start = soup.find("div", attrs = {"class" : "P6K39c"}) # get last days closing points
    index_name = soup.find("div", attrs = {"class" : "zzDege"}) # get index name

    # converting to float for calculations
    points_now_format = float(points_now.text.replace(",", ""))
    points_start_format = float(points_start.text.replace(",", ""))

    # counting prosentual rise/fall of index
    prosentual_rise = str("{0:.2f}".format(((points_now_format / points_start_format) - 1) * 100))

    # adding +-sign front of prosentual rise if prosentual_rise is positive
    if (float(prosentual_rise) > 0):
        prosentual_rise = "+" + prosentual_rise

    # append data to array
    data.append(index_name.text)
    data.append(points_now.text)
    data.append(prosentual_rise)

    # return data[]
    return data

# Tweet data
def tweetAll() :

    # add current date and time (day/month/year)
    time_now = datetime.datetime.now().strftime("%d/%m/%Y")

    # URLs for wanted indexes

    # url0 = "https://www.google.com/finance/quote/DAX:INDEXDB"
    url1 =  "https://www.google.com/finance/quote/OMXHPI:INDEXNASDAQ" # OMX Helsinki PI
    url2 = "https://www.google.com/finance/quote/FNFIEURPI:INDEXNASDAQ" # First North Finland EUR PI
    url3 = "https://www.google.com/finance/quote/OMXH25:INDEXNASDAQ" # OMX Helsinki 25

    # dax_data = get_index_data(url0)[0] + ": " + get_index_data(url0)[1] + " " + get_index_data(url0)[2]
    omxhpi_data = get_index_data(url1)[0] + ": " + get_index_data(url1)[1] + " (" + get_index_data(url1)[2] + "%)"
    fnfpi_data = get_index_data(url2)[0] + ": " + get_index_data(url2)[1] + " (" + get_index_data(url2)[2] + "%)"
    omxh25_data = get_index_data(url3)[0] + ": " + get_index_data(url3)[1] + " (" + get_index_data(url3)[2] + "%)"

    # Posting tweet
    print("updating twitter status...")

    api.update_status("Helsingin pörssi " + time_now + "\n" +
                    omxhpi_data + "\n" +
                    omxh25_data + "\n" +
                    fnfpi_data + "\n" +
                    "#talous")

    print("Status updated!")

tweetAll()


from tkinter import *
from tkinter import messagebox
from data_manager import DataManager
from flight_manager import FlightManager
from constants import GuiConst
from PIL import Image, ImageTk
import webbrowser

class MainWindow:
    """This is the GUI of the Flight alarm"""
    def __init__(self, master):
        self.master = master
        self.data_manager = DataManager()
        self.flight_manager = FlightManager(self.data_manager)

        self.master.resizable(width=False, height=False)
        self.master.title("Flight Alarm")
        self.master.config(padx=50, pady=20, bg=GuiConst.BG_COLOR)

        # ------------------------------- Images ------------------------------- #
        flight_display_img = Image.open(GuiConst.FLIGHT_DISPLAY)
        flight_display_img_resized = flight_display_img.resize((360, 255), Image.ANTIALIAS)
        self.flight_display_img = ImageTk.PhotoImage(flight_display_img_resized)

        # ------------------------------- Labels ------------------------------- #
        title_label = Label(
            master,
            text="Flight Alarm",
            bg=GuiConst.BG_COLOR,
            fg=GuiConst.FG_COLOR,
            font=GuiConst.BG_FONT
        )
        title_label.grid(column=0, row=0, columnspan=3)

        flight_display_label = Label(
            master,
            image=self.flight_display_img
        )
        flight_display_label.grid(column=0, row=1, columnspan=2, pady=20, sticky="w")

        add_label = Label(
            master,
            text="Add/Update/Delete data",
            bg=GuiConst.BG_COLOR,
            fg=GuiConst.FG_COLOR,
            font=GuiConst.FG_FONT
        )
        add_label.grid(column=0, row=2, sticky="w", pady=5)

        city_to_label = Label(
            master,
            text="City to travel to: ",
            bg=GuiConst.BG_COLOR,
            fg=GuiConst.FG_COLOR,
            font=GuiConst.FG_FONT
        )
        city_to_label.grid(column=0, row=3, sticky="w")

        price_label = Label(
            master,
            text="Ticket's maximum price:",
            bg=GuiConst.BG_COLOR,
            fg=GuiConst.FG_COLOR,
            font=GuiConst.FG_FONT
        )
        price_label.grid(column=0, row=4, sticky="w")

        currency_label = Label(
            master,
            text="Euro",
            bg=GuiConst.BG_COLOR,
            fg=GuiConst.FG_COLOR,
            font=GuiConst.FG_FONT
        )
        currency_label.grid(column=1, row=4, sticky="e")

        city_from_label = Label(
            master,
            text="City to travel from: ",
            bg=GuiConst.BG_COLOR,
            fg=GuiConst.FG_COLOR,
            font=GuiConst.FG_FONT
        )
        city_from_label.grid(column=0, row=6, sticky="w", pady=5)

        # ------------------------------- Entries ------------------------------- #
        self.price_entry = Entry(
            master,
            width=7,
            fg=GuiConst.FG_COLOR,
            font=GuiConst.FG_FONT
        )
        self.price_entry.grid(column=1, row=4, sticky="w", pady=5)

        self.city_from_entry = Entry(
            master,
            width=12,
            fg=GuiConst.FG_COLOR,
            font=GuiConst.FG_FONT
        )
        self.city_from_entry.grid(column=1, row=6, sticky="w", pady=5)

        self.city_to_entry = Entry(
            master,
            width=12,
            fg=GuiConst.FG_COLOR,
            font=GuiConst.FG_FONT
        )
        self.city_to_entry.grid(column=1, row=3, sticky="w", pady=5)

        # ------------------------------- Buttons ------------------------------- #
        self.information_button = Button(
            master,
            text="Info",
            width=5,
            bg=GuiConst.BUTTON_COLOR,
            fg=GuiConst.BUTTON_LETTERS_COLOR,
            font=GuiConst.BUTTON_FONT,
            command=self.display_information_message
        )
        self.information_button.grid(column=2, row=0, sticky="e")

        self.add_update_button = Button(
            master,
            text="Add / Update",
            width=14,
            bg=GuiConst.BUTTON_COLOR,
            fg=GuiConst.BUTTON_LETTERS_COLOR,
            font=GuiConst.BUTTON_FONT,
            command=self.check_and_update_sheety_data_input
        )
        self.add_update_button.grid(column=1, row=5, sticky="w", pady=(5, 25))

        self.delete_button = Button(
            master,
            text="Delete data",
            width=14,
            bg=GuiConst.DELETE_BUTTON_COLOR,
            fg=GuiConst.BUTTON_LETTERS_COLOR,
            font=GuiConst.BUTTON_FONT,
            command=self.delete_sheety_data
        )
        self.delete_button.grid(column=0, row=5, sticky="w", pady=(5, 25))

        self.display_flight_alarm_message_button = Button(
            master,
            text="Check flights",
            width=14,
            bg=GuiConst.BUTTON_COLOR,
            fg=GuiConst.BUTTON_LETTERS_COLOR,
            font=GuiConst.BUTTON_FONT,
            command=self.display_flights_alarm_message
        )
        self.display_flight_alarm_message_button.grid(column=1, row=7, sticky="w")

        self.hyperlinks_button = Button(
            master,
            text="Hyperlinks",
            width=14,
            bg=GuiConst.BUTTON_COLOR,
            fg=GuiConst.BUTTON_LETTERS_COLOR,
            font=GuiConst.BUTTON_FONT,
            command=self.display_hyperlinks
        )
        self.hyperlinks_button.grid(column=2, row=7, sticky="e", pady=5)

        # ------------------------------- Text boxes ------------------------------- #
        self.cities_text_box = Text(
            master,
            height=14,
            width=40,
            fg=GuiConst.FG_COLOR,
            font=GuiConst.FG_FONT
        )
        self.cities_text_box.grid(column=2, row=1, sticky="w", padx=(15, 0), pady=5)

        self.alarm_text_box = Text(
            master,
            height=10,
            width=40,
            wrap="word",
            fg=GuiConst.FG_COLOR,
            font=GuiConst.FG_FONT
        )
        self.alarm_text_box.insert(END, "Flight Alarm message...")
        self.alarm_text_box.config(state="disabled")
        self.alarm_text_box.grid(column=2, row=2, rowspan=5, sticky="w", padx=(15, 0), pady=5)

        self.display_sheety_data()

    def display_sheety_data(self):
        """Requests data from data manager and displays city and set maximum ticket's price in columns"""
        self.data_manager.request_data_from_sheety()
        self.cities_text_box.config(state="normal")
        self.cities_text_box.delete("1.0", END)
        cities_to_display = f"City | Maximum ticket's price (Euro) \n\n"
        for row in self.data_manager.sheety_data["prices"]:
            cities_to_display += f"{row['city']} | {row['ticketsMaximumPrice']} Euro\n"
        self.cities_text_box.insert(END, cities_to_display)
        self.cities_text_box.config(state="disabled")

    def check_and_update_sheety_data_input(self):
        """Updates the data in google docs via sheety.io api if no error occurred. In addition sends request to data
        manager to check if the city found by tequila api is same as put by the user. If it is not, the method
        displays a message to confirm the name of the city"""
        error_message = self.is_error_update_sheety_data()
        city_name = self.city_to_entry.get()
        if error_message:
            messagebox.showinfo(
                title="Input Info",
                message=error_message
            )
        elif not self.data_manager.does_city_exist(city_name):
            messagebox.showerror(
                title="City Error",
                message=self.data_manager.error_message
            )
        elif not self.data_manager.is_found_city_the_same(self.city_to_entry.get()) and not\
                self.data_manager.error_message:
            city_name = self.data_manager.city_to_name
            answer = messagebox.askquestion(
                title="Correct City",
                message=f"You typed {self.city_to_entry.get()}, however {city_name} was found in flight search. "
                        f"Is {city_name} the city you would like to fly to?"
            )
            if answer == "yes":
                self.update_sheety_data(city_name)
        else:
            self.update_sheety_data(city_name)

    def update_sheety_data(self, city):
        """Sends request to data manager to update the maximum price of the ticket for corresponding city"""
        update_data = {"city": city, "ticketsMaximumPrice": int(self.price_entry.get())}
        self.data_manager.edit_data(update_data)
        self.display_sheety_data()
        self.city_to_entry.delete(0, END)
        self.price_entry.delete(0, END)

    def delete_sheety_data(self):
        """Sends request to data manager to delete city from google doc via sheety.io api"""
        if self.is_error_delete_sheety_data():
            messagebox.showinfo(
                title="Input Info",
                message=self.is_error_delete_sheety_data()
            )
        else:
            city_to_delete = self.city_to_entry.get()
            self.data_manager.delete_city_row(city_to_delete)
            if self.data_manager.error_message:
                messagebox.showerror(
                    title="City Error",
                    message=self.data_manager.error_message
                )
            else:
                self.display_sheety_data()
                self.city_to_entry.delete(0, END)
                self.price_entry.delete(0, END)

    def display_flights_alarm_message(self):
        """Requests flight information (flight alarm message) from flight manager and
        displays the Flight Alarm message with all the cheapest flights found (or not)"""
        self.alarm_text_box.config(state="normal")
        self.alarm_text_box.delete("1.0", END)
        self.flight_manager.hyperlinks = []
        is_error, city_name = self.is_error_flights_alarm()
        if not is_error:
            flight_alarm = self.flight_manager.generate_flights_alarm_message(city_name)
            self.alarm_text_box.insert("1.0", flight_alarm)
        self.alarm_text_box.config(state="disabled")

    def is_error_delete_sheety_data(self):
        """Checks if the user properly filled the city to be deleted (if it is in the table and if it is of correct
        type"""
        error_message = ""
        if not self.city_to_entry.get():
            error_message = "Please fill in city name that you would like to delete. \n" \
                            "Note that the name has to be the same as in the table."
        elif not self.city_to_entry.get().replace(" ", "").isalpha():
            error_message = "Please note that city name should use only alphabetical characters."
        return error_message

    def is_error_update_sheety_data(self):
        """Checks if the user properly filled arrival city and maximum ticket's price (if both entries are filled
        and if both entries are of correct type"""
        error_message = ""
        if not self.city_to_entry.get() or not self.price_entry.get():
            error_message = "Please fill in both city name and ticket price to update or add data."

        elif not self.price_entry.get().replace(" ", "").isnumeric() or not \
                self.city_to_entry.get().replace(" ", "").isalpha():
            error_message = "Please note that city name should use only alphabetical characters," \
                            " while ticket price should be numeric."

        return error_message

    def is_error_flights_alarm(self):
        """Checks if the user properly filled departure city entry (if the entry is not empty, if the city exists,
        if the city typed is the same as found by tequila api)"""
        city_name = self.city_from_entry.get()
        if not city_name:
            messagebox.showinfo(
                title="Input Info",
                message="Please fill in city of departure."
            )
            return True, city_name
        elif not self.data_manager.does_city_exist(city_name):
            messagebox.showerror(
                title="City Error",
                message=self.data_manager.error_message
            )
            return True, city_name
        elif not self.data_manager.is_found_city_the_same(city_name) and not\
                self.data_manager.error_message:
            city_name = self.data_manager.city_to_name
            answer = messagebox.askquestion(
                title="Correct City",
                message=f"You typed {self.city_from_entry.get()}, however {city_name} was found in flight search. "
                        f"Is {city_name} the city you would like to fly from?"
            )
            if answer == "yes":
                return False, city_name
            else:
                return True, city_name
        else:
            return False, city_name

    def display_information_message(self):
        """Displays information about Flight Alarm in separate window"""
        self.alarm_text_box.config(state="normal")
        with open("READ_ME.txt") as file:
            message = file.read()
        messagebox.showinfo(title="Input Info",
                            message=message)
        self.alarm_text_box.config(state="disabled")

    def display_hyperlinks(self):
        """Displays hyperlinks in separate window"""
        hyperlinks_window = Toplevel(self.master)
        hyperlinks_window.title("Hyperlinks")
        hyperlinks_window.geometry("200x400")
        hyperlinks_window.config(
            padx=10,
            pady=10,
            bg=GuiConst.BG_COLOR
        )
        hyperlinks_window.resizable(width=False, height=False)

        background = Canvas(
            hyperlinks_window,
            width=165,
            height=370,
            bg="#ffffff",
        )
        background.pack(expand=True, fill=BOTH)

        if self.flight_manager.hyperlinks:
            for hyperlink in self.flight_manager.hyperlinks:
                flight_info_label = Label(
                    background,
                    text=hyperlink[0],
                    bg="#ffffff",
                    fg="#0000ff",
                    cursor="hand2"
                )
                flight_info_label.bind("<Button-1>", lambda e: self.open_browser(hyperlink[1]))
                flight_info_label.pack(pady=(10, 0), padx=10, fill=X)
        else:
            no_links_label = Label(
                background,
                text="No hyperlinks available.\n Check flights first.",
                bg="#ffffff",
                fg="#0000ff",
            )
            no_links_label.pack(pady=10, padx=10, fill=X)

    @staticmethod
    def open_browser(url):
        webbrowser.open_new(url)


 # -*- coding: utf-8 -*-
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse,HttpResponseRedirect, Http404, JsonResponse
from books.models import Book,Author
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.core.mail import EmailMessage

from .models import Cart,CartItem
from django.views.generic.base import View
from django.views.generic.detail import SingleObjectMixin, DetailView

import os

def cart_item_count(request):
    if request.method=="GET":
        print("Item count request is GET")
        if request.is_ajax():
            print("Item count request is AJAX")
            cart_id =request.session.get("cart_id")
            if cart_id == None:
                count = 0
            else:
                cart = Cart.objects.get(id=cart_id)
                count = cart.items.count()
            request.session["cart_item_count"] = count
            return JsonResponse({"count": count})
        else:
            raise Http404
    else:
        raise Http404

# Create your views here.
#NOT USING IT//Using cart_item_count instead

class ItemCountView(View):
	def get(self, request, *args, **kwargs):
		if request.is_ajax():
			cart_id = self.request.session.get("cart_id")
			if cart_id == None:
				count = 0
			else:
				cart = Cart.objects.get(id=cart_id)
				count = cart.items.count()
			request.session["cart_item_count"] = count
			return JsonResponse({"count": count})
		else:
			raise Http404

class CartView(SingleObjectMixin, View):
    model = Cart
    template_name = "carts/cart.html"

    def get_object(self, *args, **kwargs):
        self.request.session.set_expiry(0) #5 minutes
        cart_id = self.request.session.get("cart_id")
        if cart_id == None:
            cart = Cart()
            cart.tax_percentage = 0.075
            cart.save()
            cart_id = cart.id
            self.request.session["cart_id"] = cart_id
        cart = Cart.objects.get(id=cart_id)
        if self.request.user.is_authenticated():
            cart.user = self.request.user
            cart.save()
        return cart

    def get(self, request, *args, **kwargs):
        cart = self.get_object()
        item_id = request.GET.get("item")
        delete_item = request.GET.get("delete", False)
        flash_message = ""
        item_added = False

        if item_id:
            item_instance = get_object_or_404(Book, id=item_id)
            qty = request.GET.get("qty", 1)
            try:
                if int(qty) < 1:
                    delete_item = True
            except:
                raise Http404
            cart_item, created = CartItem.objects.get_or_create(cart=cart, item=item_instance)

            if created:
                flash_message = "আপনার নির্বাচিত বইটি কার্টে যুক্ত করা হয়েছ।"
                item_added = True
            if delete_item:
                flash_message = "বইটি কার্ট থেকে বাদ দেয়া হয়েছে।"
                cart_item.delete()
            else:
                if not created:
                    flash_message = "আপনার নির্বাচিত বইটি আগেই কার্টে যুক্ত করা হয়েছ।"
                cart_item.quantity = qty
                cart_item.save()
            if not request.is_ajax():
                # return HttpResponseRedirect(reverse("carts:cart"))
				#return cart_item.cart.get_absolute_url()
                context = {
                    "object": self.get_object(),
                    "flash_message":flash_message,
                }
                template = self.template_name
                return render(request, template, context)

        if request.is_ajax():
            try:
                total = cart_item.line_item_total
            except:
                total = None
            try:
                subtotal = cart_item.cart.subtotal
            except:
                subtotal = None

            try:
                cart_total = cart_item.cart.total
            except:
                cart_total = None

            try:
                tax_total = cart_item.cart.tax_total
            except:
                tax_total = None

            try:
                total_items = cart_item.cart.items.count()
            except:
                total_items = 0

            data = {
                    "deleted": delete_item,
                    "item_added": item_added,
                    "line_total": total,
                    "subtotal": subtotal,
                    "cart_total": cart_total,
                    "tax_total": tax_total,
                    "flash_message": flash_message,
                    "total_items": total_items
                    }

            return JsonResponse(data)

        context = {
            "object": self.get_object(),
            "nbar":"cart"
        }
        template = self.template_name
        return render(request, template, context)

@login_required
def checkout(request):

    cart_id =request.session.get("cart_id")
    cart = Cart.objects.get(id=cart_id)

    context={}

    if request.method=="POST":
        if "Select" in request.POST:
            payment_method=request.POST.get("payment_method","")

            if payment_method=="Bkash":
                context["bkash"]=True
                context["price"]=cart.total
                return render(request,"carts/checkout.html", context)
        if "bkash_payment" in request.POST:
            txid=request.POST.get("txid","")
            if txid!="":
                items=cart.cartitem_set.all()

                email_to=[]
                email=request.user.email
                email_to.append(email)
                msg="Dear "+request.user.username+" . Here are your books you purchased from our site. Gretings from Boipotro.com"
                email = EmailMessage("Books from Boipotro.Com",msg, "order@boipotro.com",email_to)
                email.content_subtype = "html"

                for book in items:
                     email.attach(book.item.book_file.name,book.item.book_file.read(),"application/epub")

                res = email.send()
                print(res)
                if(res==1):
                    request.session["cart_id"] =None
                    context["msg"]="Your purchased books has been sent to your email address. Enjoy!"
                else:
                    context["msg"]="We had some problem processing your purchase. Please try again."
                return render(request,"carts/checkout.html", context)
    context={

        "payment_method":True,
    }
    return render(request,"carts/checkout.html", context)

# @login_required
# def checkout(request):
#    emailto=[]
#    email=request.user.email
#    book=Book.objects.all()[1]
#    emailto.append(email)
#    print(emailto)
#    html_content = "Comment tu vas?"
#    email = EmailMessage("my subject", html_content, "paul@polo.com", emailto)
#    email.content_subtype = "html"
#
#
#    # file=os.path.join()
#
#    email.attach(book.title+".epub",book.book_file.read(),"application/epub")
#
#    res = email.send()
#    return HttpResponse('%s'%res)
#
#


import argparse
import sys

from quality_of_service_demo_py.common_nodes import Listener
from quality_of_service_demo_py.common_nodes import Talker

import rclpy
from rclpy.duration import Duration
from rclpy.event_handler import PublisherEventCallbacks
from rclpy.event_handler import SubscriptionEventCallbacks
from rclpy.executors import ExternalShutdownException
from rclpy.executors import SingleThreadedExecutor
from rclpy.logging import get_logger
from rclpy.qos import QoSProfile

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'deadline', type=int,
        help='Duration in positive integer milliseconds of the Deadline QoS setting.')
    parser.add_argument(
        '--publish-for', type=int, default=5000,
        help='Duration in positive integer milliseconds to publish until pausing the talker.')
    parser.add_argument(
        '--pause-for', type=int, default=1000,
        help='Duration in positive integer milliseconds to pause the talker before beginning '
             'to publish again.')
    return parser.parse_args()

def main(args=None):
    parsed_args = parse_args()
    rclpy.init(args=args)

    topic = 'qos_deadline_chatter'
    deadline = Duration(seconds=parsed_args.deadline / 1000.0)

    qos_profile = QoSProfile(
        depth=10,
        deadline=deadline)

    def sub_deadline_event(event):
        count = event.total_count
        delta = event.total_count_change
        get_logger('listener').info(f'Requested deadline missed - total {count} delta {delta}')

    subscription_callbacks = SubscriptionEventCallbacks(deadline=sub_deadline_event)
    listener = Listener(topic, qos_profile, event_callbacks=subscription_callbacks)

    def pub_deadline_event(event):
        count = event.total_count
        delta = event.total_count_change
        get_logger('talker').info(f'Offered deadline missed - total {count} delta {delta}')

    publisher_callbacks = PublisherEventCallbacks(deadline=pub_deadline_event)
    talker = Talker(topic, qos_profile, event_callbacks=publisher_callbacks)

    publish_for_seconds = parsed_args.publish_for / 1000.0
    pause_for_seconds = parsed_args.pause_for / 1000.0
    pause_timer = talker.create_timer(  # noqa: F841
        publish_for_seconds,
        lambda: talker.pause_for(pause_for_seconds))

    executor = SingleThreadedExecutor()
    executor.add_node(listener)
    executor.add_node(talker)
    try:
        executor.spin()
    except (KeyboardInterrupt, ExternalShutdownException):
        pass
    finally:
        rclpy.try_shutdown()

    return 0

if __name__ == '__main__':
    sys.exit(main())


#-*- coding:utf-8 -*-

# Author:james Zhang
"""
    utilities file for Pytorch models
"""

from functools import wraps
import traceback
from _thread import start_new_thread
import torch.multiprocessing as mp
import torch
import datetime
import numpy as np
from dgl.dataloading.pytorch import NodeDataLoader

# class MultiGraphNodeDataLoader(NodeDataLoader):
#     def

class EarlyStopping(object):
    def __init__(self, patience, filename):
        dt = datetime.datetime.now()
        self.filename = filename
        self.patience = patience
        self.counter = 0
        self.best_acc = None
        self.best_loss = None
        self.early_stop = False

    def step(self, acc, model):
        if self.best_acc is None:
            self.best_acc = acc
            self.save_checkpoint(model)
        elif acc < self.best_acc:
            self.counter += 1
            print(f'EarlyStopping counter: {self.counter} out of {self.patience}')
            if self.counter >= self.patience:
                self.early_stop = True
        else:
            if acc >= self.best_acc:
                self.save_checkpoint(model)
            self.best_acc = np.max((acc, self.best_acc))
            self.counter = 0
        return self.early_stop

    def save_checkpoint(self, model):
        """Saves model when validation loss decreases."""
        torch.save(model.state_dict(), self.filename)

    def load_checkpoint(self, model):
        """Load the latest checkpoint."""
        model.load_state_dict(torch.load(self.filename))

class early_stopper(object):

    def __init__(self, patience=10, verbose=False, delta=0):

        self.patience = patience
        self.verbose = verbose
        self.delta = delta

        self.best_value = None
        self.is_earlystop = False
        self.count = 0
        self.val_preds = []
        self.val_logits = []

    def earlystop(self, loss, preds, logits):

        value = -loss

        if self.best_value is None:
            self.best_value = value
            self.val_preds = preds
            self.val_logits = logits
        elif value < self.best_value + self.delta:
            self.count += 1
            if self.verbose:
                print('EarlyStoper count: {:02d}'.format(self.count))
            if self.count >= self.patience:
                self.is_earlystop = True
        else:
            self.best_value = value
            self.val_preds = preds
            self.val_logits = logits
            self.count = 0

# According to https://github.com/pytorch/pytorch/issues/17199, this decorator
# is necessary to make fork() and openmp work together.
def thread_wrapped_func(func):
    """
    用于Pytorch的OpenMP的包装方法。Wraps a process entry point to make it work with OpenMP.
    """
    @wraps(func)
    def decorated_function(*args, **kwargs):
        queue = mp.Queue()
        def _queue_result():
            exception, trace, res = None, None, None
            try:
                res = func(*args, **kwargs)
            except Exception as e:
                exception = e
                trace = traceback.format_exc()
            queue.put((res, exception, trace))

        start_new_thread(_queue_result, ())
        result, exception, trace = queue.get()
        if exception is None:
            return result
        else:
            assert isinstance(exception, Exception)
            raise exception.__class__(trace)
    return decorated_function