# -*- coding: utf-8 -*-
import os
from zope.interface import implements

from iol.gisweb.pieveligure.interfaces import IIolApp,IIolPraticaWeb

from AccessControl import ClassSecurityInfo
import simplejson as json

from DateTime import DateTime

from base64 import b64encode

from iol.gisweb.utils.config import USER_CREDITABLE_FIELD,USER_UNIQUE_FIELD,IOL_APPS_FIELD,STATUS_FIELD,IOL_NUM_FIELD
from iol.gisweb.utils.IolDocument import IolDocument
from iol.gisweb.utils import loadJsonFile,dateEncoder

class sciaApp(object):
    implements(IIolApp)
    security = ClassSecurityInfo()
    def __init__(self):
        self.file = 'scia'
        self.path = os.path.dirname(os.path.abspath(__file__))

    #Returns new number
    security.declarePublic('NuovoNumeroPratica')

    def NuovoNumeroPratica(self, obj):
        idx = obj.getParentDatabase().getIndex()
        query = dict(IOL_NUM_FIELD=dict(query=0, range='min'), iol_tipo_app='scia')

        brains = idx.dbsearch(query, sortindex=IOL_NUM_FIELD, reverse=1, only_allowed=False)
        if not brains:
            nuovoNumero = 1
        else:
            nuovoNumero = (brains[0].getObject().getItem(IOL_NUM_FIELD,0) or 0) +1

        return nuovoNumero

class sciaWsClient(object):
    implements(IIolPraticaWeb)
    security = ClassSecurityInfo()

    def __init__(self):
        self.resp_proc = 24
        self.file = 'scia'
        self.path = os.path.dirname(os.path.abspath(__file__))
        self.mapping = loadJsonFile("%s/mapping/%s.json" % (self.path,self.file)).result
        self.elenchi = loadJsonFile("%s/mapping/elenchi.json" % (self.path)).result

    security.declarePublic('getProcedimento')

    def getProcedimento(self, obj):
        doc = obj.document
        idoc = IolDocument(doc)
        pr = obj.client.factory.create('procedimento')
        if doc.getItem('data_inizio_lavori_opt','scia_data_inizio_presentazione')=='scia_data_inizio_presentazione':
            pr.tipo = 21100
        else:
            pr.tipo = 21200
        pr.oggetto = doc.getItem('descrizione_intervento','')
        pr.note = '\n'.join(idoc.getLabels('tipologia_intervento'))
        pr.protocollo = doc.getItem('numero_protocollo','')
        pr.data_prot = doc.getItem('data_prot',DateTime()).strftime("%d/%m/%Y")
        pr.data_presentazione = doc.getItem('data_presentazione',DateTime().strftime("%d/%m/%Y"))
        pr.online = 1
        pr.resp_proc = self.resp_proc
        pr.data_resp = DateTime().strftime("%d/%m/%Y")
        return pr

    def getSoggetti(self, obj):
        doc = obj.document
        idoc = IolDocument(doc)
        soggetti = list()
        ruoli = ['richiedente','proprietario','progettista','direttore','esecutore']
        # Recupero informazioni sui richiedenti/proprietari
        soggetto = obj.client.factory.create('soggetto')
        for i in ruoli:
            soggetto[i] = 0;
        mapfields = self.mapping['richiedente']
        for k, v in mapfields.items():
            if v:
                soggetto[k] = json.dumps(doc.getItem(v,None), cls=dateEncoder, use_decimal=True)

        soggetto['richiedente'] = 1
        soggetto['comunicazioni'] = 1
        if soggetto['sesso'] == 'Maschile':
            soggetto['sesso'] = 'M'
        else:
            soggetto['sesso'] = 'F'
        # Il richiedente è anche proprietario
        if doc.getItem('fisica_titolo', '').lower() == 'proprietario':
            soggetto['proprietario'] = 1
        soggetti.append(soggetto)
        for r in idoc.getDatagridValue('anagrafica_soggetti'):
            soggetto = obj.client.factory.create('soggetto')
            for i in ruoli:
                soggetto[i] = 0;
            for k, v in mapfields.items():
                if v:
                    if v in r.keys():
                        soggetto[k] = r[v]
                    else:
                        soggetto[k] = ''
            soggetto['richiedente'] = 1
            soggetto['comunicazioni'] = 1
            if soggetto['sesso'] == 'Maschile':
                soggetto['sesso'] = 'M'
            else:
                soggetto['sesso'] = 'F'
            # Il richiedente è anche proprietario
            if 'fisica_titolo' in r.keys():
                titolo = r['fisica_titolo']
            else:
                titolo = ''
            if titolo.lower() == 'proprietario':
                soggetto['proprietario'] = 1
            soggetti.append(soggetto)

        # Recupero informazioni sul progettista
        soggetto = obj.client.factory.create('soggetto')
        for i in ruoli:
            soggetto[i] = 0;
        mapfields = self.mapping['progettista']
        for k, v in mapfields.items():
            if v:
                value = doc.getItem(v,None)
                if isinstance(value,DateTime):
                    soggetto[k] = value.strftime("%d/%m/%Y")
                else:
                    soggetto[k] = value

        soggetto['progettista'] = 1
        soggetto['comunicazioni'] = 1
        if soggetto['sesso'] == 'Maschile':
            soggetto['sesso'] = 'M'
        else:
            soggetto['sesso'] = 'F'

        direttore = doc.getItem('direttore_opt','nodirettore')
        if direttore == 'direttoreesecutore':
            soggetto['direttore'] = 1
        soggetti.append(soggetto)
        # Il progettista è anche direttore lavori
        # Recupero informazioni sul direttore lavori

        if direttore == 'direttore':
            soggetto = obj.client.factory.create('soggetto')
            for i in ruoli:
                soggetto[i] = 0;
            mapfields = self.mapping['direttore']
            for k, v in mapfields.items():
                if v:
                    soggetto[k] = json.dumps(doc.getItem(v,None), cls=dateEncoder, use_decimal=True)
            soggetto['direttore'] = 1
            soggetto['comunicazioni'] = 1
            if soggetto['sesso'] == 'Maschile':
                soggetto['sesso'] = 'M'
            else:
                soggetto['sesso'] = 'F'
            soggetti.append(soggetto)

        # Recupero informazioni sugli esecutori se necessario
        if doc.getItem('lavori_economia_opt','economia'):
            pass
        else:
            soggetto = obj.client.factory.create('soggetto')
            for i in ruoli:
                soggetto[i] = 0;
            mapfields = self.mapping['esecutore']
            for k, v in mapfields.items():
                if v:
                    soggetto[k] = json.dumps(doc.getItem(v,None), cls=dateEncoder, use_decimal=True)

            soggetto['esecutore'] = 1
            soggetto['comunicazioni'] = 1
            if soggetto['sesso'] == 'Maschile':
                soggetto['sesso'] = 'M'
            else:
                soggetto['sesso'] = 'F'

            soggetti.append(soggetto)
            for r in idoc.getDatagridValue('altri_esecutori'):
                soggetto = obj.client.factory.create('soggetto')
                for i in ruoli:
                    soggetto[i] = 0;
                for k, v in mapfields.items():
                    if v:
                        if v in r.keys():
                            soggetto[k] = r[v]
                        else:
                            soggetto[k] = ''
                soggetto['esecutore'] = 1
                soggetto['comunicazioni'] = 1
                if soggetto['sesso'] == 'Maschile':
                    soggetto['sesso'] = 'M'
                else:
                    soggetto['sesso'] = 'F'
                soggetti.append(soggetto)
        return soggetti

    def getIndirizzi(self, obj):
        doc = obj.document
        idoc = IolDocument(doc)
        results = list()
        elencoVie = dict()
        vie = obj.client.service.elencoVie()[2]
        for via in vie:
            elencoVie[str(via.value)] = str(via.label)

        mapfields = self.mapping['indirizzo']
        for r in idoc.getDatagridValue('elenco_civici'):
            fType = obj.client.factory.create('indirizzo')
            for k, v in mapfields.items():
                if v:
                    if k == 'via':
                        fType[k] = elencoVie[r[v]]
                    else:
                        fType[k] = r[v]
            results.append(fType)
        return results

    def getNCT(self, obj):
        doc = obj.document
        idoc = IolDocument(doc)
        results = list()
        mapfields = self.mapping['nct']
        for r in idoc.getDatagridValue('elenco_nct'):
            fType = obj.client.factory.create('particella')
            for k, v in mapfields.items():
                if v:
                    fType[k] = r[v]
            results.append(fType)
        return results

    def getNCEU(self, obj):
        doc = obj.document
        idoc = IolDocument(doc)
        results = list()
        mapfields = self.mapping['nceu']
        for r in idoc.getDatagridValue('elenco_nceu'):
            fType = obj.client.factory.create('particella')
            for k, v in mapfields.items():
                if v:
                    fType[k] = r[v]
            results.append(fType)
        return results

    def getAllegati(self, obj):
        doc = obj.document
        idoc = IolDocument(doc)
        results = list()
        mapfields = self.mapping['allegato']
        for k, v in mapfields.items():
            allegato = obj.client.factory.create('allegato')
            files_allegati = list()
            for el in v:
                f = idoc.getAttachmentInfo(el)
                if f:
                    for info in f:
                        file_allegato = obj.client.factory.create('file_allegato')
                        file_allegato.nome_file = info['name']
                        file_allegato.tipo_file = info['mimetype']
                        file_allegato.size_file = info['size']
                        #file_allegato.file = ''
                        file_allegato.file = info['b64file']
                        files_allegati.append(file_allegato)
                allegato.documento = k
                allegato.allegato = 1
                allegato.files = files_allegati
            if allegato.files and allegato.documento:
                results.append(allegato)
        return results

    def getProgetto(self,obj):
        doc = obj.document
        progetto = obj.client.factory.create('progetto')
        dval = doc.getItem('immobile_destinazione', '')
        progetto.destuso1 = self.elenchi['destuso'][dval]
        return progetto


