# tạo ra file json - list of ground truth embedding vectors
# thử nghiệm trên backend trước khi deploy

import cv2
from keras_vggface.vggface import VGGFace
from tensorflow.python.keras.utils import generic_utils
from tensorflow.keras.models import load_model
from keras_vggface.utils import preprocess_input
import tensorflow as tf
from imutils import paths
import json
import numpy as np
from scipy.spatial.distance import cosine
from face_extraction import extract_face
import time

# model = VGGFace(model='resnet50', include_top=False, input_shape=(224, 224, 3), pooling='avg')
# model.save('pretrained_model')

model = load_model('models/embedding')

"""1"""
# print(model.summary())

"""2"""
# img_paths = sorted(paths.list_images('anchor'))

# feature_vectors = []

# for img_path in img_paths:
#     img = extract_face(img_path)

#     img = preprocess_input(img, version=2)
#     feature_vector = model.predict(tf.expand_dims(img, axis=0))
#     feature_vectors.append(feature_vector.tolist())

# json_object = json.dumps(feature_vectors)
# with open('embedding_database.json', 'w') as outfile:
#     outfile.write(json_object)

# print('success')

""""3"""
with open('embedding_database.json', 'r') as openfile:

    # Reading from json file
    json_object = json.load(openfile)

face_embeddings = list(map(np.array, json_object))

labels = [
    "Dang Nguyen Anh Tuan",
    "Dinh Xuan Vu",
    "Do Manh Quan",
    "Nguyen Anh Tuan",
    "Nguyen Duy Phuc",
    "Ngo Hong Quang",
    "Nguyen Thanh Vinh",
]

t1 = time.time()

def test(imgPath):
    img = extract_face(imgPath)
    img = preprocess_input(img, version=2)
    img_embedding = model.predict(tf.expand_dims(img, axis=0))

    dis_vec = [np.linalg.norm(face_embedding - img_embedding)
               for face_embedding in face_embeddings]
    idx = np.argmin(dis_vec)

    return labels[idx], dis_vec

t2 = time.time()

imgPath = 'test/5.jpg'

face, dis_vec = test(imgPath)
img = cv2.imread(imgPath)
cv2.putText(img, face, (100, 100), cv2.FONT_HERSHEY_SIMPLEX,
            4, (250, 0, 0), 2, cv2.LINE_AA)
cv2.imshow('result', img)
cv2.waitKey()

print(f'[INFO] time: {t2 - t1}')
print(f'[INFO] distance vector: {dis_vec}')


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

# In[30]:

import boto3

# In[31]:

po = boto3.client('polly')

# In[55]:

res=po.synthesize_speech(Text="this is srinivas,completing AWS workshop",OutputFormat='mp3',VoiceId='Russell')

# In[56]:

res

# In[57]:

#res['AudioStream'].read()

# In[58]:

file=open('myaudio.mp3','wb')

# In[59]:

file.write(res['AudioStream'].read())

# In[60]:

file.close()

# In[61]:

import IPython

# In[62]:

IPython.display.Audio("myaudio.mp3")

# In[ ]:


import argparse
import os
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
import scipy.io
import scipy.misc
import numpy as np
import pandas as pd
import PIL
import tensorflow as tf
from keras import backend as K
from keras.layers import Input, Lambda, Conv2D
from keras.models import load_model, Model
from yolo_utils import read_classes, read_anchors, generate_colors, preprocess_image, draw_boxes, scale_boxes
from models.keras_yolo import yolo_head, yolo_boxes_to_corners, preprocess_true_boxes, yolo_loss, yolo_body
import cv2

def yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = .6):

    box_scores = box_confidence*box_class_probs
    box_classes = K.argmax(box_scores,-1)
    box_class_scores = K.max(box_scores,-1)

    filtering_mask = box_class_scores>threshold
    scores = tf.boolean_mask(box_class_scores,filtering_mask)
    boxes = tf.boolean_mask(boxes,filtering_mask)
    classes = tf.boolean_mask(box_classes,filtering_mask)

    return scores, boxes, classes

def yolo_non_max_suppression(scores, boxes, classes, max_boxes = 10, iou_threshold = 0.5):
    """
    Applies Non-max suppression (NMS) to set of boxes
    """

    max_boxes_tensor = K.variable(max_boxes, dtype='int32')     # tensor to be used in tf.image.non_max_suppression()
    K.get_session().run(tf.variables_initializer([max_boxes_tensor])) # initialize variable max_boxes_tensor

    nms_indices = tf.image.non_max_suppression(boxes,scores,max_boxes,iou_threshold)

    scores = K.gather(scores,nms_indices)
    boxes = K.gather(boxes,nms_indices)
    classes = K.gather(classes,nms_indices)

    return scores, boxes, classes

def yolo_eval(yolo_outputs, image_shape = (720., 1280.), max_boxes=10, score_threshold=.6, iou_threshold=.5):
    """
    Converts the output of YOLO encoding (a lot of boxes) to your predicted boxes along with their scores, box coordinates and classes.

    """
    box_confidence, box_xy, box_wh, box_class_probs = yolo_outputs

    boxes = yolo_boxes_to_corners(box_xy, box_wh)

    scores, boxes, classes = yolo_filter_boxes(box_confidence, boxes, box_class_probs, threshold = score_threshold)

    boxes = scale_boxes(boxes, image_shape)

    scores, boxes, classes = yolo_non_max_suppression(scores, boxes, classes, max_boxes, iou_threshold)

    return scores, boxes, classes

def predict(sess, image_file):
    """
    Runs the graph stored in "sess" to predict boxes for "image_file". Prints and plots the preditions.
    """

    image, image_data = preprocess_image(image_file, model_image_size = (608, 608))

    out_scores, out_boxes, out_classes = sess.run([scores, boxes, classes],feed_dict={yolo_model.input:image_data,K.learning_phase(): 0})

    # Generate colors for drawing bounding boxes.
    colors = generate_colors(class_names)

    # Draw bounding boxes on the image file
    draw_boxes(image, out_scores, out_boxes, out_classes, class_names, colors)

    image = image.convert('RGB')
    image = np.array(image)

    return image

def main():
    sess = K.get_session()
    global yolo_model, class_names, anchors
    global scores, boxes, classes

    class_names = read_classes("model_data/coco_classes.txt")
    anchors = read_anchors("model_data/yolo_anchors.txt")
    image_shape = (720., 1280.)

    yolo_model = load_model("model_data/yolo.h5")
    yolo_model.summary()
    yolo_outputs = yolo_head(yolo_model.output, anchors, len(class_names))
    scores, boxes, classes = yolo_eval(yolo_outputs, image_shape)

    cap = cv2.VideoCapture(0)
    i=0
    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()
        if not ret:
            break

        height , width , layers =  frame.shape
        new_h=720
        new_w=1280
        frame = cv2.resize(frame, (new_w, new_h))
        i += 1

        # Display the resulting frame
        image = predict(sess, frame)
        cv2.imshow('frame',image)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    # When everything done, release the capture
    cap.release()
    cv2.destroyAllWindows()

main()


#!/usr/bin/env python3

from src.year2019.day05.part1 import token_parse

import unittest

class TestTokenParse(unittest.TestCase):
    def test_token_parse(self):
        cases = [
            (2, (0, 0, 0, 2)),
            (1002, (0, 1, 0, 2)),
            (101, (0, 0, 1, 1)),
            (99, (0, 0, 0, 99)),
        ]

        for case in cases:
            self.assertEqual(case[1], token_parse(case[0]))


import collections
import logging
import regex
import string
import unicodedata
from functools import partial
from multiprocessing import Pool as ProcessPool
from typing import Tuple, List, Dict
import numpy as np

"""
Evaluation code from DPR: https://github.com/facebookresearch/DPR
"""

class SimpleTokenizer(object):
    ALPHA_NUM = r'[\p{L}\p{N}\p{M}]+'
    NON_WS = r'[^\p{Z}\p{C}]'

    def __init__(self):
        """
        Args:
            annotators: None or empty set (only tokenizes).
        """
        self._regexp = regex.compile(
            '(%s)|(%s)' % (self.ALPHA_NUM, self.NON_WS),
            flags=regex.IGNORECASE + regex.UNICODE + regex.MULTILINE
        )

    def tokenize(self, text, uncased=False):
        matches = [m for m in self._regexp.finditer(text)]
        if uncased:
            tokens = [m.group().lower() for m in matches]
        else:
            tokens = [m.group() for m in matches]
        return tokens

logger = logging.getLogger(__name__)

QAMatchStats = collections.namedtuple('QAMatchStats', ['top_k_hits', 'questions_doc_hits'])

def calculate_matches(data: List, workers_num: int):
    """
    Evaluates answers presence in the set of documents. This function is supposed to be used with a large collection of
    documents and results. It internally forks multiple sub-processes for evaluation and then merges results
    :param all_docs: dictionary of the entire documents database. doc_id -> (doc_text, title)
    :param answers: list of answers's list. One list per question
    :param closest_docs: document ids of the top results along with their scores
    :param workers_num: amount of parallel threads to process data
    :param match_type: type of answer matching. Refer to has_answer code for available options
    :return: matching information tuple.
    top_k_hits - a list where the index is the amount of top documents retrieved and the value is the total amount of
    valid matches across an entire dataset.
    questions_doc_hits - more detailed info with answer matches for every question and every retrieved document
    """

    logger.info('Matching answers in top docs...')

    tokenizer = SimpleTokenizer()
    get_score_partial = partial(check_answer, tokenizer=tokenizer)

    processes = ProcessPool(processes=workers_num)
    scores = processes.map(get_score_partial, data)

    logger.info('Per question validation results len=%d', len(scores))

    n_docs = len(data[0]['ctxs'])
    top_k_hits = [0] * n_docs
    for question_hits in scores:
        best_hit = next((i for i, x in enumerate(question_hits) if x), None)
        if best_hit is not None:
            top_k_hits[best_hit:] = [v + 1 for v in top_k_hits[best_hit:]]

    return QAMatchStats(top_k_hits, scores)

def check_answer(example, tokenizer) -> List[bool]:
    """Search through all the top docs to see if they have any of the answers."""
    answers = example['answers']
    ctxs = example['ctxs']

    hits = []

    for i, doc in enumerate(ctxs):
        text = doc['text']

        if text is None:  # cannot find the document for some reason
            logger.warning("no doc in db")
            hits.append(False)
            continue

        hits.append(has_answer(answers, text, tokenizer))

    return hits

def has_answer(answers, text, tokenizer) -> bool:
    """Check if a document contains an answer string."""
    text = _normalize(text)
    text = tokenizer.tokenize(text, uncased=True)

    for answer in answers:
        answer = _normalize(answer)
        answer = tokenizer.tokenize(answer, uncased=True)
        for i in range(0, len(text) - len(answer) + 1):
            if answer == text[i: i + len(answer)]:
                return True
    return False

#################################################
########        READER EVALUATION        ########
#################################################

def _normalize(text):
    return unicodedata.normalize('NFD', text)

#Normalization and score functions from SQuAD evaluation script https://worksheets.codalab.org/rest/bundles/0x6b567e1cf2e041ec80d7098f031c5c9e/contents/blob/
def normalize_answer(s):
    def remove_articles(text):
        return regex.sub(r'\b(a|an|the)\b', ' ', text)

    def white_space_fix(text):
        return ' '.join(text.split())

    def remove_punc(text):
        exclude = set(string.punctuation)
        return ''.join(ch for ch in text if ch not in exclude)

    def lower(text):
        return text.lower()

    return white_space_fix(remove_articles(remove_punc(lower(s))))

