from functools import reduce as reduceIns

import te.lang.cce
from te import tvm
from te.platform.fusion_manager import fusion_manager
from topi import generic
from topi.cce import util

SHAPE_SIZE_LIMIT = 2147483648

# pylint: disable=unidiomatic-typecheck,too-many-branches,too-many-locals
# pylint: disable=no-member,dangerous-default-value,invalid-name
@fusion_manager.register("eltwise")
def eltwise_compute(x, y, mode=1, coeff=[], kernel_name="eltwise"):
    '''
    Compute elementwise operation
    '''
    tensor_num = len(x)
    inp_dtype = x[0].dtype
    data0_tmp = x[0]

    if mode == 1:
        if len(coeff) != 0 and len(coeff) != tensor_num:
            raise RuntimeError("lenth of coeff must equal to tensor_num or 0.")
        if len(coeff) == tensor_num:
            if type(coeff[0]) != int and type(coeff[0]) != float:
                raise RuntimeError("ele of coeff must be a number.")
            if coeff[0] != 1:
                coeff1 = tvm.const(coeff[0], dtype=inp_dtype)
                data0_tmp = te.lang.cce.vmuls(data0_tmp, coeff1)

    if tensor_num == 1:
        const_val_0 = tvm.const(0, dtype=inp_dtype)
        data0_tmp = te.lang.cce.vadds(data0_tmp, const_val_0)
        res = data0_tmp
    elif tensor_num > 1:
        for i in range(1, tensor_num):
            datan_tmp = x[i]
            if mode == 0:
                data0_tmp = te.lang.cce.vmul(data0_tmp, datan_tmp)
            elif mode == 2:
                data0_tmp = te.lang.cce.vmax(data0_tmp, datan_tmp)
            else:
                if len(coeff) == 0:
                    data0_tmp = te.lang.cce.vadd(data0_tmp, datan_tmp)
                elif coeff[i] == 1:
                    data0_tmp = te.lang.cce.vadd(data0_tmp, datan_tmp)
                else:
                    coeff2 = tvm.const(coeff[i], dtype=inp_dtype)
                    datan_tmp = te.lang.cce.vmuls(datan_tmp, coeff2)
                    data0_tmp = te.lang.cce.vadd(data0_tmp, datan_tmp)
        res = data0_tmp
    return res

def _eltwise_check_para(x, y, mode=1, coeff=[],
                        kernel_name="eltwise"):

    util.check_kernel_name(kernel_name)

    shape = x[0].get("shape")
    dtype = x[0].get("dtype").lower()

    util.check_shape_rule(shape)
    util.check_shape_size(shape, SHAPE_SIZE_LIMIT)

    dtype_check_list = ["float16", "float32"]
    if not dtype in dtype_check_list:
        raise RuntimeError("dtype is not support,"
                           "only support fp16 and fp32.")

    tensor_num = len(x)
    if tensor_num < 1 or tensor_num > 32:
        raise RuntimeError("tensor_num need in range [1,32].")

    # all input data should be same shape and dtype
    if tensor_num > 1:
        for i in range(1, tensor_num):

            shape_tmp = x[i].get("shape")
            dtype_tmp = x[i].get("dtype").lower()

            if shape_tmp != shape:
                raise RuntimeError("input shape is not same.")

            if dtype_tmp != dtype:
                raise RuntimeError("input dtype is not same.")

    shape_output = y.get("shape")
    util.check_shape_rule(shape_output)
    util.check_shape_size(shape_output, SHAPE_SIZE_LIMIT)
    if shape_output != shape:
        raise RuntimeError("output shape is not same with input.")

    dtype_output = y.get("dtype").lower()
    if dtype_output != dtype:
        raise RuntimeError("output dtype is not same with input.")

    #mode type must be 0, 1 or 2
    op_list = (0, 1, 2)
    if mode not in op_list:
        raise RuntimeError("mode is wrong, only suppor 0, 1, 2.")

@util.check_input_type((list, tuple), dict, int, (list, tuple), str)
def eltwise(x, y, mode=1, coeff=[], kernel_name="eltwise"):
    """
    Compute elementwise modes, such as 0:PRODUCT, 1:SUM and 2:MAX

    Parameters
    ----------
    x : the list of input data, it's element is dict:{"shape":[], "dtype":""}

    y : the dict of output

    mode : 0:product,1:sum,2:max;default is 1:sum.

    coeff : input_num should be equal with coeff size.

    kernel_name : cce kernel name, default value is "eltwise"

    Returns
    -------
    None

    """

    _eltwise_check_para(x, y, mode=mode,
                        coeff=coeff, kernel_name=kernel_name)
    shape = x[0].get("shape")
    dtype = x[0].get("dtype").lower()
    tensor_num = len(x)

    shape = util.shape_refine(shape)
    fuseshape = [1]
    fuseshape[0] = reduceIns(lambda x, y: x*y, shape)

    tlist = []
    with tvm.target.cce():
        for i in range(0, tensor_num):
            datan_name = 'data%d' % i
            datan_tmp = tvm.placeholder(fuseshape, name=datan_name, dtype=dtype)
            tlist.append(datan_tmp)

        y_datan_name = 'y_data'
        data_y_tmp = tvm.placeholder(fuseshape, name=y_datan_name, dtype=dtype)

        res = eltwise_compute(tlist, data_y_tmp,
                              mode, coeff, kernel_name)
        sch = generic.auto_schedule(res)
    tlist.append(res)

    config = {"print_ir": False,
              "need_build": False,
              "name": kernel_name,
              "tensor_list": tlist}
    te.lang.cce.cce_build_code(sch, config)


from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QLineEdit, QPushButton
from PyQt5.QtWidgets import QTextEdit

from PyQt5.QtGui import QIcon

import sys

class MainWindow( QMainWindow ):
    _counter = 0
    _raise = True
    _clicksCount = 0;
    def __init__(self):
        super().__init__()

        self.setFixedSize(400,400) # Fix o'lcham
        # self.setMinimumSize(400,400)
        # self.setMaximumSize(700, 700)
        # self.setFixedHeight(600)
        # self.setFixedWidth(500)
        # self.setWindowTitle("Salom")
        # self.setBaseSize(800, 800)
        # self.setStyleSheet('background-color: black;')
        # self.setWindowIcon(QIcon("IMG_1258.jpg"))

# "================================================================="

        # self.text1 = QLabel("Salom", self)
        # # self.text1.setGeometry(30, 70, 200, 70)
        # self.text1.setStyleSheet("font-size: 40px;");
        # self.text1.adjustSize()

        # self.text2 = QLabel("Hello", self)
        # self.text2.move(30, 70)
        # self.text2.setStyleSheet("font-size: 40px;")
        # self.text2.adjustSize()

# "================================================================="
        # self.lineEdit1 = QLineEdit(self)
        # self.setStyleSheet("""
        #                    font-size: 30px;
        #                    font-family: Times new Roman
        #                    """)

# "================================================================="

        # self.bigText = QTextEdit(self)
        # self.bigText.setFixedSize(200, 200)

# "================================================================="

        self.btn1 = QPushButton(self)
        self.btn1.setText("Button")
        self.btn1.clicked.connect(self.buttonClicked)

        self.labelNumber = QLabel("0",self)
        self.labelNumber.move(40, 40)
        self.labelNumber.setStyleSheet("font-size: 30px")

        self.labelCount = QLabel("0",self)
        self.labelCount.move(70, 40)
        self.labelCount.setStyleSheet("font-size: 30px; color: red;")

    def buttonClicked(self):

        self._clicksCount += 1
        self.labelCount.setText(f"{self._clicksCount}")

        if( self._raise ):
            self._counter += 1
        else:
            self._counter -= 1

        if( self._counter == 10 ):
            self._raise = False
        elif( self._counter == 0 ):
            self._raise = True

        self.labelNumber.setText(f"{self._counter}")

app = QApplication([])
print(sys.argv)
window = MainWindow()
window.show()
app.exec()


import re
from string import Template
import io
import numpy as np
from .utils import journal_macros, get_month_num, tex2unicode

class Author:
    # author structure which parses an author's
    # first and last name from the bibtex entry
    def __init__(self, bib_entry):
        bib_entry = re.sub(r'[^\\]~', ' ', bib_entry)

        # figure out if it is lastname, firstname
        # or firstname lastname

        if "," in bib_entry:
            nnames = bib_entry.split(', ')
            self.firstname = nnames[1]
            self.lastname = nnames[0]
        else:
            nnames = re.findall('[{]?([\S]+)[}]?', bib_entry)
            if len(nnames) > 1:
                self.lastname = " ".join(nnames[1:])
                self.firstname = nnames[0]
            else:
                self.lastname = nnames[0]
                self.firstname = ""

        if ("{" in self.lastname) or ("}" in self.lastname):
            self.lastname = self.lastname.replace("{", "")
            self.lastname = self.lastname.replace("}", "")

        if ("{" in self.firstname) or ("}" in self.firstname):
            self.firstname = self.firstname.replace("{", "")
            self.firstname = self.firstname.replace("}", "")

    def short_name(self):
        # format as [last name], [first name letters].
        # e.g. Sankar, R. or Sankar, R. G.
        first = self.firstname.split(' ')
        short_first = ""
        if first[0] != '':
            for name in first:
                # account for first letter unicodes
                if name[0] == "{":
                    fname = re.findall(r'(\{.+\})', name)[0]
                else:
                    fname = name[0]
                short_first = short_first + fname + ". "
        return "%s, %s" % (self.lastname, short_first[:-1])

    def long_name(self):
        # format as [last name], [first names].
        # e.g. Sankar, Ramanakumar  or Sankar, Ramanakumar Ganapathy
        first = self.firstname.split(' ')
        long_first = ""
        for name in first:
            long_first = long_first + name + " "
        return "%s %s" % (long_first[:-1], self.lastname)

class Records(object):
    def __init__(self, rec_type, entry_name):
        self.authors = []
        self.rec_type = rec_type
        self.entry_name = entry_name

    def parse_text(self, text):
        self.text = text

        # concatenate the entries together into a single
        # string so that we can parse the entries
        text = re.sub(r"[\s]{2,50}?|[\n?]", r"", text)

        # the entry pattern is [key] = [entry],
        # text_pattern = r"(\w+)\s*=\s*\"?\{*\"?(.*?)\"?\}*\"?,?(,|$)"
        text_pattern = r"(((\w+)\s*=\s*([^=]+))(,|$))"

        matches = re.findall(text_pattern, text)

        for i, (_, _, key, entry, _) in enumerate(matches):
            key = key.lower().strip()
            line = entry.strip()
            line = line.replace('"', '')

            # special case author list
            # break down individual authors
            if (key == 'author') or (key == 'authors'):
                authors = entry.split(' and')
                for author in authors:
                    authi = Author(author.strip())
                    self.authors.append(authi)
            else:
                entry = entry.replace("{", "")
                entry = entry.replace("}", "")

            # if the journaly contains a macro,
            # parse it using the dictionary
            if key == "journal":
                self.journal = entry

                if self.journal[0] == '\\':
                    try:
                        self.journal = journal_macros[self.journal]
                    except KeyError:
                        print(
                            f"Found macro {self.journal} for journal name but"
                            "no matching journal name..."
                        )
                        self.journal = entry

            # year and volume are numbers
            elif key == "year":
                try:
                    self.year = int(entry)
                except ValueError:
                    self.year = entry

            elif key == "month":
                try:
                    self.month = int(entry)
                except ValueError:
                    self.month = entry

            elif key == "volume":
                try:
                    self.volume = int(entry)
                except ValueError:
                    self.volume = entry

            # parse the DOI into a URL
            elif key == "doi":
                self.doi = entry
                self.doiurl = "https://doi.org/%s" % self.doi

            # default case, save the entry as self.[key] = [entry]
            else:
                setattr(self, key, entry)

    def __getattribute__(self, __name):
        try:
            value = object.__getattribute__(self, __name)
        except AttributeError:
            raise AttributeError(f"{self.entry_name} has no keyword {__name}")

        if __name == 'year':
            try:
                return int(value)
            except Exception:
                raise ValueError(
                    f"Year entry '{value}' cannot be converted to integer for"
                    f"{self.entry_name}")
        else:
            return value