import logging

from rq.timeouts import JobTimeoutException

from django.conf import settings
from django.db import connection

from django_push.subscriber.models import Subscription

from ..tasks import raven, enqueue

logger = logging.getLogger('feedupdater')

@raven
def update_feed(feed_url, use_etags=True):
    from .models import UniqueFeed
    try:
        UniqueFeed.objects.update_feed(feed_url, use_etags)
    except JobTimeoutException:
        feed = UniqueFeed.objects.get(url=feed_url)
        feed.backoff()
        feed.save()
        logger.info("Job timed out, backing off %s to %s" % (
            feed.url, feed.backoff_factor,
        ))
    close_connection()

@raven
def read_later(entry_pk):
    from .models import Entry  # circular imports
    Entry.objects.get(pk=entry_pk).read_later()
    close_connection()

@raven
def update_unique_feed(feed_url):
    from .models import UniqueFeed, Feed
    feed, created = UniqueFeed.objects.get_or_create(
        url=feed_url,
        defaults={'subscribers': 1},
    )
    if created:
        enqueue(update_favicon, args=[feed_url], queue='high')
    else:
        feed.subscribers = Feed.objects.filter(url=feed_url).count()
        feed.save(update_fields=['subscribers'])

@raven
def update_favicon(feed_url):
    from .models import Favicon
    Favicon.objects.update_favicon(feed_url)

@raven
def subscribe(topic_url, hub_url):
    Subscription.objects.subscribe(topic_url, hub_url)

def close_connection():
    """Close the connection only if not in eager mode"""
    if hasattr(settings, 'RQ'):
        if not settings.RQ.get('eager', False):
            connection.close()


from os.path import dirname
from random import shuffle

from shared.utils import load
from classification.knn import KNearestNeighbors
from shared.utils import mode

directory = dirname(__file__) + '/'

# labels are loaded manually since the data file doesn't include them
labels = [
    'class',
    'cap-shape',
    'cap-surface',
    'cap-color',
    'bruises',
    'odor',
    'gill-attachment',
    'gill-spacing',
    'gill-size',
    'gill-color',
    'stalk-shape',
    'stalk-root',
    'stalk-surface-above-ring',
    'stalk-surface-below-ring',
    'stalk-color-above-ring',
    'stalk-color-below-ring',
    'veil-type',
    'veil-color',
    'ring-number',
    'ring-type',
    'spore-print-color',
    'population',
    'habitat'
]