def em(prediction, ground_truth):
    return normalize_answer(prediction) == normalize_answer(ground_truth)

def f1(prediction, ground_truth):
    prediction_tokens = normalize_answer(prediction).split()
    ground_truth_tokens = normalize_answer(ground_truth).split()
    common = Counter(prediction_tokens) & Counter(ground_truth_tokens)
    num_same = sum(common.values())
    if num_same == 0:
        return 0
    precision = 1.0 * num_same / len(prediction_tokens)
    recall = 1.0 * num_same / len(ground_truth_tokens)
    f1 = (2 * precision * recall) / (precision + recall)
    return f1

def f1_score(prediction, ground_truths):
    return max([f1(prediction, gt) for gt in ground_truths])

def exact_match_score(prediction, ground_truths):
    return max([em(prediction, gt) for gt in ground_truths])

####################################################
########        RETRIEVER EVALUATION        ########
####################################################

def eval_batch(scores, inversions, avg_topk, idx_topk):
    for k, s in enumerate(scores):
        s = s.cpu().numpy()
        sorted_idx = np.argsort(-s)
        score(sorted_idx, inversions, avg_topk, idx_topk)

def count_inversions(arr):
    inv_count = 0
    lenarr = len(arr)
    for i in range(lenarr):
        for j in range(i + 1, lenarr):
            if (arr[i] > arr[j]):
                inv_count += 1
    return inv_count

def score(x, inversions, avg_topk, idx_topk):
    x = np.array(x)
    inversions.append(count_inversions(x))
    for k in avg_topk:
        # ratio of passages in the predicted top-k that are
        # also in the topk given by gold score
        avg_pred_topk = (x[:k]<k).mean()
        avg_topk[k].append(avg_pred_topk)
    for k in idx_topk:
        below_k = (x<k)
        # number of passages required to obtain all passages from gold top-k
        idx_gold_topk = len(x) - np.argmax(below_k[::-1])
        idx_topk[k].append(idx_gold_topk)


from collections import deque

from shoehorn import logging

class TestTarget(object):

    __test__ = False

    #: .. note:: This isn't used during handling of events,
    #            it's only here for testing setting and un-setting
    #            error handlers.
    error_target = None

    def __init__(self, propagate=False):
        self.events = []
        self.propagate = propagate

    def __call__(self, event):
        self.events.append(event)
        if self.propagate:
            return event

class Capture(object):

    def __init__(self, stack):
        self._targets = deque()
        self.events = []
        self.stack = stack

    @property
    def targets(self):
        # don't include our own test target
        return list(self._targets)[:-1]

    def error_target(self, event):
        raise

    def start(self):
        # vars is just a view, so need to take a copy:
        self.existing = dict(vars(self.stack))
        self.stack.targets = self._targets
        self.stack.error_target = self.error_target
        self.stack.error_target_installed = []
        target = TestTarget()
        self.stack.push(target)
        self.events = target.events

    def stop(self):
        targets = []
        while self._targets:
            targets.append(self.stack.pop())
        for attr, value in self.existing.items():
            setattr(self.stack, attr, value)
        # for later inspection
        self._targets = targets

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.stop()

try:
    import pytest
except ImportError:  # pragma: no cover
    pass
else:
    @pytest.fixture()
    def capture():
        with Capture(logging) as capture:
            yield capture


from Graph import Graph

class two_opt(Graph):
    """
    this class is inherited by class Graph
    """
    def __init__(sefl):
        super().__init__()

    def route_distance(self, route):
        """
        function calculate the length of road route
        """
        sum = 0
        for i in range(1, len(route)):
            sum += self.distance(route[i-1], route[i])
        return sum

    def swap_2opt(self, route, i, k):
        """
        function get the route and return the new_route has reversed
        from item i to k
        """
        new_route = route[0:i]
        new_route.extend(reversed(route[i:k+1]))
        new_route.extend(route[k+1:])
        return new_route

    def find_shortest_path(self):
        improvement = True
        best_route = self.list_city.copy()
        best_distance = self.route_distance(best_route)
        while improvement:
            improvement = False
            for i in range(1, len(best_route)-1):
                for k in range(i+1, len(best_route)):
                    new_route = self.swap_2opt(best_route, i, k)
                    new_distance = self.route_distance(new_route)
                    if new_distance < best_distance:
                        best_distance = new_distance
                        best_route = new_route
                        improvement = True
        self.result = best_route
        self.length = best_distance


from django.shortcuts import (
    render, redirect, get_object_or_404
)
from django.urls import reverse
from django.conf import settings
from decimal import Decimal
from orders.models import Order
from django.http import (
    HttpRequest, HttpResponseRedirect, HttpResponse
)
import stripe

# Stripe API key
stripe.api_key: str = settings.STRIPE_SK
stripe.api_version: str = settings.STRIPE_API_VERSION

def payment_process(request: HttpRequest) -> HttpResponse | HttpResponseRedirect:
    """Redirect to stripe payment process modal"""

    # Retrieve the order ID set in django session (payment init I.e. "order_create view").
    order: Order = get_object_or_404(Order, id=request.session.get('order_id', None))

    if request.method == 'POST':
        # Callback URLs
        cancel_url: str = request.build_absolute_uri(reverse('payment:pay_canceled'))
        callback_url: str = request.build_absolute_uri(reverse('payment:pay_completed'))

        # Checkout session data.
        metadata: dict = {
            'mode': 'payment',
            'client_reference_id': order.id,
            'success_url': callback_url,
            'cancel_url': cancel_url,
            'line_items': [],
        }
        # Add order items to checkout session.
        for item in order.items.all():
            metadata['line_items'].append({
            'price_data': {
                'unit_amount': int(item.price * Decimal('100')),
                'currency': 'usd',
                'product_data': {
                    'name': item.product.name,
                },
            },
            'quantity': item.quantity,
            })

        # Create checkout session.
        session = stripe.checkout.Session.create(**metadata)
        if session:
            try:
                return redirect(session.url, code=303)
            except:
                raise stripe.max_network_retries
        return render(request, 'payment/pay_process.html', locals())
    return render(request, 'payment/pay_process.html', locals())

def payment_completed(request: HttpRequest) -> HttpResponse:
    return render(request, 'payment/pay_completed.html')

def payment_canceled(request: HttpRequest) -> HttpResponse:
    return render(request, 'payment/pay_canceled.html')


from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
import argparse
import multiprocessing as mp
import os
import os.path as osp
import pickle
import sys

import svm_helper
import tqdm
from sklearn.svm import LinearSVC

def task(cls, cost, opts, features, targets):
    """The task function to train the model."""
    suffix = '_'.join(
        opts.targets_data_file.split('/')[-1].split('.')[0].split('_')[-2:])
    out_file = svm_helper.get_low_shot_output_file(opts, cls, cost, suffix)
    if not osp.exists(out_file):
        clf = LinearSVC(
            C=cost,
            class_weight={
                1: 2,
                -1: 1
            },
            intercept_scaling=1.0,
            verbose=0,
            penalty='l2',
            loss='squared_hinge',
            tol=0.0001,
            dual=True,
            max_iter=2000,
        )
        train_feats, train_cls_labels = svm_helper.get_cls_feats_labels(
            cls, features, targets, opts.dataset)
        clf.fit(train_feats, train_cls_labels)

        with open(out_file, 'wb') as fwrite:
            pickle.dump(clf, fwrite)
    return 0

def mp_helper(args):
    return task(*args)

def train_svm_low_shot(opts):
    """Train the svm low-shot model."""
    assert osp.exists(opts.data_file), 'Data file not found. Abort!'
    if not osp.exists(opts.output_path):
        os.makedirs(opts.output_path)

    features, targets = svm_helper.load_input_data(opts.data_file,
                                                   opts.targets_data_file)
    # normalize the features: N x 9216 (example shape)
    features = svm_helper.normalize_features(features)

    # parse the cost values for training the SVM on
    costs_list = svm_helper.parse_cost_list(opts.costs_list)

    # classes for which SVM testing should be done
    num_classes, cls_list = svm_helper.get_low_shot_svm_classes(
        targets, opts.dataset)

    num_task = len(cls_list) * len(costs_list)
    args_cls = []
    args_cost = []
    for cls in cls_list:
        for cost in costs_list:
            args_cls.append(cls)
            args_cost.append(cost)
    args_opts = [opts] * num_task
    args_features = [features] * num_task
    args_targets = [targets] * num_task

    pool = mp.Pool(mp.cpu_count())
    for _ in tqdm.tqdm(
            pool.imap_unordered(
                mp_helper,
                zip(args_cls, args_cost, args_opts, args_features,
                    args_targets)),
            total=num_task):
        pass

def main():
    parser = argparse.ArgumentParser(description='Low-shot SVM model training')
    parser.add_argument(
        '--data_file',
        type=str,
        default=None,
        help='Numpy file containing image features')
    parser.add_argument(
        '--targets_data_file',
        type=str,
        default=None,
        help='Numpy file containing image labels')
    parser.add_argument(
        '--costs_list',
        type=str,
        default='0.01,0.1',
        help='comma separated string containing list of costs')
    parser.add_argument(
        '--output_path',
        type=str,
        default=None,
        help='path where to save the trained SVM models')
    parser.add_argument(
        '--random_seed',
        type=int,
        default=100,
        help='random seed for SVM classifier training')
    parser.add_argument(
        '--dataset', type=str, default='voc', help='voc | places')
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    opts = parser.parse_args()
    train_svm_low_shot(opts)

if __name__ == '__main__':
    main()


"""Utility functions to display the pose detection results."""

from typing import List, Tuple

import cv2
import numpy as np
from numpy import ndarray
import configSim

from object_detector import Detection

_MARGIN = 10  # pixels
_ROW_SIZE = 10  # pixels
_FONT_SIZE = 1
_FONT_THICKNESS = 1
_TEXT_COLOR = (0, 0, 255)  # red

rpx = configSim.RPX
rpy = configSim.RPY
cx = None
cy = None

def visualize(
    image: np.ndarray,
    detections: List[Detection],
    cx=cx,
    cy=cy,
) -> Tuple[ndarray, int, int]:
  """Draws bounding boxes on the input image and return it.

  Args:
    image: The input RGB image.
    detections: The list of all "Detection" entities to be visualize.

  Returns:
    Image with bounding boxes and cx, cy (center of bounding box)
    :param cy:
    :param cx:
  """

  # draw coordinates origin
  cv2.circle(image, (rpx, rpy), 5, (0, 0, 255), -1)
  cv2.circle(image, (rpx, rpy), 15, (0, 0, 255), 2)

  for detection in detections:
    # Draw bounding_box
    start_point = detection.bounding_box.left, detection.bounding_box.top
    end_point = detection.bounding_box.right, detection.bounding_box.bottom
    cv2.rectangle(image, start_point, end_point, _TEXT_COLOR, 3)

    # calculate center of bounding box
    cx = int(start_point[0] + (end_point[0] - start_point[0]) / 2)
    cy = int(start_point[1] + (end_point[1] - start_point[1]) / 2)

    # Draw label and score
    category = detection.categories[0]
    class_name = category.label
    probability = round(category.score, 2)
    result_text = class_name + ' (' + str(probability) + ')'
    text_location = (_MARGIN + detection.bounding_box.left, _MARGIN + _ROW_SIZE + detection.bounding_box.top)
    cv2.putText(image, result_text, text_location, cv2.FONT_HERSHEY_PLAIN, _FONT_SIZE, _TEXT_COLOR, _FONT_THICKNESS)
    cv2.circle(image, (cx, cy), 5, (255, 0, 0), -1)
    cv2.line(image, (cx, cy), (rpx, rpy), (255, 255, 0), 2)

  return image, cx, cy


