from django.db import models
from authenticator.models import Employee, Service
from django.utils import timezone
import datetime
from inventory.models import Product
# Create your models here.

class Customer(models.Model):
    name = models.CharField(max_length=30,null=False)
    mobile = models.CharField(max_length=13,null=False)
    email = models.CharField(max_length=30,null=True)
    dob = models.DateField(blank=True, null=True, default=None)
    anniversary = models.DateField(blank=True, null=True, default=None)
    class Meta:
        verbose_name = "Client"
        verbose_name_plural = "Clients"
    def __str__(self):
        return self.name
    def getB(self):
        return self.dob.strftime("%Y-%m-%d").split("-")[1:]
    def getA(self):
        return self.anniversary.strftime("%Y-%m-%d").split("-")[1:]
    def is_birthday(self):
        if self.dob == None:
            return False
        month, day = datetime.date.today().strftime("%Y-%m-%d").split("-")[1:]
        bm, bd = self.getB()
        return day == bd and month == bm
    def is_anniversary(self):
        if self.anniversary == None:
            return False
        month, day = datetime.date.today().strftime("%Y-%m-%d").split("-")[1:]
        am, ad = self.getA()
        return day == ad and month == am
    @property
    def communication_type(self):
        type="none"
        if self.mobile and self.email:
            type="both"
        else:
            if self.mobile:
                type="sms"
            elif self.email:
                type="mail"
        return type

    @property
    def is_special_day(self):
        return self.is_birthday() or self.is_anniversary()

class Discount(models.Model):
    label = models.CharField(max_length=30,null=True)
    percentage = models.IntegerField(default=10)

class BillQuerySet(models.QuerySet):
    def total_bill(self):
        return list(self.aggregate(models.Sum('final_amount')).values())[0]
    def avg_bill(self):
        return list(self.aggregate(models.Avg('final_amount')).values())[0]
    def bill_count(self):
        return self.count()
    def this_month(self):
        start_of_month = timezone.now().today().replace(day=1)
        return self.filter(created_at__gte=start_of_month)
    def today(self):
        today = timezone.localtime().replace(hour=0, minute=0, second=0, microsecond=0)
        return self.filter(created_at__gte=today)

class BillManager(models.Manager):
    user_for_related_fields = True

    def get_queryset(self):
        return BillQuerySet(self.model, using=self._db)

class Bill(models.Model):
    objects = BillManager()

    DISCOUNTS = (
        (0,"0%"),
        (5,"5%"),
        (10,"10%"),
        (15,"15%")
    )
    GIFTS = (
        ("N", "None"),
        ("C", "Coupon"),
        ("V", "Voucher")
    )
    discount = models.IntegerField(default=0)
    amount = models.FloatField(default=0.0,null=True, blank= True)
    taxable_amount = models.FloatField(default=0.0, null=True, blank=True)
    final_amount = models.FloatField(default=0.0,null=True, blank= True)
    gst = models.FloatField(default=0.0, null=True, blank= True)
    payments = models.ManyToManyField('Payment',related_name="bill")
    created_at = models.DateTimeField(default=timezone.now)
    gift_type= models.CharField(choices=GIFTS,default="N", max_length=1)
    voucher = models.ForeignKey('Voucher', on_delete=models.PROTECT,blank=True, null=True, related_name="bills")
    coupon_code = models.CharField(max_length=20, null=True, blank=True)
    @property
    def paid(self):
        acc = 0
        for i in self.payments.all():
            acc += i.paid
        return  acc

class Package(models.Model):
    name = models.CharField(max_length=30)
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=False, null=False, related_name="packages")
    bill = models.OneToOneField('Bill', on_delete=models.PROTECT, null=True, related_name="package")

class BookingQuerySet(models.QuerySet):

    def total_bill(self):
        return list(self.aggregate(models.Sum('bill__final_amount')).values())[0]

    def total_payment(self):
        amount = 0
        for i in self:
            amount+= i.bill.paid if i.bill else 0
        return amount

    def services_count(self):
        count = 0
        for booking in self:
            count += booking.appointments.count()
        return count

class BookingManager(models.Manager):
    user_for_related_fields = True

    def get_queryset(self):
        return BookingQuerySet(self.model, using=self._db)

class Booking(models.Model):
    objects = BookingManager()
    Booked=1
    Pending=2
    Completed=3
    Cancelled=4
    STATUS = (
        (Booked,"Booked"),
        (Pending,"Pending"),
        (Completed,"Completed"),
        (Cancelled,"Cancelled")
    )
    bill = models.OneToOneField('Bill', on_delete=models.PROTECT, null=True, related_name="booking")
    package = models.ForeignKey(Package, on_delete=models.PROTECT, null=True, related_name="bookings")
    customer = models.ForeignKey(Customer,on_delete=models.PROTECT, null=False, blank=False, default=1, related_name="bookings")
    products = models.ManyToManyField(Product, related_name="booking", through="ProductBooking")
    branch = models.ForeignKey('inventory.Branch', null=False, blank=False, on_delete=models.PROTECT, related_name="bookings")
    date = models.DateField(blank=True, null=True)
    starttime = models.TimeField(blank=True, null=True)
    endtime = models.TimeField(blank=True, null=True)
    status = models.IntegerField(choices=STATUS, default=Booked)
    status_lookup = {key: value for (key, value) in STATUS}
    @property
    def status_to_str(self):
        return self.status_lookup[self.status]

    def status_int_to_str(self,i):
        return self.status_lookup[i]

    def status_str_to_int(self,i):
        for key, val in self.status_lookup.items():
            if val==i:
                return key
    @property
    def total_amount(self):
        if self.appointments.count() > 0:
            return sum([appointment.service.price for appointment in self.appointments.all()])
        elif self.products.count() > 0:
            return sum([pb.product.price_per_unit*pb.quantity for pb in self.product_booking.all()])
        else:
            return 0
    @property
    def total_taxable_amount(self):
        if self.appointments.count() > 0:
            return sum([appointment.service.price for appointment in self.appointments.all() if appointment.service.taxable])
        elif self.products.count() > 0:
            return sum([pb.product.price_per_unit*pb.quantity for pb in self.product_booking.all() if pb.product.taxable])
        else:
            return 0

class Offer(models.Model):
    name= models.CharField(max_length=30)
    services = models.ManyToManyField(Service, related_name="offers", through="OfferService")
    percentage = models.FloatField(null=False)

class OfferService(models.Model):
    offer = models.ForeignKey(Offer, related_name="offer_service", on_delete=models.CASCADE, null=False)
    service = models.ForeignKey(Service, related_name="offer_service", on_delete=models.CASCADE, null=False)
    quantity = models.IntegerField(default=0)

class ProductBooking(models.Model):
    product = models.ForeignKey(Product, related_name="product_booking", on_delete=models.PROTECT, null=False)
    booking = models.ForeignKey(Booking, related_name="product_booking",on_delete=models.CASCADE, null=False)
    quantity = models.IntegerField(default=1)
    price_per_product = models.FloatField(default=0.0)

class Voucher(models.Model):
    code = models.CharField(max_length=30)
    description = models.CharField(max_length=50)
    percentage = models.FloatField(default=0.0)

class Payment(models.Model):
    Cash = 0
    Card = 1
    PAYMENT_MODES = (
        (Cash,"Cash"),
        (Card,"Card")
    )
    Customer = 0
    Bajaj_Finance = 1
    Capital_Float = 2
    PAYMENT_SOURCES = (
        (Customer,"Customer"),
        (Bajaj_Finance,"Bajaj_Finance"),
        (Capital_Float,"Capital_Float")
    )
    payment_type = models.IntegerField(choices=PAYMENT_MODES, default=Cash)
    card = models.ForeignKey("Card", on_delete=models.PROTECT, null=True, related_name="payments")
    paid = models.FloatField(default=0.0,null=False)
    payment_by = models.IntegerField(choices=PAYMENT_SOURCES, default=Customer)
    payment_date = models.DateField(auto_now_add=True)

class Card(models.Model):
    number = models.CharField(max_length=20)

class AppointmentQuerySet(models.QuerySet):
    def total_price(self):
        return list(self.aggregate(models.Sum('price')).values())[0]
        return list(self.aggregate(models.Sum('price')).values())[0]

class AppointmentManager(models.Manager):
    user_for_related_fields = True

    def get_queryset(self):
        return AppointmentQuerySet(self.model, using=self._db)

class Appointment(models.Model):
    objects = AppointmentManager()
    employee = models.ForeignKey(Employee,on_delete=models.SET_NULL, null=True, blank=True, related_name="appointments")
    service = models.ForeignKey(Service, on_delete=models.PROTECT, null=True, blank=True, related_name="appointments")
    price = models.FloatField(default=0.0)
    booking = models.ForeignKey(Booking,on_delete=models.CASCADE, related_name="appointments")
    cancelled = models.BooleanField(default=False)
    notes = models.TextField(null=True, blank=True)
    def __str__(self):
        return "Appointment:"+str(self.service)


from pyspark.sql import Row, types
from pyspark.ml import feature, classification
from nose.tools import assert_equal
import pyspark
import py_sparkling

from optimus import Optimus

import optimus.ml.encoding as fe

op = Optimus(master='local')

df_cancer = op.spark.read.csv('tests/data_cancer.csv', sep=',', header=True, inferSchema=True)
columns = ['diagnosis', 'radius_mean', 'texture_mean', 'perimeter_mean', 'area_mean', 'smoothness_mean',
           'compactness_mean', 'concavity_mean', 'concave points_mean', 'symmetry_mean',
           'fractal_dimension_mean']

columns_h2o = ['radius_mean', 'texture_mean', 'perimeter_mean', 'area_mean', 'smoothness_mean',
           'compactness_mean', 'concavity_mean', 'concave points_mean', 'symmetry_mean',
           'fractal_dimension_mean']

def assert_spark_df(df):
    assert isinstance(df, pyspark.sql.dataframe.DataFrame), "Not a Spark DF"

def assert_spark_model(model):
    assert isinstance(model, pyspark.ml.PipelineModel), "Not a model"

def test_ml_pipe():
    df = op.sc. \
         parallelize([Row(sentence='this is a test', label=0.),
                     Row(sentence='this is another test', label=1.)]). \
         toDF()

    pl = feature.Tokenizer().setInputCol('sentence') | feature.CountVectorizer()
    ml = pl | classification.LogisticRegression()

    ml_model = ml.fit(df)
    assert_equal(ml_model.transform(df).count(), 2)

def test_logistic_regression_text():
    df = op.sc. \
        parallelize([Row(sentence='this is a test', label=0.),
                     Row(sentence='this is another test', label=1.)]). \
        toDF()

    df_predict, ml_model = op.ml.logistic_regression_text(df, "sentence")

    assert_spark_df(df_predict)

    assert_spark_model(ml_model)

def test_n_gram():
    df = op.sc. \
        parallelize([['this is the best sentence ever'],
                     ['this is however the worst sentence available']]). \
        toDF(schema=types.StructType().add('sentence', types.StringType()))

    df_model, tfidf_model = fe.n_gram(df, input_col="sentence", n=2)

    assert_spark_df(df_model)

    assert_spark_model(tfidf_model)

    assert_equal(df_model.select('sentence', 'features').count(), 2)