# load iris data
with open(directory + 'datasets/agaricus-lepiotadata.txt', 'r') as csv_file:
    dataset = load(csv_file, labels=labels)

shuffle(dataset)
test_set = dataset[:len(dataset)//4]  # use 25% for test set
training_set = dataset[len(dataset)//4:]

bad_predictions = 0

# test every datapoint in the test set
for datapoint in test_set:
    neighbors = KNearestNeighbors.neighbors(k=3, unknown_datapoint=datapoint, dataset=training_set, ignored=['class'])
    if datapoint['class'] != mode(neighbors, 'class'):
        print('bad prediction')
        bad_predictions += 1

success_rate = (len(test_set)-bad_predictions)/len(test_set)
print('predicted ' + str(success_rate) + ' correctly')


import tensorflow as tf
tf.enable_eager_execution()

def l2diff(x1, x2):
    """
    standard euclidean norm
    """
    return tf.math.sqrt(tf.cast(tf.reduce_sum((x1 - x2) ** 2), "float32"))

def moment_diff(sx1, sx2, k):
    """
    difference between moments
    """
    print(sx1, sx2)
    ss1 = tf.reduce_mean(sx1 * tf.cast(k, 'int32'), 0)
    ss2 = tf.reduce_mean(sx2 * tf.cast(k, 'int32'), 0)
    return l2diff(ss1, ss2)

def gaussian_kernel(x1, x2, beta=1.0):
    r = x1.dimshuffle(0, 'x', 1)
    return tf.exp(-beta * tf.square(r - x2).sum(axis=-1))

class Distance(object):
    def __init__(self, distance_name="cmd", beta=1.0):
        if distance_name == "cmd":
            self.distance = self.cmd
        elif distance_name == "mmd":
            self.distance = self.mmd
            self.beta = beta
        elif distance_name == "coral":
            self.coral = self.mmd

    def cmd(self, x1, x2, n_moments=5):
        mx1 = tf.reduce_mean(x1, 0)
        mx2 = tf.reduce_mean(x2, 0)
        sx1 = x1 - mx1
        sx2 = x2 - mx2
        dm = l2diff(mx1, mx2)
        for i in range(n_moments - 1):
            dm += moment_diff(sx1, sx2, i + 2)
        return dm

    def mmd(self, x1, x2):
        x1x1 = gaussian_kernel(x1, x1, beta=self.beta)
        x1x2 = gaussian_kernel(x1, x2, beta=self.beta)
        x2x2 = gaussian_kernel(x2, x2, beta=self.beta)
        diff = x1x1.mean() - 2 * x1x2.mean() + x2x2.mean()
        return diff

    def coral(self, x1, x2):
        c1 = 1. / (x1.shape[0] - 1) * (tf.tensordot(tf.transpose(x1), x1) -
                                       tf.tensordot(tf.transpose(x1.mean(axis=0)), x1.sum(axis=0)))
        c2 = 1. / (x2.shape[0] - 1) * (tf.tensordot(tf.transpose(x2), x2) -
                                       tf.tensordot(tf.transpose(x2.mean(axis=0)), x2.sum(axis=0)))
        return 1. / (4 * x1.shape[0] ** 2) * ((c1 - c2) ** 2).sum()

if __name__ == '__main__':
    dist = Distance("coral")
    a = tf.constant([[4,2,3,4], [1,2,3,4]])
    b = tf.constant([[2,2,3,4], [2,2,3,4]])
    print(dist.distance(a, b))


from urllib.parse import unquote

from docutils import nodes
from docutils.parsers.rst import directives
from sphinx import addnodes
from sphinx.util.docutils import SphinxDirective

def setup_link_button(app):
    app.add_directive("link-button", LinkButton)

class LinkButton(SphinxDirective):
    """A directive to turn a link into a button."""

    has_content = False
    required_arguments = 1
    option_spec = {
        "type": lambda arg: directives.choice(arg, ("url", "ref")),
        "text": directives.unchanged,
        "tooltip": directives.unchanged,
        "classes": directives.unchanged,
    }

    def run(self):

        uri = self.arguments[0]
        link_type = self.options.get("type", "url")

        text = self.options.get("text", uri)
        innernode = nodes.inline("", text)

        if link_type == "ref":
            ref_node = addnodes.pending_xref(
                reftarget=unquote(uri),
                reftype="any",
                # refdoc=self.env.docname,
                refdomain="",
                refexplicit=True,
                refwarn=True,
            )
            innernode["classes"] = ["xref", "any"]
            if "tooltip" in self.options:
                ref_node["title"] = self.options["tooltip"]
        else:
            ref_node = nodes.reference()
            ref_node["refuri"] = uri
            if "tooltip" in self.options:
                ref_node["reftitle"] = self.options["tooltip"]

        self.set_source_info(ref_node)

        ref_node["classes"] = ["sphinx-bs", "btn", "text-wrap"] + self.options.get(
            "classes", ""
        ).split()
        ref_node += innernode
        # sphinx requires that a reference be inside a block element
        container = nodes.paragraph()
        container += ref_node

        return [container]


import torch
import torch.nn as nn
from torchvision import models
from torchsummary import summary
from getdata import GetData
from torch.utils.data import DataLoader
import matplotlib.pyplot as plt

# 冻结网络层的参数
def set_parameter_requires_grad(model, feature_extracting):
    if feature_extracting:
        for param in model.parameters():
            param.required_grad = False

# VGG网络结构定义
class VGG16net(nn.Module):
    def __init__(self, feature_extract = True, num_class = 2):
        super(VGG16net, self).__init__()
        model = models.vgg16(pretrained = False)
        # model = models.vgg16(pretrained = True)
        self.features = model.features
        set_parameter_requires_grad(self.features, feature_extract)
        self.avgpool = model.avgpool
        self.classifier = nn.Sequential(
            # nn.Linear(512 * 7 * 7, 512),
            # nn.ReLU(True),
            # nn.Dropout(),
            # nn.Linear(512, 128),
            # nn.ReLU(True),
            # nn.Dropout(),
            # nn.Linear(128, num_class),

            #
            nn.Linear(512 * 7 * 7, 1024),
            nn.ReLU(),
            nn.Linear(1024, 1024),
            nn.ReLU(),
            nn.Linear(1024, num_class)
        )

    def forward(self, x):
        x = self.features(x)
        x = self.avgpool(x)
        # 改变tensor形状，拉伸成一维
        x = x.view(x.size(0), -1)
        out = self.classifier(x)
        return out

# 画图函数
def plt_image(x_input, y_input, title, xlabel, ylabel):
    plt.plot(x_input, y_input, linewidth=2)
    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.show()

def main():
    # GPU选择
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model = VGG16net().to(device)

    # 关键参数设置
    learning_rate=0.001
    num_epochs = 30
    train_batch_size = 16
    test_batch_size = 16

    # 优化器设置
    criterion = nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(model.classifier.parameters(), lr=learning_rate)

    # 加载数据集
    train_dataset = GetData('./data', 224, 'train')
    test_dataset = GetData('./data', 224, 'test')

    train_loader = DataLoader(train_dataset, batch_size=train_batch_size, shuffle=True)
    test_loader = DataLoader(test_dataset, batch_size=test_batch_size, shuffle=True)

    # 画图需要的参数
    epochs = []
    evaloss = []
    acc = []

    # 打印模型结构
    backbone = summary(model, (3, 224, 224))

    for epoch in range(num_epochs):
        epochs.append(epoch+1)
        # train过程

        total_step = len(train_loader)
        train_epoch_loss = 0
        for i, (images, labels) in enumerate(train_loader):
            # 梯度清零
            optimizer.zero_grad()

            # 加载标签与图片
            images = images.to(device)
            labels = labels.to(device)

            # 前向计算
            output = model(images)
            loss = criterion(output, labels)

            # 反向传播与优化
            loss.backward()
            optimizer.step()

            # 累加每代中所有步数的loss
            train_epoch_loss += loss.item()

            # 打印部分结果
            if (i + 1) % 2 == 0:
                print('Epoch [{}/{}], Step [{}/{}], Loss: {:.5f}'
                    .format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))
            if (i + 1) == total_step:
                epoch_eva_loss = train_epoch_loss / total_step
                evaloss.append(epoch_eva_loss)
                print('Epoch_eva loss is : {:.5f}'.format(epoch_eva_loss))

        # test过程
        model.eval()
        with torch.no_grad():
            correct = 0
            total = 0
            for images, labels in test_loader:
                images = images.to(device)
                labels = labels.to(device)
                output = model(images)
                _, predicted = torch.max(output.data, 1)
                print(predicted)
                total += labels.size(0)
                correct += (predicted == labels).sum().item()
            acc.append(100*(correct/total))
            print('Test Accuracy  {} %'.format(100*(correct/total)))

    # print(model.state_dict())
    torch.save(obj = model.state_dict(), f='model/model.pth')
    # 训练结束后绘图
    plt_image(epochs, evaloss, 'loss', 'Epochs', 'EvaLoss')
    plt_image(epochs, acc, 'ACC', 'Epochs', 'EvaAcc' )
if __name__ == "__main__" :
    main()


import config.package
import os

class Configure(config.package.Package):
  def __init__(self, framework):
    config.package.Package.__init__(self, framework)
    self.includes         = ['mkl.h','mkl_spblas.h']
    self.functions        = ['mkl_sparse_optimize','mkl_sparse_s_create_bsr']
    self.liblist          = [[]] # use MKL detected by BlasLapack.py
    self.precisions       = ['single','double']
    self.lookforbydefault = 1
    self.requires32bitint = 1
    return

  def setupDependencies(self, framework):
    config.package.Package.setupDependencies(self, framework)
    self.blasLapack = framework.require('config.packages.BlasLapack',self)
    self.deps       = [self.blasLapack]
    return

  def checksSupportBaijCrossCase(self):
    '''Determines if MKL Sparse BLAS create routine returns correct status with zero based indexing and columnMajor block layout'''
    includes = '''#include <sys/types.h>\n#if STDC_HEADERS\n#include <stdlib.h>\n#include <stdio.h>\n#include <stddef.h>\n#endif\n#include <mkl.h>'''
    body     = '''sparse_matrix_t A;\n
                  int n=1,ia[1],ja[1];\n
                  float a[1];
                  sparse_status_t status = mkl_sparse_s_create_bsr(&A,SPARSE_INDEX_BASE_ZERO,SPARSE_LAYOUT_COLUMN_MAJOR,n,n,n,ia,ia,ja,a);\n
                  fprintf(output, "  '--known-mklspblas-supports-zero-based=%d',\\n",(status != SPARSE_STATUS_NOT_SUPPORTED));\n
                  '''
    temp1 = self.compilers.LIBS
    temp2 = self.compilers.CPPFLAGS
    self.compilers.LIBS = self.libraries.toString(self.dlib)+' -lm '+self.compilers.LIBS
    self.compilers.CPPFLAGS += ' '+self.headers.toString(self.dinclude)
    result = self.blasLapack.runTimeTest('known-mklspblas-supports-zero-based',includes,body,self.dlib)
    self.compilers.LIBS = temp1
    self.compilers.CPPFLAGS = temp2
    if result:
      self.log.write('Checking for MKL spblas supports zero based indexing: result ' +str(result)+'\n')
      result = int(result)
      if result:
        self.addDefine('MKL_SUPPORTS_BAIJ_ZERO_BASED', 1)
        self.log.write('Found MKL spblas supports zero based indexing: result\n')

  def checkHaveUsableSp2m(self):
    sp2m_test = '#include <mkl_spblas.h>\nsparse_request_t request = SPARSE_STAGE_FULL_MULT_NO_VAL;\n'
    result = self.checkCompile(sp2m_test)
    self.log.write('Looking for mkl_sparse_sp2m() that is usable for MatMatMultSymbolic()/Numeric(): result ' + str(int(result)) + '\n')
    if result:
      # We append _FEATURE at the end to avoid confusion, because some versions of MKL have mkl_sparse_sp2m(), but not a version
      # that is usable for implementing MatMatMultSymbolic()/Numeric().
      self.addDefine('HAVE_MKL_SPARSE_SP2M_FEATURE', 1)

  def checkMklSpblasDeprecated(self):
    # Some versions of MKL use MKL_DEPRECATED and others just use DEPRECATED, so we must check for both.
    deprecated_test1='#include <mkl_spblas.h>\nDEPRECATED void foo();\n'
    deprecated_test2='#include <mkl_spblas.h>\nMKL_DEPRECATED void foo();\n'
    result1 = self.checkCompile(deprecated_test1)
    result2 = self.checkCompile(deprecated_test2)
    result = result1 or result2
    self.log.write('Checking to see if original MKL SpBLAS is declared deprecated: result ' + str(int(result)) + '\n')
    if result:
      self.addDefine('MKL_SPBLAS_DEPRECATED', 1)

  def configureLibrary(self):
    config.package.Package.configureLibrary(self)
    if self.found:
      self.executeTest(self.checksSupportBaijCrossCase)
      self.executeTest(self.checkHaveUsableSp2m)
      self.executeTest(self.checkMklSpblasDeprecated)


"""
Encoding layers (stacked transformers)
"""

import math
import torch
import torch.nn as nn
import model.act_funcs as act

# %% Attention
class SelfAttention(nn.Module):
    def __init__(self, config):
        super(SelfAttention, self).__init__()
        if config.hidden_size % config.num_attention_heads != 0:
            raise ValueError(
                "The hidden size ({}) is not a multiple of the number of attention "
                "heads ({})".format(config.hidden_size, config.num_attention_heads)
            )

        self.num_attention_heads = config.num_attention_heads
        self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
        self.all_head_size = self.num_attention_heads * self.attention_head_size

        self.query = nn.Linear(config.hidden_size, self.all_head_size)
        self.key = nn.Linear(config.hidden_size, self.all_head_size)
        self.value = nn.Linear(config.hidden_size, self.all_head_size)

        self.dropout = nn.Dropout(config.attention_dropout_prob)

    def transpose_for_scores(self, x):
        new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
        x = x.view(*new_x_shape)
        return x.permute(0, 2, 1, 3)

    def forward(self, hidden_states, attention_mask):
        mixed_query_layer = self.query(hidden_states)
        mixed_key_layer = self.key(hidden_states)
        mixed_value_layer = self.value(hidden_states)

        query_layer = self.transpose_for_scores(mixed_query_layer)
        key_layer = self.transpose_for_scores(mixed_key_layer)
        value_layer = self.transpose_for_scores(mixed_value_layer)

        attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
        attention_scores = attention_scores / math.sqrt(self.attention_head_size)
        if attention_mask is not None:
            attention_scores = attention_scores + attention_mask

        attention_probs = nn.Softmax(dim=-1)(attention_scores)
        attention_probs = self.dropout(attention_probs)

        context_layer = torch.matmul(attention_probs, value_layer)

        context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
        new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
        context_layer = context_layer.view(*new_context_layer_shape)
        return context_layer

class SelfOutput(nn.Module):
    def __init__(self, config):
        super(SelfOutput, self).__init__()
        self.dense = nn.Linear(config.hidden_size, config.hidden_size)
        self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)

    def forward(self, hidden_states, input_tensor):
        hidden_states = self.dense(hidden_states)
        hidden_states = self.dropout(hidden_states)
        hidden_states = self.LayerNorm(hidden_states + input_tensor)
        return hidden_states