import sys

sys.setrecursionlimit(10 ** 9)

# Top-Down
class Solution:
    def dp(self, n, dp):
        global ans
        if dp[n]:
            return dp[n]

        if n <= 2:
            ans = n
        elif n == 3:
            ans = 4
        else:
            ans = self.dp(n - 1, dp) + (n - 1) * self.dp(n - 2, dp)
            ans %= 10003

        dp[n] = ans
        return ans

    def party(self, A):
        dp = [0 for _ in range(A + 1)]
        return self.dp(A, dp)

    # Bottom-Up
    def solve(self, A):
        if A <= 2:
            return A
        if A == 3:
            return 4
        dp = [0 for _ in range(A + 1)]
        dp[1] = 1
        dp[2] = 2
        dp[3] = 4

        for i in range(4, A + 1):
            dp[i] = dp[i - 1] + (i - 1) * dp[i - 2]
            dp[i] %= 10003

        return dp[-1]

if __name__ == '__main__':
    A = 500
    B = Solution()
    print(B.party(A))
    print(B.solve(A))

Dynamic Programming/DP I/4. Let's Party.py


from flask import Flask, request, jsonify, make_response
from config import app, db, ma
from models.pagos_model import Pago

# Esquema Pagos
class PagoSchema(ma.Schema):
    class Meta:
        fields = ('pagos_id', 'id_suscripcion', 'mes', 'anio', 'pago', 'fecha_creacion', 'usuario_creacion', 'fecha_actualizacion', 'usuario_actualizacion')

# Una sola respuesta
pago_schema = PagoSchema()
# Cuando sean muchas respuestas
pagos_schema = PagoSchema(many=True)

# GET all pagos
@app.route('/pagos', methods=['GET'])
def get_pagos():
    all_pagos = Pago.query.all()
    result = pagos_schema.dump(all_pagos)
    return jsonify(result)

# GET pago by ID
@app.route('/pagos/<pagos_id>', methods=['GET'])
def get_pago_by_id(pagos_id):
    pago = Pago.query.get(pagos_id)
    return pago_schema.jsonify(pago)

# POST create a pago
@app.route('/pagos/crear', methods=['OPTIONS'])
def handle_pagos_options():
    response = make_response()
    response.headers.add('Access-Control-Allow-Origin', 'http://localhost:4200')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
    response.headers.add('Access-Control-Allow-Methods', 'POST')
    return response

@app.route('/pagos/crear', methods=['POST'])
def insert_pago():
    data = request.get_json(force=True)
    id_suscripcion = data['id_suscripcion']
    mes = data['mes']
    anio = data['anio']
    pago = data['pago']
    usuario_creacion = data['usuario_creacion']
    usuario_actualizacion = data['usuario_actualizacion']

    nuevo_pago = Pago(id_suscripcion, mes, anio, pago, usuario_creacion, usuario_actualizacion)

    db.session.add(nuevo_pago)
    db.session.commit()
    return pago_schema.jsonify(nuevo_pago), 201

# PUT update a pago
@app.route('/pagos/actualizar/<pagos_id>', methods=['OPTIONS', 'PUT'])
def update_pago(pagos_id):
    if request.method == 'OPTIONS':
        response = jsonify({'status': 'success'})
        response.headers.add('Access-Control-Allow-Methods', 'PUT')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type')
        return response

    pago = Pago.query.get(pagos_id)

    data = request.get_json(force=True)
    pago.id_suscripcion = data['id_suscripcion']
    pago.mes = data['mes']
    pago.anio = data['anio']
    pago.pago = data['pago']
    pago.usuario_actualizacion = data['usuario_actualizacion']

    db.session.commit()

    return pago_schema.jsonify(pago)

# DELETE a pago
@app.route('/pagos/eliminar/<pagos_id>', methods=['DELETE'])
def delete_pago(pagos_id):
    pago = Pago.query.get(pagos_id)
    db.session.delete(pago)
    db.session.commit()
    return pago_schema.jsonify(pago)


import dj_database_url, os
import logging

# TODO(nikolai) straighten this shit out
DEBUG = bool(os.environ.get('ISDEVENV', False))
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    ('Nikolai Mushegian', 'nikolai.mushegian+logging@gmail.com'),
    ('Andrey Kostov', 'kostov.andrey@gmail.com')
)

MANAGERS = ADMINS

# sets up DB config for Heroku
DATABASES = {}
DATABASES['default'] = dj_database_url.config(default='postgres://localhost')

if (os.environ.get('ISDEVENV', True)):
    logger = logging.getLogger(__name__)
    logger.info("Using DEVDB (sqlite)")
    DATABASES['default'] = {
        'ENGINE' : 'django.db.backends.sqlite3',
        'NAME' : 'DEVDB'
    }

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))

# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'

SITE_ID = 1

# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = False

# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True

# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True

# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''

# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''

# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles/')

# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'

LOGIN_URL = '/signin/'

# Additional locations of static files
STATICFILES_DIRS = (
    os.path.join(PROJECT_ROOT, 'templates/css/'),
    os.path.join(PROJECT_ROOT, 'templates/js/'),
    os.path.join(PROJECT_ROOT, 'templates/img/'),
    os.path.join(PROJECT_ROOT, 'templates/fonts/'),
)

# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
#    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)

# Make this unique, and don't share it with anybody.
SECRET_KEY = '##09(!5=cs2nqpez&x)*8k2i#=fwd95wn7zg4fm$$=dx#kxsi4'

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

ROOT_URLCONF = 'webapp.urls'

# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'webapp.wsgi.application'

TEMPLATE_DIRS = (
    # this is so that we can use the same relative paths on heroku
    os.path.join(PROJECT_ROOT, 'templates')

    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.db.backends.sqlite3',
    'webapp',
    'gunicorn',
    'django.contrib.admin',
    'django.contrib.admindocs',
)

AUTH_PROFILE_MODULE = "UserProfile"

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        #TODO this does not support multiple processes, figure out how to incorporate ConcurrentLogHandler from PyPi
        'file_info_writer': {
            'level': 'INFO',
            'class': 'logging.FileHandler',
            'formatter': 'verbose',
            'filename': os.path.join(PROJECT_ROOT, 'log', 'general_info.log')
        },
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
        }
    },
    'loggers': {
        'file_info': {
            'handlers': ['file_info_writer'],
            'level': 'INFO',
            'propagate': False,
        },
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': False,
        },
    }
}


"""
Author: Filip Vlasic
		@s4vgR

Date: 30-Oct-2013

Using Team Cymru IP2ASN service.
"""

import wx
import wx.lib.mixins.listctrl as listmix
import os
import csv
import re
import webbrowser
import urllib
import urllib2

import cymru

_SIZE = (950, 1000)
_ValidIpAddressRegex = r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b'

def get_info_url(org, asn):
    ARIN_URL = 'http://whois.arin.net/rest/asn/'
    RIPE_URL = 'http://apps.db.ripe.net/whois/lookup/ripe/aut-num/AS'
    LACNIC_URL = 'http://lacnic.net/cgi-bin/lacnic/whois?lg=EN&query=AS'
    APNIC_URL = 'http://wq.apnic.net/apnic-bin/whois.pl?searchtext=AS'

    def prepare_afrinic_request():
        url = 'https://www.afrinic.net/en/services/whois-query'
        values = {'query' : 'as%s' %asn,
                  'alt_database' : 'AFRINIC',
                  'object_type' : 'All',
                  'ip_search_lvl' : 'Default',
                  'inverse_attributes' : None,
                  'queryType' : 'simple',
                  'option' : 'com_whois',
                  'controller' : 'whois' }

        data = urllib.urlencode(values)
        req = urllib2.Request(url, data)
        response = urllib2.urlopen(req)
        the_page = response.read()
        with open('afrinic.html', 'wb') as f:
            f.write(the_page)

    if asn != 'NA':
        if org == 'arin':
            return ARIN_URL + asn
        elif org == 'ripencc':
            return RIPE_URL + asn
        elif org == 'lacnic':
            return LACNIC_URL + asn
        elif org == 'apnic':
            return APNIC_URL + asn
        elif org == 'afrinic':
            prepare_afrinic_request()
            return 'file://' + os.path.join(os.getcwd(), 'afrinic.html').replace('\\', '/')
    else:
        return ''

class MyDialog(wx.Dialog):
    def __init__(self, parent, object):
        super(MyDialog, self).__init__(parent)
        self.parent = parent
        self.panel =  object(self)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.panel, 1, wx.EXPAND)
        self.SetSizer(sizer)
        self.SetInitialSize()
        #self.SetSize(_SIZE)
        self.Show(True)
        self.ip = None

    def OnOK(self, e):
        self.parent.mtable.enterItems([self.panel.ip.GetValue()])
        self.parent.ips.add(self.panel.ip.GetValue())
        self.Destroy()
        e.Skip()

class AddSingleIPPanel(wx.Panel):
    def __init__(self, parent):
        super(AddSingleIPPanel, self).__init__(parent)

        self.ip = wx.TextCtrl(self)
        self.parent = parent

        sizer = wx.FlexGridSizer(2, 2, 8, 8)
        sizer.Add(wx.StaticText(self, label='IP address:'), 0, wx.ALIGN_CENTER_VERTICAL)
        sizer.Add(self.ip, 0, wx.EXPAND)

        msizer = wx.BoxSizer(wx.VERTICAL)
        msizer.Add(sizer, 1, wx.EXPAND|wx.ALL, 20)
        btnszr = wx.StdDialogButtonSizer()
        buttonOK = wx.Button(self, wx.ID_OK)
        self.Bind(wx.EVT_BUTTON, parent.OnOK, buttonOK)
        buttonOK.SetDefault()
        buttonCancel = wx.Button(self, wx.ID_CANCEL)
        btnszr.AddButton(buttonOK)
        btnszr.AddButton(buttonCancel)
        msizer.Add(btnszr, 0, wx.ALIGN_CENTER|wx.ALL, 12)
        btnszr.Realize()

        self.SetSizer(msizer)