def test_string_to_index_kargs():
    df = op.spark.createDataFrame([(0, "a"), (1, "b"), (2, "c"), (3, "a"), (4, "a"), (5, "c")],
                                 ["id", "category"])

    df_indexed = fe.string_to_index(df, "category", stringOrderType="frequencyAsc")

    assert_spark_df(df_indexed)

    expected_collect = op.sc.parallelize([Row(id=0, category='a', category_index=2.0),
                                          Row(id=1, category='b', category_index=0.0),
                                          Row(id=2, category='c', category_index=1.0),
                                          Row(id=3, category='a', category_index=2.0),
                                          Row(id=4, category='a', category_index=2.0),
                                          Row(id=5, category='c', category_index=1.0)]).toDF()

    assert_equal(df_indexed.select("category", "category***STRING_TO_INDEX", "id").collect(), expected_collect.collect())

def test_random_forest():
    df_model, rf_model = op.ml.random_forest(df_cancer, columns, "diagnosis")

    assert_spark_df(df_model)

    assert isinstance(rf_model, pyspark.ml.classification.RandomForestClassificationModel), "Not a RF model"

def test_decision_tree():
    df_model, rf_model = op.ml.decision_tree(df_cancer, columns, "diagnosis")

    assert_spark_df(df_model)

    assert isinstance(rf_model, pyspark.ml.classification.DecisionTreeClassificationModel), "Not a DT model"

def test_gbt():
    df_model, rf_model = op.ml.gbt(df_cancer, columns, "diagnosis")

    assert_spark_df(df_model)

    assert isinstance(rf_model, pyspark.ml.classification.GBTClassificationModel), "Not a GBT model"

def test_h2o_automl():
    df_model, automl_model = op.ml.h2o_automl(df_cancer, "diagnosis", columns_h2o)

    assert_spark_df(df_model)

    assert isinstance(automl_model, py_sparkling.ml.models.H2OMOJOModel), "Not a H2OMOJOModel"

def test_h2o_deeplearning():
    df_model, dl_model = op.ml.h2o_deeplearning(df_cancer, "diagnosis", columns_h2o)

    assert_spark_df(df_model)

    assert isinstance(dl_model, py_sparkling.ml.models.H2OMOJOModel), "Not a H2OMOJOModel"

def test_h2o_xgboost():
    df_model, xgboost_model = op.ml.h2o_xgboost(df_cancer, "diagnosis", columns_h2o)

    assert_spark_df(df_model)

    assert isinstance(xgboost_model, py_sparkling.ml.models.H2OMOJOModel), "Not a H2OMOJOModel"

def test_h2o_gbm():
    df_model, gbm_model = op.ml.h2o_gbm(df_cancer, "diagnosis", columns_h2o)

    assert_spark_df(df_model)

    assert isinstance(gbm_model, py_sparkling.ml.models.H2OMOJOModel), "Not a H2OMOJOModel"


import hashlib
import io
import logging
import os
import PIL.Image
import tensorflow as tf
import pickle
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import inout
import sys
sys.path.append("../..")
from object_detection.utils import dataset_util
from object_detection.utils import label_map_util
import scipy.misc as scimisc
import numpy as np

########################################################################################################################
# def dict_to_tf_example(data,
#                        label_map_dict,
#                        image_subdirectory,
#                        ignore_difficult_instances=False):
def dict_to_tf_example(img_path,visible_obj,scene_gt,label_map_dict):

    ################################ juil_ have to change this part
    img = scimisc.imread(img_path)()
    height = img.shape[0]
    width = img.shape[1]
    output_im = np.zeros((height, width, 3))
    output_im[:, :, 0] = img
    output_im[:, :, 1] = img
    output_im[:, :, 2] = img
    scimisc.imsave('temp.jpg',output_im)
    with tf.gfile.GFile('temp.jpg', 'rb') as fid:
        encoded_jpg = fid.read()
    encoded_jpg_io = io.BytesIO(encoded_jpg)
    image = PIL.Image.open(encoded_jpg_io)
    if image.format != 'JPEG':
        raise ValueError('Image format not JPEG')
    key = hashlib.sha256(encoded_jpg).hexdigest()

    # width = int(data['size']['width'])
    # height = int(data['size']['height'])
    width = int(image.size[0])
    height= int(image.size[1])

    xmin = []
    ymin = []
    xmax = []
    ymax = []
    classes = []
    classes_text = []
    truncated = []
    poses = []
    difficult_obj = []
    for obj in range(0,len(scene_gt)):
        if (scene_gt[obj]['visib_percentage']<0.3):
            difficult = True
        else:
            difficult = False
        if (difficult is False):

            difficult_obj.append(int(difficult))

            # xmin.append(float(obj['bndbox']['xmin']) / width)
            # ymin.append(float(obj['bndbox']['ymin']) / height)
            # xmax.append(float(obj['bndbox']['xmax']) / width)
            # ymax.append(float(obj['bndbox']['ymax']) / height)

            xmin.append(float(scene_gt[obj]['obj_bb'][1]) / width)
            ymin.append(float(scene_gt[obj]['obj_bb'][0]) / height)
            xmax.append(float(scene_gt[obj]['obj_bb'][1]+scene_gt[obj]['obj_bb'][3]) / width)
            ymax.append(float(scene_gt[obj]['obj_bb'][0]+scene_gt[obj]['obj_bb'][2]) / height)
            scene_gt[obj]['obj_id'] = 1
            classes.append(scene_gt[obj]['obj_id'])
            classes_text.append(label_map_dict.keys()[label_map_dict.values().index(scene_gt[obj]['obj_id'])].encode('utf8'))

            truncated.append(int(0))
            poses.append('unspecified'.encode('utf8'))

            # # visualize
            # print(scene_gt[obj]['obj_id'])
            # fig,ax = plt.subplots(1)
            # ax.imshow(image)
            # rect = patches.Rectangle((scene_gt[obj]['obj_bb'][1],scene_gt[obj]['obj_bb'][0]),scene_gt[obj]['obj_bb'][3],scene_gt[obj]['obj_bb'][2],linewidth=1,edgecolor='r',facecolor='none')
            # ax.add_patch(rect)
            # plt.show()
            # 1

    example = tf.train.Example(features=tf.train.Features(feature={
        'image/height': dataset_util.int64_feature(height),
        'image/width': dataset_util.int64_feature(width),
        'image/filename': dataset_util.bytes_feature(
            img_path.encode('utf8')),
        'image/source_id': dataset_util.bytes_feature(
            img_path.encode('utf8')),
        'image/key/sha256': dataset_util.bytes_feature(key.encode('utf8')),
        'image/encoded': dataset_util.bytes_feature(encoded_jpg),
        'image/format': dataset_util.bytes_feature('jpeg'.encode('utf8')),
        'image/object/bbox/xmin': dataset_util.float_list_feature(xmin),
        'image/object/bbox/xmax': dataset_util.float_list_feature(xmax),
        'image/object/bbox/ymin': dataset_util.float_list_feature(ymin),
        'image/object/bbox/ymax': dataset_util.float_list_feature(ymax),
        'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
        'image/object/class/label': dataset_util.int64_list_feature(classes),
        'image/object/difficult': dataset_util.int64_list_feature(difficult_obj),
        'image/object/truncated': dataset_util.int64_list_feature(truncated),
        'image/object/view': dataset_util.bytes_list_feature(poses),
    }))
    return example
########################################################################################################################

# center_obj_id,scene_id, im_id = 1,1,0

flags = tf.app.flags
flags.DEFINE_string('data_dir', '', 'Root directory to raw PASCAL VOC dataset.')
flags.DEFINE_string('set', 'train', 'Convert training set, validation set or '
                    'merged set.')
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
FLAGS = flags.FLAGS
SETS = ['train', 'val', 'trainval', 'test']

# def main(_):
FLAGS.set = 'train'
if FLAGS.set not in SETS:
    raise ValueError('set must be in : {}'.format(SETS))
DataPath = '/home/juil/workspace/GitHub/TF_detection/Data'
FLAGS.data_dir = '/home/juil/workspace/training_scene_generator_20170912/sixd_toolkit-master/output/render'
FLAGS.output_path = DataPath+'/data_for_training/synthetic_train_cups_depth_300_samples.record'
label_map_dict = label_map_util.get_label_map_dict('../../data/synthetic_label_map_cup.pbtxt')

writer = tf.python_io.TFRecordWriter(FLAGS.output_path)

for scene_id in range(1,930):
    base_path = FLAGS.data_dir + '/coffee_{:03d}'.format(scene_id)
    num_img = len(os.listdir(base_path+'/rgb'))
    scene_info = inout.load_info(FLAGS.data_dir + '/coffee_{:03d}/info.yml'.format(scene_id))
    scene_gt = inout.load_gt(FLAGS.data_dir + '/coffee_{:03d}/gt.yml'.format(scene_id))

    for im_id in range(0,len(scene_gt.keys())-1):
        print('scene_id : {:03d}, im_id : {:03d}'.format(scene_id,im_id))
        im_id_str = '{0:04d}'.format(im_id)
        img_path = base_path + '/rgb/' + im_id_str + '.png'
        surface_path = base_path + '/normal_map/' + im_id_str + '.png'
        depth_path = base_path + '/depth/' + im_id_str + '.png'
        # visibmask_path = base_path+'/visib'+img_num_str+'.png'
        # invisibmask_path = base_path+'/invisib'+img_num_str+'.png'
        # visible_obj = scene_info[im_id]['visible_obj']
        visible_obj = 1
        tf_example = dict_to_tf_example(depth_path, visible_obj, scene_gt[im_id], label_map_dict)
        writer.write(tf_example.SerializeToString())

writer.close()


"""
Inspired by:
 - https://github.com/biocore/scikit-bio/blob/master/skbio/alignment/_pairwise.py
 - https://github.com/lingpy/lingpy/blob/master/lingpy/algorithm/cython/calign.pyx
"""

import itertools
from itertools import product

import numba as nb
import numpy as np

import pyximport; pyximport.install()  # noqa: E702
from . import _align

VGAP, HGAP, END, MATCH, UNPROCESSED = range(1, 6)
GAP_SYM = -1

def _get_embedding_scores(s1, s2, S_lut, match, mismatch, factor):
    scores = np.zeros((len(s1), len(s2)))
    for (i, a), (j, b) in product(enumerate(s1), enumerate(s2)):
        if a == b:
            scores[i, j] = match
        elif (a, b) in S_lut:
            scores[i, j] = match * (S_lut[a, b] ** factor)
        else:
            scores[i, j] = mismatch
    return scores

def create_embedding_scorer(embs, **kwargs):
    """
    embs : retrieve.Embeddings object
    """
    _, S = embs.get_S()
    return EmbeddingScorer(list(embs.keys), S, **kwargs)