class Attention(nn.Module):
    def __init__(self, config):
        super(Attention, self).__init__()
        self.self = SelfAttention(config)
        self.output = SelfOutput(config)

    def forward(self, hidden_states, attention_mask):
        self_outputs = self.self(hidden_states, attention_mask)
        attention_output = self.output(self_outputs, hidden_states)
        return attention_output

# %% Intermediate
class Intermediate(nn.Module):
    def __init__(self, config):
        super(Intermediate, self).__init__()
        self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
        self.intermediate_act_fn = act.ACT_FCN[config.hidden_act]

    def forward(self, hidden_states):
        hidden_states = self.dense(hidden_states)
        hidden_states = self.intermediate_act_fn(hidden_states)
        return hidden_states

# %% Output
class Output(nn.Module):
    def __init__(self, config):
        super(Output, self).__init__()
        self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
        self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
        self.dropout = nn.Dropout(config.hidden_dropout_prob)

    def forward(self, hidden_states, input_tensor):
        hidden_states = self.dense(hidden_states)
        hidden_states = self.dropout(hidden_states)
        hidden_states = self.LayerNorm(hidden_states + input_tensor)
        return hidden_states

# %% Overall Layers
class Layer(nn.Module):
    def __init__(self, config):
        super(Layer, self).__init__()
        self.attention = Attention(config)
        self.intermediate = Intermediate(config)
        self.output = Output(config)

    def forward(self, hidden_states, attention_mask):
        attention_output = self.attention(hidden_states, attention_mask)
        intermediate_output = self.intermediate(attention_output)
        layer_output = self.output(intermediate_output, attention_output)
        return layer_output