class InPanelWithSort(wx.Panel, listmix.ColumnSorterMixin):
    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, id)
        self.selectedItem = False
        self.InitUI()

    def InitUI(self):
        # table
        self.list = wx.ListCtrl(self, style=wx.LC_REPORT)

        self.list.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
        self.list.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeselected)
        self.list.InsertColumn(0, '', width=30)
        self.list.InsertColumn(1, 'IP address', width=120)
        self.list.InsertColumn(2, 'ASN', width=50)
        self.list.InsertColumn(3, 'Country', width=50)
        self.list.InsertColumn(4, 'Organization', width=360)
        self.list.InsertColumn(5, 'RIR', width=120)
        self.list.InsertColumn(6, 'More info', width=200)

        # load DB data
        #self.dbrecords = []
        #self.updateItems()
        self.whois_dict = {}
        self.itemDataMap = {}

        hbox = wx.BoxSizer(wx.HORIZONTAL)
        hbox.Add(self.list, 1, wx.EXPAND)
        self.SetSizer(hbox)
        self.Show(True)

        # for sort
        listmix.ColumnSorterMixin.__init__(self, 6)
        self.Bind(wx.EVT_LIST_COL_CLICK, self.OnColClick, self.list)

    def enterItems(self, ip_list):
        existing_items_count = self.list.GetItemCount()
        for no, ip in enumerate(ip_list):
            index = existing_items_count + no
            #index = self.list.InsertStringItem(sys.maxint, str(no+1))
            self.list.InsertStringItem(index, str(index + 1))
            self.list.SetStringItem(index, 1, str(ip))
            self.list.SetStringItem(index, 2, '')
            self.list.SetStringItem(index, 3, '')
            self.list.SetStringItem(index, 4, '')
            self.list.SetStringItem(index, 5, '')
            self.list.SetStringItem(index, 6, '')
            self.list.SetItemData(index, index)
            self.itemDataMap[index] = (str(index), str(ip), '', '', '', '', '')

    def updateItems(self, whois_dict):
        self.deleteAllItems()
        self.whois_dict = whois_dict
        for index, ip in enumerate(whois_dict.keys()):
            #index = self.list.InsertStringItem(sys.maxint, str(no+1))
            self.list.InsertStringItem(index, str(index+1))
            self.list.SetStringItem(index, 1, str(ip))
            self.list.SetStringItem(index, 2, str(whois_dict[ip][0])) # asn
            self.list.SetStringItem(index, 3, str(whois_dict[ip][1])) # cc
            self.list.SetStringItem(index, 4, str(whois_dict[ip][2])) # org
            self.list.SetStringItem(index, 5, str(whois_dict[ip][3])) # rir
            self.list.SetStringItem(index, 6, get_info_url(str(whois_dict[ip][3]), str(whois_dict[ip][0])))
            self.whois_dict[ip].append(self.list.GetItem(index, 6).GetText())
            #if self.list.GetItem(index, 3).GetText() in ['HR']:
            #    self.list.SetItemBackgroundColour(index, col='#FFEC8B')
            self.list.SetItemData(index, index)
            self.itemDataMap[index] = (str(index), str(ip), str(whois_dict[ip][0]), str(whois_dict[ip][1]), str(whois_dict[ip][2]),\
                                     str(whois_dict[ip][3]), get_info_url(str(whois_dict[ip][3]), str(whois_dict[ip][0])))

    def deleteAllItems(self):
        self.whois_dict.clear()
        self.itemDataMap.clear()
        self.list.DeleteAllItems()

    def getSelectedItems(self):  # get indexes
        selection = []
        index = self.list.GetFirstSelected()
        selection.append(index)
        while len(selection) != self.list.GetSelectedItemCount():
            index = self.list.GetNextSelected(index)
            selection.append(index)
        return selection

    def getItems(self):
        items = []
        if self.selectedItem: # get selection
            indexes = self.getSelectedItems()
            for no, ip in enumerate(self.whois_dict.keys()):
                if no in indexes:
                    item = ( str(ip), str(self.whois_dict[ip][0]), str(self.whois_dict[ip][1]),\
                     str(self.whois_dict[ip][2]), str(self.whois_dict[ip][3]), str(self.whois_dict[ip][4]) )
                    items.append(item)
            self.selectedItem = False
            return items
        else: # get all
            for ip in self.whois_dict.keys():
                item = ( str(ip), str(self.whois_dict[ip][0]), str(self.whois_dict[ip][1]),\
                 str(self.whois_dict[ip][2]), str(self.whois_dict[ip][3]), str(self.whois_dict[ip][4]) )
                #print item
                items.append(item)
            return items

    def getMoreInfoURL(self):
        return self.list.GetItem(self.selectedItem, 6).GetText()

    def OnItemSelected(self, event):
        self.selectedItem = event.m_itemIndex # index

    def OnItemDeselected(self, event):
        self.selectedItem = False

    # sort (mixin)
    # Used by the ColumnSorterMixin, see wx/lib/mixins/listctrl.py
    def GetListCtrl(self):
        return self.list

    def OnColClick(self, event):
        #print "column clicked"
        event.Skip()

class MainFrame(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, size = _SIZE)
        self.toolbar = self.CreateToolBar()
        self.mtable =  InPanelWithSort(self, -1)
        # big box
        self.vbox = wx.BoxSizer(wx.VERTICAL)
        #self.statusbar = self.CreateStatusBar()
        self.InitUI()
        self.ips = set()

    def InitUI(self):
            add_ip = self.toolbar.AddLabelTool(wx.ID_ANY, 'Add a single IP address', wx.Bitmap('media/add_ip.png'), shortHelp = 'Add a single IP address')
            import_ips = self.toolbar.AddLabelTool(wx.ID_ANY, 'Load IP address(es) from file', wx.Bitmap('media/open.png'), shortHelp = 'Load IP address(es) from file')
            delete_ips = self.toolbar.AddLabelTool(wx.ID_ANY, 'Clear', wx.Bitmap('media/delete.png'), shortHelp = 'Clear')
            whois = self.toolbar.AddLabelTool(wx.ID_ANY, 'Run WHOIS', wx.Bitmap('media/whois.png'), shortHelp = 'Run WHOIS')
            export = self.toolbar.AddLabelTool(wx.ID_ANY, 'Export to CSV file', wx.Bitmap('media/csv.png'), shortHelp = 'Export to CSV file')
            more_info = self.toolbar.AddLabelTool(wx.ID_ANY, 'More info online', wx.Bitmap('media/www.png'), shortHelp = 'More info online')
            self.toolbar.AddSeparator()
            info = self.toolbar.AddLabelTool(wx.ID_ANY, 'About', wx.Bitmap('media/info.png'), shortHelp = 'About')
            quit = self.toolbar.AddLabelTool(wx.ID_ANY, 'Quit', wx.Bitmap('media/quit.png'), shortHelp = 'Quit')
            self.toolbar.Realize()

            self.vbox.Add(self.mtable, 1, wx.EXPAND)

            self.Bind(wx.EVT_TOOL, self.OnAddIP, add_ip)
            self.Bind(wx.EVT_TOOL, self.OnIPImport, import_ips)
            self.Bind(wx.EVT_TOOL, self.OnDeleteIPs, delete_ips)
            self.Bind(wx.EVT_TOOL, self.OnStartWhois, whois)
            self.Bind(wx.EVT_TOOL, self.OnExport, export)
            self.Bind(wx.EVT_TOOL, self.OnGetMoreInfo, more_info)
            self.Bind(wx.EVT_TOOL, self.OnAbout, info)
            self.Bind(wx.EVT_TOOL, self.OnQuit, quit)

            self.SetSizer(self.vbox)
            self.SetTitle('AutoIs')
            self.Centre()

            self.Show(True)

    def OnAddIP(self, e):
        MyDialog(self, AddSingleIPPanel)
        #self.mtable.enterItems([dialog.ip])

    def OnDeleteIPs(self, e):
        self.ips = set()
        self.mtable.deleteAllItems()

    def OnIPImport(self, e):
        wildcard = "All files (*.*)|*.*"
        dlg = wx.FileDialog(self, message="Choose a file",\
            defaultDir = os.getcwd(), defaultFile = "", wildcard = wildcard,\
            style = wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR)
        if dlg.ShowModal() == wx.ID_OK:
            filename = dlg.GetFilename()
            with open(filename) as f:
                #self.ips = f.readlines()
                for line in f.readlines():
                    self.ips |= set(re.findall(_ValidIpAddressRegex, line))
            self.mtable.enterItems(self.ips)
        dlg.Destroy()

    def OnStartWhois(self, e):
        result = cymru.whoare(self.ips)
        self.mtable.updateItems(result)

    def OnExport(self, e):
        wildcard = "CSV files (*.csv)|*.csv|""Text files (*.txt)|*.txt|""All files (*.*)|*.*"
        dlg = wx.FileDialog(self, message="Choose a file",\
            defaultDir = os.getcwd(), defaultFile = "", wildcard = wildcard,\
            style = wx.SAVE | wx.CHANGE_DIR)
        if dlg.ShowModal() == wx.ID_OK:
            filename = dlg.GetFilename()
            with open(filename, 'wb') as f:
                csvr = csv.writer(f)
                for item in self.mtable.getItems():
                    csvr.writerow(item)
        dlg.Destroy()

    def OnGetMoreInfo(self, e):
        url = self.mtable.getMoreInfoURL()
        if url:
            webbrowser.open(url, new = 2)

    def OnAbout(self, e):
        info = wx.AboutDialogInfo()
        #info.SetIcon(wx.Icon('media/.png', wx.BITMAP_TYPE_PNG))
        info.SetName('AutoIs')
        info.SetVersion('1.1')
        info.SetCopyright('(c) 2013 Filip Vlasic')
        info.SetWebSite('www.securitynuggets.co.uk')
        wx.AboutBox(info)

    def OnQuit(self, e):
        #self.refresh_thread.Stop()
        #for t in self.pingthreads:
            #t.Stop()
        #self.Close()
        self.Destroy()

def main():
    guiapp = wx.App() #redirect = True, filename = "error_log.txt") # DEBUG
    MainFrame(None, -1)
    guiapp.MainLoop()

if __name__ == '__main__':
    main()


from random import randint
import abc

from mnkgame import GameResult

# This is the abstract base class (hence the use of the abc import) that specifies an agent
class Agent(object):
    __metaclass__ = abc.ABCMeta

    # agents ALL need to know whether they are playing X or O,
    # as well as the sequence length they seek to create
    def __init__(self, squareType, m, n, k):
        self.type = squareType
        self.m = m
        self.n = n
        self.k = k

    def observeReward(self, history, result, settings):
        if settings.verbose:
            if result == GameResult.GAME_WIN:
                print("Agent ", self.type, " has observed a WIN reward")
            if result == GameResult.GAME_DRAW:
                print("Agent ", self.type, " has observed a DRAW reward")
            if result == GameResult.GAME_LOSE:
                print("Agent ", self.type, " has observed a LOSS penalty")
            for i in range(0, len(history)-1):
                print(history[i])

    # This specifies that all Agents must specify a move function to override this one
    @abc.abstractmethod
    def move(self, board, settings): pass

# This agent simply behaves randomly (within the rules).
class RandomAgent(Agent):
    def move(self, board, settings):
        openSquares = board.getOpenSquares()
        if [] == openSquares:
            print("PANIC, selecting from 0 options")
        return openSquares[randint(0, len(openSquares) - 1)]


from random import Random
from flowitem import Material
from capacity_sources import Machine
import numpy as np