class bibtexParser:
    '''
        Parses bibtex entries from a file and creates
        a Record object of each entry

        Attributes
        ----------
        records : list
            array of ``records`` objects

        Methods
        -------
        get_records()
            Gets the records from input filename (run automatically)
        to_html()
            Parse the entries as HTML output with each entry as an
            <li> element
        to_latex_item()
            Parse the entries to a .text file with each entry as an
            \\item
        to_text()
            Parse all entries as a plain text (.txt) file with
            each entry separated by a newline

    '''

    def __init__(self, fname, fileIO=None):
        '''
            Initialize

            Pareters
            ------
            fname : str
                Input filename (.bib)

        '''
        self.fname = fname

        if (fileIO is not None) and isinstance(fileIO, io.StringIO):
            self.lines = fileIO.readlines()
            fileIO.close()
            self.filetype = 'buffer'
        else:
            file = open(self.fname, "r", encoding='utf-8')
            self.lines = file.readlines()
            file.close()
            self.filetype = 'file'

        self.get_records()

    def get_records(self):
        self.records = []

        # start pattern is @[type]{[name],
        pattern = r"@(\w+)\s*\{(.*?),\n?([\s\S\n\t]*?[^\w\.\)\!])\}\n"

        lines = "".join(self.lines) + "\n"

        records = re.findall(pattern, lines)

        for record in records:
            entry_type, entry_name, ref_text = record
            reci = Records(entry_type, entry_name)
            reci.parse_text(ref_text)

            self.records.append(reci)

        print("Found %d records from %s" % (len(self.records), self.fname))

    def to_out(self, outname, templatefile,
               convunicode=True, clean=False, sort=False):
        # output to [outname] using the template given

        # open the output file
        if isinstance(outname, io.StringIO):
            outfile = outname
            outfile.seek(0)
        else:
            outfile = open(outname, "w", encoding='utf-8')

        # no unicode output for .tex files
        if convunicode:
            encodeunicode = True
        else:
            encodeunicode = False

        # check if we want to clean or sort
        if clean:
            recs = self.cleanup(sort=sort)
            self.records = [reci[0] for reci in recs]

        # get the template string -- we will replace this for
        # each entry
        if isinstance(templatefile, io.StringIO):
            templatelines = templatefile.readlines()
        else:
            templatelines = open(templatefile, 'r').readlines()

        templates = []
        for linei in templatelines:
            if linei[0] == '@':
                temptype = re.findall(r'@([A-Za-z]*?):', linei)[0]
                templates.append(
                    [temptype.lower(), linei.replace('@%s:' % temptype, '')])
            else:
                templates.append(['all', linei])
        nalls = 0
        for template in templates:
            if template[0] == 'all':
                generictempstring = template[1]
                nalls += 1

        if nalls > 1:
            print("Error! Can only have one general template")
            return

        # loop through all the records
        for record in self.records:
            rectype = record.rec_type

            templatestring = generictempstring
            for template in templates:
                if rectype.lower() == template[0]:
                    templatestring = template[1]

            # first, find the author template because this is going to
            # be common to all
            authtemplate = re.findall(r'auth([sf])([0-9]+|[a]{1})?', templatestring)
            try:
                if len(authtemplate) > 1:
                    raise ValueError(
                        "Error! Only one entry for author is allowed!")
                authstyle = authtemplate[0][0]
            except IndexError:
                raise IndexError("Please enter an author template")

            if authstyle == 's':
                try:
                    if authtemplate[0][1] != 'a':
                        authnum = int(authtemplate[0][1])
                    else:
                        authnum = int(1e10)
                except Exception:
                    raise ValueError(
                        "Please use $authsa for all authors or enter a number "
                        "after $auths")
            else:
                authnum = 1

            # then find the groups
            groups = re.findall(
                r"(?<!\\)([\{]{1}.*?(?<!\\)[\}]{1})", templatestring)

            # then find all the templates
            kws = re.findall(r'(\$[a-z0-9]+)', templatestring)
            # copy the template string to replace later
            tempstring = templatestring

            # this will hold all the attribute values
            tempdict = {}
            for tempi in kws:

                # get the variable name
                tempstr = tempi.replace('$', '')

                # special case -- authors
                if "auth" in tempi:
                    authtext = ''
                    if authstyle == 's':  # short author (lastname initials)
                        if len(record.authors) > authnum:
                            author = record.authors[0]
                            if encodeunicode:
                                short_name = tex2unicode(author.short_name())
                            else:
                                short_name = author.short_name()

                            authtext = authtext + short_name + " et al."
                        else:
                            nauths = min([len(record.authors), authnum])
                            for authi in range(nauths):
                                author0 = record.authors[authi]
                                if encodeunicode:
                                    short_name = tex2unicode(
                                        author0.short_name())
                                else:
                                    short_name = author0.short_name()

                                authtext = authtext + short_name
                                if authi == (nauths - 2):
                                    authtext = authtext + " and "
                                elif authi == (nauths - 1):
                                    authtext = authtext + " "
                                else:
                                    authtext = authtext + ", "
                    elif authstyle == 'f':
                        for i, author in enumerate(record.authors):
                            if encodeunicode:
                                long_name = tex2unicode(author.long_name())
                            else:
                                long_name = author.long_name()

                            if i != (len(record.authors) - 1):
                                authtext = authtext + long_name + ", "
                            else:
                                authtext = authtext + long_name
                    # save the author string to the output dictionary
                    tempdict[tempstr] = authtext
                else:  # for everything else
                    if hasattr(record, tempstr):
                        if encodeunicode:
                            try:
                                tempdict[tempstr] = tex2unicode(
                                    record.__getattribute__(tempstr))
                            except AttributeError:
                                tempdict[tempstr] = record.__getattribute__(
                                    tempstr)
                        else:
                            tempdict[tempstr] = record.__getattribute__(
                                tempstr)

                    else:
                        # if the record does not have this attribute
                        # find the group that this attribute is in
                        remgroup = None
                        for groupi in groups:
                            if tempstr in groupi:
                                remgroup = groupi

                        if remgroup is None:
                            raise KeyError(
                                f"entry '{tempstr}' is not available "
                                f"in record {record.entry_name}")

                        # remove the group
                        tempstring = tempstring.replace(remgroup, '')
                        tempdict[tempstr] = ''

            # finally, remove all the group {}'s and replace the string
            for groupi in groups:
                repgroup = re.sub(r'{(.*?)}', r'\1', groupi)
                tempstring = tempstring.replace(groupi, repgroup)

            # and also replace all the actual escaped \{ to {
            tempstring = tempstring.replace('\\{', '{')
            tempstring = tempstring.replace('\\}', '}')
            # and then substitute
            newtemplate = Template(tempstring)
            outfile.write(newtemplate.safe_substitute(tempdict))

    def cleanup(self, sort=False, save=False, outfile=None):
        if save:
            if outfile is None:
                if self.filetype == 'file':
                    outname = self.fname.replace(".bib", "_clean.bib")
                else:
                    raise RuntimeError(
                        "Please provide an output writer for non-file inputs")

        # sort the data first
        if sort:
            names = []

            # create a list of author/year/month so that we can sort by this
            # key later
            record_sub = []
            for record in self.records:
                if 'Yoden' in record.entry_name:
                    print(record.entry_name)
                if hasattr(record, "month"):
                    monthnum = get_month_num(record.month)
                else:
                    monthnum = 0
                try:
                    namei = "%s%d%02d_%s" % (
                        record.authors[0].lastname, record.year,
                        monthnum, record.title[:5])
                except IndexError:
                    try:
                        namei = "%d%02d" % (record.year, monthnum)
                    except Exception:
                        continue
                except Exception as e:
                    print(f"failing on {record.entry_name}")
                    print(e)
                    continue
                names.append(namei)
                record_sub.append(record)
            # namesort = sorted(names)
            # records = [record_sub[names.index(name)] for name in namesort]
            records = np.asarray(record_sub)[np.argsort(names)]

        else:
            # if we don't want to sort then just use the same list
            records = self.records

        recs = []
        rec_list = []

        for record in records:
            try:
                # [record.authors[0].short_name(), record.title, record.year]
                reci = f"{record.authors[0].lastname}_{record.title[:5]}"
                f"_{record.year}_{record.entry_name}"
            except IndexError:
                try:
                    reci = f"{record.title[:5]}_{record.year}"
                    f"_{record.entry_name}"
                except Exception as e:
                    print(f"failing on {record.entry_name}")
                    print(e)
                    continue
            # find duplicates
            if reci not in rec_list:
                recs.append([record, record.entry_name])
                rec_list.append(reci)
            # recs.append([record, record.entry_name])
        print(f"Down to {len(recs)} records")

        # check if we want to save this out
        if save:
            # for input from the web UI
            # or if a file handler is passed in
            if outfile is not None:
                for rec in recs:
                    outfile.write("@%s{%s,\n" % (rec[0].rec_type, rec[1]))
                    for text in rec[0].text:
                        outfile.write("%s" % text)
                    outfile.write("\n}\n\n")
            # for a file input
            elif self.filetype == 'file':
                with open(outname, "w", encoding='utf-8') as outfile:
                    for rec in recs:
                        outfile.write("@%s{%s,\n" % (rec[0].rec_type, rec[1]))
                        for text in rec[0].text:
                            outfile.write("%s" % text)
                        outfile.write("\n}\n\n")

        return recs


#first program for submission for google analytics competition.

import os
import json
import numpy as np
import pandas as pd
from pandas.io.json import json_normalize
import matplotlib.pyplot as plt
import seaborn as sns
color = sns.color_palette()

def load_df(csv_path='train.csv', nrows=None):
    JSON_COLUMNS = ['device', 'geoNetwork', 'totals', 'trafficSource']

    df = pd.read_csv(csv_path,
                     converters={column: json.loads for column in JSON_COLUMNS},
                     dtype={'fullVisitorId': 'str'}, # Important!!
                     nrows=nrows)

    for column in JSON_COLUMNS:
        column_as_df = json_normalize(df[column])
        column_as_df.columns = [f"{column}.{subcolumn}" for subcolumn in column_as_df.columns]
        df = df.drop(column, axis=1).merge(column_as_df, right_index=True, left_index=True)
    print(f"Loaded {os.path.basename(csv_path)}. Shape: {df.shape}")
    return df