class Encoder(nn.Module):
    def __init__(self, config):
        super(Encoder, self).__init__()
        self.layer = nn.ModuleList([Layer(config) for _ in range(config.num_encoder_layers)])
        self.num_encoder_layers = config.num_encoder_layers
        self.attn_dist = config.attention_distance
        self.attn_step = config.attention_step

    def forward(self, embedded_states, dist_matrix):
        encoded_states = embedded_states
        for i in range(self.num_encoder_layers):
            attention_mask = (dist_matrix > min(11, self.attn_dist + i * self.attn_step))
            attention_mask = -10000.0 * (attention_mask.float().unsqueeze(1))
            encoded_states = self.layer[i](encoded_states, attention_mask)
        return encoded_states


# coding:iso-8859-9 Türkçe
# p_31003b.py: Numpy dizisel veya matrissel bire-bir bölüm örneği.

import numpy as np

x = np.array ([
    (2, 3),
    (3, 5) ])

y = np.array (( # [ veya ( olabilir...
   (1, 2),
    (5, -1) ))

z = x / y

print ("x dizisi:\n", x, " ==>Şekli: ", x.shape, "\n\ny dizisi:\n", y, " ==>Şekli: ", y.shape,
    "\n\n(np.array(x) * np.array(y)) bire-bir bölüm dizisi:\n", z, " ==>Şekli: ", z.shape, sep="")