class EmbeddingScorer:
    def __init__(self, d, S, match=2, mismatch=-1, factor=1, cutoff=0.8):
        self.match = match
        self.mismatch = mismatch
        self.factor = factor
        self.cutoff = cutoff

        # construct lookup similarity
        self.S_lut = self.construct_S(d, S)

    def construct_S(self, keys, S):
        S_lut = {}
        for i, j in zip(*np.where(S >= self.cutoff)):
            if i == j:
                continue
            S_lut[keys[i], keys[j]] = S[i, j]
            S_lut[keys[j], keys[i]] = S[i, j]

        return S_lut

    def get_scores(self, s1, s2):
        return _get_embedding_scores(
            s1, s2, self.S_lut, self.match, self.mismatch, self.factor)

def _get_constant_scores(s1, s2, match, mismatch):
    scores = np.zeros((len(s1), len(s2)))
    for (i, a), (j, b) in product(enumerate(s1), enumerate(s2)):
        scores[i, j] = match if a == b else mismatch
    return scores

class ConstantScorer:
    def __init__(self, match=2, mismatch=-1):
        self.match = match
        self.mismatch = mismatch

    def get_scores(self, s1, s2):
        return _get_constant_scores(s1, s2, self.match, self.mismatch)

@nb.njit
def compute_input_matrices(
        s1len, s2len, scores,
        extend_gap=-1, open_gap=-1, terminal_gap=0):
    smatrix = np.zeros((s1len + 1, s2len + 1))
    tmatrix = np.zeros((s1len + 1, s2len + 1), dtype=np.int64) + END
    best_score = 0.0
    row = col = None

    for i in range(1, s1len + 1):
        for j in range(1, s2len + 1):
            mscore = smatrix[i-1, j-1] + scores[i-1, j-1]

            # vertical gap
            if i == s1len:
                # don't penalize vertical gaps if we are finished with s1
                vscore = smatrix[i-1, j] + terminal_gap
            elif tmatrix[i-1, j] == VGAP:
                vscore = smatrix[i-1, j] + extend_gap
            else:
                vscore = smatrix[i-1, j] + open_gap

            # horizontal gap
            if j == s2len:
                # don't penalize horizontal gaps if we are finished with s2
                hscore = smatrix[i, j-1] + terminal_gap
            elif tmatrix[i, j-1] == HGAP:
                hscore = smatrix[i, j-1] + extend_gap
            else:
                hscore = smatrix[i, j-1] + open_gap

            # pick best move
            score, move = 0.0, 0
            for cscore, cmove in [(0, END),
                                  (hscore, HGAP),
                                  (vscore, VGAP),
                                  (mscore, MATCH)]:
                if cscore >= score:
                    score, move = cscore, cmove

            smatrix[i, j], tmatrix[i, j] = score, move

            if score >= best_score:
                best_score = score
                row, col = i, j

    return smatrix, tmatrix, row, col, best_score

@nb.njit
def traceback(smatrix, tmatrix, row, col, gap_sym=GAP_SYM):
    a1, a2 = [], []
    move = tmatrix[row, col]

    while move != END:
        if move == MATCH:
            a1.append(row - 1)
            a2.append(col - 1)
            row -= 1
            col -= 1
        elif move == VGAP:
            a1.append(row - 1)
            a2.append(gap_sym)
            row -= 1
        else:
            a1.append(gap_sym)
            a2.append(col - 1)
            col -= 1
        move = tmatrix[row, col]

    return a1[::-1], a2[::-1]

def get_alignment_string(s1, s2, a1, a2, gap_sym=GAP_SYM):
    return ([s1[idx] if idx != gap_sym else gap_sym for idx in a1],
            [s2[idx] if idx != gap_sym else gap_sym for idx in a2])

def get_alignment_ranges(a1, a2, gap_sym=GAP_SYM):

    def _get_alignment_ranges(alignment, gap_sym):
        ranges = []
        for key, group in itertools.groupby(alignment, lambda item: item == gap_sym):
            if key:
                continue
            group = list(group)
            if len(group) > 1:
                start, *_, end = group
            else:
                start = end = group[0]
            ranges.append((start, end + 1))
        return ranges

    return _get_alignment_ranges(a1, gap_sym), _get_alignment_ranges(a2, gap_sym)

def get_printable_string(s1, s2, a1, a2, gap_sym=GAP_SYM):
    a1s, a2s = get_alignment_string(s1, s2, a1, a2, gap_sym=gap_sym)
    assert len(a1s) == len(a2s)

    max1, max2 = max(map(len, a1s)), max(map(len, a2s))
    lines = []
    for a1_i, a2_i in zip(a1s, a2s):
        if a1_i == a2_i:
            sep = '=='
        elif a1_i == gap_sym or a2_i == gap_sym:
            sep = '-'
        else:
            sep = '!='
        lines.append("{} {} {}".format(
            a1_i.ljust(max1),
            sep,
            a2_i.ljust(max2)))

    return '\n'.join(lines)

def get_horizontal_alignment(s1, s2, a1=None, a2=None, gap_sym=GAP_SYM, **kwargs):
    if a1 is None or a2 is None:
        a1, a2, _ = local_alignment(s1, s2, **kwargs)

    # empty alignment
    if not a1 or not a2:
        return ' '.join(s1), ' ', ' '.join(s2)

    # find start of both seqs
    str1 = str2 = alignment = ''
    start1 = next(filter(lambda it: it != gap_sym, a1))
    start2 = next(filter(lambda it: it != gap_sym, a2))
    str1 += ' '.join(s1[:start1])
    str2 += ' '.join(s2[:start2])
    str1, str2 = str1.rjust(len(str2)), str2.rjust(len(str1))
    alignment += ' ' * len(str1)
    for w1, w2 in zip(a1, a2):
        if w1 == gap_sym:
            str1 += ' ' + (' ' * len(s2[w2]))
            str2 += ' ' + s2[w2]
            alignment += ' ' + (' ' * len(s2[w2]))
        elif w2 == gap_sym:
            str1 += ' ' + s1[w1]
            str2 += ' ' + (' ' * len(s1[w1]))
            alignment += ' ' + (' ' * len(s1[w1]))
        else:
            str1 += ' ' + s1[w1].rjust(len(s2[w2]))
            str2 += ' ' + s2[w2].rjust(len(s1[w1]))
            sym = ('-' if s1[w1] == s2[w2] else 'x')
            alignment += ' ' + (sym * len(s2[w2])).rjust(len(s1[w1]))

    # attach end of both seqs
    end1 = next(filter(lambda it: it != gap_sym, reversed(a1))) + 1
    end2 = next(filter(lambda it: it != gap_sym, reversed(a2))) + 1
    end1, end2 = ' '.join(s1[end1:]), ' '.join(s2[end2:])
    str1 += ' ' + end1.ljust(len(end2))
    str2 += ' ' + end2.ljust(len(end1))

    return str1, alignment, str2

def get_local_alignment_numba(s1, s2, scorer, extend_gap, open_gap, terminal_gap):
    scores = scorer.get_scores(list(s1), list(s2))
    smatrix, tmatrix, row, col, score = compute_input_matrices(
        len(s1), len(s2), scores, extend_gap, open_gap, terminal_gap)
    a1, a2 = traceback(smatrix, tmatrix, row, col)
    return a1, a2, score

def get_local_alignment_cython(s1, s2, scorer, extend_gap, open_gap, terminal_gap):
    scores = scorer.get_scores(list(s1), list(s2))
    return _align.sw_alignment(
        len(s1), len(s2), extend_gap, open_gap, terminal_gap, scores)

def local_alignment(s1, s2, scorer=ConstantScorer(),
                    extend_gap=-1, open_gap=-1, terminal_gap=0, impl='cython'):
    if len(s1) == 0 or len(s2) == 0:
        return [], [], 0.0

    fn = get_local_alignment_cython if impl == 'cython' else get_local_alignment_numba
    return fn(s1, s2, scorer, extend_gap, open_gap, terminal_gap)


import pygame, sys
from pygame.locals import *

pygame.init()
DISPLAYSURF = pygame.display.set_mode((400,300))
pygame.display.set_caption('Hello World!')

WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLUE = (0,0,128)

font0bj = pygame.font.Font('freesandsbold.ttf', 32)
textSurface0bj = font0bj.render('Hello world!', True, GREEND, BLUE)
textRect0bj = textSurface0bj.get_rect()
textRect0bj.center = (200, 150)

while True:
    DISPLAYSURF.fill(WHITE)
    DISPLAYSURF.blit(textSurface0bj, textRect0bj)
    for event in pygame.event.get():
        if event.type == QUIT():
            pygame.quit()
            sys.exit()
        pygame.display.update()


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

'''
Код в скрипте должен быть разбит на функции.
Какие именно функции и как разделить код, надо решить самостоятельно.
Часть кода может быть глобальной.

В примере из раздела, скрипту передавались два аргумента:
* key - имя столбца, по которому надо найти информацию
* value - значение

Теперь необходимо расширить функциональность таким образом:
* если скрипт был вызван без аргументов, вывести всё содержимое таблицы dhcp
 * отформатировать вывод в виде столбцов
* если скрипт был вызван с двумя аргументами, вывести информацию из таблицы dhcp, которая соответствует полю и значению
* если скрипт был вызван с любым другим количеством аргументов, вывести сообщение, что скрипт поддерживает только два или ноль аргументов

> Обработка некорректного ввода аргумента будет выполняться в следующем задании

Файл БД можно скопировать из прошлых заданий

Ниже копия скрипта get_data_ver1.py из раздела
'''

import sqlite3
import sys

db_filename = 'dhcp_snooping.db'

key, value = sys.argv[1:]
keys = ['mac', 'ip', 'vlan', 'interface']
keys.remove(key)

conn = sqlite3.connect(db_filename)

#Позволяет далее обращаться к данным в колонках, по имени колонки
conn.row_factory = sqlite3.Row

print("\nDetailed information for host(s) with", key, value)
print('-' * 40)

query = "select * from dhcp where {} = ?".format( key )
result = conn.execute(query, (value,))

for row in result:
    for k in keys:
        print("{:12}: {}".format(k, row[k]))
    print('-' * 40)


""" this document defines the project urls """

from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns(
    '',
    url(r'^admin/', include(admin.site.urls)),
    (r'^accounts/', include('users.urls')),
    (r'^api/', include('api.urls')),
    url(r'^$', 'base.views.index', name='home'),
)

if settings.DEBUG:
    urlpatterns += patterns(
        '',
        (r'^%s(?P<path>.*)$' % settings.MEDIA_URL[1:],
         'django.views.static.serve', {
             'document_root': settings.MEDIA_ROOT})
    )


#code taken from Simple ROI - Medium
#Example code for cropping for the car train data
import cv2 as cv
from matplotlib import pyplot as plt

def sketch_transform(image):
    image_grayscale = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    image_grayscale_blurred = cv.GaussianBlur(image_grayscale, (7,7),0)
    image_canny = cv.Canny(image_grayscale_blurred, 10, 80)
    _, mask = image_canny_inverted = cv.threshold(image_canny, 30, 255, cv.THRESH_BINARY_INV)

    return mask

cam_capture = cv.VideoCapture(0)
cv.destroyAllWindows()

upper_left = (50,50)
bottom_right = (300,300)