train_df = load_df(nrows=10000)
test_df = load_df(csv_path="test.csv",nrows=10000)

train_df["totals.transactionRevenue"] = train_df["totals.transactionRevenue"].astype('float')
gdf = train_df.groupby("fullVisitorId")["totals.transactionRevenue"].sum().reset_index()

plt.figure(figsize=(8,6))
plt.scatter(range(gdf.shape[0]), np.sort(np.log1p(gdf["totals.transactionRevenue"].values)))
plt.xlabel('index', fontsize=12)
plt.ylabel('TransactionRevenue', fontsize=12)
plt.show()

Google Analytics Customer Revenue Prediction/GoogleAnalyticsRegression.py


import argparse
import subprocess
from ...core.command import Command

class BranchCreate(Command):
    def __init__(self, parserMgr: argparse._SubParsersAction):
        self._parser = parserMgr.add_parser('create',
                                            help='Create a new branch and switch to it')
        self._parser.set_defaults(func=self.run)
        self._parser.add_argument('branch_name',
                                  type=str,
                                  help='name for the new branch',
                                )

    def run(self, args: argparse.Namespace):
        commandArray = ["git", "checkout", "-b", args.branch_name]
        subprocess.run(commandArray)


from fastapi import Depends, HTTPException
from sqlalchemy import select
from sqlalchemy.orm import Session

from .. import crud, models
from ..database import get_session
from .menu_repository import MenuRepository

class SubmenuRepository(MenuRepository):
    def __init__(self, db: Session = Depends(get_session)) -> None:
        self.db = db
        self.orm_model = models.Submenu
        self.detail_404 = 'submenu not found'
        self.detail_400 = 'Submenu with this title already exists'

    async def get_all(self, skip: int = 0, limit: int = 100, **kwargs) -> list[models.Menu | models.Submenu | models.Dish | None]:
        # menus = self.db.query(self.orm_model).filter_by(**kwargs).offset(
        # skip).limit(limit).all()

        lookup_query = select(self.orm_model).filter_by(**kwargs).offset(skip).limit(limit)
        result = await self.db.execute(lookup_query)
        menus = result.scalars().all()
        # count submenus and dishes
        for db_menu in menus:
            db_menu.dishes_count = await crud.get_sumbenus_dishes_count(
                self.db, db_menu.id)
        return menus

    async def get(self, **kwargs):
        # menu = self.db.query(
        # self.orm_model).filter_by(**kwargs).first()
        lookup_query = select(self.orm_model).filter_by(**kwargs)
        result = await self.db.execute(lookup_query)
        menu = result.scalars().first()
        if not menu:
            raise HTTPException(
                status_code=404, detail=f'{self.detail_404}')
        # count submenus and dishes
        menu.dishes_count = await crud.get_sumbenus_dishes_count(self.db, menu.id)
        return menu


# Run on python 3 for CSEProj 145
import numpy as np
import cv2

top = 461
for i in range(1,top):
# Load an color image in grayscalei
	try:
		name = 'img_' + str(i) + '.png'
		img = cv2.imread(name)
	except:
		continue
	if img is not None:
		#print(np.shape(img))
		a = img[:,0:255,:]
		b = img[:,255:510,:]
		c = np.concatenate((b,a),axis=1)
		cv2.imwrite(name,c)
	else:
		print(i)


s=input()
n={}
for i in range(0,len(s)):
    if s[i] not in n:
        n[s[i]] = 1
    else:
        n[s[i]] = n[s[i]] + 1
result = []
print(n)
for i in n:
    if n[i]!=1:
        result.append(i)
print(*result)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar  5 21:10:41 2018