print ("-"*50)
#-------------------------------------------------------------------------------------------

x = np.matrix (x)
y = np.matrix (y)
z = x / y

print ("Matris bölümü yoktur, her halukarda bire-bir bölüm yapar==>")
print ("\n(np.matrix(x) / np.matrix (y)) matrissel bölümü:\n", z, " ==>Şekli: ", z.shape, sep="")

"""Çıktı:
>python p_31003b.py
x dizisi:
[[2 3]
 [3 5]] ==>Şekli: (2, 2)

y dizisi:
[[ 1  2]
 [ 5 -1]] ==>Şekli: (2, 2)

(np.array(x) * np.array(y)) bire-bir bölüm dizisi:
[[ 2.   1.5]
 [ 0.6 -5. ]] ==>Şekli: (2, 2)
--------------------------------------------------
Matris bölümü yoktur, her halukarda bire-bir bölüm yapar==>

(np.matrix(x) / np.matrix (y)) matrissel bölümü:
[[ 2.   1.5]
 [ 0.6 -5. ]] ==>Şekli: (2, 2)
"""

Bernd Klein (520) ile Python/p_31003b.py


import imdb

# creating instance of IMDb
ia = imdb.IMDb()

# getting top 250 movies
search = ia.get_top250_movies()

# printing only first 10 movies title
for i in range(10):
    print(search[i]['title'])


import random
import torch
from torchvision.transforms import functional as F

# In this file some more transformations (apart from the ones defined in torchvision.transform)
# are added. Particularly helpful to train imagenet, and in the style of the transforms
# used by fb.resnet https://github.com/facebook/fb.resnet.torch/blob/master/datasets/imagenet.lua

# This file is taken from a proposed pull request on the torchvision github project.
# At the moment this pull request has not been accepted yet, that is why I report it here.
# Link to the pull request: https://github.com/pytorch/vision/pull/27/files

class Lighting(object):
    """Lighting noise(AlexNet - style PCA - based noise)"""

    def __init__(self, alphastd):
        self.alphastd = alphastd
        self.eigval = torch.Tensor([0.2175, 0.0188, 0.0045])
        self.eigvec = torch.Tensor([
            [-0.5675, 0.7192, 0.4009],
            [-0.5808, -0.0045, -0.8140],
            [-0.5836, -0.6948, 0.4203],
        ])

    def __call__(self, img):
        # img is supposed go be a torch tensor

        if self.alphastd == 0:
            return img

        alpha = img.new().resize_(3).normal_(0, self.alphastd)
        rgb = self.eigvec.type_as(img).clone() \
            .mul(alpha.view(1, 3).expand(3, 3)) \
            .mul(self.eigval.view(1, 3).expand(3, 3)) \
            .sum(1).squeeze()

        return img.add(rgb.view(3, 1, 1).expand_as(img))

class RandomScale(object):
    """ResNet style data augmentation"""

    def __init__(self, minSize, maxSize):
        self.minSize = minSize
        self.maxSize = maxSize

    def __call__(self, img):
        targetSz = int(round(random.uniform(self.minSize, self.maxSize)))

        return F.resize(img, targetSz)


# MIT License
# Copyright (c) 2019 Fabien Boucher

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from elasticsearch.helpers import bulk
from elasticsearch import client

from monocle.db import queries
from monocle import utils

from datetime import datetime

class ELmonocleDB():

    def __init__(self, index='monocle'):
        self.es = client.Elasticsearch('localhost:9200')
        self.index = index
        self.mapping = {
            self.index: {
                "properties": {
                    "id": {"type": "keyword"},
                    "type": {"type": "keyword"},
                    "number": {"type": "keyword"},
                    "repository_fullname_and_number": {"type": "keyword"},
                    "title": {"type": "keyword"},
                    "commits": {"type": "keyword"},
                    "additions": {"type": "integer"},
                    "deletions": {"type": "integer"},
                    "changed_files": {"type": "integer"},
                    "repository_prefix": {"type": "keyword"},
                    "repository_fullname": {"type": "keyword"},
                    "repository_shortname": {"type": "keyword"},
                    "author": {"type": "keyword"},
                    "on_author": {"type": "keyword"},
                    "committer": {"type": "keyword"},
                    "merged_by": {"type": "keyword"},
                    "created_at": {
                        "type": "date",
                        "format": "date_time_no_millis"
                    },
                    "on_created_at": {
                        "type": "date",
                        "format": "date_time_no_millis"
                    },
                    "merged_at": {
                        "type": "date",
                        "format": "date_time_no_millis"
                    },
                    "updated_at": {
                        "type": "date",
                        "format": "date_time_no_millis"
                    },
                    "closed_at": {
                        "type": "date",
                        "format": "date_time_no_millis"
                    },
                    "authored_at": {
                        "type": "date",
                        "format": "date_time_no_millis"
                    },
                    "committed_at": {
                        "type": "date",
                        "format": "date_time_no_millis"
                    },
                    "state": {"type": "keyword"},
                    "duration": {"type": "integer"},
                    "mergeable": {"type": "keyword"},
                    "label": {"type": "keyword"},
                    "assignee": {"type": "keyword"},
                    "approval": {"type": "keyword"},
                }
            }
        }
        settings = {
            'mappings': self.mapping
        }
        self.ic = client.IndicesClient(self.es)
        self.ic.create(index=self.index, ignore=400, body=settings)

    def update(self, source_it):
        def gen(it):
            for source in it:
                d = {}
                d['_index'] = self.index
                d['_type'] = self.index
                d['_op_type'] = 'update'
                d['_id'] = source['id']
                d['doc'] = source
                d['doc_as_upsert'] = True
                yield d
        bulk(self.es, gen(source_it))
        self.es.indices.refresh(index=self.index)

    def delete_repository(self, repository_fullname):
        params = {'index': self.index, 'doc_type': self.index}
        body = {
            "query": {
                "bool": {
                    "filter": {
                        "regexp": {
                            "repository_fullname": {
                                "value": repository_fullname
                            }
                        }
                    }
                }
            }
        }
        params['body'] = body
        self.es.delete_by_query(**params)
        self.es.indices.refresh(index=self.index)

    def get_last_updated(self, repository_fullname):
        params = {'index': self.index, 'doc_type': self.index}
        body = {
            "sort": [{
                "updated_at": {
                    "order": "desc"
                }
            }],
            "query": {
                "bool": {
                    "filter": [
                        {"term": {"type": "Change"}},
                        {"regexp": {
                            "repository_fullname": {
                                "value": repository_fullname
                            }
                        }}
                    ]
                }
            }
        }
        params['body'] = body
        try:
            res = self.es.search(**params)
        except Exception:
            return []
        ret = [r['_source'] for r in res['hits']['hits']]
        if not ret:
            return []
        return ret[0]

    def run_named_query(self, name, *args, **kwargs):
        # Here we set gte and gte if not provided by user
        # especially to be able to set the histogram extended_bounds
        if not args[1].get('gte'):
            args[1]['gte'] = int(utils.dbdate_to_datetime(
                queries._first_created_event(
                    self.es, self.index, *args, **kwargs)).timestamp() * 1000)
        if not args[1].get('lte'):
            args[1]['lte'] = int(datetime.now().timestamp() * 1000)
        return getattr(queries, name)(
            self.es, self.index, *args, **kwargs)