while True:
    _, image_frame = cam_capture.read()

    #Rectangle marker
    r = cv.rectangle(image_frame, upper_left, bottom_right, (100,50,200), 5)
    rect_img = image_frame[upper_left[1] : bottom_right[1], upper_left[0] : bottom_right[0]]

    sketcher_rect = rect_img
    sketcher_rect = sketch_transform(sketcher_rect)

    #Conversion for 3 channels to put back on original image (streaming)
    sketcher_rect_rgb = cv.cvtColor(sketcher_rect, cv.COLOR_GRAY2RGB)

    #Replacing the sketched image on ROI
    image_frame[upper_left[1] : bottom_right[1], upper_left[0] : bottom_right[0]] = sketcher_rect_rgb

    cv.imshow("Sketcher ROI", image_frame)
    if cv.waitKey(1) == 13:
        break
cam_capture.release()
cv.destroyAllWindows()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr  9 21:09:48 2018

@author: xinjie
"""

import pandas as pd
import numpy as np
from numpy.linalg import inv, det, norm
import matplotlib.pyplot as plt
from scipy.optimize import minimize
df = pd.read_csv(r'/home/xinjie/Dropbox/courses/2018_Spring/STAT_MODEL/sds383d/code/ex4/iris.csv')
x = np.array(df.iloc[:, 1:3])
y = np.zeros(3 * len(x))
y[0:len(x)] = df.iloc[:, 5] == 'setosa'
y[len(x):2*len(x)] = df.iloc[:, 5] == 'versicolor'
y[2*len(x):3*len(x)] = df.iloc[:, 5] == 'virginica'

def kernel(x, y, l):
    n = x.shape[0]
    m = y.shape[0]
    result = np.zeros((n,m))
    for i in range(n):
        for j in range(m):
            result[i,j] = kernel_comp(x[i,:], y[j, :], l)
    return result
def kernel_comp(x, y, l):
    return np.exp(-norm(x-y)**2/(2*l**2))

K = kernel(x, x, 1)
K_inv = inv(K + 0.001*np.identity(K.shape[0]))
n = len(x)
def posterior(f, K_inv, y, n):
    result = -0.5 * np.dot(f[0:n], np.dot(K_inv, f[0:n]))-0.5 * np.dot(f[n:2*n], np.dot(K_inv, f[n:2*n]))-0.5 * np.dot(f[2*n:3*n], np.dot(K_inv, f[2*n:3*n]))
    result += np.dot(y, f)
    for i in range(n):
        result -= np.log(np.exp(f[i]) + np.exp(f[i+n]) + np.exp(f[i + 2*n]))
    return result
def negposterior(f, K_inv, y, n):
    result = -posterior(f, K_inv, y, n)
    return result
def derivative(f, K_inv, y, n):
    result = np.zeros(len(f))
    result[0:n] = np.dot(K_inv, f[0:n])
    result[n:2*n] = np.dot(K_inv, f[n:2*n])
    result[2*n:3*n] = np.dot(K_inv, f[2*n:3*n])
    pi = np.zeros(len(f))
    expf = np.exp(f)
    tmp = (expf[0:n] + expf[n:2*n] + expf[2*n:3*n])
    pi[0:n] = expf[0:n] / tmp
    pi[n:2*n] = expf[n:2*n] / tmp
    pi[2*n:3*n] = expf[2*n:3*n] / tmp
    result  += pi - y
    return result
res = minimize(negposterior, x0 = np.ones(450), args = (K_inv,y,n), method='BFGS', jac=derivative, options={'disp': True})

expf = np.exp(res.x)
predict1 = expf[0:n] / (expf[0:n] + expf[n:2*n] + expf[2*n:3*n])
predict2 = expf[n:2*n]/ (expf[0:n] + expf[n:2*n] + expf[2*n:3*n])
predict3 = expf[2*n:3*n] / (expf[0:n] + expf[n:2*n] + expf[2*n:3*n])
plt.plot(predict1)
plt.plot(predict2)
plt.plot(predict3)
## prediction for new x*
numpoints = 20
x = np.array(df.iloc[:, 1:3])
tmp = np.meshgrid(*[np.linspace(i,j, numpoints) for i, j in zip(np.amin(x, axis = 0), np.amax(x, axis = 0))])
x_star = np.zeros((numpoints**2, 2))
x_star[:,0] = np.reshape(tmp[0], (1,-1))
x_star[:,1] = np.reshape(tmp[1], (1,-1))
l = 1
K = kernel(x, x, l)
K_star = kernel(x_star, x, l)
K_starstar = kernel(x_star, x_star, l)
K_inv = inv(K + 0.0001*np.identity(K.shape[0]))

mean_star1 = K_star @ K_inv @ res.x[0:n]
mean_star2 = K_star @ K_inv @ res.x[n:2*n]
mean_star3 = K_star @ K_inv @ res.x[2*n:3*n]
sd_star = np.power(np.diag(K_starstar - K_star @ K_inv @ K_star.T), 1/2)
mean_matrix1 = np.exp(np.reshape(mean_star1, (numpoints, numpoints)))
mean_matrix2 = np.exp(np.reshape(mean_star2, (numpoints, numpoints)))
mean_matrix3 = np.exp(np.reshape(mean_star3, (numpoints, numpoints)))
sum_mean_matrix = mean_matrix1 + mean_matrix2 + mean_matrix3
prob_matrix1 = mean_matrix1 / sum_mean_matrix
prob_matrix2 = mean_matrix2 / sum_mean_matrix
prob_matrix3 = mean_matrix3 / sum_mean_matrix
sd_matrix = np.reshape(sd_star, (numpoints, numpoints))

plt.subplots_adjust(hspace=0.5,
                    wspace=0.35)
plt.subplot(2,2,1)
plt.pcolormesh(prob_matrix1,  cmap='RdBu_r')
plt.colorbar()
curves = 10
m = max([max(row) for row in prob_matrix1])
levels = np.arange(0, m, (1 / float(curves)) * m)
plt.contour(prob_matrix1, colors="white", levels=levels)
plt.title('Probabilities in class ' + 'setosa')
#plt.xlabel(list(df)[1])
#plt.ylabel(list(df)[2])

plt.subplot(2,2,2)
plt.pcolormesh(prob_matrix2,  cmap='RdBu_r')
plt.colorbar()
curves = 10
m = max([max(row) for row in prob_matrix2])
levels = np.arange(0, m, (1 / float(curves)) * m)
plt.contour(prob_matrix2, colors="white", levels=levels)
plt.title('Probabilities in class ' + 'versicolor')
#plt.xlabel(list(df)[1])
#plt.ylabel(list(df)[2])

plt.subplot(2,2,3)
plt.pcolormesh(prob_matrix3,  cmap='RdBu_r')
plt.colorbar()
curves = 10
m = max([max(row) for row in prob_matrix3])
levels = np.arange(0, m, (1 / float(curves)) * m)
plt.contour(prob_matrix3, colors="white", levels=levels)
plt.title('Probabilities in class ' + 'virginica')
#plt.xlabel(list(df)[1])
#plt.ylabel(list(df)[2])

plt.subplot(2,2,4)
plt.pcolormesh(sd_matrix,  cmap='RdBu_r')
plt.colorbar()
curves = 10
m = max([max(row) for row in sd_matrix])
levels = np.arange(0, m, (1 / float(curves)) * m)
plt.contour(sd_matrix, colors="white", levels=levels)
plt.title('Uncertainty(sd) of predictions')
#plt.xlabel(list(df)[1])
#plt.ylabel(list(df)[2])


import os
from azure.cognitiveservices.language.luis.runtime.models import LuisResult

from botbuilder.ai.luis import LuisApplication, LuisRecognizer, LuisPredictionOptions
from botbuilder.ai.qna import QnAMaker, QnAMakerEndpoint
from botbuilder.core import ActivityHandler, TurnContext, RecognizerResult, CardFactory, MessageFactory
from botbuilder.schema import ChannelAccount, HeroCard, ActionTypes, CardAction, CardImage, Attachment

from config import DefaultConfig
import pandas as pd
from geopy.geocoders import AzureMaps
import geopy
# Set a sane HTTP request timeout for geopy
geopy.geocoders.options.default_timeout = 8

from . import helpers

class HeroBot(ActivityHandler):
    def __init__(self, config: DefaultConfig):

        luis_application = LuisApplication(
            config.LUIS_APP_ID,
            config.LUIS_API_KEY,
            "https://" + config.LUIS_API_HOST_NAME,
        )
        luis_options = LuisPredictionOptions(
            include_all_intents=True, include_instance_data=True
        )
        self.recognizer = LuisRecognizer(luis_application, luis_options, True)

        self.fetch_dataset()

        self._AzMap = AzureMaps(subscription_key=config.AZURE_MAPS_KEY)

    def fetch_dataset(self):
        self._confirmed = pd.read_csv(
            "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Confirmed.csv",
            index_col=["Country/Region", "Province/State"]).iloc[:, -1]
        self._deaths = pd.read_csv(
            "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Deaths.csv",
            index_col=["Country/Region", "Province/State"]).iloc[:, -1]
        self._recovered = pd.read_csv(
            "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Recovered.csv",
            index_col=["Country/Region", "Province/State"]).iloc[:, -1]
        self._curr_date = pd.to_datetime(self._confirmed.name)

    def _filter_by_cntry(self, cntry):
        out = None
        try:
            out = (self._confirmed[cntry].sum(), self._deaths[cntry].sum(), self._recovered[cntry].sum())
        except Exception as e:
            out = None
            print(f"[WARNING] Encountered country matching problem, Country =  {e}")
        return out

    async def on_members_added_activity(
        self, members_added: [ChannelAccount], turn_context: TurnContext
    ):
        for member in members_added:
            if member.id != turn_context.activity.recipient.id:
                card = HeroCard(
                    title="Welcome to the COVID-19 Information bot",
                    images=[
                        CardImage(
                            url="https://i.imgur.com/zm095AG.png"
                        )
                    ],
                    buttons=[
                        CardAction(
                            type=ActionTypes.open_url,
                            title="Repository link",
                            value="https://github.com/vykhand/realherobot",
                        )
                    ],
                )
                repl = MessageFactory.list([])
                repl.attachments.append(CardFactory.hero_card(card))
                await turn_context.send_activity(repl)

    async def on_message_activity(self, turn_context: TurnContext):
        # First, we use the dispatch model to determine which cognitive service (LUIS or QnA) to use.
        recognizer_result = await self.recognizer.recognize(turn_context)

        # Top intent tell us which cognitive service to use.
        intent = LuisRecognizer.top_intent(recognizer_result)

        # Next, we call the dispatcher with the top intent.
        await self._dispatch_to_top_intent(turn_context, intent, recognizer_result)

    async def _dispatch_to_top_intent(
        self, turn_context: TurnContext, intent, recognizer_result: RecognizerResult
    ):
        if intent == "get-status":
            await self._get_status(
                turn_context, recognizer_result.properties["luisResult"]
            )
        elif intent == "None":
            await self._none(
                turn_context, recognizer_result.properties["luisResult"]
            )
        else:
            await turn_context.send_activity(f"Dispatch unrecognized intent: {intent}.")
    async def _get_status(self, turn_context: TurnContext, luis_result: LuisResult):
        # await turn_context.send_activity(
        #     f"Matched intent {luis_result.top_scoring_intent}."
        # )
        #
        # intents_list = "\n\n".join(
        #     [intent_obj.intent for intent_obj in luis_result.intents]
        # )
        # await turn_context.send_activity(
        #     f"Other intents detected: {intents_list}."
        # )
        #

        outputs =  []
        if luis_result.entities:
            for ent in luis_result.entities:
                loc = self._AzMap.geocode(ent.entity, language='en-US')
                cntry = loc.raw["address"]["country"]
                out = self._filter_by_cntry(cntry)
                if out is None:
                    cntry_code = loc.raw["address"]["countryCode"]
                    out = self._filter_by_cntry( cntry_code)
                if out is not None:
                    confirmed, deaths, recovered = out
                    dt  = helpers.to_human_readable(self._curr_date)
                    outputs.append(f"As of {dt}, for Country: {cntry} there were {confirmed} confirmed cases, {deaths} deaths and {recovered} recoveries")
                else:
                    #TODO: propose the card with options
                    outputs.append(f"Country : {cntry}, Code: {cntry_code} not found in the dataset, please try different spelling")
            await turn_context.send_activity(
                 "\n".join(outputs)
             )

    async def _none(self, turn_context: TurnContext, luis_result: LuisResult):
        await self._get_status(turn_context, luis_result)
        return


import argparse

import torch

def load_model(model_path):
    try:
        ckpt = torch.load(model_path)
    except RuntimeError:
        ckpt = torch.load(model_path, map_location="cpu")

    if "model" in ckpt.keys():
        return ckpt["model"]
    return ckpt

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--novel-model", type=str,
                        required=True,
                        help="path to the final trained model")
    parser.add_argument("--base-model", type=str,
                        default="/path/to/your/model.pth",
                        help="path to the base model")
    parser.add_argument("--save-model", type=str,
                        default="model_redetect.pth",
                        help="path to the saved model")
    return parser.parse_args()

def combine_and_save(
    base_model="/path/to/your/model.pth",
    novel_model="log/model_final.pth",
    save_model="log/model_redetect.pth"
):
    base_model = load_model(base_model)
    novel_model = load_model(novel_model)
    # ensemble rpn
    rpn_cls_keys = [
        'proposal_generator.rpn_head.objectness_logits.weight',
        'proposal_generator.rpn_head.objectness_logits.bias'
    ]
    for k in rpn_cls_keys:
        novel_model[k.replace(".objectness", ".finetuned_objectness")] = \
            novel_model[k]
        novel_model[k] = base_model[k]
    rpn_keys = [k for k in base_model.keys() if "rpn" in k]
    for k in rpn_keys:
        assert torch.all(base_model[k] == novel_model[k]), f"{k} not equal!"

    torch.save(novel_model, save_model)
    return save_model

if __name__ == "__main__":
    args = parse_args()
    combine_and_save(args.base_model, args.novel_model, args.save_model)


# coding:utf-8
# Copyright (C)
# Author: I
# Contact: 12157724@qq.com
import datetime

import tensorflow as tf

class __tensor_boader_single():
    def __init__(self):
        self.__tensor_board = None

    def tf_board_instance(self, name):
        log_dir = "../tmp/logs/tb/" + name + "/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
        if self.__tensor_board is None:
            print("created TensorBoard")
            self.__tensor_board = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1, profile_batch=0)
        return self.__tensor_board

tb = __tensor_boader_single()


#-- encoding: utf-8 --

from django.db import models
from django.db.models.signals import post_save
from django.utils.translation import ugettext_lazy as _

from django.contrib.auth.models import User

from django_extensions.db.fields import UUIDField
from userena.models import UserenaLanguageBaseProfile
from userena.models import PROFILE_PERMISSIONS

from apps.coworking.models import Service, ServiceConsumption

class CoroutineProfile(UserenaLanguageBaseProfile):
    """
    Userena Profile with language switch
    """
    class Meta:
        permissions = PROFILE_PERMISSIONS

    GENDER_TYPE = (
       ('M', _('male')),
       ('F', _('female'))
    )
    gender = models.CharField(max_length=1, choices=GENDER_TYPE, null=True, blank=True)
    address = models.TextField(null=True, blank=True)

    about = models.TextField(null=True, blank=True)
    birthday = models.DateField(null=True, blank=True)
    website = models.URLField(verbose_name=_('website'), verify_exists=True, max_length=200, blank=True)
    linkedin = models.URLField(verbose_name=_('linkedin'), verify_exists=True, max_length=200, blank=True)
    twitter = models.URLField(verbose_name=_('twitter'), verify_exists=True, max_length=200, blank=True)
    facebook = models.URLField(verbose_name=_('facebook'), verify_exists=True, max_length=200, blank=True)

    user = models.ForeignKey(User)

    @models.permalink
    def get_absolute_url(self):
        return ('userena_profile_detail', (), {'username': self.user.username})

class ServiceUnits(models.Model):
    """
    Available Units for a given service
    """
    card = models.ForeignKey('member.MembershipCard', related_name='remaining_units')
    service = models.ForeignKey(Service, related_name='user_units')
    amount = models.PositiveIntegerField(default=0)

    def __unicode__(self):
        return "%s - %s" % (self.service.label, self.amount)

class MembershipCard(models.Model):
    uuid = UUIDField(unique=True, db_index=True, auto=True, editable=True)

    user = models.OneToOneField(CoroutineProfile, related_name='membership_card')

    credit = models.PositiveIntegerField(default=0)
    units = models.ManyToManyField(Service, through=ServiceUnits)

    consumptions = models.ManyToManyField(Service, through=ServiceConsumption,
                                          related_name='membership_card')

    # Expiration

    def __unicode__(self):
        return u"Membership card of %s" % self.user.user


import pytest

def pytest_addoption(parser):
    parser.addoption("--custom_attribute", action="store",
                     default="", help="name of the custom attribute")
    parser.addoption("--dmp_keyspace", action="store",
                     default="", help="Cassandra keyspace to use")
    parser.addoption("--dmp_keyspace_prefix", action="store",
                     default="", help="Cassandra keyspace prefix")
    parser.addoption("--dmp_cassandra", action="store",
                     default="", help="Cassandra hosts to use")
    parser.addoption("--output_file", action="store",
                     default="segmenterData.txt",
                     help=('Synthetic data output file name.\n'
                           'The default is segmenterData.txt'))
    parser.addoption("--dmp_nibbler_ip", action="store",
                     default="10.150.71.91",
                     help='IP address of Firehose Nibbler instance')
    parser.addoption("--dmp_nibbler_port", action="store",
                     default="722",
                     help='ssh port of Firehose Nibbler instance')
    parser.addoption("--dmp_plexus_ip", action="store",
                     default="10.150.71.174",
                     help='IP address of Firehose Plexus instance')
    parser.addoption("--dmp_plexus_port", action="store",
                     default="722",
                     help='ssh port of Firehose Plexus instance')
    parser.addoption("--dmp_onboarding_ip", action="store",
                     default="10.150.71.158",
                     help='IP address of Firehose DMP Onboarding instance')
    parser.addoption("--dmp_onboarding_port", action="store",
                     default="722",
                     help='ssh port of Firehose DMP Onboarding instance')
    parser.addoption("--private_key", action="store", default='',
                     help='Need to specify a private key file to reach remote server')
    parser.addoption("--log_level", action="store",
                     default="INFO",
                     help="Need to logging level")

@pytest.fixture
def custom_attribute(request):
    """ Must specify a attributesconf file"""
    return request.config.getoption("--custom_attribute")

@pytest.fixture(scope="session")
def dmp_keyspace(request):
    """ Must specify a cassandra keyspace """
    return request.config.getoption("--dmp_keyspace")

@pytest.fixture(scope="session")
def dmp_keyspace_prefix(request):
    """ Must specify a cassandra keyspace prefix"""
    return request.config.getoption("--dmp_keyspace_prefix")

@pytest.fixture(scope="session")
def dmp_cassandra(request):
    """ Must specify a cassandra host """
    return request.config.getoption("--dmp_cassandra")

@pytest.fixture(scope="session")
def output_file(request):
    """ Optional: specify a synthetic data output file name """
    return request.config.getoption("--output_file")

@pytest.fixture(scope="session")
def dmpNibblerIP(request):
    """ IP Address of Firehose Nibbler instance """
    return request.config.getoption("--dmp_nibbler_ip")

@pytest.fixture(scope="session")
def dmpNibblerPort(request):
    """ ssh port of Firehose Nibbler instance """
    return request.config.getoption("--dmp_nibbler_port")

@pytest.fixture(scope="session")
def dmpPlexusIP(request):
    """ IP Address of Firehose Plexus instance """
    return request.config.getoption("--dmp_plexus_ip")

@pytest.fixture(scope="session")
def dmpPlexusPort(request):
    """ ssh port of Firehose Plexus instance """
    return request.config.getoption("--dmp_plexus_port")

@pytest.fixture(scope="session")
def dmpOnboardingIP(request):
    """ IP Address of Firehose DMP Onboarding instance """
    return request.config.getoption("--dmp_onboarding_ip")

@pytest.fixture(scope="session")
def dmpOnboardingPort(request):
    """ ssh port of Firehose DMP Onboarding instance """
    return request.config.getoption("--dmp_onboarding_port")

@pytest.fixture(scope="session")
def private_key(request):
    """ Must specify a private key file to reach remote server """
    return request.config.getoption("--private_key")

@pytest.fixture(scope="session")
def log_level(request):
    """ Need to specify logging level """
    return request.config.getoption("--log_level")


import numpy as np
import numpy.random as npr

from sds_numpy import ARHMM
from sds_numpy.utils import permutation

import matplotlib.pyplot as plt
from hips.plotting.colormaps import gradient_cmap

import seaborn as sns

import torch

npr.randn(1337)
torch.manual_seed(1337)

sns.set_style("white")
sns.set_context("talk")

color_names = ["windows blue", "red", "amber",
               "faded green", "dusty purple", "orange"]

colors = sns.xkcd_palette(color_names)
cmap = gradient_cmap(colors)

true_arhmm = ARHMM(nb_states=3, dm_obs=2)

# trajectory lengths
T = [1250, 1150, 1025]

true_z, x = true_arhmm.sample(horizon=T)
true_ll = true_arhmm.log_norm(x)

arhmm = ARHMM(nb_states=3, dm_obs=2, preprocess=False)
arhmm.initialize(x)

lls = arhmm.em(x, nb_iter=100, prec=0.)
print("true_ll=", true_ll, "hmm_ll=", lls[-1])

plt.figure(figsize=(5, 5))
plt.plot(np.ones(len(lls)) * true_ll, '-r')
plt.plot(lls)
plt.show()

_, arhmm_z = arhmm.viterbi(x)
_seq = npr.choice(len(x))
arhmm.permute(permutation(true_z[_seq], arhmm_z[_seq], K1=3, K2=3))

_, arhmm_z = arhmm.viterbi(x[_seq])

plt.figure(figsize=(8, 4))
plt.subplot(211)
plt.imshow(true_z[_seq][None, :], aspect="auto", cmap=cmap, vmin=0, vmax=len(colors) - 1)
plt.xlim(0, len(x[_seq]))
plt.ylabel("$z_{\\mathrm{true}}$")
plt.yticks([])

plt.subplot(212)
plt.imshow(arhmm_z[0][None, :], aspect="auto", cmap=cmap, vmin=0, vmax=len(colors) - 1)
plt.xlim(0, len(x[_seq]))
plt.ylabel("$z_{\\mathrm{inferred}}$")
plt.yticks([])
plt.xlabel("time")

plt.tight_layout()
plt.show()

arhmm_x = arhmm.mean_observation(x)

plt.figure(figsize=(8, 4))
plt.plot(x[_seq] + 10 * np.arange(arhmm.dm_obs), '-k', lw=2)
plt.plot(arhmm_x[_seq] + 10 * np.arange(arhmm.dm_obs), '-', lw=2)
plt.show()


# Copyright 2018 The Meson development team

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import shutil
import glob
import subprocess

from .. import build
from .. import mlog
from ..mesonlib import MesonException, Popen_safe, File
from . import ModuleReturnValue
from . import ExtensionModule
from ..dependencies import InternalDependency
from ..interpreterbase import permittedKwargs

class DlangModule(ExtensionModule):
    girtod_path = None

    def _detect_girtod(self, env):
        if self.girtod_path:
            return

        self.girtod_path = shutil.which('girtod')
        if not self.girtod_path:
            raise MesonException('Can not use gir-to-d, girtod binary was not found.')
        mlog.log('Found girtod:', mlog.bold(self.girtod_path))

    @permittedKwargs({'gir_dir'})
    def gir_to_d(self, state, args, kwargs):
        self._detect_girtod(state.environment)

        if len(args) < 1:
            raise MesonException('Not enough arguments; The path to the wrap files directory is required')

        wrap_dir = args[0]
        if isinstance(wrap_dir, str):
            wrap_dir = os.path.join(state.subdir, wrap_dir)
        else:
            raise MesonException('Invalid wrap dir argument: {!r}'.format(wrap_dir))

        build_by_default = kwargs.get('build_by_default', False)

        wrap_dir_out = os.path.join(state.environment.get_build_dir(), wrap_dir)
        wrap_dir_out = wrap_dir_out.rstrip(os.sep)
        target_name = os.path.basename(wrap_dir_out) + '-bind'
        wrap_dir_out = wrap_dir_out + '.gen'
        os.makedirs(wrap_dir_out, exist_ok=True)

        cmd = [self.girtod_path,
               '-i', wrap_dir,
               '-o', wrap_dir_out]
        if 'gir_dir' in kwargs:
            gir_dir = kwargs.pop('gir_dir')
            if not isinstance(gir_dir, str):
                raise MesonException('Invalid gir dir argument: {!r}'.format(wrap_dir))
            cmd.extend(['-g', gir_dir])

        pc, stdout, stderr = Popen_safe(cmd, cwd=state.environment.get_source_dir())
        if pc.returncode != 0:
            m = 'girtod failed to generate D bindings {}:\n{}'
            mlog.warning(m.format(cmd[1], stderr))
            raise subprocess.CalledProcessError(pc.returncode, cmd)

        d_sources = []
        build_dir = os.path.relpath(state.environment.get_build_dir(), state.environment.get_source_dir())
        files = glob.glob(os.path.join(wrap_dir_out, '**', '*.d'), recursive=True)
        for fname in sorted(files):
            rel_fname = os.path.relpath(fname, state.environment.get_build_dir())
            d_sources.append(File.from_source_file(state.environment.get_source_dir(), build_dir, rel_fname))

        # generate static library target to compile the D wrapper code, which can be added
        # to the actual targets using the wrapped library.
        inc_dirs = build.IncludeDirs(state.subdir, [wrap_dir_out], False)
        custom_kwargs = {'build_by_default': build_by_default,
                         'install': False,
                         'include_directories': inc_dirs
                         }
        target = build.StaticLibrary(target_name,
                                     state.subdir,
                                     state.subproject,
                                     state.environment.is_cross_build(),
                                     d_sources,
                                     [],
                                     state.environment,
                                     custom_kwargs)

        rv = InternalDependency(None, inc_dirs, [], [], [target], [], [], [])

        return ModuleReturnValue(rv, [rv])

def initialize(*args, **kwargs):
    return DlangModule(*args, **kwargs)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Classes for nonlinearities

@author: Benjamin Cowen, Feb 24 2018
@contact: bc1947@nyu.edu, bencowen.com/lsalsa
"""
from torch.autograd import Variable
import torch
import torch.nn as nn
import torch.nn.functional as F