class Supply(object):
    def __init__(self, simulation):
        self.sim = simulation
        self.random_generator: Random = Random()
        self.random_generator.seed(999999)
        self.mean_replenishment_time = self.sim.model_panel.expected_replenishment_time

        """
        supply process
            - parallel
            - capacitated
        """
        self.supply_situation = 'parallel'

        # make supplier
        if self.supply_situation == 'capacitated':
            self.supplier = Machine(sim=self.sim,
                                    env=self.sim.env,
                                    capacity_slots=1,
                                    id=f"supplier"
                                    )

        # disruption parameters
        self.start_time_disruption = self.sim.model_panel.RUN_TIME/2
        self.item_type_disrupted = []
        self.pick_disrupted_item()
        return

    def delivery(self, item_type):
        if self.supply_situation == 'parallel':
            self.sim.env.process(self.parallel_delivery(item_type=item_type))
        elif self.supply_situation == 'capacitated':
            self.sim.env.process(self.capacitated_delivery(item_type=item_type))
        return

    def pick_disrupted_item(self):
        material_types = self.sim.model_panel.material_types.copy()
        for run in range(0, self.sim.model_panel.NUMBER_OF_RUNS):
            material = self.sim.NP_random_generator['disruption'].choice(a=material_types, size=1, replace=True)
            self.item_type_disrupted.append(material)
        return

    def disruption_index(self, item_type):
        t = self.sim.env.now
        run_number = int(t / (self.sim.model_panel.WARM_UP_PERIOD + self.sim.model_panel.RUN_TIME)) + 1
        if item_type != self.item_type_disrupted[run_number - 1]:
            # this item is not disrupted
            return 1
        else:
            # check if there is a disruption
            run_start_time = (run_number - 1) * (self.sim.model_panel.WARM_UP_PERIOD + self.sim.model_panel.RUN_TIME)
            disruption_starts = run_start_time + self.sim.model_panel.WARM_UP_PERIOD + self.start_time_disruption
            disruption_ends = disruption_starts + self.sim.model_panel.disruption_duration
            if t < disruption_starts or t > disruption_ends:
                return 1
            else:
                time_evolved = t - disruption_starts
                disruption_index = (self.sim.model_panel.disruption_severity / self.sim.model_panel.disruption_duration)
                return 1 + (disruption_index * (self.sim.model_panel.disruption_duration - time_evolved))

    def parallel_delivery(self, item_type):
        # determine the expected time
        if not self.sim.model_panel.DISRUPTION:
            mean_replenishment_time = self.sim.model_panel.materials[item_type]['expected_lead_time']
        else:
            mean_replenishment_time = self.disruption_index(item_type=item_type) * \
                                      self.sim.model_panel.materials[item_type]['expected_lead_time']
        # get stochastic value
        if self.sim.model_panel.SUPPLY_DISTRIBUTION == 'constant':
            shipping_time = mean_replenishment_time
        elif self.sim.model_panel.SUPPLY_DISTRIBUTION == 'exponential':
            shipping_time = self.sim.NP_random_generator['supply'].exponential(mean_replenishment_time)
        elif self.sim.model_panel.SUPPLY_DISTRIBUTION == 'k_erlang':
            shipping_time = self.sim.NP_random_generator['supply'].gamma(scale=mean_replenishment_time/self.sim.model_panel.supply_k,
                                                                         shape=self.sim.model_panel.supply_k)
        elif self.sim.model_panel.SUPPLY_DISTRIBUTION == 'normal':
            shipping_time = -np.inf
            while shipping_time < 0:
                shipping_time = self.sim.NP_random_generator['supply'].normal(loc=mean_replenishment_time,
                                                                              scale=self.sim.model_panel.supply_sigma)
        else:
            raise Exception(f'unknown replenishment time distribution')
        # get material expected_lead_time
        material = Material(simulation=self.sim,
                            identifier=self.sim.generation.identifier(),
                            attributes=self.sim.model_panel.materials[item_type])
        # find replenishment time
        yield self.sim.env.timeout(shipping_time)
        # determine delivery time
        material.material_delivery_time = self.sim.env.now
        material.material_shipping_time = shipping_time
        # put in inventory
        self.sim.inventory.put_in_inventory(material=material)
        return

    def capacitated_delivery(self, item_type):
        # determine the expected time
        if not self.sim.model_panel.DISRUPTION:
            mean_replenishment_time = self.sim.model_panel.materials[item_type]['expected_lead_time']
        else:
            mean_replenishment_time = self.disruption_index(item_type=item_type) * \
                                      self.sim.model_panel.materials[item_type]['expected_lead_time']
        # get stochastic value
        if self.sim.model_panel.SUPPLY_DISTRIBUTION == 'constant':
            shipping_time = mean_replenishment_time
        elif self.sim.model_panel.SUPPLY_DISTRIBUTION == 'exponential':
            shipping_time = self.sim.NP_random_generator['supply'].exponential(mean_replenishment_time)
        else:
            raise Exception(f'unknown replenishment time distribution')
        # get material expected_lead_time
        material = Material(simulation=self.sim,
                            identifier=self.sim.generation.identifier(),
                            attributes=self.sim.model_panel.materials[item_type])
        # find replenishment time
        req = self.supplier.request(priority=self.sim.env.now)
        # yield a request
        with req as req:
            yield req
            # Request is finished, order directly processed
            yield self.sim.env.timeout(shipping_time)
        # determine delivery time
        material.material_delivery_time = self.sim.env.now
        material.material_shipping_time = shipping_time
        # put in inventory
        self.sim.inventory.put_in_inventory(material=material)
        return


from test_api import *
from basic.models import *

test_register('user1', 'qb', 'user', '1', 'user1@gmail.com')
test_register('user2', 'qb', 'user', '2', 'user2@gmail.com')
test_register('user3', 'qb', 'user', '3', 'user3@gmail.com')
test_register('user4', 'qb', 'user', '4', 'user4@gmail.com')

user1 = User.objects.get(username = 'user1')
user2 = User.objects.get(username = 'user2')
user3 = User.objects.get(username = 'user3')
user4 = User.objects.get(username = 'user4')

post1 = Post(title='Post1')
post2 = Post(title='Post2')
post3 = Post(title='Post3')

post1.save()
post2.save()
post3.save()

postContent1 = PostContent(pid=post1, uid=user1, content="I am user 1 in post 1")
postContent2 = PostContent(pid=post1, uid=user2, content="I am user 2 in post 1")
postContent3 = PostContent(pid=post1, uid=user3, content="I am user 3 in post 1")
postContent4 = PostContent(pid=post2, uid=user2, content="I am user 2 in post 2")
postContent5 = PostContent(pid=post2, uid=user3, content="I am user 3 in post 2")

postContent1.save()
postContent2.save()
postContent3.save()
postContent4.save()
postContent5.save()

mesg1 = SystemMesg(content="hello user1", uid=user1)
mesg2 = SystemMesg(content="hello again user1", uid=user1)
mesg3 = SystemMesg(content="hello user2", uid=user2)
mesg4 = SystemMesg(content="hello user3", uid=user3)

mesg1.save()
mesg2.save()
mesg3.save()
mesg4.save()


import logging

import gobject
import gtk

from jarabe.model import shell

_RAISE_DELAY = 250

class TabbingHandler(object):
    def __init__(self, frame, modifier):
        self._frame = frame
        self._tabbing = False
        self._modifier = modifier
        self._timeout = None

    def _start_tabbing(self):
        if not self._tabbing:
            logging.debug('Grabing the input.')

            screen = gtk.gdk.screen_get_default()
            window = screen.get_root_window()
            keyboard_grab_result = gtk.gdk.keyboard_grab(window)
            pointer_grab_result = gtk.gdk.pointer_grab(window)

            self._tabbing = (keyboard_grab_result == gtk.gdk.GRAB_SUCCESS and
                             pointer_grab_result == gtk.gdk.GRAB_SUCCESS)

            # Now test that the modifier is still active to prevent race
            # conditions. We also test if one of the grabs failed.
            mask = window.get_pointer()[2]
            if not self._tabbing or not (mask & self._modifier):
                logging.debug('Releasing grabs again.')

                # ungrab keyboard/pointer if the grab was successfull.
                if keyboard_grab_result == gtk.gdk.GRAB_SUCCESS:
                    gtk.gdk.keyboard_ungrab()
                if pointer_grab_result == gtk.gdk.GRAB_SUCCESS:
                    gtk.gdk.pointer_ungrab()

                self._tabbing = False
            else:
                self._frame.show(self._frame.MODE_NON_INTERACTIVE)

    def __timeout_cb(self, event_time):
        self._activate_current(event_time)
        self._timeout = None
        return False

    def _start_timeout(self, event_time):
        self._cancel_timeout()
        self._timeout = gobject.timeout_add(_RAISE_DELAY,
                lambda: self.__timeout_cb(event_time))

    def _cancel_timeout(self):
        if self._timeout:
            gobject.source_remove(self._timeout)
            self._timeout = None

    def _activate_current(self, event_time):
        home_model = shell.get_model()
        activity = home_model.get_tabbing_activity()
        if activity and activity.get_window():
            activity.get_window().activate(event_time)

    def next_activity(self, event_time):
        if not self._tabbing:
            first_switch = True
            self._start_tabbing()
        else:
            first_switch = False

        if self._tabbing:
            shell_model = shell.get_model()
            zoom_level = shell_model.zoom_level
            zoom_activity = (zoom_level == shell.ShellModel.ZOOM_ACTIVITY)

            if not zoom_activity and first_switch:
                activity = shell_model.get_active_activity()
            else:
                activity = shell_model.get_tabbing_activity()
                activity = shell_model.get_next_activity(current=activity)

            shell_model.set_tabbing_activity(activity)
            self._start_timeout(event_time)
        else:
            self._activate_next_activity(event_time)

    def previous_activity(self, event_time):
        if not self._tabbing:
            first_switch = True
            self._start_tabbing()
        else:
            first_switch = False

        if self._tabbing:
            shell_model = shell.get_model()
            zoom_level = shell_model.zoom_level
            zoom_activity = (zoom_level == shell.ShellModel.ZOOM_ACTIVITY)

            if not zoom_activity and first_switch:
                activity = shell_model.get_active_activity()
            else:
                activity = shell_model.get_tabbing_activity()
                activity = shell_model.get_previous_activity(current=activity)

            shell_model.set_tabbing_activity(activity)
            self._start_timeout(event_time)
        else:
            self._activate_next_activity(event_time)

    def _activate_next_activity(self, event_time):
        next_activity = shell.get_model().get_next_activity()
        if next_activity:
            next_activity.get_window().activate(event_time)

    def stop(self, event_time):
        gtk.gdk.keyboard_ungrab()
        gtk.gdk.pointer_ungrab()
        self._tabbing = False

        self._frame.hide()

        self._cancel_timeout()
        self._activate_current(event_time)

        home_model = shell.get_model()
        home_model.set_tabbing_activity(None)

    def is_tabbing(self):
        return self._tabbing


df_dict = {
    'área_(m2)': [0.],
    'quartos': [0.],
    'banheiros': [0.],
    'vagas_de_garagem': [0.],
    'Casa': [0.],
    'Casa_de_condomínio': [0.],
    'Cobertura': [0.],
    'Abraão': [0.],
    'Agronômica': [0.],
    'Alto_Ribeirão': [0.],
    'Autódromo': [0.],
    'Barra_da_Lagoa': [0.],
    'Barreiros': [0.],
    'Beira_Mar_Norte': [0.],
    'Bom_Abrigo': [0.],
    'Cachoeira_do_Bom_Jesus': [0.],
    'Cacupé': [0.],
    'Caiacanga': [0.],
    'Campeche': [0.],
    'Campinas': [0.],
    'Canajurê': [0.],
    'Canasvieiras': [0.],
    'Canto': [0.],
    'Canto_da_Lagoa': [0.],
    'Canto_dos_Araçás': [0.],
    'Capoeiras': [0.],
    'Carianos': [0.],
    'Carvoeira': [0.],
    'Centro': [0.],
    'Coloninha': [0.],
    'Coqueiros': [0.],
    'Costa_da_Lagoa': [0.],
    'Costeira_Do_Ribeirao_Da_Ilha': [0.],
    'Costeira_do_Pirajubaé': [0.],
    'Costeira_do_Ribeirão': [0.],
    'Córrego_Grande': [0.],
    'Daniela': [0.],
    'Estreito': [0.],
    'Ingleses': [0.],
    'Ingleses_do_Rio_Vermelho': [0.],
    'Itacorubi': [0.],
    'Itaguaçu': [0.],
    'Jardim_Anchieta': [0.],
    'Jardim_Atlântico': [0.],
    'José_Mendes': [0.],
    'João_Paulo': [0.],
    'Jurerê': [0.],
    'Jurerê_Internacional': [0.],
    'Lagoa_Pequena': [0.],
    'Lagoa_da_Conceição': [0.],
    'Lagoinha': [0.],
    'Moenda': [0.],
    'Monte_Cristo': [0.],
    'Monte_Verde': [0.],
    'Morro_da_Cruz': [0.],
    'Morro_das_Pedras': [0.],
    'Muquém': [0.],
    'Pantanal': [0.],
    'Parque_São_Jorge': [0.],
    'Pedrita': [0.],
    'Ponta_das_Canas': [0.],
    'Porto_da_Lagoa': [0.],
    'Praia_Brava': [0.],
    'Praia_Mole': [0.],
    'Praia_da_Lagoinha': [0.],
    'Praia_dos_Açores': [0.],
    'Pântano_do_Sul': [0.],
    'Ratones': [0.],
    'Ribeirão_da_Ilha': [0.],
    'Rio_Tavares': [0.],
    'Saco_Grande': [0.],
    'Saco_dos_Limões': [0.],
    'Sambaqui': [0.],
    'Santa_Mônica': [0.],
    'Santinho': [0.],
    'Santo_Antônio_de_Lisboa': [0.],
    'Serrinha': [0.],
    'São_João_do_Rio_Vermelho': [0.],
    'Trindade': [0.],
    'Vargem_Grande': [0.],
    'Vargem_Pequena': [0.],
    'Vargem_do_Bom_Jesus': [0]
}