@author: atul
"""

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv('50_Startups.csv')
X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, 4].values

#encoding the categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelEncoder_X = LabelEncoder()
X[:, 3] = labelEncoder_X.fit_transform(X[:, 3])
onehotEncoder = OneHotEncoder(categorical_features = [3])
X = onehotEncoder.fit_transform(X).toarray()

#Avoid the dummy variable trap, (it is taken care off by the libraries but this is how it is done)
X = X[:, 1:]

from sklearn.cross_validation import train_test_split
X_train , X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.2, random_state = 0)

from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, Y_train)

y_pred = regressor.predict(X_test)

#Building the optimal model using Backward Elemination

import statsmodels.formula.api as sm
X = np.append(arr = np.ones((50, 1)).astype(int), values = X, axis = 1) ## adding the bo value in the slope formula

X_opt = X[:, [0, 1, 2, 3, 4, 5]]
'''
#Naive way
regressor_OLS = sm.OLS(endog = Y, exog = X_opt).fit()
#endog -> 1-d endogenous response variable. The dependent Variable
#exog -> a nobs x k array
regressor_OLS.summary()
X_opt = X[:, [0, 1, 3, 4, 5]]
regressor_OLS = sm.OLS(endog = Y, exog = X_opt).fit()
regressor_OLS.summary()

X_opt = X[:, [0, 3, 4, 5]]
regressor_OLS = sm.OLS(endog = Y, exog = X_opt).fit()
regressor_OLS.summary()

X_opt = X[:, [0, 3, 5]]
regressor_OLS = sm.OLS(endog = Y, exog = X_opt).fit()
regressor_OLS.summary()

X_opt = X[:, [0, 3]]
regressor_OLS = sm.OLS(endog = Y, exog = X_opt).fit()
regressor_OLS.summary()
'''

'''
Using function with p_values and Adjusted R-Squared
'''
def backwardElimination(x, sl):
    numVars = len(x[0])
    temp = np.zeros((50, 6)).astype(int)
    for i in range(0, numVars):
        regressor_OLS = sm.OLS(Y, x).fit()
        maxVars = max(regressor_OLS.pvalues).astype(float)
        adjR_before = regressor_OLS.rsquared_adj.astype(float)
        if maxVars > sl:
            for j in range(0, numVars - i):
                if regressor_OLS.pvalues[j].astype(float) == maxVars:
                    temp[:, j] = x[:, j]
                    x = np.delete(x, j, 1)
                    tmp_regressor = sm.OLS(Y, x).fit()
                    adjR_after = tmp_regressor.rsquared_adj.astype(float)
                    if adjR_before >= adjR_after :
                        x_rollback = np.hstack((x, temp[:, [0, j]]))
                        x_rollback = np.delete(x_rollback, j, 1)
                        print(regressor_OLS.summary())
                        return x_rollback
                    else:
                        continue
    regressor_OLS.summary()
    return x

SL = 0.05
X_opt = X[:, [0, 1, 2, 3, 4, 5]]
X_Modeled = backwardElimination(X_opt, SL)

X_train_mod, X_test_mod, Y_train_mod, Y_test_mod = train_test_split(X_Modeled, Y, test_size = 0.2, random_state = 0)
regressor = LinearRegression()
regressor.fit(X_train_mod, Y_train)

y_pred_mod = regressor.predict(X_test_mod)

Regression/Section 5 - Multiple Linear Regression/multiple_linear_regression_my.py


import tkinter as tk
from tkinter import filedialog

from kivy.app import App
from kivy.uix.screenmanager import Screen

import client.utils as utils
from client.screens.common import *
from client.utils import ApiException
from client.utils import background
from definitions import ROOT_DIR

# Load corresponding kivy file
Builder.load_file(
    os.path.join(
        ClientConfig.DATA_DIR,
        'project_tool_screen.kv'))

class ProjectToolScreen(Screen):
    def __init__(self, **kw):
        super().__init__(**kw)
        self.app = App.get_running_app()

    def upload_images(self, *args):
        root = tk.Tk()
        root.withdraw()
        filepath = filedialog.askdirectory(initialdir=ROOT_DIR)
        image_paths = []
        if isinstance(filepath, str):
            for (root, _, filename) in os.walk(filepath):
                for f in filename:
                    # tkinter does not return windows style filepath
                    image_paths.append(root + '/' + f)
        self._upload_images(self.app.current_project_id, image_paths)

        self._upload_images(self.app.current_project_id, image_paths)

    @background
    def _upload_images(self, pid, image_paths):
        resp = utils.add_project_images(pid, image_paths)
        if resp.status_code == 200:
            result = resp.json()
            msg = []
            for row in result["results"]:
                if "error" in row:
                    msg.append(row["error"]["message"])
            msg = '\n'.join(msg)
            raise ApiException(
                message="The following errors occurred while trying to upload images:\n %s" %
                (msg,), code=resp.status_code)
        elif resp.status_code != 201:
            raise ApiException(
                "Failed to upload images to project.",
                resp.status_code)
        else:
            pop_up = Alert()
            pop_up.title = "Success!"
            pop_up.alert_message = "Successfully added new images to the '%s' project" % self.app.current_project_name
            pop_up.open()


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

import sys
import os
sys.path.insert(0, os.path.abspath(__file__ + "/../../"))

import json
import argparse
import pickle
import numpy as np

from data_processing.utils import *
from functools import partial

def main():
    parser = argparse.ArgumentParser(
        description="Maps the tokenized reviews onto the provided vocabulary.")
    parser.add_argument(
        'review_path',
        help="The location of json file of tokenized reviews to map over",
        type=str)
    parser.add_argument(
        'vocab_pickle',
        help="The location of the vocabulary pickle file",
        type=str)
    parser.add_argument(
        'mapped_vocab_path',
        help="The location of the json file to save the vocab mapped json to",
        type=str)
    parser.add_argument(
        '--progress_interval',
        metavar='secs',
        help="The progress printing interval in seconds",
        type=restricted_int,
        default=5)
    parser.add_argument(
        '--map_to_index',
        help='Whether the text gets mapped to its index in the vocabulary or not',
        default=False,
        type=bool)
    args = parser.parse_args()

    directory = os.path.dirname(args.mapped_vocab_path)
    if not os.path.exists(directory):
        os.makedirs(directory)

    with open(args.review_path, 'r') as review_file,\
            open(args.vocab_pickle, 'rb') as vocab_pickle,\
            open(args.mapped_vocab_path, 'x+') as mapped_vocab_file:
        print("Beginning vocabulary mapping!")
        num_reviews = sum(1 for _ in review_file)
        print("There are %d reviews." % num_reviews)

        vocab_dict = pickle.load(vocab_pickle)
        num_words = len(vocab_dict)
        vocab_list = list(key for key, _ in vocab_dict.items())
        print("There are %d words in the vocabulary." % num_words)

        review_file.seek(0)  # Reset stream position to start
        reviews = (json.loads(line) for line in review_file)

        unknown_idx = vocab_list.index(UNKNOWN_TOKEN)
        numerical_idx = vocab_list.index(NUMERICAL_TOKEN)

        def map_word_to_vocab(word):
            if word.isnumeric():
                if args.map_to_index:
                    return numerical_idx
                else:
                    return NUMERICAL_TOKEN
            try:
                if args.map_to_index:
                    return vocab_list.index(word)
                else:
                    return word
            except ValueError:
                if args.map_to_index:
                    return unknown_idx
                else:
                    return UNKNOWN_TOKEN

        def map_to_vocab(review, acc):
            text = review['text']
            review['text'] = [[map_word_to_vocab(word) for word in sentence] for sentence in text]
            json.dump(review, mapped_vocab_file)
            mapped_vocab_file.write('\n')
            return acc + 1

        apply_count = 0
        apply_count = apply_over_generator(
            reviews, map_to_vocab, acc=apply_count, num_elements=num_reviews, progress_interval=args.progress_interval)

        if apply_count != num_reviews:
            print(("ERROR! The vocab mapper ran on %d reviews but the number of reviews in the file is %d. " +
                  "They should match! Something went wrong.") % (apply_count, num_reviews))
            return -1
        print("Vocabulary mapping complete!")

if __name__ == '__main__':
    main()


import re
import os
import sys
import time
import numpy
import pickle
import datetime

from pygbe.lspr import main as pygbe

try:
    import pycuda
except ImportError:
    ans = input('PyCUDA not found.  Regression tests will take forever.  Do you want to continue? [y/n] ')
    if ans in ['Y', 'y']:
        pass
    else:
        sys.exit()

mesh = ['512', '2K', '8K', '32K']

def picklesave(test_outputs, file_name):
    with open(file_name,'wb') as f:
        pickle.dump(test_outputs, f, 2)

def mesh_ratio(N):
    """
    Calculates the mesh refinement ratio between consecutive meshes.

    Arguments:
    ----------
    N: list, Number of elements / avg_density in test (depends on what applies).

    Returns:
    --------
    mesh_ratio: list of float, mesh refinement ratio between consequtive meshes.
    """
    mesh_ratio = []
    for i in range(len(N)-1):
        mesh_ratio.append(N[i+1]/N[i])

    return mesh_ratio

def run_convergence(mesh, test_name, problem_folder, param):
    """
    Runs convergence tests over a series of mesh sizes

    Inputs:
    ------
        mesh          : array of mesh suffixes
        problem_folder: str, name of folder containing meshes, etc...
        param         : str, name of param file

    Returns:
    -------
        N         : len(mesh) array, elements of problem.
        iterations: len(mesh) array, number of iterations to converge.
        Cext_0    : len(mesh) array of float, Cross extinction section of the
                    main sphere.
        Time      : len(mesh) array of float, time to solution (wall-time)
    """
    print('Runs convergence')
    N = numpy.zeros(len(mesh))
    iterations = numpy.zeros(len(mesh))
    Cext_0 = numpy.zeros(len(mesh))
    Time = numpy.zeros(len(mesh))

    for i in range(len(mesh)):
        try:
            print('Start run for mesh '+mesh[i])
            results = pygbe(['',
                            '-p', problem_folder + '{}'.format(param),
                            '-c', problem_folder +'{}_{}.config'.format(test_name, mesh[i]),
                            '-o', problem_folder + 'output_{}_{}'.format(test_name, mesh[i]),
                            '{}'.format(problem_folder),], return_results_dict=True)

            N[i] = results['total_elements']
            iterations[i] = results['iterations']
            Cext_0[i] = results.get('Cext_0') #We do convergence analysis in the main sphere
            Time[i] = results['total_time']

        except (pycuda._driver.MemoryError, pycuda._driver.LaunchError) as e:
            print('Mesh {} failed due to insufficient memory.'
                  'Skipping this test, but convergence test should still complete'.format(mesh[i]))
            time.sleep(4)

    mesh_rate = mesh_ratio(N)
    expected_rate = 0

    if all(ratio==mesh_rate[0] for ratio in mesh_rate):
        expected_rate = mesh_rate[0]
    else:
        print('Mesh ratio inconsistency. \nIf you are running a system protein-sensor, remember \n'
                'that we do not refine the protein mesh, since measurements are taken over the sensor. \n'
                'Do not worry about the warning as soon as the refinement in your sensor mesh keeps a constant \n'
                'ratio. \n'
                'If you are running a case of single sensor, the refinement should keep a constant ratio, \n'
                'otherwise convergence will not be computed properly.')

    return(N, iterations, expected_rate, Cext_0, Time)

def Cext_analytical(radius, wavelength, diel_out, diel_in):
    """
    Calculates the analytical solution of the extinction cross section.
    This solution is valid when the nano particle involved is a sphere.

    Arguments
    ----------
    radius    : float, radius of the sphere in [nm].
    wavelength: float/array of floats, wavelength of the incident
                electric field in [nm].
    diel_out  : complex/array of complex, dielectric constant inside surface.
    diel_in   : complex/array of complex, dielectric constant inside surface.

    Returns
    --------
    Cext_an   : float/array of floats, extinction cross section.
    """
    wavenumber = 2 * numpy.pi * numpy.sqrt(diel_out) / wavelength
    C1 = wavenumber**2 * (diel_in / diel_out - 1) / (diel_in / diel_out + 2)
    Cext_an = 4 * numpy.pi * radius**3 / wavenumber.real * C1.imag

    return Cext_an

def richardson_extrapolation_lspr(test_result):
    """
    Performs an estimate of the exact solution using
    Richardson extrapolation, given by

    f_ex = (f_1 * f_3 - f_2^2) / (f_3 - 2*f_2+f_1)

    where f_1 is a result from the finest grid and f_3 is from the coarsest.
    The grids f_1, f_2, f_3 should have the same refinement ratio (e.g. 2 -> 4 -> 8)

    Arguments:
    ----------
    test_result:

    Returns:
    --------
    f_ex : float, richardson_extrapolation estimated exact solution.
    """
    #We perform the richardson extrapolation in the main body. The body we
    #meassure
    try:
        Cext_0 = test_result['Cext_0']
    except KeyError:
        print('No results found for main body cross extinction section  \n'
              'Something has gone wrong.')
        sys.exit()

    # Using last 3 meshes asumming the latest is the finner one
    f1 = Cext_0[-1]
    f2 = Cext_0[-2]
    f3 = Cext_0[-3]

    f_ex = (f1 * f3 - f2**2) / (f3 - 2 * f2 + f1)

    return f_ex


import datetime
import os
import re
import string
import subprocess
import webbrowser as wb
from os import path

from unidecode import unidecode

import Microfone as m

import pyttsx3

import comandos
from pln.calssificador import classificar
import urllib.request, json

### ----------- TEXTO EM VOZ ----------- ###
engine = pyttsx3.init()  # object creation

voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)
engine.setProperty('rate', 135)

def falar(texto):
    engine.say(texto)
    engine.runAndWait()

### ----------- TEXTO EM VOZ ----------- ###

def boas_vindas():
    Horario = int(datetime.datetime.now().hour)

    if Horario >= 0 and Horario < 12:
        falar('Bom dia, em que posso ajudar ?')

    elif Horario >= 12 and Horario < 18:
        falar('Boa tarde, em que posso ajudar ?')

    elif Horario >= 18 and Horario != 0:
        falar('Boa noite, em que posso ajudar ?')

class SystemInfo:
    def __init__(self):
        pass

    @staticmethod
    def obter_horario():
        now = datetime.datetime.now()
        resposta = 'São {} horas e {} minutos.'.format(now.hour, now.minute)
        return resposta

    @staticmethod
    def obter_data():
        now = datetime.datetime.now()
        resposta = 'Hoje é dia {} de {} de {}'.format(now.day, now.strftime("%B"), now.year)
        return resposta

    @staticmethod
    def abrir_chrome():
        chrome_path = 'open -a /Applications/Google\ Chrome.app %s'
        return wb.get(chrome_path)

    @staticmethod
    def abrir_navegador():
        return wb.open_new_tab('http://www.google.com')

    @staticmethod
    def abrir_google():
        return wb.open_new_tab('http://www.google.com')

    @staticmethod
    def abrir_youtube():
        return wb.open_new_tab('https://www.youtube.com')

    @staticmethod
    def abrir_facebook():
        return wb.open_new_tab('https://www.facebook.com')

    @staticmethod
    def abrir_instagram():
        return wb.open_new_tab('https://www.instagram.com')

    @staticmethod
    def obter_dolar():
        with urllib.request.urlopen("https://economia.awesomeapi.com.br/json/last/USD-BRL") as url:
            data = json.loads(url.read().decode())

        now = datetime.datetime.now()
        valor = round(float(data['USDBRL']['ask']), 2)

        resposta = 'O valor do Dólar é R$ {}, valor atualizado às {} horas e {} minutos'.format(valor, now.hour,
                                                                                now.minute)
        return resposta

    @staticmethod
    def obter_euro():
        with urllib.request.urlopen("https://economia.awesomeapi.com.br/json/last/EUR-BRL") as url:
            data = json.loads(url.read().decode())

        now = datetime.datetime.now()
        valor = round(float(data['EURBRL']['ask']), 2)

        resposta = 'O valor do Euro é R$ {}, valor atualizado às {} horas e {} minutos'.format(valor, now.hour,
                                                                                now.minute)
        return resposta

    @staticmethod
    def buscar_endereco(cep):

        temp_string = cep
        out = temp_string.translate(str.maketrans('', '', string.punctuation))
        numbers = [int(temp) for temp in out.split() if temp.isdigit()]
        cep_limpo = ''.join(char for char in str(numbers) if char.isalnum())

        with urllib.request.urlopen(f"https://viacep.com.br/ws/{cep_limpo}/json/") as url:
            data = json.loads(url.read().decode())

        resposta = 'O CEP informado está localizado no estado {}, na cidade de {}, no bairro {}, {}'.format(data['uf'],
                                                                                data[
                                                                                'localidade'],
                                                                                data[
                                                                                'bairro'],
                                                                                data[
                                                                                'logradouro'])

        return resposta

    @staticmethod
    def cumprimentar():

        Horario = int(datetime.datetime.now().hour)

        if Horario >= 0 and Horario < 12:
            resposta = 'Olá, Bom dia, tudo bem com você ? espero que sim. Em que posso ajudar ?'

        elif Horario >= 12 and Horario < 18:
            resposta = 'Olá, Boa tarde, tudo bem com você ? espero que sim. Em que posso ajudar ?'

        elif Horario >= 18 and Horario != 0:
            resposta = 'Olá, Boa noite, tudo bem com você ? espero que sim. Em que posso ajudar ?'

        return resposta

    @staticmethod
    def pesquisar_internet(pesquisa):

        remover_palavras = ['pesquisar', 'pesquise', 'busque', 'buscar', 'procure', 'procurar']
        lista_frase = pesquisa.split()

        result = [palavra for palavra in lista_frase if palavra.lower() not in remover_palavras]

        retorno = ' '.join(result)

        return wb.open_new_tab('http://google.com/search?q='+ retorno)

    @staticmethod
    def lower_lista(lista):
        a = (map(lambda x: x.lower(), lista))
        b = list(a)
        return b

    @staticmethod
    def navegacao():
        mic = m.cMicrofone()

        alfabeto = list(string.ascii_lowercase)

        diretorio = ""
        diretorio_anterior = ""
        listadir = []

        while (True):
            comandos.falar("Qual disco inicial ?")
            print("❖ - Assistente: Qual disco inicial ?")
            palavra = mic.Ouvir()
            print('🎤 - Audio captado: '+palavra)

            # if ((palavra.lower() in alfabeto) or ("de" in palavra.lower())):

            if "de" in palavra.lower():

                diretorio = "D:\\"

            elif((" c" in palavra.lower()) or ("se" in palavra.lower())):

                diretorio = "C:\\"
            else:
                print('🎤 - Audio captado: '+ palavra)
                print("❖ - Assistente: Desculpe, Não consegui encontrar o disco... \n ❖ - Assistente: Saindo do modo navegação por diretórios")
                print('\n________________________________\n')
                falar("Desculpe, Não consegui encontrar o disco...")
                falar("Saindo do modo navegação por diretórios")
                break

            diretorio_anterior = diretorio

            listadir.append(diretorio_anterior)

            while (True):

                diretorio_anterior = diretorio

                try:

                    lista = os.listdir(diretorio)
                    comandos.falar("Qual diretório?")
                    print('________________________________')
                    print("❖ - Assistente: Qual diretorio ?\n")
                    print(str(lista))
                    #for i in lista:
                        #print(f"-- {i}")

                    print('________________________________')
                    palavra = unidecode((mic.Ouvir()).lower())
                    print('🎤 - Audio captado: '+palavra)

                    if palavra == "voltar" and len(listadir) > 1:
                        diretorio = listadir.__getitem__(len(listadir) - 2)
                        listadir.remove(listadir.__getitem__(len(listadir) - 1))
                    else:
                        str_match = [x for x in comandos.SystemInfo.lower_lista(lista) if re.search(palavra, x)]

                        palavra = str(str_match)
                        simbolos = '[]\''

                        if (str_match.__len__() > 1):
                            dirduplicado = (f"Foram encontrados os seguintes diretórios: {str(str_match)}. Diga qual deles deseja acessar.")
                            print('❖ - Assistente: ' +dirduplicado)
                            comandos.falar(dirduplicado)

                            while True:
                                diroficial = mic.Ouvir()
                                palavra = [x for x in comandos.SystemInfo.lower_lista(lista) if diroficial == x]
                                if (palavra != ''):
                                    palavra = palavra[0]
                                    break

                        for i in simbolos:
                            palavra = palavra.replace(i, '')

                        if palavra != "":
                            diretorio += "\\" + palavra

                    # if (('.txt' or '.lnk' or '.exe' or '.docx' or '.xls') in diretorio):
                    if ("." in diretorio):
                        os.startfile(diretorio)
                        diretorio = diretorio_anterior
                    else:
                        os.listdir(diretorio)
                        if not listadir.__contains__(diretorio):
                            listadir.append(diretorio)

                    #print(listadir)

                except:
                    print("❖ - Assistente: diretorio não encontrado")
                    if (diretorio == str(palavra).upper() + ":\\"):
                        print("Por favor selecione um disco válido!")
                        break
                    diretorio = diretorio_anterior

            else:
                print('Por favor selecione um disco válido!')

class Executar:

    @staticmethod
    def excutar_comandos(frase):

        grupo = classificar(frase)
        fala = ''

        if grupo == 'horario|retornarHorario':
            fala = SystemInfo.obter_horario()
            falar(fala)
        elif grupo == 'data|retornarData':
            fala = SystemInfo.obter_data()
            falar(fala)
            # Abrir softwares listados
        elif grupo == 'cumprimento|responderCumprimento':
            fala = SystemInfo.cumprimentar()
            falar(fala)
            # Abrir softwares listados
        elif grupo == 'abrir|notepad':
            fala = 'Abrindo o bloco de notas'
            falar(fala)
            subprocess.Popen('notepad.exe')
        elif grupo == 'abrir|abrirCalculadora':
            fala = 'Abrindo calculadora'
            falar(fala)
            subprocess.Popen('calc.exe')
        elif grupo == 'abrir|abrirNavegador':
            fala = 'Abrindo o navegador'
            falar(fala)
            SystemInfo.abrir_navegador()
            # Abrir softwares sites
        elif grupo == 'abrir|acessarGoogle' and 'google' in frase:
            fala = 'Acessando Google'
            falar(fala)
            SystemInfo.abrir_google()
        elif grupo == 'abrir|acessarGoogle' and 'google' not in frase:
            fala = 'Acho que não entendi muito bem oque você disse, estou realizando uma pesquisa na web para ajudar!'
            falar(fala)
            SystemInfo.pesquisar_internet(frase)
        elif grupo == 'abrir|acessarYoutube' and 'youtube' in frase:
            fala = 'Acessando Youtube'
            falar(fala)
            SystemInfo.abrir_youtube()
        elif grupo == 'abrir|acessarYoutube' and 'youtube' not in frase:
            fala = 'Acho que não entendi muito bem oque você disse, estou realizando uma pesquisa na web para ajudar!'
            falar(fala)
            SystemInfo.pesquisar_internet(frase)
        elif grupo == 'abrir|acessarFacebook' and 'facebook' in frase:
            fala = 'Acessando Facebook'
            falar(fala)
            SystemInfo.abrir_facebook()
        elif grupo == 'abrir|acessaracebook' and 'facebook' not in frase:
            fala = 'Acho que não entendi muito bem oque você disse, estou realizando uma pesquisa na web para ajudar!'
            falar(fala)
            SystemInfo.pesquisar_internet(frase)
        elif grupo == 'abrir|acessarInstagram' and 'instagram' in frase:
            fala = 'Acessando Instragram'
            falar(fala)
            SystemInfo.abrir_instagram()
        elif grupo == 'abrir|acessarInstagram' and 'instagram' not in frase:
            fala = 'Acho que não entendi muito bem oque você disse, estou realizando uma pesquisa na web para ajudar!'
            falar(fala)
            SystemInfo.pesquisar_internet(frase)
        elif (grupo == 'cotacao|retornarCotacaoAtual') and 'dolar' in frase:
            falar('Buscando valor atual do dólar ...')
            fala = SystemInfo.obter_dolar()
            falar(fala)
        elif (grupo == 'cotacao|retornarCotacaoAtual') and 'euro' in frase:
            falar('Buscando valor atual do euro ...')
            fala = SystemInfo.obter_euro()
            falar(fala)
        elif grupo == 'pesquisa|buscarCep':
            falar('Buscando o CEP informado ...')
            fala = SystemInfo.buscar_endereco(frase)
            falar(fala)
        elif grupo == 'pesquisa|pesquisaWeb':
            fala = 'Ok, já estou pesquisando o\'que você me disse!'
            falar(fala)
            SystemInfo.pesquisar_internet(frase)
        elif grupo == 'navegacao|navegarDiretorio':
            falar('Ok, abrindo a navegação por diretório!')
            SystemInfo.navegacao()

        # Mostrar informações (resultado e a qual grupo ele pertence)
        print("\n\n❖ - Assistente: Ouvindo...")
        print('\n________________________________\n')
        print('🎤 - Audio captado: {} - Grupo: {}\n'.format(frase, grupo))
        print('\n________________________________\n')
        print('❖ - Assistente: '+fala)


# names = ['Helen','Paul','Joe','Motunrayo','David','Johnson']
# maxi = len(names[0])
# for i in range (len(names)):
#     if len(names[i]) < maxi:
#         maxi = len(names[i])
# print(names[maxi])

class_a = ['chinonso','esther','joe','candy']
class_b = ['oyinyechi','ugochi','chidinma','kachi']

length =0
for i in class_a,class_b:
    for j in i:
        if len(j)>length:
            length = len(j)
            word =j
            position = i.index(j)
print(word, position)


import numpy as np
from copy import deepcopy

def normalize_max_crit(matrix: np.array, crit_num: int) -> np.array:
    m = deepcopy(matrix).transpose()
    mini = min(m[crit_num])
    div = max(m[crit_num]) - min(m[crit_num])
    m[crit_num] = [(i - mini) / div for i in m[crit_num]]
    return m.transpose()

def normalize_min_crit(matrix: np.array, crit_num: int) -> np.array:
    m = deepcopy(matrix).transpose()
    maxi = max(m[crit_num])
    div = max(m[crit_num]) - min(m[crit_num])
    m[crit_num] = [(maxi - i) / div for i in m[crit_num]]
    return m.transpose()

length = 4
matrix = np.array(
    [
        [3, 7, 2, 9],
        [8, 3, 6, 7],
        [4, 8, 3, 5],
        [9, 6, 5, 4]
    ]
).astype(float)
weight = np.array([8, 9, 6, 7])

matrix = normalize_max_crit(normalize_max_crit(normalize_max_crit(normalize_min_crit(matrix, 0), 1), 2), 3)
result = [sum(row * weight) for row in matrix]

print(result)


"""
Each node has a set of attributes that allows for quick access to properties and
other node of interest.  For example, if `node` has a name, it can be referred
to by `node.name`.  Another example is to access the parent node by
`node.parent`.