def nothing():
    pass

class soft_thresh(nn.Module):

    def __init__(self,lams,n_list=[],use_cuda=False):
        super(soft_thresh, self).__init__()

        self.use_cuda = use_cuda
        self.shrink = []
        self.n_list = n_list

        if type(lams)==float:
            self.lams = [lams]
            self.shrink.append( nn.Softshrink(lams) )

        elif type(lams)==list:
            self.lams = lams
            for lam in lams:
               self.shrink.append( nn.Softshrink(lam) )

        if use_cuda:
            for s,shr in enumerate(self.shrink):
               self.shrink[s]= shr.cuda()

#        soft_thresh.register_forward_pre_hook(nothing)

    def forward(self,input):

        if len(self.lams)==1:
           return self.shrink[0](input)
        else:
           outputs = []
           beg = 0
           n_d = 0
           for t,shrink in enumerate(self.shrink):
               beg += n_d
               n_d = self.n_list[t]
               outputs.append( shrink(input.narrow(1,beg,n_d)) )
           return torch.cat(outputs,1)

class one_hard_thresh(nn.Module):

    def __init__(self, lam, wantcuda):
        super(one_hard_thresh, self).__init__()
        if wantcuda:
            self.hard = nn.Threshold(lam,0).cuda()
        else:
            self.hard = nn.Threshold(lam,0)

    def forward(self,input):
        return torch.mul(torch.sign(input),self.hard(input.abs()))