from django.contrib import messages

from homepage.templatetags.has_group import has_group
from announcements.utils.messages import SuccessMessage, ErrorMessages

def announcement_delete(request, announcements_obj, member_obj, logged_user_id):

    # Get the announcement_id from the request
    announcement_id = request.POST.get('delete_announcement_id')

    # Get the announcement record from db
    this_announcement = announcements_obj.get(id=announcement_id)

    # Check if the user is admin, system_admin or manager
    if has_group(request.user, ['admin', 'system_admin']):

        # Delete the announcement record
        this_announcement.delete()

        # Return success message
        return messages.success(request, SuccessMessage.SUCCESSFUL_DELETION)

    elif has_group(request.user, ['manager']):

        # Get member record from db
        member = member_obj.get(id=logged_user_id)

        # If manager belongs to the portal that tries to delete
        if member.portal_id == this_announcement.portal_id:

            # Delete the record from db
            this_announcement.delete()

            # Return success message
            return messages.success(request, SuccessMessage.SUCCESSFUL_DELETION)
        else:

            # Return error message
            return messages.error(request, ErrorMessages.CANNOT_DELETE_ADMIN_ANNOUNCEMENTS)


class INPUT:
  def __init__(self):
    self._l=open(0).read().split()
    self._length=len(self._l)
    self._index=0
    return

  def stream(self,k=1,f=int,f2=False):
    assert(-1<k)
    if self._length==self._index or self._length-self._index<k:
      raise Exception("There is no input!")
    elif f!=str:
      if k==0:
        ret=list(map(f,self._l[self._index:]))
        self._index=self._length
        return ret
      if k==1 and not f2:
        ret=f(self._l[self._index])
        self._index+=1
        return ret
      if k==1 and f2:
        ret=[f(self._l[self._index])]
        self._index+=1
        return ret
      ret=[]
      for _ in [0]*k:
        ret.append(f(self._l[self._index]))
        self._index+=1
      return ret
    else:
      if k==0:
        ret=list(self._l[self._index:])
        self._index=self._length
        return ret
      if k==1 and not f2:
        ret=self._l[self._index]
        self._index+=1
        return ret
      if k==1 and f2:
        ret=[self._l[self._index]]
        self._index+=1
        return ret
      ret=[]
      for _ in [0]*k:
        ret.append(self._l[self._index])
        self._index+=1
      return ret
pin=INPUT().stream

#pin(number[default:1],f[default:int],f2[default:False])
#if number==0 -> return left all
#listを変数で受け取るとき、必ずlistをTrueにすること。

def main():
  H,W=pin(2)
  N=pin(1)
  a=pin(N,int,1)
  C=[[0]*W for i in range(H)]
  cnt=1
  for i in range(H):
    for j in range(W):
      C[i][j]=cnt
      a[cnt-1]-=1
      if a[cnt-1]==0:
        cnt+=1
  for i in range(H):
    if i%2==1:
      C[i]=C[i][::-1]
    for j in range(W):
      print(C[i][j],end=" ")
    print()
  return

main()


#!python
# _*_ coding=utf-8 _*_
# original source:https://github.com/dashee87/blogScripts/blob/master/Jupyter/2017-11-20-predicting-cryptocurrency-prices-with-deep-learning.ipynb

# @#!pip install lxml
# @#!mkdir lstm-models
import argparse
import code
import readline
import signal
import sys
import pandas as pd
import json
import os
import numpy as np
import urllib3
import time
from keras.models import Sequential
from keras.layers import Activation, Dense
from keras.layers import LSTM
from keras.layers import Dropout
from keras.models import load_model
from keras import models
from keras import layers

window_len = 10
split_date = "2018-03-01"

def SigHandler_SIGINT(signum, frame):
    print()
    sys.exit(0)

class Argparser(object):
    def __init__(self):
        parser = argparse.ArgumentParser()
        parser.add_argument("--string", type=str, help="string")
        parser.add_argument(
            "--bool", action="store_true", help="bool", default=False
        )
        parser.add_argument(
            "--dbg", action="store_true", help="debug", default=False
        )
        self.args = parser.parse_args()

def getData_CMC(crypto, crypto_short):
    market_info = pd.read_html(
        "https://coinmarketcap.com/currencies/"
        + crypto
        + "/historical-data/?start=20160428&end="
        + time.strftime("%Y%m%d")
    )[0]
    print(type(market_info))
    market_info = market_info.assign(Date=pd.to_datetime(market_info["Date"]))
    # print(market_info)
    # if crypto == "ethereum": market_info.loc[market_info["Market Cap"]=="-","Market Cap"]=0
    # if crypto == "dogecoin": market_info.loc[market_info["Volume"]=="-","Volume"]=0
    market_info["Volume"] = market_info["Volume"].astype("int64")
    market_info.columns = market_info.columns.str.replace("*", "")
    # print(type(market_info))
    # print(crypto + " head: ")
    # print(market_info.head())
    kwargs = {
        "close_off_high": lambda x: 2
        * (x["High"] - x["Close"])
        / (x["High"] - x["Low"])
        - 1,
        "volatility": lambda x: (x["High"] - x["Low"]) / (x["Open"]),
    }
    market_info = market_info.assign(**kwargs)
    model_data = market_info[
        ["Date"]
        + [
            coin + metric
            for coin in [""]
            for metric in ["Close", "Volume", "close_off_high", "volatility"]
        ]
    ]
    model_data = model_data.sort_values(by="Date")
    # print(model_data.head())
    print(type(model_data))
    return model_data

def getData_Stock(name, period):
    info = pd.read_csv(
        "./data/" + name + "/" + period + ".csv", encoding="utf-16"
    )
    return info

def get_sets(crypto, model_data):
    training_set, test_set = (
        model_data[model_data["Date"] < split_date],
        model_data[model_data["Date"] >= split_date],
    )
    training_set = training_set.drop("Date", 1)
    test_set = test_set.drop("Date", 1)
    norm_cols = [
        coin + metric for coin in [] for metric in ["Close", "Volume"]
    ]
    LSTM_training_inputs = []
    for i in range(len(training_set) - window_len):
        temp_set = training_set[i : (i + window_len)].copy()
        for col in norm_cols:
            temp_set.loc[:, col] = temp_set[col] / temp_set[col].iloc[0] - 1
        LSTM_training_inputs.append(temp_set)
    LSTM_training_outputs = (
        training_set["Close"][window_len:].values
        / training_set["Close"][:-window_len].values
    ) - 1
    LSTM_test_inputs = []
    for i in range(len(test_set) - window_len):
        temp_set = test_set[i : (i + window_len)].copy()
        for col in norm_cols:
            temp_set.loc[:, col] = temp_set[col] / temp_set[col].iloc[0] - 1
        LSTM_test_inputs.append(temp_set)
    LSTM_test_outputs = (
        test_set["Close"][window_len:].values
        / test_set["Close"][:-window_len].values
    ) - 1
    print(LSTM_training_inputs[0])
    LSTM_training_inputs = [
        np.array(LSTM_training_input)
        for LSTM_training_input in LSTM_training_inputs
    ]
    LSTM_training_inputs = np.array(LSTM_training_inputs)

    LSTM_test_inputs = [
        np.array(LSTM_test_inputs) for LSTM_test_inputs in LSTM_test_inputs
    ]
    LSTM_test_inputs = np.array(LSTM_test_inputs)
    return LSTM_training_inputs, LSTM_test_inputs, training_set, test_set

def build_model(
    inputs,
    output_size,
    neurons,
    activ_func="linear",
    dropout=0.25,
    loss="mae",
    optimizer="adam",
):
    model = Sequential()
    model.add(LSTM(neurons, input_shape=(inputs.shape[1], inputs.shape[2])))
    model.add(Dropout(dropout))
    model.add(Dense(units=output_size))
    model.add(Activation(activ_func))
    model.compile(loss=loss, optimizer=optimizer)
    return model

def stock():
    split_date = "2017.01.01"
    model_data = getData_Stock("irxo", "Daily")
    model_data = model_data.sort_values(by="Date")

    training_set, test_set = (
        model_data[model_data["Date"] < split_date],
        model_data[model_data["Date"] >= split_date],
    )
    training_set = training_set.drop("Date", 1)
    test_set = test_set.drop("Date", 1)

    training_inputs = training_set
    training_outputs = training_set.drop(
        ["Open", "High", "Low", "NTx", "Volume"], axis=1
    )
    test_inputs = test_set
    test_outputs = test_set.drop(
        ["Open", "High", "Low", "NTx", "Volume"], axis=1
    )

    print(training_set.head)
    print(test_set.head)
    print(training_inputs.shape)
    print(test_inputs.shape)
    print(training_outputs.shape)
    print(test_outputs.shape)

    model = models.Sequential()
    model.add(
        layers.Dense(
            64, activation="relu", input_shape=(training_inputs.shape[1],)
        )
    )
    model.add(layers.Dense(64, activation="relu"))
    model.add(layers.Dense(1))
    model.compile(optimizer="rmsprop", loss="mse", metrics=["mae"])
    history = model.fit(
        training_inputs,
        training_outputs,
        validation_data=(test_inputs, test_outputs),
        epochs=10,
        batch_size=1,
        verbose=2,
    )

def lstm_type_1(crypto, crypto_short):
    model_data = getData_CMC(crypto, crypto_short)
    np.random.seed(202)
    training_inputs, test_inputs, training_set, test_set = get_sets(
        crypto, model_data
    )
    model = build_model(training_inputs, output_size=1, neurons=20, loss="mse")
    training_outputs = (
        training_set["Close"][window_len:].values
        / training_set["Close"][:-window_len].values
    ) - 1
    history = model.fit(
        training_inputs,
        training_outputs,
        epochs=50,
        batch_size=1,
        verbose=2,
        shuffle=True,
    )

def lstm_type_4(crypto, crypto_short, crypto2, crypto_short2):
    model_data = getData_CMC(crypto, crypto_short)
    model_data2 = getData_CMC(crypto2, crypto_short2)
    np.random.seed(202)
    training_inputs, test_inputs, training_set, test_set = get_sets(
        crypto, model_data
    )
    training_inputs2, test_inputs2, training_set2, test_set2 = get_sets(
        crypto2, model_data2
    )
    return
    model = build_model(
        training_inputs / training_inputs2,
        output_size=1,
        neurons=20,
        loss="mse",
    )
    training_outputs = (
        (training_set["Close"][window_len:].values)
        / (training_set["Close"][:-window_len].values)
    ) - 1
    history = model.fit(
        training_inputs / training_inputs2,
        training_outputs,
        epochs=10,
        batch_size=1,
        verbose=2,
        shuffle=True,
    )