import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt

img1 = cv.imread('train_img.jpg',1)# queryImage
img1 = cv.cvtColor(img1,cv.COLOR_BGR2RGB)
img2 = cv.imread('3.jpg',1) # trainImage
img2 = cv.cvtColor(img2,cv.COLOR_BGR2RGB)
img_replace = cv.imread('img_replace.jpg', 1)
img_replace = cv.cvtColor(img_replace,cv.COLOR_BGR2RGB)
# sift = cv.SIFT_create()
sift = cv.ORB_create(nfeatures=1000)
kp1, des1 = sift.detectAndCompute(img1,None)
kp_replace, des_replace = sift.detectAndCompute(img_replace,None)

cap = cv.VideoCapture('video.mp4')
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
size = (frame_width, frame_height)
result = cv.VideoWriter('filename.avi',
                         cv.VideoWriter_fourcc(*'MJPG'),
                         10, size)

while(True):
    B = []
    ret, frame = cap.read()
    dim = (512, 756)
    img2 = cv.resize(frame, dim, interpolation=cv.INTER_AREA)
    try:
        kp2, des2 = sift.detectAndCompute(img2, None)
        # bf = cv.BFMatcher()
        bf = cv.BFMatcher(cv.NORM_HAMMING)
        matches = bf.knnMatch(des1, des2, k=2)
        good = []
        for m, n in matches:
            if m.distance < 0.8 * n.distance:
                good.append(m)
        if len(good)>10:
            src_pts = np.float32([ kp1[m.queryIdx].pt for m in good ]).reshape(-1,1,2)
            dst_pts = np.float32([ kp2[m.trainIdx].pt for m in good ]).reshape(-1,1,2)
            M, mask = cv.findHomography(src_pts, dst_pts, cv.RANSAC,5.0)
            matchesMask = mask.ravel().tolist()
            h, w, d = img1.shape
            pts = np.float32([ [0,0],[0,h-1],[w-1,h-1],[w-1,0] ]).reshape(-1,1,2)
            dst = cv.perspectiveTransform(pts,M)
            img_w = cv.warpPerspective(img_replace, M, ((img2.shape[1], img2.shape[0])))
            frame_white = np.zeros((img2.shape[0], img2.shape[1]), np.uint8)
            cv.fillPoly(frame_white, [np.int32(dst)], (255, 255, 255))
            frame_not = cv.bitwise_not(frame_white)
            img_copy = cv.bitwise_and(img2, img2, mask=frame_not)
            img2 = cv.bitwise_or(img_w, img_copy)
    except:
        font = cv.FONT_HERSHEY_SIMPLEX
        cv.putText(img2,
                   'it looks like he\'s not here',
                   (50, 50),
                   font, 1,
                   (0, 255, 255),
                   2,
                   cv.LINE_4)
    cv.imshow('frame', img2)
    if cv.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv.destroyAllWindows()


from airflow.hooks.postgres_hook import PostgresHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults

class DataQualityOperator(BaseOperator):

    ui_color = '#89DA59'

    @apply_defaults
    def __init__(self,
                 redshift_conn_id="redshift",
                 test_cases=None,
                 *args, **kwargs):
        """
        :test_cases: tuple of (sql statement, test function) where the test function expects to be passed a list of list
                     of records that are the result of the SQL statement
        """

        super(DataQualityOperator, self).__init__(*args, **kwargs)
        self.redshift_conn_id = redshift_conn_id
        self.test_cases = test_cases

    def execute(self, context):
        self.log.info('Executing the Data Quality checks')

        redshift = PostgresHook(self.redshift_conn_id)

        failures = 0
        for test_case in self.test_cases:
            statement, test_func = test_case

            self.log.info(f"Running Data Quality Check: {statement}")
            actual_result = redshift.get_records(statement)
            test_correct = test_func(actual_result)

            if not test_correct:
                failures += 1
                self.log.error(f"Data Quality Check failed.\n"
                               f"Statement Was: {statement}\n"
                               f"Actual Result was {actual_result}")
            else:
                self.log.info("Check Passed")

        if failures > 0:
            raise Exception("One or more data quality checks failed, please check the logs for more details")


#!/usr/bin/python3

import numpy as np
import sys
import re

global nsamples
global dt