class hard_thresh(nn.Module):

    def __init__(self,lams,n_list=[],use_cuda=False):
        super(hard_thresh, self).__init__()

        self.use_cuda = use_cuda
        self.thrsh = []
        self.n_list = n_list

        if type(lams)==float:
            self.lams = [lams]
            self.thrsh.append( one_hard_thresh(lams,use_cuda) )

        elif type(lams)==list:
            self.lams = lams
            for lam in lams:
               self.thrsh.append( one_hard_thresh(lam,use_cuda) )

        if use_cuda:
            for s,th in enumerate(self.thrsh):
               self.thrsh[s]= th.cuda()

#        hard_thresh.register_forward_pre_hook(nothing)

    def forward(self,input):

        if len(self.lams)==1:
           return self.thrsh[0](input)
        else:
           outputs = []
           beg = 0
           n_d = 0
           for t,thrsh in enumerate(self.thrsh):
               beg += n_d
               n_d = self.n_list[t]
               outputs.append( thrsh(input.narrow(1,beg,n_d)) )
           return torch.cat(outputs,1)

def makeSALSAthreshes(l1w,mu,ns,use_cuda):

        if type(l1w)==float:
            th = l1w/mu
        elif type(l1w)==list:
            th = []
            for a in l1w:
                th.append(1.0*a/mu)

        shrink = soft_thresh(th, ns, use_cuda)
        hard   = hard_thresh(th, ns, use_cuda)
        return shrink,hard


# coding: utf-8

"""
    AYLIEN News API

    The AYLIEN News API is the most powerful way of sourcing, searching and syndicating analyzed and enriched news content. It is accessed by sending HTTP requests to our server, which returns information to your client.   # noqa: E501

    The version of the OpenAPI document: 5.2.3
    Contact: support@aylien.com
    Generated by: https://openapi-generator.tech
"""

import pprint
import re  # noqa: F401

import six

from aylien_news_api.configuration import Configuration