def lstm_type_2(crypto, crypto_short, pred_range, neuron_count):
    model_data = getData_CMC(crypto, crypto_short)
    np.random.seed(202)
    training_inputs, test_inputs, training_set, test_set = get_sets(
        crypto, model_data
    )
    model = build_model(
        training_inputs,
        output_size=pred_range,
        neurons=neuron_count,
        loss="mse",
    )
    training_outputs = (
        training_set["Close"][window_len:].values
        / training_set["Close"][:-window_len].values
    ) - 1
    training_outputs = []
    for i in range(window_len, len(training_set["Close"]) - pred_range):
        training_outputs.append(
            (
                training_set["Close"][i : i + pred_range].values
                / training_set["Close"].values[i - window_len]
            )
            - 1
        )
    training_outputs = np.array(training_outputs)
    history = model.fit(
        training_inputs[:-pred_range],
        training_outputs,
        epochs=50,
        batch_size=1,
        verbose=2,
        shuffle=True,
    )

def lstm_type_3(crypto, crypto_short, pred_range, neuron_count):
    model_data = getData_CMC(crypto, crypto_short)
    np.random.seed(202)
    training_inputs, test_inputs, training_set, test_set = get_sets(
        crypto, model_data
    )
    model = build_model(training_inputs, output_size=1, neurons=neuron_count)
    training_outputs = (
        training_set["Close"][window_len:].values
        / training_set["Close"][:-window_len].values
    ) - 1
    training_outputs = []
    for rand_seed in range(775, 800):
        print(rand_seed)
        np.random.seed(rand_seed)
        temp_model = build_model(
            training_inputs, output_size=1, neurons=neuron_count
        )
        temp_model.fit(
            training_inputs,
            (
                training_set["Close"][window_len:].values
                / training_set["Close"][:-window_len].values
            )
            - 1,
            epochs=50,
            batch_size=1,
            verbose=0,
            shuffle=True,
        )
        temp_model.save(
            "./lstm-models/" + crypto + "_model_randseed_%d.h5" % rand_seed
        )

def load_models(crypto, crypto_short):
    preds = []
    model_data = getData_CMC(crypto, crypto_short)
    np.random.seed(202)
    training_inputs, test_inputs, training_set, test_set = get_sets(
        crypto, model_data
    )
    for rand_seed in range(775, 800):
        temp_model = load_model(
            "./lstm-models/" + crypto + "_model_randseed_%d.h5" % rand_seed
        )
        preds.append(
            np.mean(
                abs(
                    np.transpose(temp_model.predict(test_inputs))
                    - (
                        test_set["Close"].values[window_len:]
                        / test_set["Close"].values[:-window_len]
                        - 1
                    )
                )
            )
        )

# write code here
def premain(argparser):
    signal.signal(signal.SIGINT, SigHandler_SIGINT)
    # here
    # lstm_type_1("ethereum", "ether")
    # lstm_type_2("ethereum", "ether", 5, 20)
    # lstm_type_3("ethereum", "ether", 5, 20)
    # lstm_type_4("ethereum", "ether", "dogecoin", "doge")
    # load_models("ethereum", "eth")
    stock()

def main():
    argparser = Argparser()
    if argparser.args.dbg:
        try:
            premain(argparser)
        except Exception as e:
            print(e.__doc__)
            if e.message:
                print(e.message)
            variables = globals().copy()
            variables.update(locals())
            shell = code.InteractiveConsole(variables)
            shell.interact(banner="DEBUG REPL")
    else:
        premain(argparser)

if __name__ == "__main__":
    main()


import random
import urllib.request
def download_web_image():
    url = input("Enter the Url: ")
    name = random.randrange(1,1000)
    full_name = str(name) + ".jpg"
    urllib.request.urlretrieve(url, full_name)
    print("The Image was downloaded !")
    print("The Image was named {}".format(full_name))
download_web_image()


# https://codeforces.com/contest/1850/problem/A

def check(seq):
    seq.sort()
    if seq[1] + seq[2] >= 10:
        return "YES"
    return "NO"

for _ in range(int(input())):
    a = list(map(int, input().split()))
    print(check(a))


import os
import sys
import numpy as np
import pickle
import torch
from random import randint, shuffle
from torch.utils.data import DataLoader, Dataset

def selected_frame(data, num_frame):
    """This function uniformly samples data to num_frame frames.
    Not suitable for online recognition model
    """
    frame, joint, dim = data.shape
    if frame == num_frame:
        return data
    interval = frame / num_frame
    uniform_list = [int(i * interval) for i in range(num_frame)]
    return data[uniform_list, :]

def data_aug(data, cls, state):
    def scale(dt):
        for point in range(dt.shape[0]):
            ratio = 0.1
            factor = np.random.uniform(1 - ratio, 1 + ratio)
            dt[point][:][:3] *= factor  # scale each joint
        return dt

    def noise(dt):
        ratio = 0.1
        # select 4 joints
        all_joint = list(range(1, dt.shape[2]))
        shuffle(all_joint)
        selected_joint = all_joint[:5]  # 5 noisy joints

        for point in range(dt.shape[0]):
            for j_id in selected_joint:
                # noise_offset = np.random.uniform(low, high, 7)
                factor = np.random.uniform(1 - ratio, 1 + ratio)
                for t in range(dt.shape[1]):
                    dt[point][t][j_id] *= factor
        return dt

    skeleton_aug = data[:]
    cls_aug = cls[:]
    state_aug = state[:]

    x = np.random.randint(5)
    # skeleton_aug = np.append(skeleton_aug, noise(data[x::5]), axis=0)
    skeleton_aug = np.append(skeleton_aug, scale(data[x::5]), axis=0)
    cls_aug = np.append(cls_aug, cls[x::5], axis=0)
    state_aug = np.append(state_aug, state[x::5], axis=0)

    return skeleton_aug, cls_aug, state_aug
    # return noise(data), cls, state

class SkeletonData(Dataset):
    def __init__(self, data, cls_labels, state_labels, mode="train", use_data_aug=False):
        if use_data_aug and mode == "train":
            data, cls_labels, state_labels = data_aug(data, cls_labels, state_labels)
            self.data = torch.tensor(data, dtype=torch.float)
            self.cls_labels = torch.tensor(cls_labels, dtype=torch.float)
            self.state_labels = torch.tensor(state_labels, dtype=torch.float)
            self.mode = mode
        else:
            self.data = torch.tensor(data, dtype=torch.float)
            self.cls_labels = torch.tensor(cls_labels, dtype=torch.float)
            self.state_labels = torch.tensor(state_labels, dtype=torch.float)
            self.mode = mode

    def __len__(self):
        return len(self.cls_labels)

    def __getitem__(self, item):
        skeleton_data = self.data[item]
        cls_label = int(self.cls_labels[item])
        stt_label = self.state_labels[item]

        return skeleton_data, cls_label, stt_label


import numpy as np
import os, sys
import scipy.ndimage as ndi
import matplotlib.pyplot as plt
from scipy.cluster.vq import kmeans, vq
no_dementia_base_path = sys.path[0]+os.sep+'Non_dementia'
dementia_base_path = sys.path[0]+os.sep+'dementia'

base_path = dementia_base_path
for id in range(1,13):
    os.mkdir(base_path+os.sep+str(id))
    #f, axes = plt.subplots(nrows=2, ncols=1, figsize=(15, 10))
    sarraster = plt.imread(base_path+os.sep+'subj'+os.sep+str(id)+'.gif')
    # Removing speckles
    sarraster = ndi.median_filter(sarraster , size=2)
    # Flatten image to get line of values
    flatsarraster = sarraster.flatten().astype(float)

    print(flatsarraster.shape)

    # In remaining subplots add k-means classified images
    for i in range(2,6):
        #This scipy code classifies k-mean, code has same length as flattened
        #SAR raster and defines which class the SAR value corresponds to
        centroids, variance = kmeans(flatsarraster, i)
        code, distance = vq(flatsarraster, centroids)
        fig = plt.figure()
        fig.suptitle('K-Means Classification')

        # In first subplot add original SAR image
        ax = plt.subplot(241)
        plt.axis('off')
        ax.set_title('Original Image')
        plt.imshow(sarraster, cmap = 'gray')
        print(sarraster.shape)
        #Since code contains the classified values, reshape into SAR dimensions
        codeim = code.reshape(sarraster.shape[0], -1)
        print(codeim.shape)
        #codeim = ndi.median_filter(codeim , size=4)
        for j in range(i):
            #Plot the subplot with (i+2)th k-means
            ax = plt.subplot(2,4,j+2)
            c = codeim == j
            c = ndi.median_filter(c , size=10)
            plt.axis('off')
            xlabel = str(j+1) , ' clusters'
            ax.set_title(xlabel)
            plt.imsave(base_path+os.sep+str(id)+'/gradient'+str(i)+str(j)+'.png', c, cmap='gray')

    #plt.show()


"""Utilities for linear drift rate measurements."""

import numpy as np
import scipy.signal

class DynamicSpectrum():
    """Holds intensity data parameters."""
    def __init__(self, dt_s, df_mhz, nchan, freq_bottom_mhz, freq_top_mhz):
        self.dt_s = dt_s
        self.df_mhz = df_mhz
        self.nchan = nchan
        self.freq_bottom_mhz = freq_bottom_mhz
        self.freq_top_mhz = freq_top_mhz

def delay_from_dm(dm, freq_emitted):
    """Return the delay in seconds caused by dispersion in the
    interstellar medium.

    Parameters
    ----------
    dm : float
        Dispersion measure,  in pc cm-3.
    freq_emitted : float
        Observing frequency, in MHz.

    Returns
    -------
    float
        Dispersive delay, in seconds.

    """
    if type(freq_emitted) == type(0.0):
        if freq_emitted > 0.0:
            return dm / (0.000241 * freq_emitted * freq_emitted)
        else:
            return 0.0
    else:
        return np.where(
            freq_emitted > 0.0, dm / (0.000241 * freq_emitted * freq_emitted),
            0.0
        )

def boxcar_kernel(width):
    """Returns the boxcar kernel of given width normalized by
    sqrt(width) for S/N reasons.

    Parameters
    ----------
    width : int
        Width of the boxcar.

    Returns
    -------
    boxcar : array_like
        Boxcar of width `width` normalized by sqrt(width).

    """
    width = int(round(width, 0))
    return np.ones(width, dtype="float32") / np.sqrt(width)