def getheader(infile):
    line = infile.readline()
    listvals = [x.strip() for x in line.split(',')]
    (scopename,scopemodel,arraytype) = (listvals[0],listvals[1],listvals[2])
    line = infile.readline()
    listvals = [x.strip() for x in line.split(',')]
    (nsegments,nsamples) = (int(listvals[1]),int(listvals[3]))
    #nsegments = int(nsegmentsStr)
    #nsamples = int(nsamplesStr)
    line = infile.readline()
    line = infile.readline()
    #(dummy1,dummy2,dummy3) = [x.strip for x in line.split(',')]
    #(dummy1,dummy2,dummy3) = [x.strip for x in line.split(',')]
    line = infile.readline()
    (xlabel,ylabel) = [x.strip() for x in line.split(',')]
    return (scopename,scopemodel,arraytype,nsegments,nsamples,xlabel,ylabel)

def c2(freq,bwd):
    csqr = np.zeros(freq.shape[0],dtype=float)
    inds = np.where(np.abs(freq)<bwd)
    csqr[inds] = np.power(np.cos(freq[inds]/bwd*np.pi/2.),int(2))
    return csqr

def sampleandhold(y,thresh,dead,e):
    result = np.zeros(y.shape,dtype=float)
    i = 0
    while i < e.shape[0]:
        ramp = e[i]
        result[i] = ramp
        if y[i] < thresh:
            while i<e.shape[0] and y[i]<0:
                if i<e.shape[0]:
                    ramp = e[i]
                    result[i] = ramp
                    hold = ramp
                    i += 1
            if i+int(dead+.5) < e.shape[0]:
                result[i:i+int(dead+.5)] = hold
                i += int(dead+.5)
        if i<e.shape[0]:
            ramp = e[i]
            result[i] = ramp
            i += 1
    return result

#def processfiles(filelist,c2,en,jac,b):
def processfiles(filelist,c2):
    dirlist = []
    filecounter = int(0)
    #nbins = jac.shape[0]
    nbins=1024
    hist = np.zeros(nbins,dtype=float)
    jac = np.zeros(nbins,dtype=float)
    en = np.zeros((0,),dtype=float)
    (en_low,en_high) = (0.25,11.25)
    for filename in filelist:
        m = re.search('(^.+/)(C\d--C\d.+).txt$',filename)
        if m:
            dirstr = m.group(1)
            fileheadstr = m.group(2)
            infile = open(filename,'rt')
            (scopename,scopemodel,arraytype,nsegments,nsamples_chk,xlabel,ylabel) = getheader(infile)
            if (nsamples_chk != c2.shape[0]):
                print("failed, {} is unequal nsamples for file {}".format(c2.shape[0],m.group(0)))
                continue
            d = np.loadtxt(infile,dtype=float,delimiter=',')
            t0=d[0,0]
            t=(d[:,0]-t0)*1e9
            y=d[:,1]
            dt = t[1]-t[0]
            infile.close()
            #f = np.fft.fftfreq(y.shape[0],dt)
            #BOX = 1.*(np.abs(f)<0.24)
            #Y = np.fft.fft(y)*c2
            #DY = 1j*f*Y*c2
            #outfile = dirstr + fileheadstr + '.fft'
            #np.savetxt(outfile,np.column_stack((f,np.abs(Y),np.abs(DY))),fmt='%.3e')
            #dy = np.fft.ifft(DY).real
            #num = np.fft.ifft(np.fft.fft(dy*t)*BOX).real
            #denom = np.fft.ifft(DY*BOX).real
            #inds = np.where(np.abs(denom)>0)
            #result = np.zeros(y.shape,dtype=float)
            #result[inds] = num[inds]/denom[inds]
            if en.shape[0] < t.shape[0]:
                en = np.zeros(t.shape[0],dtype=float)
                (ramp0,rampstart,rampstop) = (250,300,1300)
                inds = np.where((t>rampstart)*(t<rampstop))
                en[inds] = 2e4 * float(rampstart-ramp0)*np.power(t[inds]-t[ramp0],int(-2))
                (jac,_) = np.histogram(en,bins = nbins,range=(en_low,en_high))
            result_hold = sampleandhold(y,-.05,.5/dt,en)
            #outfile = dirstr + fileheadstr + '.expect'
            #np.savetxt(outfile,np.column_stack((t,y,result_hold)),fmt='%.6e')
            (h,b) = np.histogram(result_hold,bins = nbins,range=(en_low,en_high))
            h = (h-jac)
            inds = np.where(h>0)
            hist[inds] += 1
            #hist += (h-jac)

            filecounter +=1
            if (len(dirlist) > 0):
                if dirlist[-1] != dirstr:
                    dirlist.append(dirstr)
            else:
                dirlist.append(dirstr)

    return (dirlist,b,hist,jac)

def main():
    if len(sys.argv)<2:
        print("I need a list of files to process")
        return

    checkfile = sys.argv[1]
    m = re.search('(^.+/)(C\d--C\d.+).txt$',checkfile)
    if m:
        infile = open(m.group(0),'rt')
        (scopename,scopemodel,arraytype,nsegments,nsamples,xlabel,ylabel) = getheader(infile)
        t = np.loadtxt(infile,dtype=float,delimiter=',',usecols=0)
        dt = t[1]-t[0]
        infile.close()
    f = np.fft.fftfreq(nsamples,dt*1e9) #in GHz
    t = np.arange(nsamples)*dt
    bwd = 2.4
    cos2 = c2(f,bwd)
    data = np.zeros((nsamples,),dtype=float)
    nbins = 1024
    (dirlist,bins,hist,jac) = processfiles(sys.argv[1:],cos2)
    if m:
        headerStr = "\t".join(dirlist)
        outfilename = dirlist[-1] + 'hist.out'
        np.savetxt(outfilename,np.column_stack((bins[:-1],hist,jac)),header=headerStr)
    return

if __name__=="__main__":
    main()


n = int(input())

mod = 1000007
count = 0
mul = 1

for i in range(n):
    u,v,w = map(int, input().split())
    if u == v:
        count += 1
        mul *= w
        mul %= mod

if count:
    print(count, mul)
else:
    print(-1)