class Story(object):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    """
    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    openapi_types = {
        'author': 'Author',
        'body': 'str',
        'categories': 'list[Category]',
        'characters_count': 'int',
        'clusters': 'list[int]',
        'entities': 'list[Entity]',
        'hashtags': 'list[str]',
        'id': 'int',
        'keywords': 'list[str]',
        'language': 'str',
        'links': 'StoryLinks',
        'media': 'list[Media]',
        'paragraphs_count': 'int',
        'published_datetime': 'datetime',
        'published_at': 'datetime',
        'sentences_count': 'int',
        'sentiment': 'Sentiments',
        'social_shares_count': 'ShareCounts',
        'source': 'Source',
        'summary': 'Summary',
        'title': 'str',
        'translations': 'StoryTranslations',
        'words_count': 'int',
        'license_type': 'int',
        'industries': 'list[Category]'
    }

    attribute_map = {
        'author': 'author',
        'body': 'body',
        'categories': 'categories',
        'characters_count': 'characters_count',
        'clusters': 'clusters',
        'entities': 'entities',
        'hashtags': 'hashtags',
        'id': 'id',
        'keywords': 'keywords',
        'language': 'language',
        'links': 'links',
        'media': 'media',
        'paragraphs_count': 'paragraphs_count',
        'published_datetime': 'published_datetime',
        'published_at': 'published_at',
        'sentences_count': 'sentences_count',
        'sentiment': 'sentiment',
        'social_shares_count': 'social_shares_count',
        'source': 'source',
        'summary': 'summary',
        'title': 'title',
        'translations': 'translations',
        'words_count': 'words_count',
        'license_type': 'license_type',
        'industries': 'industries'
    }

    def __init__(self, author=None, body=None, categories=None, characters_count=None, clusters=None, entities=None, hashtags=None, id=None, keywords=None, language=None, links=None, media=None, paragraphs_count=None, published_datetime=None, published_at=None, sentences_count=None, sentiment=None, social_shares_count=None, source=None, summary=None, title=None, translations=None, words_count=None, license_type=None, industries=None, local_vars_configuration=None):  # noqa: E501
        """Story - a model defined in OpenAPI"""  # noqa: E501
        if local_vars_configuration is None:
            local_vars_configuration = Configuration()
        self.local_vars_configuration = local_vars_configuration

        self._author = None
        self._body = None
        self._categories = None
        self._characters_count = None
        self._clusters = None
        self._entities = None
        self._hashtags = None
        self._id = None
        self._keywords = None
        self._language = None
        self._links = None
        self._media = None
        self._paragraphs_count = None
        self._published_datetime = None
        self._published_at = None
        self._sentences_count = None
        self._sentiment = None
        self._social_shares_count = None
        self._source = None
        self._summary = None
        self._title = None
        self._translations = None
        self._words_count = None
        self._license_type = None
        self._industries = None
        self.discriminator = None

        if author is not None:
            self.author = author
        if body is not None:
            self.body = body
        if categories is not None:
            self.categories = categories
        if characters_count is not None:
            self.characters_count = characters_count
        if clusters is not None:
            self.clusters = clusters
        if entities is not None:
            self.entities = entities
        if hashtags is not None:
            self.hashtags = hashtags
        if id is not None:
            self.id = id
        if keywords is not None:
            self.keywords = keywords
        if language is not None:
            self.language = language
        if links is not None:
            self.links = links
        if media is not None:
            self.media = media
        if paragraphs_count is not None:
            self.paragraphs_count = paragraphs_count
        if published_datetime is not None:
            self.published_datetime = published_datetime
        if published_at is not None:
            self.published_at = published_at
        if sentences_count is not None:
            self.sentences_count = sentences_count
        if sentiment is not None:
            self.sentiment = sentiment
        if social_shares_count is not None:
            self.social_shares_count = social_shares_count
        if source is not None:
            self.source = source
        if summary is not None:
            self.summary = summary
        if title is not None:
            self.title = title
        if translations is not None:
            self.translations = translations
        if words_count is not None:
            self.words_count = words_count
        if license_type is not None:
            self.license_type = license_type
        if industries is not None:
            self.industries = industries

    @property
    def author(self):
        """Gets the author of this Story.  # noqa: E501

        :return: The author of this Story.  # noqa: E501
        :rtype: Author
        """
        return self._author

    @author.setter
    def author(self, author):
        """Sets the author of this Story.

        :param author: The author of this Story.  # noqa: E501
        :type author: Author
        """

        self._author = author

    @property
    def body(self):
        """Gets the body of this Story.  # noqa: E501

        Body of the story  # noqa: E501

        :return: The body of this Story.  # noqa: E501
        :rtype: str
        """
        return self._body

    @body.setter
    def body(self, body):
        """Sets the body of this Story.

        Body of the story  # noqa: E501

        :param body: The body of this Story.  # noqa: E501
        :type body: str
        """

        self._body = body

    @property
    def categories(self):
        """Gets the categories of this Story.  # noqa: E501

        Suggested categories for the story  # noqa: E501

        :return: The categories of this Story.  # noqa: E501
        :rtype: list[Category]
        """
        return self._categories

    @categories.setter
    def categories(self, categories):
        """Sets the categories of this Story.

        Suggested categories for the story  # noqa: E501

        :param categories: The categories of this Story.  # noqa: E501
        :type categories: list[Category]
        """

        self._categories = categories

    @property
    def characters_count(self):
        """Gets the characters_count of this Story.  # noqa: E501

        Character count of the story body  # noqa: E501

        :return: The characters_count of this Story.  # noqa: E501
        :rtype: int
        """
        return self._characters_count

    @characters_count.setter
    def characters_count(self, characters_count):
        """Sets the characters_count of this Story.

        Character count of the story body  # noqa: E501

        :param characters_count: The characters_count of this Story.  # noqa: E501
        :type characters_count: int
        """

        self._characters_count = characters_count

    @property
    def clusters(self):
        """Gets the clusters of this Story.  # noqa: E501

        An array of clusters the story is associated with  # noqa: E501

        :return: The clusters of this Story.  # noqa: E501
        :rtype: list[int]
        """
        return self._clusters

    @clusters.setter
    def clusters(self, clusters):
        """Sets the clusters of this Story.

        An array of clusters the story is associated with  # noqa: E501

        :param clusters: The clusters of this Story.  # noqa: E501
        :type clusters: list[int]
        """

        self._clusters = clusters

    @property
    def entities(self):
        """Gets the entities of this Story.  # noqa: E501

        An array of entities  # noqa: E501

        :return: The entities of this Story.  # noqa: E501
        :rtype: list[Entity]
        """
        return self._entities

    @entities.setter
    def entities(self, entities):
        """Sets the entities of this Story.

        An array of entities  # noqa: E501

        :param entities: The entities of this Story.  # noqa: E501
        :type entities: list[Entity]
        """

        self._entities = entities

    @property
    def hashtags(self):
        """Gets the hashtags of this Story.  # noqa: E501

        An array of suggested Story hashtags  # noqa: E501

        :return: The hashtags of this Story.  # noqa: E501
        :rtype: list[str]
        """
        return self._hashtags

    @hashtags.setter
    def hashtags(self, hashtags):
        """Sets the hashtags of this Story.

        An array of suggested Story hashtags  # noqa: E501

        :param hashtags: The hashtags of this Story.  # noqa: E501
        :type hashtags: list[str]
        """

        self._hashtags = hashtags

    @property
    def id(self):
        """Gets the id of this Story.  # noqa: E501

        ID of the story which is a unique identification  # noqa: E501

        :return: The id of this Story.  # noqa: E501
        :rtype: int
        """
        return self._id

    @id.setter
    def id(self, id):
        """Sets the id of this Story.

        ID of the story which is a unique identification  # noqa: E501

        :param id: The id of this Story.  # noqa: E501
        :type id: int
        """

        self._id = id

    @property
    def keywords(self):
        """Gets the keywords of this Story.  # noqa: E501

        Extracted keywords mentioned in the story title or body  # noqa: E501

        :return: The keywords of this Story.  # noqa: E501
        :rtype: list[str]
        """
        return self._keywords

    @keywords.setter
    def keywords(self, keywords):
        """Sets the keywords of this Story.

        Extracted keywords mentioned in the story title or body  # noqa: E501

        :param keywords: The keywords of this Story.  # noqa: E501
        :type keywords: list[str]
        """

        self._keywords = keywords

    @property
    def language(self):
        """Gets the language of this Story.  # noqa: E501

        Language of the story  # noqa: E501

        :return: The language of this Story.  # noqa: E501
        :rtype: str
        """
        return self._language

    @language.setter
    def language(self, language):
        """Sets the language of this Story.

        Language of the story  # noqa: E501

        :param language: The language of this Story.  # noqa: E501
        :type language: str
        """

        self._language = language

    @property
    def links(self):
        """Gets the links of this Story.  # noqa: E501

        :return: The links of this Story.  # noqa: E501
        :rtype: StoryLinks
        """
        return self._links

    @links.setter
    def links(self, links):
        """Sets the links of this Story.

        :param links: The links of this Story.  # noqa: E501
        :type links: StoryLinks
        """

        self._links = links

    @property
    def media(self):
        """Gets the media of this Story.  # noqa: E501

        An array of extracted media such as images and videos  # noqa: E501

        :return: The media of this Story.  # noqa: E501
        :rtype: list[Media]
        """
        return self._media

    @media.setter
    def media(self, media):
        """Sets the media of this Story.

        An array of extracted media such as images and videos  # noqa: E501

        :param media: The media of this Story.  # noqa: E501
        :type media: list[Media]
        """

        self._media = media

    @property
    def paragraphs_count(self):
        """Gets the paragraphs_count of this Story.  # noqa: E501

        Paragraph count of the story body  # noqa: E501

        :return: The paragraphs_count of this Story.  # noqa: E501
        :rtype: int
        """
        return self._paragraphs_count

    @paragraphs_count.setter
    def paragraphs_count(self, paragraphs_count):
        """Sets the paragraphs_count of this Story.

        Paragraph count of the story body  # noqa: E501

        :param paragraphs_count: The paragraphs_count of this Story.  # noqa: E501
        :type paragraphs_count: int
        """

        self._paragraphs_count = paragraphs_count

    @property
    def published_datetime(self):
        """Gets the published_datetime of this Story.  # noqa: E501

        Publication time of the story, if available, otherwise time of acquisition  # noqa: E501

        :return: The published_datetime of this Story.  # noqa: E501
        :rtype: datetime
        """
        return self._published_datetime

    @published_datetime.setter
    def published_datetime(self, published_datetime):
        """Sets the published_datetime of this Story.

        Publication time of the story, if available, otherwise time of acquisition  # noqa: E501

        :param published_datetime: The published_datetime of this Story.  # noqa: E501
        :type published_datetime: datetime
        """

        self._published_datetime = published_datetime

    @property
    def published_at(self):
        """Gets the published_at of this Story.  # noqa: E501

        Acquisition time of the story  # noqa: E501

        :return: The published_at of this Story.  # noqa: E501
        :rtype: datetime
        """
        return self._published_at

    @published_at.setter
    def published_at(self, published_at):
        """Sets the published_at of this Story.

        Acquisition time of the story  # noqa: E501

        :param published_at: The published_at of this Story.  # noqa: E501
        :type published_at: datetime
        """

        self._published_at = published_at

    @property
    def sentences_count(self):
        """Gets the sentences_count of this Story.  # noqa: E501

        Sentence count of the story body  # noqa: E501

        :return: The sentences_count of this Story.  # noqa: E501
        :rtype: int
        """
        return self._sentences_count

    @sentences_count.setter
    def sentences_count(self, sentences_count):
        """Sets the sentences_count of this Story.

        Sentence count of the story body  # noqa: E501

        :param sentences_count: The sentences_count of this Story.  # noqa: E501
        :type sentences_count: int
        """

        self._sentences_count = sentences_count

    @property
    def sentiment(self):
        """Gets the sentiment of this Story.  # noqa: E501

        :return: The sentiment of this Story.  # noqa: E501
        :rtype: Sentiments
        """
        return self._sentiment

    @sentiment.setter
    def sentiment(self, sentiment):
        """Sets the sentiment of this Story.

        :param sentiment: The sentiment of this Story.  # noqa: E501
        :type sentiment: Sentiments
        """

        self._sentiment = sentiment

    @property
    def social_shares_count(self):
        """Gets the social_shares_count of this Story.  # noqa: E501

        :return: The social_shares_count of this Story.  # noqa: E501
        :rtype: ShareCounts
        """
        return self._social_shares_count

    @social_shares_count.setter
    def social_shares_count(self, social_shares_count):
        """Sets the social_shares_count of this Story.

        :param social_shares_count: The social_shares_count of this Story.  # noqa: E501
        :type social_shares_count: ShareCounts
        """

        self._social_shares_count = social_shares_count

    @property
    def source(self):
        """Gets the source of this Story.  # noqa: E501

        :return: The source of this Story.  # noqa: E501
        :rtype: Source
        """
        return self._source

    @source.setter
    def source(self, source):
        """Sets the source of this Story.

        :param source: The source of this Story.  # noqa: E501
        :type source: Source
        """

        self._source = source

    @property
    def summary(self):
        """Gets the summary of this Story.  # noqa: E501

        :return: The summary of this Story.  # noqa: E501
        :rtype: Summary
        """
        return self._summary

    @summary.setter
    def summary(self, summary):
        """Sets the summary of this Story.

        :param summary: The summary of this Story.  # noqa: E501
        :type summary: Summary
        """

        self._summary = summary

    @property
    def title(self):
        """Gets the title of this Story.  # noqa: E501

        Title of the story  # noqa: E501

        :return: The title of this Story.  # noqa: E501
        :rtype: str
        """
        return self._title

    @title.setter
    def title(self, title):
        """Sets the title of this Story.

        Title of the story  # noqa: E501

        :param title: The title of this Story.  # noqa: E501
        :type title: str
        """

        self._title = title

    @property
    def translations(self):
        """Gets the translations of this Story.  # noqa: E501

        :return: The translations of this Story.  # noqa: E501
        :rtype: StoryTranslations
        """
        return self._translations

    @translations.setter
    def translations(self, translations):
        """Sets the translations of this Story.

        :param translations: The translations of this Story.  # noqa: E501
        :type translations: StoryTranslations
        """

        self._translations = translations

    @property
    def words_count(self):
        """Gets the words_count of this Story.  # noqa: E501

        Word count of the story body  # noqa: E501

        :return: The words_count of this Story.  # noqa: E501
        :rtype: int
        """
        return self._words_count

    @words_count.setter
    def words_count(self, words_count):
        """Sets the words_count of this Story.

        Word count of the story body  # noqa: E501

        :param words_count: The words_count of this Story.  # noqa: E501
        :type words_count: int
        """

        self._words_count = words_count

    @property
    def license_type(self):
        """Gets the license_type of this Story.  # noqa: E501

        License type of the story  # noqa: E501

        :return: The license_type of this Story.  # noqa: E501
        :rtype: int
        """
        return self._license_type

    @license_type.setter
    def license_type(self, license_type):
        """Sets the license_type of this Story.

        License type of the story  # noqa: E501

        :param license_type: The license_type of this Story.  # noqa: E501
        :type license_type: int
        """

        self._license_type = license_type

    @property
    def industries(self):
        """Gets the industries of this Story.  # noqa: E501

        An array of industries categories  # noqa: E501

        :return: The industries of this Story.  # noqa: E501
        :rtype: list[Category]
        """
        return self._industries

    @industries.setter
    def industries(self, industries):
        """Sets the industries of this Story.

        An array of industries categories  # noqa: E501

        :param industries: The industries of this Story.  # noqa: E501
        :type industries: list[Category]
        """

        self._industries = industries

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.openapi_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, Story):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        if not isinstance(other, Story):
            return True

        return self.to_dict() != other.to_dict()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from db import *
from flask import Flask ,render_template,jsonify,request

app = Flask(__name__)

@app.route('/')
def index():
	return render_template('index.html')

@app.route('/get_item_list',methods=['POST'])
def get_item_list():
	if request.method=='POST':
		page_num,limt,item_type=(int(request.form['page_num']),int(request.form['limt']),str(request.form['item_type']))
		data=db_get_item_list(page_num,limt,item_type)
		return jsonify({'stat_code':200,'data':data})
@app.route('/get_items_pics',methods=['POST'])
def get_items_pics():
	if request.method=='POST':
		item_id=int(request.form['item_id'])
		data=db_get_item_pic(item_id)
		return jsonify(data)

if __name__=='__main__':
	app.run(host='localhost',port='80')


import asyncio

async def myCoroutine():
    print("Simple Event Loop Example")

def main():
    # Define an instance of an event loop
    loop = asyncio.get_event_loop()
    # Tell this event loop to run until all the tasks assigned
    # to it are complete. In this example just the execution of
    # our myCoroutine() coroutine.
    loop.run_until_complete(myCoroutine())
    # Tidying up our loop by calling close()
    loop.close()

if __name__ == '__main__':
    main()


import re

from setuptools import setup
from setuptools.command.test import test

# use pytest instead
def run_tests(self):
    pyc = re.compile(r'\.pyc|\$py\.class')
    test_file = pyc.sub('.py', __import__(self.test_suite).__file__)
    raise SystemExit(__import__('pytest').main(['-vv', test_file]))
test.run_tests = run_tests

setup(
    name='ingreedypy',
    py_modules=['ingreedypy'],
    version='1.3.1',
    description='ingreedy-py parses recipe ingredient lines into a object',
    author='Scott Cooper',
    author_email='scttcper@gmail.com',
    url='https://github.com/openculinary/ingreedy-py',
    keywords=['ingreedy', 'ingreedypy', 'recipe', 'parser'],
    install_requires=[
        'parsimonious'
    ],
    tests_require=['pytest'],
    test_suite='ingreedytest',
    classifiers=[],
)


import datetime
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Buzz',
            fields=[
                ('id_buzz', models.AutoField(primary_key=True, serialize=False)),
                ('text', models.TextField(max_length=140)),
                ('created_at', models.DateTimeField(blank=True, default=datetime.datetime.now)),
                ('published_date', models.DateTimeField(blank=True, null=True)),
                ('file', models.FileField(blank=True, upload_to='buzzfile', verbose_name='Buzz File')),
                ('file_type', models.CharField(max_length=100)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Chat',
            fields=[
                ('id_chat', models.AutoField(primary_key=True, serialize=False)),
                ('name', models.CharField(max_length=50)),
                ('members', models.ManyToManyField(blank=True, to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Follow',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created', models.DateTimeField(auto_now_add=True, db_index=True)),
                ('rejected', models.DateTimeField(blank=True, null=True)),
                ('followed', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='who_follows', to=settings.AUTH_USER_MODEL)),
                ('follower', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='who_is_followed', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'ordering': ('-created',),
            },
        ),
        migrations.CreateModel(
            name='Hashtag',
            fields=[
                ('text', models.TextField(max_length=140, primary_key=True, serialize=False)),
                ('buzzs', models.ManyToManyField(to='buzzer.Buzz')),
            ],
        ),
        migrations.CreateModel(
            name='Message',
            fields=[
                ('id_message', models.AutoField(primary_key=True, serialize=False)),
                ('date', models.DateTimeField(blank=True, null=True)),
                ('content', models.CharField(max_length=140)),
                ('notified', models.BooleanField(default=False)),
                ('chat', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='buzzer.Chat')),
                ('user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='Notification',
            fields=[
                ('id_notification', models.AutoField(primary_key=True, serialize=False)),
                ('title', models.TextField(max_length=140)),
                ('description', models.TextField(max_length=140)),
                ('created', models.DateTimeField(auto_now_add=True, db_index=True)),
                ('showed', models.BooleanField(default=False)),
                ('type_notification', models.PositiveIntegerField(default=0)),
                ('buzz', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='buzzer.Buzz')),
                ('follower', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='follower', to=settings.AUTH_USER_MODEL)),
                ('message', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='buzzer.Message')),
                ('user_notify', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='who_is_notified', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'ordering': ('-created',),
            },
        ),
        migrations.CreateModel(
            name='Profile',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('screen_name', models.CharField(max_length=50)),
                ('location', models.CharField(max_length=150)),
                ('url', models.CharField(max_length=150)),
                ('bio', models.CharField(max_length=150)),
                ('birthday', models.DateField(null=True)),
                ('image', models.ImageField(default='media/buzzer_logo.png', upload_to='media', verbose_name='Image')),
                ('count_follower', models.PositiveIntegerField(default=0)),
                ('count_followed', models.PositiveIntegerField(default=0)),
                ('count_notification', models.PositiveIntegerField(default=0)),
                ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
    ]


from Heartbeat import Monitor
from Heartbeat import Heartbeat_Maker
import time
import multiprocessing
import queue

True_Message=6 #count of true message
None_Message=5 #count of false message
q = multiprocessing.Queue()
if __name__ == "__main__":

    po=Heartbeat_Maker(q,True_Message,None_Message)
    pq=Monitor(q)

    #creating multiprocessing
    t2 = multiprocessing.Process(target=pq.run)
    t1 = multiprocessing.Process(target=po.run)

    #starting
    t2.start()
    t1.start()

    t1.join()
    t2.join()


# Snake
import curses
import time
import random #for the food
screen = curses.initscr()
screen.keypad(1)
dims = screen.getmaxyx()
def game():
    screen = curses.initscr()
    screen.nodelay(1)  # it's on,don't have to wait for anything to happen
    head = [1, 1]
    body = [head[:]]*5 #"[:]" <-- means "copy", five times
    screen.border()
    direction = 0 #0: right, 1: down, 2: left, 3: up
    gameover = False
    foodmade = False
    deadcell = body[-1][:]
    while not gameover: #True is not working because of gameover's False&True

        while not foodmade:
            y, x = random.randrange(1, int(dims[0]-1)), random.randrange(1, int(dims[1]-1))
            if screen.inch(y, x) == ord(' '):
                foodmade = True
                screen.addch(y, x, ord("o"))

        if deadcell not in body:
            screen.addch(deadcell[0], deadcell[1], ' ')
        screen.addch(head[0], head[1], '¤')

        action = screen.getch()
        if action == curses.KEY_UP and direction != 1: #if action is KEY_UP and dir. is not down(+1)
            direction = 3
        elif action == curses.KEY_DOWN and direction != 3:#doesn't allow the snake to simply turn around
            direction = 1
        elif action == curses.KEY_RIGHT and direction != 2:
            direction = 0
        elif action == curses.KEY_LEFT and direction != 0:
            direction = 2

        if direction == 0:
            head[1] += 1
        elif direction == 2:
            head[1] -= 1
        elif direction == 1:
            head[0] += 1
        elif direction == 3:
            head[0] -= 1

        deadcell = body[-1]
        for z in range(len(body)-1, 0, -1):
            body[z] = body[z-1][:]

        body[0] = head[:]

        if screen.inch(head[0], head[1]) != ord(' '):
            if screen.inch(head[0], head[1]) == ord('o'):#this 01
                foodmade = False#this 02
                body.append(body[-1])#for growing the body
            else:#this03
                gameover = True#and this04 making the food not to esc from the game
        screen.move(int(dims[0]-1), int(dims[1]-1))
        screen.refresh()
        time.sleep(0.1)
#The following lines are still sending ERROR messages, but I've spent too many time
#with this game and not with the homework. Please ignore me that this time.
    #screen.clear()
    #screen.nodelay(0)
    #message1 = "Game Over"
    #message2 = "You got" +str(len(body)-5)+ "points."
    #message3 = "Press Space to play again"
    #message4 = "Press Enter to quit"
    #screen.addstr(int(dims[0])/2 - 1, (int(dims[1]) - len(message1))/2, message1)
    #screen.addstr(int(dims[0])/2, (int(dims[1]) - len(message2))/2, message2)
    #screen.addstr(int(dims[0])/2 + 1, (int(dims[1]) - len(message3))/2, message3)
    #screen.addstr(int(dims[0])/2 + 2, (int(dims[1]) - len(message4))/2, message4)
    #screen.refresh()
    #q = 0
    #while q not in [32, 10]:
        #q = screen.getch()
    #if q == 32:
        #game()

game()
curses.endwin()


"""# action_trackings admin
- ActionTrackingAdmin
- PointRuleAdmin
"""
from django.contrib import admin

from .models import ActionTracking, PointRule

@admin.register(ActionTracking)
class ActionTrackingAdmin(admin.ModelAdmin):
    """ ## ActionTrackingAdmin
        - admin페이지에서 관리할 ActionTracking 모델 설정
    """

    list_display = [
        'user',
        'point_rule',
        'actionable_type',
        'actionable_id',
        'count',
        'point'
    ]

    list_filter = [
        'user',
        'point_rule',
        'actionable_type',
        'actionable_id',
        'count',
    ]

    search_fields = [
        'user__name',
        'point_rule__name',
    ]

    ordering = [
        '-updated_at',
    ]

@admin.register(PointRule)
class PointRuleAdmin(admin.ModelAdmin):
    """## PointRuleAdmin
        - admin페이지에서 관리할 PointRule모델을 설정
    """

    list_display = [
        'name',
        'point',
    ]