def find_burst(ts, width_factor=4, min_width=1, max_width=128):
    """Find burst peak and width using boxcar convolution.

    Parameters
    ----------
    ts : array_like
        Time-series.
    width_factor : int, optional
        Windowing factor for on and off-pulse determination.
    min_width : int, optional
        Minimum width to search from, in number of time samples.
        1 by default.
    max_width : int, optional
        Maximum width to search up to, in number of time samples.
        128 by default.

    Returns
    -------
    peak : int
        Index of the peak of the burst in the time-series.
    width : int
        Width of the burst in number of samples.
    snr : float
        S/N of the burst.

    """
    min_width = int(min_width)
    max_width = int(max_width)

    # do not search widths bigger than timeseries
    widths = list(range(min_width,
                        min(max_width + 1, int((len(ts) - 50) // 6))))

    # envelope finding
    snrs = np.empty_like(widths, dtype=float)
    peaks = np.empty_like(widths, dtype=int)

    # borders for on and off-pulse determination
    outer = 3 * width_factor // 2
    inner = width_factor // 2

    for i in range(len(widths)):
        convolved = scipy.signal.convolve(ts, boxcar_kernel(widths[i]))
        peaks[i] = np.nanargmax(convolved)
        # peak should not be on the edge of time-series
        if (peaks[i] > 0.9 * ts.shape[0]) or (peaks[i] < 0.1 * ts.shape[0]):
            snrs[i] = np.nan
        else:
            # get RMS for S/N weighting, as in PRESTO's single_pulse_search.py
            baseline = np.concatenate(
                [
                    convolved[0 : max(0, peaks[i] - 3 * widths[i])],
                    convolved[peaks[i] + 3 * widths[i] :],
                ]
            )

            # cutoff of at least 50 samples is a bit arbitrary, but seems
            # reasonable
            if baseline.shape[0] > 50:
                rms = np.std(baseline)
            else:
                rms = np.nan

            snrs[i] = convolved[peaks[i]] / rms

    best_idx = np.nanargmax(snrs)

    return peaks[best_idx], widths[best_idx], snrs[best_idx]

def add_text(ax, text, color="black"):
    """Add text in top left corner of plot."""
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()

    xtext = 0.03 * (xlim[1] - xlim[0]) + xlim[0]
    ytext = 0.95 * (ylim[1] - ylim[0]) + ylim[0]

    ax.text(xtext, ytext, text, ha="left", va="top", color=color)

def shift_channels(intensity, bins):
    """Shift each channel to the left by the corresponding value in
    bins.

    Parameters
    ----------
    bins : array_like
        Array containing the number of bins to shift each channel
        by.

    Note
    ----
    *** Shifting happens in-place! ***

    """
    nchan, nsamp = intensity.shape
    assert nchan == len(bins)

    pad = np.ones_like(bins)

    for ii in range(nchan):
        intensity[ii, :] = np.roll(intensity[ii, :], -bins[ii], axis=0)

def dedisperse(intensity, center_frequencies, dt_s, dm=0.0,
               reference_frequency=600.0):
    """Shift channels according to the delays predicted by the given
    dispersion measure.

    Parameters
    ----------
    intensity : array_like
        Intensity array of shape (nchan, nsamp).
    center_frequencies : array_like
        Center frequencies of nchan channels, in MHz.
    dt_s : float
        Sampling time, in seconds.
    dm : float
        Dispersion measure, in pc cm-3.
    reference_frequency : float
        Reference frequency for DM calculation, in MHz. 600 MHz by
        default.

    Note
    ----
    *** Dedispersion happens in place! ***

    """
    dm = float(dm)
    reference_frequency = float(reference_frequency)

    # calculate the integer shifts for the full DM and
    # then subtract the existing integer shifts. Reduces rounding error.
    ref_delay = delay_from_dm(dm, reference_frequency)
    delays = delay_from_dm(dm, center_frequencies)

    # relative delay
    rel_delays = delays - ref_delay
    rel_bindelays = np.round(rel_delays / dt_s).astype("int")

    shift_channels(intensity, rel_bindelays)


import subprocess

def get_tokens():
    with open("tokens.txt", "r") as f:
        return f.read().splitlines()

if __name__ == "__main__":
    tokens = get_tokens()
    for token in tokens:
        subprocess.Popen(r"python %s%s" % ("", f"sub.py -t {token}"), shell=True)


# -*- coding: utf-8 -*-
from json import dumps

from django.conf import settings
from django.forms import Textarea
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe

from .parser import ALL_TAGS
from .syntax import LEXERS

class TextVal(unicode):
	@property
	def field_format(self):
		return self.split(':', 1)[0] if ':' in self else ''

	@property
	def field_text(self):
		return self.split(':', 1)[1] if ':' in self else ''

class RichEditorMixin(Textarea):
	class Media:
		js = [
			'js/richeditor/editor.js',
		]
		css = {
			'screen': [
				'css/editor.light.css',
			],
		}

	def __init__(self, attrs=None, **kwargs):
		self.language = settings.LANGUAGE_CODE
		self.formats = ()
		self.skin = 'shakal'
		super(RichEditorMixin, self).__init__(attrs)

	def get_tags_info(self, supported_tags):
		unsupported_tags = set(ALL_TAGS) - set(supported_tags.keys()) - set(('html', 'body'))
		defined_tags = set(supported_tags.keys()) - set('')
		for tag in supported_tags:
			if tag == '':
				tag_name = 'body'
			else:
				tag_name = tag
			unsupported_tags.update([tag_name + ' > ' + t for t in defined_tags - supported_tags[tag].get_child_tags() if t != ''])
			unsupported_tags = unsupported_tags - set(['pre > span'])
		return {
			'unsupported': list(unsupported_tags),
			'known': supported_tags.keys(),
		}

class RichEditor(RichEditorMixin):
	def render(self, name, value, attrs=None, **kwargs):
		supported_tags = self.attrs.pop('supported_tags', {})
		self.attrs.pop('parsers_conf', {})
		widget = super(RichEditor, self).render(name, value, attrs)

		context = {
			'name': name,
			'lang': self.language[:2],
			'tags': dumps(self.get_tags_info(supported_tags)),
			'widget': widget,
			'lexers': dumps(LEXERS),
		}
		return mark_safe(render_to_string('widgets/editor.html', context))

class RichOriginalEditor(RichEditorMixin):
	template_name = 'widgets/editor.html'

	def __init__(self, formats=(('html', 'HTML'), ), *args, **kwargs):
		super(RichOriginalEditor, self).__init__(*args, **kwargs)
		self.formats = formats

	def render(self, name, value, attrs=None, **kwargs):
		if value is None:
			field_format = self.formats[0][0]
			text = ''
		else:
			field_format = value.field_format
			text = value.field_text

		formats = []
		for fmt, label in self.formats:
			formats.append({
				'format': fmt,
				'label': label,
				'checked': fmt == field_format
			})
		if not field_format in dict(self.formats):
			formats[0]['checked'] = True

		supported_tags = self.attrs.pop('supported_tags', {})
		parsers_conf = self.attrs.pop('parsers_conf', {})
		widget = super(RichOriginalEditor, self).render(name, text, attrs)

		context = {
			'name': name,
			'lang': self.language[:2],
			'tags': dumps(self.get_tags_info(supported_tags)),
			'parsers': dumps(parsers_conf),
			'widget': widget,
			'format': field_format,
			'formats': formats,
			'skin': self.skin,
			'lexers': dumps(LEXERS),
		}
		return mark_safe(render_to_string(self.template_name, context))

	def value_from_datadict(self, data, files, name):
		text = data.get(name)
		if self.attrs.get('no_format'):
			return text
		fmt = data.get(name + "_format") or self.formats[0][0]
		if not fmt in dict(self.formats):
			fmt = self.formats[0][0]
		return TextVal(fmt + ':' + text)


from setuptools import setup, find_packages

with open('README.rst') as f:
    readme = f.read()

with open('LICENSE') as f:
    license = f.read()

setup(
    name='Forwarder App',
    version='0.1.0',
    description='Telegram Forwarder App based on TDLib',
    long_description=readme,
    author='Álvaro Fernández (Alvhix)',
    author_email='alvhix@gmail.com',
    url='https://github.com/Alvhix/ForwarderApp',
    license=license,
    packages=find_packages(exclude=('tests', 'docs'))
)


# Solution to 1584. Min Cost to Connect All Points
# https://leetcode.com/problems/min-cost-to-connect-all-points/

###################################################################################################
#
#   This approach uses a variant of Prim's algorithm, where one array stores the minimum cost to
#   connect each point, and another to store all visited points (i.e. the MST).
#
#   For each unvisited point added to the MST, store the minimum cost to connect to all unvisited
#   points. The next point to visit has the least minimum cost in the array.
#
#   Finally, return the total cost of the MST.
#
#   Time complexity:    O(N^2) For each point, the algorithm checks all adjacent points, which
#                       takes O(N) time.
#
#   Space complexity:   O(N) Two arrays of size N.
#
###################################################################################################
def minCostConnectPoints(points):
    out = 0
    # List of visited points
    list_visit = [False] * len(points)
    # List of minimum costs to connect all points
    list_min = [10**7] * len(points)

    # Set the cost to first point to 0
    if len(points) <= 0:
        return out
    else:
        list_min[0] = 0

    i = 0
    while i >= 0:
        min_cost = 10**7
        next_point = -1

        # Visit point
        list_visit[i] = True

        for j in range(0, len(points)):
            if i != j and not(list_visit[j]):
                # Get cost to connect points i and j
                cost = abs(points[i][0] - points[j][0]) + abs(points[i][1] - points[j][1])

                # Add lesser cost to min list
                if cost < list_min[j]:
                    list_min[j] = cost

                # Set min cost and next point to visit
                if min_cost > list_min[j]:
                    min_cost = list_min[j]
                    next_point = j

        # Go to next point
        i = next_point

    # Add total minimum cost
    for min_cost in list_min:
        out += min_cost

    return out

# Some leetcode test cases
print(minCostConnectPoints([[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]]))
print(minCostConnectPoints([[3, 12], [-2, 5], [-4, 1]]))
print(minCostConnectPoints([[0, 0], [1, 1], [1, 0], [-1, 1]]))


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

from django.db import migrations, models
import django.utils.timezone

class Migration(migrations.Migration):

	dependencies = [
		('article', '0001_initial'),
	]

	operations = [
		migrations.AlterField(
			model_name='article',
			name='pub_time',
			field=models.DateTimeField(default=django.utils.timezone.now, verbose_name='\u010das publik\xe1cie', db_index=True),
		),
	]


from PIL import Image
import pytesseract
from pdf2image import convert_from_path

# PDF_file = "/home/shiva/Sirius/PDF/Division orders/19049.pdf"
# pages = convert_from_path(PDF_file, 500)
# image_counter = 1
# for page in pages:
# 	filename = "page_"+str(image_counter)+".jpg"
# 	page.save(filename, 'JPEG')
# 	image_counter = image_counter + 1
# filelimit = image_counter-1
# outfile = "/home/shiva/Sirius/Text/Division orders/19049.txt"
# f = open(outfile, "a")
# for i in range(1, filelimit + 1):
# 	filename = "page_"+str(i)+".jpg"
# 	text = str(((pytesseract.image_to_string(Image.open(filename)))))
# 	text = text.replace('-\n', '')
# 	f.write(text)
# f.close()

import os,glob

def convertMultiple(pdfDir, txtDir):
    if pdfDir == "": pdfDir = os.getcwd() + "\\"
    for pdf in os.listdir(pdfDir):
        fileExtension = pdf.split(".")[-1]
        if fileExtension == "pdf":
            pdfFilename = pdfDir + pdf
            text = convert_from_path(pdfFilename)
            image_counter = 1
            for page in text:
                filename = "page_"+str(image_counter) + ".jpg"
                page.save(filename,'JPEG')
                image_counter = image_counter + 1
            filelimit = image_counter - 1
            for i in range(1, filelimit +1):
                filename = "page_"+str(i)+".jpg"
                text = str(((pytesseract.image_to_string(Image.open(filename)))))
                text = text.replace('-\n','')
            textFilename = txtDir + pdf[-9:-4] + ".txt"
            textFile = open(textFilename, "w") #make text file
            textFile.write(str(text)) #write text to text file

pdfDir = "/home/shiva/Sirius/PDF/Division orders/"
txtDir = "/home/shiva/Sirius/Text/Division orders/"
str(convertMultiple(pdfDir, txtDir))