Note that, if a reference does not exist, the node itself will be returned.
"""

groups = [
    "Assign", "Assigns", "Branch", "For", "Func", "Main",
    "Set", "Cset", "Fset", "Nset", "Sset",
    "Get", "Cget", "Fget", "Nget", "Sget",
    "Statement", "Switch", "Tryblock", "Matrix",
    "While", "Block", "Node", "Transpose", "Ctranspose",
]

nondeclares = ("Program", "Project", "Include", "Includes", "Struct", "Structs")
structvars = ("Fvar", "Fget", "Fset", "Nget", "Nset", "Sget", "Sset")

class Property_reference(object):
    "general property node"

    def __init__(self, name, default=None):
        self.name = name

    def __get__(self, instance, owner):
        return instance.prop[self.name]

    def __set__(self, instance, value):
        instance.prop[self.name] = value

class Recursive_property_reference(object):
    "recursive property node"

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

    def __get__(self, instance, owner):

        a = instance.prop[self.name]
        if not (a is None):
            return a

        assert not (instance is instance.parent)

        a = Recursive_property_reference.__get__(self, instance.parent, owner)
        instance.prop[self.name] = a

        return a

    def __set__(self, instance, value):
        instance.prop[self.name] = value

class File_reference(object):
    def __get__(self, instance, owner):
        if hasattr(instance, "_file"):
            return instance._file

        if instance.cls == "Program":
            file_name = instance.name
        else:
            file_name = instance.program.name

        instance._file = file_name
        return file_name

class Line_reference(object):

    def __get__(self, instance, owner):
        if hasattr(instance, "_line"):
            return instance._line

        if instance.cls == "Project":
            line = 0

        elif instance.cls == "Funcs":
            line = 1

        else:
            pline = instance.parent.line
            pcur = instance.parent.cur
            cur = instance.cur

            if pcur == cur:
                line = pline
            else:
                line = pline + instance.program.code.count("\n", pcur, cur)

        instance._line = line
        return line

class Group_reference(object):

    def __get__(self, instance, owner):

        if hasattr(instance, "_group"):
            return instance._group

        if instance.parent.cls in groups:
            group = instance.parent

        else:
            group = instance.parent.group

        instance._group = group
        return group

class Func_reference(object):

    def __get__(self, instance, owner):

        if hasattr(instance, "_func"):
            return instance._func

        if instance.cls in ("Func", "Main", "Program"):
            func = instance
        else:
            func = instance.parent.func

        instance._func = func
        return func

class Program_reference(object):
    def __get__(self, instance, owner):

        if hasattr(instance, "_program"):
            return instance._program

        if instance.cls == "Program":
            program = instance
        else:
            program = instance.parent.program

        instance._program = program
        return program

class Project_reference(object):
    def __get__(self, instance, owner):

        if hasattr(instance, "_project"):
            return instance._project

        if instance.cls == "Project":
            project = instance
        else:
            project = instance.parent.project

        instance._project = project
        return project

class Names(object):
    def __get__(self, instance, owner):
        return [i.prop["name"] for i in instance.children]

class Declare_reference(object):

    def __get__(self, instance, owner):

        if hasattr(instance, "_declare"):
            return instance._declare

        if instance.cls in nondeclares:
            return instance

        if instance.cls in structvars or\
                instance.backend in ("structs", "struct"):

            if instance.cls in ("Nget", "Nset"):
                if instance[0].cls == "String":
                    value = instance[0]["value"]
                else:
                    return instance

            else:
                value = instance.value

            if instance not in instance.program[3]:
                return instance

            struct = instance.program[3][instance]

            if value not in struct.names:
                return instance

            out = struct[struct.names.index(value)]
            instance._declare = out
            return out

        elif instance.parent.cls in "Struct":
            return instance

        else:

            if instance in instance.func[0]:
                out = instance.func[0][instance]
                instance._declare = out
                return out

            if instance in instance.func[2]:
                out = instance.func[2][instance]
                instance._declare = out
                return out

        return instance


"""
28.03.2020
Tuple unpacking
Bogdan Prădatu - Fluent Python
"""

# Tuple unpacking works with any iterable object. The only requirement
# is that the iterable yields exactly one item per variable in the
# receiving tuple, unless you use a star (*) to capture excess items

name = ("Bogdan", "Prădatu")
firstname, lastname = name
print("Firstname:", firstname, "\nLastname:", lastname)

t = (20, 8)
print(divmod(*t))

one, two, *rest = range(5)
print("One:", one)
print("Two:", two)
print("Rest:", rest)

print("\nNested tuple unpacking:\n")
metro_areas = [
    ('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),
    ('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
    ('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
    ('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
    ('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)),
]
print('{:15} | {:^9} | {:^9}'.format('', 'lat.', 'long.'))
fmt = '{:15} | {:9.4f} | {:9.4f}'
for name, cc, pop, (latitude, longitude) in metro_areas:
    if longitude <= 0:
        print(fmt.format(name, latitude, longitude))


this_dict={ "name":"Misky",
"interests":["dancing","cooking"],
"age":10,
"workdays":("mon","tue"),
"parents":{"mother":"Sarah"}}

#key can be unique (wrapped around quotations) and value should be a datatype,any datatype
print(this_dict)
#checking  type
print(type(this_dict))
#print a value eg  the name
print(this_dict["name"])
print(this_dict["parents"]["mother"])
print(this_dict["interests"][0])

myinfo={
    "name":"Misky",
    "primarySchools":{
        "primary1":{
            "headteacher":{"first":"Lucy","last":"Mwendia"},
            "approximatepop":{"total":1000,"male":300,"female":700} ,
            "name":"Our Lady of Mercy"
        } ,
    "primary2":{
        "headteacher":{"first":"Mary","last":"Mwangu"} ,
        "approximatepop":{"total":700,"male":350,"female":350} ,
        "name":"Mariakani Primary School"
        },
    "languages":["English","Swahili","Somali","Arabic"]
}
}

"""
methods to manipulate lists
.append
.replace
.pop
.insert(what you want to include,where)
.remove
.count
.extend
.sort
"""


#!/usr/bin/env python3
import pathlib
import re
import sys

ROOT_DIR = pathlib.Path(__file__).parent.parent
README = ROOT_DIR / "README.md"
INDEX = ROOT_DIR / "docs" / "index.md"
SETUP = ROOT_DIR / "setup.py"
QUICKSTART = ROOT_DIR / "examples" / "quickstart.py"

USED_FILES = {str(path.relative_to(ROOT_DIR)) for path in (INDEX, SETUP, QUICKSTART)}

def main():
    version_match = re.search(r"version=\"(\d+\.\d+)", SETUP.read_text())
    assert version_match is not None
    version = version_match.group(1)
    content = INDEX.read_text()
    # Set title
    content = re.sub(r"# Overview\s*## apischema", "# apischema", content)
    # Remove FAQ
    content = content[: content.index("## FAQ")]
    # Remove admonitions
    content = re.sub(r"!!! note\n\s*(.*)\n", lambda m: f"> {m.group(1)}\n", content)
    # Add chart
    content = content.replace(
        r"<!--insert chart-->",
        "\n".join(
            f"![benchmark chart](https://wyfo.github.io/apischema/{version}/"
            f"benchmark_chart_{theme}#gh-{theme}-mode-only)"
            for theme in ("light", "dark")
        ),
    )
    # Uncomment
    content = re.sub(r"<!--\n(\s*(.|\n)*?\s*)\n-->", lambda m: m.group(1), content)
    content = re.sub(
        r"(\d+\.\d+)/benchmark_chart\.svg", f"{version}/benchmark_chart.svg", content
    )
    # Rewrite links
    content = re.sub(
        r"\(([\w/]+)\.(md|svg)(#[\w-]+)?\)",
        lambda m: f"(https://wyfo.github.io/apischema/{version}/{m.group(1)}"
        + (".svg" if m.group(2) == "svg" else "")
        + (m.group(3) or "")
        + ")",
        content,
    )
    # Add quickstart
    content = re.sub(
        "```python(.|\n)*?```", f"```python\n{QUICKSTART.read_text()}```", content
    )
    README.write_text(content)

if __name__ == "__main__":
    if not set(sys.argv).isdisjoint(USED_FILES):
        main()


import constants
import comms.queueSubscriber
import lib.helpers
import datalayer.dbConnection
import datalayer.plantLogRecorder
import signal
import sys

def signal_handler(sig, frame):
    #Clean exit
    print("Stopping MQTT client")
    pc.stop()
    print("Test details")
    datalayer.dbConnection.testPrintSql(db_connection, "select * from plant_logs where log_variable = 'light'")
    print("Closing DB connection")
    db_connection.close()
    sys.exit(0)

def record_log(client, userdata, message):
    message_json = lib.helpers.message_to_string(message)
    print(message_json)
    insert_sql = datalayer.plantLogRecorder.create_log_sql(db_connection, message_json)
    datalayer.dbConnection.runSql(db_connection, insert_sql)
    db_connection.commit()

#Starting here

signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)

db_file = datalayer.dbConnection.get_config_parameter(
            datalayer.dbConnection.get_config_json(constants.dbConfigFilename),
            constants.dbFilenameConfigParameter
        )
db_connection = None
db_connection = datalayer.dbConnection.get_db_connection(db_connection, db_file)

pc = comms.queueSubscriber.QueueSubscriber(constants.clientSubscribeName)
pc.on_message = record_log
pc.run(constants.brokerAddress, constants.topic_subscribe)


#!/usr/bin/python3

import os, stat, atexit
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
import time
import common

hostName = ""
hostPort = common.WEBSERVER_PORT
FIFO = common.FIFO
logger = common.homeSecurityLogger

serverWasStarted = False
@atexit.register
def exit_handler():
    logger.info("Exit command received. Should close web server")
    if serverWasStarted:
        myServer.server_close()
        logger.info("Web Server Stops - %s:%s" % (hostName, hostPort))
    else:
        logger.info("Web server was not started. Nothing to close")

def writeToPipe(message):
    """
    check whether the named pipe exists and write to it
    Returns number of characters written or False otherwise
    """
    try:
        isFIFO = stat.S_ISFIFO(os.stat(FIFO).st_mode)
        if not isFIFO: raise FileNotFoundError
        logger.debug("Writing {} to IPC pipe".format(message))
        pipe = open(FIFO, 'w')
        count = pipe.write(message)
        logger.debug("Written {} chars to pipe".format(count))
        pipe.close()
        return count
    except FileNotFoundError:
        logger.critical("IPC write failed. File does not exist or is not a pipe")

    return False

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(bytes("Received\r\n", "utf-8"))
        query_components = parse_qs(urlparse(self.path).query)
        if('motion' in query_components):
            logger.info("Motion parameter set in request")
            writeToPipe(common.MOTION_DETECTED_COMMAND)

    def log_message(self, format, *args):
        logger.info("Request from {}:{} - ".format(self.client_address[0], self.client_address[1]) + format%args)

if __name__ == "__main__":
    try:
        myServer = HTTPServer((hostName, hostPort), MyServer)
    except Exception as e:
        logger.critical("Exception was raised while starting server: {}".format(str(e)))
        if not writeToPipe(common.WEBSERVER_FAIL_COMMAND):
            logger.critical("Can't signal fail state. Need to exit")
        exit(1)
    else:
        logger.info("Web Server Starts - %s:%s" % (hostName, hostPort))
        serverWasStarted = True
        if not writeToPipe(common.WEBSERVER_READY_COMMAND):
            logger.critical("Can't signal ready state. Need to exit")
            exit(1)
        try:
            myServer.serve_forever()
        except KeyboardInterrupt:
            pass


import matplotlib.pyplot as plt
import numpy as np
from Kidera import kidera

w = 'McPAS-TCR_with_V'
t = 'TCRGP_with_V'
nt = 'TCRGP_negs_with_V'

def tcr_length_dist_comp(data1, data2, title, normalize=False):
    with open(data1, 'r') as data:
        lens1 = {}
        for line in data:
            t = line.strip().split()[0]
            try:
                lens1[len(t)] += 1
            except KeyError:
                lens1[len(t)] = 1
    with open(data2, 'r') as data:
        lens2 = {}
        for line in data:
            t = line.strip().split()[0]
            try:
                lens2[len(t)] += 1
            except KeyError:
                lens2[len(t)] = 1
    x1 = [k for k in sorted(lens1)]
    y1 = [lens1[k] for k in sorted(lens1)]
    x2 = [k for k in sorted(lens2)]
    y2 = [lens2[k] for k in sorted(lens2)]
    if normalize:
        y1 = [y/sum(y1) for y in y1]
        y2 = [y/sum(y2) for y in y2]
    fig, ax = plt.subplots()
    width = 0.35
    plot1 = ax.bar([x + width for x in x1], y1, width,
                    color='SkyBlue', label='McPAS (Weizmann) data')
    plot2 = ax.bar(x2, y2, width,
                    color='IndianRed', label='TCRGP paper data')
    ax.set_ylabel('Number of TCRs')
    ax.set_title(title)
    ax.set_xticks(x1)
    ax.legend()
    plt.show()

# tcr_length_dist_comp(w, t, 'TCR Length Distribution')
# tcr_length_dist_comp(w, t, 'Normalized TCR Length Distribution', normalize=True)
# tcr_length_dist_comp(w, nt, 'Normalized TCR Length Distribution' ,normalize=True)

def amino_corr_map(datafile, c, title):
    with open(datafile, 'r') as data:
        amino_acids = ['start'] + [letter for letter in 'ARNDCEQGHILKMFPSTWYV'] + ['end']
        amino_to_ix = {aa: index for index, aa in enumerate(amino_acids)}
        # P[i, j] = p(j | i) stochastic transition matrix as in markov models
        P = np.zeros([22, 22])
        for line in data:
            if c == 'tcr':
                t = line.strip().split()[0]
            if c == 'pep':
                t = line.strip().split()[1]
            if '*' in t or '*' in t:
                continue
            if '/' in t:
                continue
            # REMOVE INITIAL 'CAS' AND 'F' SUFFIX
            t = t[3:-1]
            P[amino_to_ix['start'], amino_to_ix[t[0]]] += 1
            for i in range(len(t) - 1):
                P[amino_to_ix[t[i]], amino_to_ix[t[i+1]]] += 1
            P[amino_to_ix[t[-1]], amino_to_ix['end']] += 1
        P = P.astype('float') / P.sum(axis=1)[:, np.newaxis]
        # for i in range(22)
        print(P)
        plt.matshow(P)
        plt.xticks(range(22), amino_acids)
        plt.yticks(range(22), amino_acids)
        plt.title(title)
        plt.show()
    pass

def amino_corr_map_comp(data1, data2, c, title):
    amino_acids = ['start'] + [letter for letter in 'ARNDCEQGHILKMFPSTWYV'] + ['end']
    amino_to_ix = {aa: index for index, aa in enumerate(amino_acids)}
    # P[i, j] = p(j | i) stochastic transition matrix as in markov models
    with open(data1, 'r') as data:
        P1 = np.zeros([22, 22])
        for line in data:
            if c == 'tcr':
                t = line.strip().split()[0]
            if c == 'pep':
                t = line.strip().split()[1]
            if '*' in t or '*' in t:
                continue
            if '/' in t:
                continue
            # REMOVE INITIAL 'CAS' AND 'F' SUFFIX
            t = t[3:-1]
            P1[amino_to_ix['start'], amino_to_ix[t[0]]] += 1
            for i in range(len(t) - 1):
                P1[amino_to_ix[t[i]], amino_to_ix[t[i+1]]] += 1
            P1[amino_to_ix[t[-1]], amino_to_ix['end']] += 1
        P1 = P1.astype('float') / P1.sum(axis=1)[:, np.newaxis]
        print(P1)
    with open(data2, 'r') as data:
        P2 = np.zeros([22, 22])
        for line in data:
            if c == 'tcr':
                t = line.strip().split()[0]
            if c == 'pep':
                t = line.strip().split()[1]
            if '*' in t or '*' in t:
                continue
            if '/' in t:
                continue
            # REMOVE INITIAL 'CAS' AND 'F' SUFFIX
            t = t[3:-1]
            P2[amino_to_ix['start'], amino_to_ix[t[0]]] += 1
            for i in range(len(t) - 1):
                P2[amino_to_ix[t[i]], amino_to_ix[t[i+1]]] += 1
            P2[amino_to_ix[t[-1]], amino_to_ix['end']] += 1
        P2 = P2.astype('float') / P2.sum(axis=1)[:, np.newaxis]
        print(P2)
    # P = np.log(P1 / P2)
    P = P1 - P2
    plt.matshow(P)
    plt.xticks(range(22), amino_acids)
    plt.yticks(range(22), amino_acids)
    plt.colorbar()
    plt.title(title)
    plt.show()

# amino_corr_map(w, 'tcr', 'Amino acids correlation map in McPAS data')
# amino_corr_map(t, 'tcr', 'Amino acids correlation map in TCRGP data')
# amino_corr_map_comp(w, t, 'tcr', 'Amino acids correlation maps, P1 - P2')

# amino_corr_map(w, 'tcr', 'Amino acids correlation map in McPAS data')
# amino_corr_map(nt, 'tcr', 'Amino acids correlation map in TCRGP data')
# amino_corr_map_comp(w, nt, 'tcr', 'Amino acids correlation maps difference')

def amino_acids_distribution(data1, data2, title, normalize=False):
    amino_acids = [letter for letter in 'ARNDCEQGHILKMFPSTWYV']
    with open(data2, 'r') as data:
        amino_count2 = {aa: 0 for aa in amino_acids}
        for line in data:
            t = line.strip().split()[0]
            if '*' in t or '*' in t:
                continue
            if '/' in t:
                continue
            for aa in t:
                amino_count2[aa] += 1
    with open(data1, 'r') as data:
        amino_count1 = {aa: 0 for aa in amino_acids}
        for line in data:
            t = line.strip().split()[0]
            if '*' in t or '*' in t:
                continue
            if '/' in t:
                continue
            for aa in t:
                amino_count1[aa] += 1
    x = np.arange(len(amino_acids))
    y1 = [amino_count1[k] for k in amino_acids]
    y2 = [amino_count2[k] for k in amino_acids]
    if normalize:
        y1 = [y/sum(y1) for y in y1]
        y2 = [y/sum(y2) for y in y2]
    fig, ax = plt.subplots()
    width = 0.35
    plot1 = ax.bar([key + width for key in x], y1, width,
                   color='SkyBlue', label='McPAS (Weizmann) data')
    plot2 = ax.bar(x, y2, width,
                   color='IndianRed', label='TCRGP paper data')
    ax.set_ylabel('Number of amino acids')
    ax.set_title(title)
    plt.xticks(x, amino_acids)
    ax.legend()
    plt.show()

# amino_acids_distribution(w, t, 'Animo Acids Distribution')
# amino_acids_distribution(w, t, 'Normalized Animo Acids Distribution', normalize=True)
# amino_acids_distribution(w, nt, 'Normalized Animo Acids Distribution', normalize=True)

def v_gene_dist(data1, data2, title, normalize=False):
    with open(data2, 'r') as data:
        v_count2 = {}
        for line in data:
            v = line.strip().split()[1]
            #if '*' in t or '*' in t:
            #    continue
            #if '/' in t:
            #    continue
            try:
                v_count2[v] += 1
            except KeyError:
                v_count2[v] = 1
    '''
    with open(data1, 'r') as data:
        amino_count1 = {aa: 0 for aa in amino_acids}
        for line in data:
            t = line.strip().split()[0]
            if '*' in t or '*' in t:
                continue
            if '/' in t:
                continue
            for aa in t:
                amino_count1[aa] += 1
    '''
    print(v_count2)
    x = np.arange(len(v_count2))
    y1 = [amino_count1[k] for k in amino_acids]
    y2 = [amino_count2[k] for k in amino_acids]
    if normalize:
        y1 = [y/sum(y1) for y in y1]
        y2 = [y/sum(y2) for y in y2]
    fig, ax = plt.subplots()
    width = 0.35
    plot1 = ax.bar([key + width for key in x], y1, width,
                   color='SkyBlue', label='McPAS (Weizmann) data')
    plot2 = ax.bar(x, y2, width,
                   color='IndianRed', label='TCRGP paper data')
    ax.set_ylabel('Number of amino acids')
    ax.set_title(title)
    plt.xticks(x, amino_acids)
    ax.legend()
    plt.show()
    pass

def avg_kidera_score(datafile):
    with open(datafile, 'r') as data:
        index = 0
        avg = np.zeros((10))
        for line in data:
            line = line.split('\t')
            tcr = line[0]
            tcr = tcr[3:-1]
            v = kidera.score_sequence(tcr)
            v = v.values
            avg += v
            index += 1
    avg /= index
    return avg

def plot_kidera():
    w_avg = avg_kidera_score(w)
    nt_avg = avg_kidera_score(nt)
    print('weizmann avg:', w_avg)
    print('TCRGP avg:', nt_avg)
    x = np.arange(10)
    fig, ax = plt.subplots()
    width = 0.35
    plot1 = ax.bar([t + width for t in x], w_avg, width,
                   color='SkyBlue', label='McPAS (Weizmann) data')
    plot2 = ax.bar(x, nt_avg, width,
                   color='IndianRed', label='TCRGP paper data')
    ax.set_ylabel('Average Kidera score')
    ax.set_title('Average Kidera Score')
    ax.set_xticks(x)
    ax.set_xlabel('Kidera factor')
    ax.legend()
    plt.show()

# plot_kidera()

def kidera_hist(data1, data2):
    factor_observations1 = [[] for i in range(10)]
    with open(data1, 'r') as data:
        for line in data:
            line = line.split('\t')
            tcr = line[0]
            tcr = tcr[3:-1]
            v = kidera.score_sequence(tcr)
            v = v.values
            for i in range(len(v)):
                factor_observations1[i].append(v[i])
    factor_observations2 = [[] for i in range(10)]
    with open(data2, 'r') as data:
        for line in data:
            line = line.split('\t')
            tcr = line[0]
            tcr = tcr[3:-1]
            v = kidera.score_sequence(tcr)
            v = v.values
            for i in range(len(v)):
                factor_observations2[i].append(v[i])
    for i in range(len(factor_observations1)):
        fig, ax = plt.subplots()
        a = factor_observations1[i]
        b = factor_observations2[i]
        weights1 = np.ones_like(a) / float(len(a))
        weights2 = np.ones_like(b) / float(len(b))
        bins = np.linspace(-1.0, 1.0, 10)
        plot1 = ax.hist(a, weights=weights1, bins=bins,
                       color='SkyBlue', alpha=0.5, label='McPAS (Weizmann) data')
        plot2 = ax.hist(b, weights=weights2, bins=bins,
                       color='IndianRed', alpha=0.5, label='TCRGP paper data')
        #ax.set_ylabel('Number of TCRs')
        ax.set_title('Kidera ' + str(i+1) + ' factor normalized histogram')
        #ax.set_xticks(x1)
        ax.legend()
        # plt.show()
        plt.savefig('stats_compare_plots/kidera_factors/kidera_bins10_' + str(i+1))

# kidera_hist(w, nt)


from pontu_tools import *

if __name__ == '__main__':
  agent0 = "human_agent"
  agent1 = "human_agent"

  initial_state = PontuState()
  agent0 = getattr(__import__(agent0), 'MyAgent')()
  agent0.set_id(0)
  agent1 = getattr(__import__(agent1), 'MyAgent')()
  agent1.set_id(1)
  res = make_match(initial_state, [agent0, agent1], None, True, None)
  print(res)


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

# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import print_function

from abc import abstractmethod, ABC
from enum import Enum

class PropertyConstraint(object):
    """
    PropertyConstraint's class definition

    The user can specify a constraint acting only
    on properties too. The MOCServer asks for an
    algebraic expression dealing with properties.
    Example : a user can ask the MOCServer all datasets
    having the word CDS(Center of astronomical Data of
    Strasbourg) in its ID property or/and a moc_sky_fraction
    < 1 %

    """

    def __init__(self, expression):
        """
        PropertyConstraint's constructor

        :param expression:
            can be a PropertiesExpr or a string
        """

        if not isinstance(expression, PropertiesExpr) and not isinstance(expression, str):
            raise TypeError

        self.expr = expression
        self.request_payload = dict()
        self.compute_payload()

    def compute_payload(self):
        """Update the property constraints payload"""
        if isinstance(self.expr, str):
            self.request_payload = {'expr': self.expr}
        else:
            self.request_payload = {'expr': self.expr.eval()}

    def __repr__(self):
        result = "Properties constraints' request payload :\n{0}".format(self.request_payload)
        return result

class OperandExpr(Enum):
    """Operand Enum which allow the user to define relationship between expr"""
    Inter = 1,
    Union = 2,
    Subtr = 3

class PropertiesExpr(ABC):
    """
    General expression interface

    Expressions are built like a binary tree. A parent expression can
    have one or two children. The parent defines an operand between
    its two children (if it is a ParentNode) or nothing in
    the other case (only one child).

    """

    @abstractmethod
    def eval(self):
        """
        Evaluate recursively the whole expression

        Returns a str understandable by the MOCServer
        """

        pass

class ChildNode(PropertiesExpr):
    """Leaf expression node of the binary tree expression"""

    def __init__(self, condition):
        assert condition is not None
        self.condition = condition

    def eval(self):
        return str(self.condition)

class ParentNode(PropertiesExpr):
    """Parent expression node of the binary tree expression"""

    def __init__(self, operand, left_expr, right_expr):
        if not isinstance(right_expr, PropertiesExpr) or not isinstance(left_expr, PropertiesExpr):
            raise TypeError

        if operand not in (OperandExpr.Inter, OperandExpr.Union, OperandExpr.Subtr):
            raise TypeError

        self.left_expr = left_expr
        self.right_expr = right_expr
        self.operand = operand

    def eval(self):
        left_expr_str = str(self.left_expr.eval())
        right_expr_str = str(self.right_expr.eval())

        operand_str = " &! "
        if self.operand is OperandExpr.Inter:
            operand_str = " && "
        elif self.operand is OperandExpr.Union:
            operand_str = " || "

        if isinstance(self.left_expr, ParentNode):
            left_expr_str = '(' + left_expr_str + ')'
        if isinstance(self.right_expr, ParentNode):
            right_expr_str = '(' + right_expr_str + ')'

        return left_expr_str + operand_str + right_expr_str


alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
spec_char = [' ','1','2','3','4','5','6','7','8','9','0','!','?','/','@','#','$','%','^','&','*','(',')','-','_','[',']','{','}','|',',','.','<','>']

def encrypt():
    new = ''
    for i in message:
        if i in spec_char:
            new = new + spec_char[spec_char.index(i)]
        elif alphabet.index(i)+key > len(alphabet)-1:
            overflow = alphabet.index(i)+key-25
            new = new+alphabet[overflow-1]
        else:
            new = new + alphabet[alphabet.index(i)+key]
    print(new)

def decrypt():
    new = ''
    for i in message:
        if i in spec_char:
            new = new + spec_char[spec_char.index(i)]
        else:
            new = new + alphabet[alphabet.index(i)-key]
    print(new)

running = True
while running:
    mode = input("would you like to encrypt or decrypt? (e/d) - ")

    key = int(input("which key would you like your cypher to use? (1-9) - "))

    message = input("enter a message to decrypt/encrypt - ").lower()

    if mode == 'e':
        encrypt()
    else:
        decrypt()

    cont = input("would you like to encrypt/decrypt again? (y/n) - ")
    if cont == 'y':
        pass
    else:
        running = False


import os
import factsbeach

from setuptools import setup, find_packages

here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()

requires = []

with open('requirements.txt') as f:
    requires = f.read().splitlines()

setup(name='Factsbeach',
      version=factsbeach.__version__,
      description='Factsbeach',
      long_description=README + '\n\n' + CHANGES,
      classifiers=[
        "Programming Language :: Python",
        "Framework :: Pyramid",
        "Topic :: Internet :: WWW/HTTP",
        "Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
        ],
      author='',
      author_email='',
      url='',
      keywords='factsbeach pyaella',
      packages=find_packages(),
      include_package_data=True,
      package_data={'':[
          '*.mako', '*.yaml', '*.csv',
          '*.sql', '*.css', '*.sass',
          '*.js', '*.rb', '*.txt'
      ]},
      zip_safe=False,
      install_requires=requires,
      tests_require=requires,
      test_suite="factsbeach",
      entry_points="""      [paste.app_factory]
      main = pyaella.server.instance:main
      """,
      )


#Time :O(N)
#Space: O(1)
#Linkedlist
# https://leetcode.com/problems/palindrome-linked-list/
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        if not head.next:
            return True
        p1,p2 = head,head.next
        val1 = 0

        while p2 and p2.next:
            val1 =val1*10+p1.val
            p1 = p1.next
            p2 = p2.next.next
        if p2:
            val1=val1*10+p1.val
        p1 = p1.next
        val2=  0
        mult=1
        while p1:
            val2 = p1.val*mult+val2
            p1 = p1.next
            mult*=10
        return val1 == val2


from pages.base_page import Page
from selenium.webdriver.common.by import By
from time import sleep

class CartPage(Page):

    MINUS_BUTTON = (By.CSS_SELECTOR, "button[name='minus']")
    EMPTY_CART_TEXT = (By.CSS_SELECTOR, "h2.cart__empty-text")

    def click_on_minus_button(self):
        self.click(*self.MINUS_BUTTON)
        sleep(5)

    def verify_cart_is_empty(self):
        self.verify_text('Your cart is currently empty', *self.EMPTY_CART_TEXT)


import pymc3 as mc
from numpy import random, dot, array, inf
import theano

class PyFBU(object):
    """A class to perform a MCMC sampling.

    [more detailed description should be added here]

    All configurable parameters are set to some default value, which
    can be changed later on, but before calling the `run` method.
    """
    #__________________________________________________________
    def __init__(self,data=[],response=[],background={},
                 backgroundsyst={},objsyst={'signal':{},'background':{}},
                 lower=[],upper=[],regularization=None,
                 rndseed=-1,verbose=False,name='',monitoring=False):
        #                                     [MCMC parameters]
        self.nTune = 1000
        self.nMCMC = 10000 # N of sampling points
        self.nCores = 1 # number of CPU threads to utilize
        self.nChains = 2 # number of Markov chains to sample
        self.nuts_kwargs = None
        self.discard_tuned_samples = True # whether to discard tuning steps from posterior
        self.lower = lower  # lower sampling bounds
        self.upper = upper  # upper sampling bounds
        #                                     [unfolding model parameters]
        self.prior = 'DiscreteUniform'
        self.priorparams = {}
        self.regularization = regularization
        #                                     [input]
        self.data        = data           # data list
        self.response    = response       # response matrix
        self.background  = background     # background dict
        self.backgroundsyst = backgroundsyst
        self.objsyst        = objsyst
        self.systfixsigma = 0.
        #                                     [settings]
        self.rndseed   = rndseed
        self.verbose   = verbose
        self.name      = name
        self.monitoring = monitoring
        self.sampling_progressbar = True

    #__________________________________________________________
    def validateinput(self):
        def checklen(list1,list2):
            assert len(list1)==len(list2), 'Input Validation Error: inconstistent size of input'
        responsetruthbins = self.response
        responserecobins = [row for row in self.response]
        for bin in list(self.background.values())+responserecobins:
            checklen(self.data,bin)
        for bin in [self.lower,self.upper]:
            checklen(bin,responsetruthbins)
    #__________________________________________________________
    def fluctuate(self, data):
        random.seed(self.rndseed)
        return random.poisson(data)
    #__________________________________________________________
    def run(self):
        self.validateinput()
        data = self.data
        data = self.fluctuate(data) if self.rndseed>=0 else data

        # unpack background dictionaries
        backgroundkeys = self.backgroundsyst.keys()
        nbckg = len(backgroundkeys)

        backgrounds = []
        if nbckg>0:
            backgrounds = array([self.background[key] for key in backgroundkeys])
            backgroundnormsysts = array([self.backgroundsyst[key] for key in backgroundkeys])

        # unpack object systematics dictionary
        objsystkeys = self.objsyst['signal'].keys()
        nobjsyst = len(objsystkeys)
        if nobjsyst>0:
            signalobjsysts = array([self.objsyst['signal'][key] for key in objsystkeys])
            if nbckg>0:
                backgroundobjsysts = array([])
                backgroundobjsysts = array([[self.objsyst['background'][syst][bckg]
                                             for syst in objsystkeys]
                                            for bckg in backgroundkeys])

        recodim  = len(data)
        resmat = self.response
        truthdim = len(resmat)

        model = mc.Model()
        from .priors import wrapper
        with model:
            truth = wrapper(priorname=self.prior,
                            low=self.lower,up=self.upper,
                            other_args=self.priorparams)

            if nbckg>0:
                bckgnuisances = []
                for name,err in zip(backgroundkeys,backgroundnormsysts):
                    if err<0.:
                        bckgnuisances.append(
                            mc.Uniform('norm_%s'%name,lower=0.,upper=3.)
                            )
                    else:
                        BoundedNormal = mc.Bound(mc.Normal, lower=(-1.0/err if err>0.0 else -inf))
                        bckgnuisances.append(
                            BoundedNormal('gaus_%s'%name,
                                          mu=0.,tau=1.0)
                            )
                bckgnuisances = mc.math.stack(bckgnuisances)

            if nobjsyst>0:
                objnuisances = [ mc.Normal('gaus_%s'%name,mu=0.,tau=1.0#,
                                           #observed=(True if self.systfixsigma!=0 else False)
                                           )
                                 for name in objsystkeys]
                objnuisances = mc.math.stack(objnuisances)

        # define potential to constrain truth spectrum
            if self.regularization:
                truthpot = self.regularization.getpotential(truth)

        #This is where the FBU method is actually implemented
            def unfold():
                smearbckg = 1.
                if nbckg>0:
                    bckgnormerr = [(-1.+nuis)/nuis if berr<0. else berr
                                         for berr,nuis in zip(backgroundnormsysts,bckgnuisances)]
                    bckgnormerr = mc.math.stack(bckgnormerr)

                    smearedbackgrounds = backgrounds
                    if nobjsyst>0:
                        smearbckg = smearbckg + theano.dot(objnuisances,backgroundobjsysts)
                        smearedbackgrounds = backgrounds*smearbckg

                    bckg = theano.dot(1. + bckgnuisances*bckgnormerr,smearedbackgrounds)

                tresmat = array(resmat)
                reco = theano.dot(truth, tresmat)
                out = reco
                if nobjsyst>0:
                    smear = 1. + theano.dot(objnuisances,signalobjsysts)
                    out = reco*smear
                if nbckg>0:
                    out = bckg + out
                return out

            unfolded = mc.Poisson('unfolded', mu=unfold(),
                                  observed=array(data))

            import time
            from datetime import timedelta
            init_time = time.time()
            trace = mc.sample(self.nMCMC,tune=self.nTune,cores=self.nCores,
                              chains=self.nChains, nuts_kwargs=self.nuts_kwargs,
                              discard_tuned_samples=self.discard_tuned_samples,
                              progressbar=self.sampling_progressbar)
            finish_time = time.time()
            print('Elapsed {0} ({1:.2f} samples/second)'.format(
                str(timedelta(seconds=(finish_time-init_time))).split('.')[0],
                (self.nMCMC+self.nTune)*self.nChains/(finish_time-init_time)
            ))

            self.trace = [trace['truth%d'%bin][:] for bin in range(truthdim)]
            self.nuisancestrace = {}
            if nbckg>0:
                for name,err in zip(backgroundkeys,backgroundnormsysts):
                    if err<0.:
                        self.nuisancestrace[name] = trace['norm_%s'%name][:]
                    if err>0.:
                        self.nuisancestrace[name] = trace['gaus_%s'%name][:]
            for name in objsystkeys:
                if self.systfixsigma==0.:
                    self.nuisancestrace[name] = trace['gaus_%s'%name][:]

        if self.monitoring:
            from fbu import monitoring
            monitoring.plot(self.name+'_monitoring',data,backgrounds,resmat,self.trace,
                            self.nuisancestrace,self.lower,self.upper)


# -*- coding:utf-8 -*-
# asdfqwer - fqwerasd

class Solution:
    def LeftRotateString(self, s, n):
        # write code here
        if not s:
            return s
        for i in range(n):
            s += s[i]
        s = s[n:]
        return s