"""Manual Strategy - indicators.py

Copyright 2018, Georgia Institute of Technology (Georgia Tech)
Atlanta, Georgia 30332
All Rights Reserved

Template code for CS 4646/7646

Georgia Tech asserts copyright ownership of this template and all derivative
works, including solutions to the projects assigned in this course. Students
and other users of this template code are advised not to share it with others
or to make it available on publicly viewable websites including repositories
such as github and gitlab.  This copyright statement should not be removed
or edited.

We do grant permission to share solutions privately with non-students such
as potential employers. However, sharing with other current or future
students of CS 7646 is prohibited and subject to being investigated as a
GT honor code violation.

-----do not edit anything above this line---

Student Name: Krishna kanth Atmakuru
GT User ID: katmakuru3
GT ID: 903362367
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import datetime as dt
from util import get_data

def get_momentum(price, window=21):
    """Calculate momentum indicator:
    Returns: Momentum, series of the same size as input data
    """
    momentum = pd.Series(np.nan, index=price.index)
    momentum.iloc[window:] = price.iloc[window:] / price.values[:-window] - 1
    return momentum

def get_sma_indicator(price, rolling_mean):
    """Calculate simple moving average indicator, i.e. price / rolling_mean.
    Parameters:
    price: Price, typically adjusted close price, series of a symbol
    rolling_mean: Rolling mean of a series
    Returns: The simple moving average indicator
    """
    return price / rolling_mean - 1
#CAlculate EMA
def get_ema(price, window=50, min_periods=0):
    ema = price.ewm(span=window, min_periods=min_periods, adjust=False).mean()
    ema.rename(index='EMA', inplace=True)
    return ema

#Calculate MACD
def get_macd(series, fast_window=12, slow_window=26, signal_window=9):
    macd = get_ema(series, window=fast_window) - get_ema(series, window=slow_window)
    signal = get_ema(macd, window=signal_window)
    return macd, signal

#Calculate upper and lower Bollinger Bands.
def get_bollinger_bands(rolling_mean, rolling_std, num_std=2):
    upper_band = rolling_mean + rolling_std * num_std
    lower_band = rolling_mean - rolling_std * num_std
    return upper_band, lower_band

"""Output a value indicating how many standard deviations
a price is from the mean.
Parameters:
price: Price, typically adjusted close price, series of a symbol
rolling_mean: Rolling mean of a series
rolling_std: Rolling std of a series
Returns:
bollinger_val: the number of standard deviations a price is from the mean
"""

def compute_bollinger_value(price, rolling_mean, rolling_std):

    bollinger_val = (price - rolling_mean) / rolling_std
    return bollinger_val

def plot_momentum(sym_price, sym_mom, title="Momentum Indicator", fig_size=(14, 7)):
    """Plot momentum and prices for a symbol.
    Parameters:
    sym_price: Price, typically adjusted close price, series of symbol
    sym_mom: Momentum of symbol
    fig_size: Width and height of the chart in inches

    Returns:
    Plot momentum and prices on the sample plot with two scales
    """
    # Create two subplots on the same axes with different left and right scales
    fig, ax1 = plt.subplots()

    # The first subplot with the left scale: prices
    ax1.grid(linestyle='--')
    line1 = ax1.plot(sym_price.index, sym_price, label="Adjusted Close Price",
                     color="b")
    ax1.set_xlabel("Date")
    # Make the y-axis label, ticks and tick labels match the line color
    ax1.set_ylabel("Adjusted Close Price", color="b")
    ax1.tick_params("y", colors="b")

    # The second subplot with the right scale: momentum
    ax2 = ax1.twinx()
    line2 = ax2.plot(sym_mom.index, sym_mom, label="Momentum", color="k",
                     alpha=0.4)
    ax2.set_ylabel("Momentum", color="k")
    ax2.tick_params("y", colors="k")

    # Align gridlines for the two scales
    align_y_axis(ax1, ax2, .1, .1)

    # Show legend with all labels on the same legend
    lines = line1 + line2
    line_labels = [l.get_label() for l in lines]
    ax1.legend(lines, line_labels, loc="upper center")

    # Set figure size
    fig = plt.gcf()
    fig.set_size_inches(fig_size)

    plt.suptitle(title)
    plt.savefig("mom.png")

def plot_sma_indicator(sym_price, sma_indicator, rolling_mean, title="SMA Indicator", fig_size=(14, 7)):
    """Plot SMA indicator, price and rolling_mean for a symbol.
    """
    # Create two subplots on the same axes with different left and right scales
    fig, ax1 = plt.subplots()

    # The first subplot with the left scale: prices
    ax1.grid(linestyle='--')
    line1 = ax1.plot(sym_price.index, sym_price, label="Adjusted Close Price",
                     color="b")
    line2 = ax1.plot(rolling_mean.index, rolling_mean, label="SMA", color="g")
    ax1.set_xlabel("Date")
    # Make the y-axis label, ticks and tick labels match the line color
    ax1.set_ylabel("Adjusted Close Price", color="b")
    ax1.tick_params("y", colors="b")

    # The second subplot with the right scale: momentum
    ax2 = ax1.twinx()
    line3 = ax2.plot(sma_indicator.index, sma_indicator,
                     label="SMA Indicator", color="k", alpha=0.4)
    ax2.set_ylabel("SMA indicator", color="k")
    ax2.tick_params("y", colors="k")

    # Align gridlines for the two scales
    align_y_axis(ax1, ax2, .1, .1)

    # Show legend with all labels on the same legend
    lines = line1 + line2 + line3
    line_labels = [l.get_label() for l in lines]
    ax1.legend(lines, line_labels, loc="upper center")

    # Set figure size
    fig = plt.gcf()
    fig.set_size_inches(fig_size)

    plt.title(title)
    plt.savefig("sma.png")

def plot_bollinger(sym_price, upper_band, lower_band, bollinger_val, num_std=1, title="Bollinger Indicator", fig_size=(14, 7)):
    """Plot Bollinger bands and value for a symbol.
    """
    # Create 2 subplots
    # Plot symbol's adjusted close price, rolling mean and Bollinger Bands
    f, ax = plt.subplots(2, sharex=True)
    ax[0].fill_between(upper_band.index, upper_band, lower_band, color="gray",
                       alpha=0.4, linewidth=2.0,
                       label="Region btwn Bollinger Bands")
    ax[0].plot(sym_price, label="Adjusted Close Price", color="b")
    ax[0].set_ylabel("Adjusted Close Price")
    ax[0].legend(loc="upper center")

    # Plot the bollinger value
    ax[1].axhspan(-num_std, num_std, color="gray", alpha=0.4, linewidth=2.0,
                  label="Region btwn {} & {} std".format(-num_std, num_std))
    ax[1].plot(bollinger_val, label="Bollinger Value", color="b")
    ax[1].set_xlabel("Date")
    ax[1].set_ylabel("Bollinger Value")
    ax[1].set_xlim(bollinger_val.index.min(), bollinger_val.index.max())
    ax[1].legend(loc="upper center")

    # Set figure size
    fig = plt.gcf()
    fig.set_size_inches(fig_size)

    plt.suptitle(title)
    plt.savefig("blg.png")

def plot_macd_indicator(sym_price, macd_indicator, signal_macd, title="MACD Indicator", fig_size=(14, 7)):
    """Plot macd indicator, price and rolling_mean for a symbol.
    """
    # Create two subplots on the same axes with different left and right scales
    fig, ax1 = plt.subplots()

    # The first subplot with the left scale: prices
    ax1.grid(linestyle='--')
    line1 = ax1.plot(sym_price.index, sym_price, label="Adjusted Close Price",
                     color="b")
    line2 = ax1.plot(macd_indicator.index, macd_indicator, label="MACD Indicator", color="g")
    ax1.set_xlabel("Date")
    # Make the y-axis label, ticks and tick labels match the line color
    ax1.set_ylabel("Adjusted Close Price", color="blue")
    ax1.tick_params("y", colors="b")

    # The second subplot with the right scale: momentum
    ax2 = ax1.twinx()
    line3 = ax2.plot(signal_macd.index, signal_macd,
                     label="MACD Signal", color="k", alpha=0.4)
    ax2.set_ylabel("MACD indicator", color="k")
    ax2.tick_params("y", colors="k")

    # Align gridlines for the two scales
    align_y_axis(ax1, ax2, .1, .1)

    # Show legend with all labels on the same legend
    lines = line1 + line2 + line3
    line_labels = [l.get_label() for l in lines]
    ax1.legend(lines, line_labels, loc="upper center")

    # Set figure size
    fig = plt.gcf()
    fig.set_size_inches(fig_size)

    plt.title(title)
    plt.savefig("macd.png")

def align_y_axis(ax1, ax2, minresax1, minresax2):
    """Set tick marks of twinx axes to line up with 7 total tick marks.
    """
    ax1ylims = ax1.get_ybound()
    ax2ylims = ax2.get_ybound()
    ax1factor = minresax1 * 6
    ax2factor = minresax2 * 6
    ax1.set_yticks(np.linspace(ax1ylims[0],
                               ax1ylims[1] + (ax1factor -
                                              (ax1ylims[1] - ax1ylims[0]) % ax1factor) %
                               ax1factor, 7))
    ax2.set_yticks(np.linspace(ax2ylims[0],
                               ax2ylims[1] + (ax2factor -
                                              (ax2ylims[1] - ax2ylims[0]) % ax2factor) %
                               ax2factor, 7))

if __name__ == "__main__":
    start_date = dt.datetime(2008, 1, 1)
    end_date = dt.datetime(2009, 12, 31)

    dates = pd.date_range(start_date, end_date)
    symbols = ["JPM"]
    # Get stock data and normalize it
    df_price = get_data(symbols, dates)
    norm_price = df_price / df_price.iloc[0, :]

    window = 21
    num_std = 2

    for symbol in symbols:
        # Compute rolling mean
        rolling_mean = norm_price[symbol].rolling(window=window).mean()
        # Compute rolling standard deviation
        rolling_std = norm_price[symbol].rolling(window=window).std()
        # Get momentum
        momentum = get_momentum(norm_price[symbol], window)
        #get MACD
        macd,macd_signal = get_macd(norm_price[symbol])

        # Plot momentum
        plot_momentum(norm_price[symbol], momentum,
                      "Momentum Indicator for {} with lookback={} days \n \
                      Prices are normalized to the first date)".format(symbol, window))

        # Get SMA indicator
        sma_indicator = get_sma_indicator(norm_price[symbol], rolling_mean)

        # Plot SMA indicator
        plot_sma_indicator(norm_price[symbol], sma_indicator, rolling_mean,
                           "SMA Indicator for {} with lookback={} days \n \
                           (Prices are normalized to the first date)".format(symbol, window))

        #MACD indicator
        sig_window = 9
        plot_macd_indicator(norm_price[symbol], macd, macd_signal, "MACD Indicator for {} with signalwindow={} days \n \
                           (Prices are normalized to the first date)".format(symbol, sig_window))

        # Compute Bollinger bands and value
        upper_band, lower_band = get_bollinger_bands(rolling_mean, rolling_std,
                                                     num_std)
        bollinger_val = compute_bollinger_value(norm_price[symbol], rolling_mean, rolling_std)

        # Plot Bollinger bands and values
        plot_bollinger(norm_price[symbol], upper_band, lower_band,
                       bollinger_val, num_std,
                       "Bollinger Indicator for {} with num_std={}, lookback={} days \
                       \n(Prices are normalized to the first date)".
                       format(symbol, num_std, window))


import numpy, sys, time
import matplotlib.pyplot as plt

# if (len(sys.argv) != 2):
#     print("usage: python %s N" % sys.argv[0])
#     quit()

timelist = []

for number in range(80):

    n = int(number)
    a = numpy.zeros((n, n)) # Matrix A
    b = numpy.zeros((n, n)) # Matrix B
    c = numpy.zeros((n, n)) # Matrix C

    # Initialize the matrices to some values.
    for i in range(n):
        for j in range(n):
            a[i, j] = i * n + j
            b[i, j] = j * n + i
            c[i, j] = 0

    print(a)
    print(b)
    begin = time.time()

    ######################################################
    # Write code to calculate C = A * B                  #
    # (without using numpy librarlies e.g., numpy.dot()) #
    ######################################################

    for i in range(n):
        for j in range(n):
            for k in range(n):
                c[i,j] += a[i,k]*b[k,j]

    end = time.time()
    print("time: %.6f sec" % (end - begin))
    timelist.append(end-begin)

        # Print C for debugging. Comment out the print before measuring the execution time.
    total = 0
    for i in range(n):
        for j in range(n):
            # print c[i, j]
            total += c[i, j]
    # Print out the sum of all values in C.
    # This should be 450 for N=3, 3680 for N=4, and 18250 for N=5.
    print("sum: %.6f" % total)

plt.plot(range(80), timelist, label="test")
plt.title("N*N calculate")
plt.xlabel("N")
plt.ylabel("time")
plt.grid(color='gray')
plt.show()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
off_listing_RAW_spirou.py [night_directory]

Recipe to display raw frame + cut across orders + statistics

Created on 2016-06-12

@author: fbouchy

Last modified: 2016-06-15
"""
from __future__ import division
import numpy as np
import os
from collections import OrderedDict

from SpirouDRS import spirouConfig
from SpirouDRS import spirouCore
from SpirouDRS import spirouImage
from SpirouDRS import spirouStartup

# =============================================================================
# Define variables
# =============================================================================
# Name of program
__NAME__ = 'off_listing.py'
# Get version and author
__version__ = spirouConfig.Constants.VERSION()
__author__ = spirouConfig.Constants.AUTHORS()
__date__ = spirouConfig.Constants.LATEST_EDIT()
__release__ = spirouConfig.Constants.RELEASE()
# Get Logging function
WLOG = spirouCore.wlog
# Get param dictionary
ParamDict = spirouConfig.ParamDict

# =============================================================================
# Define functions
# =============================================================================
def main(directory=None):
    # ----------------------------------------------------------------------
    # Set up
    # ----------------------------------------------------------------------
    # get parameters from config files/run time args/load paths + calibdb
    p = spirouStartup.Begin(recipe=__NAME__)
    # deal with arguments being None (i.e. get from sys.argv)
    pos = [0]
    fmt = [str, str]
    names = ['directory']
    call = [directory]
    # now get custom arguments
    customargs = spirouStartup.GetCustomFromRuntime(p, pos, fmt, names,
                                                    calls=call,
                                                    require_night_name=False)
    p = spirouStartup.LoadArguments(p, customargs=customargs,
                                    require_night_name=False)

    # ----------------------------------------------------------------------
    # Check if we have an index file
    # ----------------------------------------------------------------------
    # get expected index file name and location
    index_file = spirouConfig.Constants.INDEX_OUTPUT_FILENAME()
    path = p['DIRECTORY']
    index_path = os.path.join(path, index_file)
    # get expected columns
    columns = spirouConfig.Constants.GEN_OUTPUT_COLUMNS(p)
    # create storage
    loc = OrderedDict()
    # if file exists then we have some indexed files
    if os.path.exists(index_path):
        rawloc = spirouImage.ReadFitsTable(p, index_path)
        loc['FILENAME'] = list(rawloc['FILENAME'])
        loc['LAST_MODIFIED'] = list(rawloc['LAST_MODIFIED'])
        for col in columns:
            if col not in rawloc.keys():
                WLOG(p, '', '\t- Skipping column {0}'.format(col))
                loc[col] = list(np.repeat([''], len(loc['FILENAME'])))
            else:
                loc[col] = list(rawloc[col])
    # else we have to create this file
    else:
        loc['FILENAME'] = []
        loc['LAST_MODIFIED'] = []
        # loop around columns and add blank list to each
        for col in columns:
            loc[col] = []

    # ----------------------------------------------------------------------
    # Get all files in raw night_name directory
    # ----------------------------------------------------------------------
    # get all files in DRS_DATA_RAW/ARG_NIGHT_NAME
    files = os.listdir(p['DIRECTORY'])
    # sort file by name
    files = np.sort(files)

    # ----------------------------------------------------------------------
    # Loop around all files and extract required header keys
    # ----------------------------------------------------------------------
    # log progress
    WLOG(p, '', 'Analysing {0} files'.format(len(files)))
    # loop around files and extract properties
    for filename in files:
        # skip any non-fits file files
        if '.fits' not in filename:
            continue
        # skip the index file
        if filename == os.path.basename(index_file):
            continue
        # skip non-preprocessed files (without .fits)
        if p['PROCESSED_SUFFIX'].split('.fits')[0] not in filename:
            continue
        # if already in loc['FILENAME'] then skip
        if filename in loc['FILENAME']:
            continue
        # construct absolute path for file
        fitsfilename = os.path.join(p['DIRECTORY'], filename)
        # read file header
        hdr = spirouImage.ReadHeader(p, filepath=fitsfilename)
        # add filename
        loc['FILENAME'].append(filename)
        loc['LAST_MODIFIED'].append(os.path.getmtime(fitsfilename))
        # loop around columns and look for key in header
        for col in columns:
            # get value from header
            if col in hdr:
                value = str(hdr[col])
            else:
                value = '--'
            # push into loc
            loc[col].append(value)

    # Make sure we have some files
    if len(loc['FILENAME']) == 0:
        wmsg = 'No pre-processed (*{0}) files present.'
        WLOG(p, 'warning', wmsg.format(p['PROCESSED_SUFFIX']))

    # ----------------------------------------------------------------------
    # archive to table
    # ----------------------------------------------------------------------
    if len(loc['FILENAME']) != 0:
        # construct table filename
        outfile = spirouConfig.Constants.OFF_LISTING_RAW_FILE(p)
        # log progress
        WLOG(p, '', 'Creating ascii file for listing.')
        # get column names
        colnames = ['FILENAME', 'LAST_MODIFIED'] + list(columns)
        # define the format for each column
        formats = [None] * len(colnames)
        # get the values for each column
        values = []
        for col in colnames:
            values.append(loc[col])
        # construct astropy table from column names, values and formats
        table = spirouImage.MakeTable(p, colnames, values, formats)

        # log saving of file
        wmsg = 'Listing of directory on file {0}'
        WLOG(p, '', wmsg.format(outfile))

        # print out to screen
        WLOG('', '', '')
        WLOG('', '', 'Listing table:')
        WLOG('', '', '')
        spirouImage.PrintTable(table)

    # ----------------------------------------------------------------------
    # Update Index
    # ----------------------------------------------------------------------
    # ask whether to update index
    question = 'Update/Write index.fits? [Y]es or [N]o'
    cond = spirouStartup.spirouStartup.spirou_input_yes_no(p, question)
    # if cond is True can update
    if cond:
        # log writing index file
        wmsg = 'Writing index to file {0}'
        WLOG(p, '', wmsg.format(index_path))
        # update index
        spirouStartup.SortSaveOutputs(p, loc, index_path)
    else:
        WLOG(p, 'warning', 'Skipped writing to index file')

    # ----------------------------------------------------------------------
    # End Message
    # ----------------------------------------------------------------------
    p = spirouStartup.End(p, outputs=None)
    # return a copy of locally defined variables in the memory
    return dict(locals())

# =============================================================================
# Start of code
# =============================================================================
if __name__ == "__main__":
    # run main with no arguments (get from command line - sys.argv)
    ll = main()
    # exit message if in debug mode
    spirouStartup.Exit(ll, has_plots=False)

# =============================================================================
# End of code
# =============================================================================


from django.shortcuts import render
from django.http import HttpResponse
from .models import Labels
from .models import DefaultLabelPrinters
from .models import LinkedPrinters
from django.shortcuts import redirect

from django.template import Template, Context

from functions.my_database import Database
from functions.my_functions import get_ip
from functions.my_functions import id_generator

from django.views.decorators.csrf import csrf_exempt
from pathlib import Path
import requests

from datetime import datetime
from django.conf import settings

# print labels
@csrf_exempt
def index(request):
    if request.method == "POST":
        if 'type' in request.POST and 'printer_ip' in request.POST and 'value' in request.POST:
            label_type = request.POST.get("type")

            # completion labels
            if label_type == 'completion_label':
                job_list = request.POST.get('value').split(",")
                me = Database()
                me.oracle_connect()

                for job in job_list:
                    #try:
                    data = me.run_url_f_r('jit_completion_label.sql',[["jobnumber",job.strip()]]).fetchall()

                    if len(data) == 0:

                        return HttpResponse("Error: Invalid job number.")
                    else:
                        data = data[0]

                    if data[8] == None:
                        pick_line = None
                    elif data[8] == 'Yes':
                        pick_line = """^FO66,10^GB42,140,42^FS^FT74,10^A0R,34,36^FR^FH\^FDPicks:Yes^FS"""
                    else:
                        pick_line = "^FT74,10^A0R,34,36^FR^FH\^FDPicks:No^FS"
                    #try:
                    #print(data[7])
                    print_label(
                                request = request,
                                value = job.strip(),
                                type= label_type,
                                project_number = data[1],
                                picks = pick_line,
                                top_line = data[3],
                                jit_jobs = data[6],
                                top_bore =data[7],
                                quantity = data[2],
                                priority = str(data[4]),
                                top_job = data[5],
                                released = data[9],
                                due = data[10],
                                job = job.strip(),
                                ms_number = data[11],
                                length = data[12]
                                )
                    #except Exception as e:
                    #    return HttpResponse(str(e))

                me.close()

                return HttpResponse("Successfully printed.")

            elif label_type == "move_order":

                date = datetime.now().strftime("%A, %b %d, %Y %I:%M %p")

                move_order_number = request.POST.get('value')
                ppg_choice = request.POST.get('ppg_choice')

                me = Database()
                me.oracle_connect()

                if ppg_choice == 'on':
                    my_args = [['moveordernumber',move_order_number],["'PPG HR'","'asdf'"]]

                else:
                    my_args = [['moveordernumber',move_order_number]]

                data = me.run_url_f_r('move_order_details.sql',my_args).fetchall()

                length = str(len(data))

                me.close()

                if int(length) > 0:

                    # header label
                    try:
                        print_label(
                            request = request,
                            type = 'move_order_id',
                            value = move_order_number,
                            move_order_number = move_order_number,
                            date = date
                            )
                    except Exception as e:
                        return HttpResponse(str(e))

                    # on hold labels

                    for row in data:
                        if row[12] != "Released":
                            job = row[9]

                            try:
                                print_label(
                                    request = request,
                                    value = job,
                                    type = 'move_order_on_hold',
                                    job = job
                                )
                            except Exception as e:
                                return HttpResponse(str(e))

                    # pick tickets
                    for row in data:
                        job = row[9]
                        try:
                            print_label(
                                request = request,
                                value = str(row[1]) + '-' + str(row[2]), # move_order-line
                                type = 'move_order_pick_ticket',
                                subinventory = row[6],
                                priority = row[11],
                                locator = row[7],
                                part_number = row[3],
                                quantity = row[5],
                                date = row[0],
                                project = row[10],
                                job = row[9],
                                move_order_number = row[1],
                                description = row[4],
                                line = row[8],
                                line_number = row[2],
                                )

                        except Exception as e:
                            return HttpResponse(str(e))

                        # print labels for discrete lines
                        if str(row[8]) in ('CSS', 'EF','UL', 'PT','UB', 'TB','DW','OLE','PM') or 'SUB' in str(row[8]) :

                            date = datetime.now().strftime("%m/%d/%Y")

                            me = Database()
                            me.oracle_connect()
                            #print(job)
                            i = me.run_url_f_r('discrete_job_summary.sql',[["jobnumber",job]]).fetchall()[0]

                            try:
                                print_label(
                                    request = request,
                                    value = i[1],
                                    type = 'discrete_label',
                                    project = i[0],
                                    job = i[1],
                                    quantity = i[2],
                                    part_number = i[3],
                                    line = i[4],
                                    due_date = i[5],
                                    date = date
                                )
                            except Exception as e:
                                return HttpResponse(str(e))
                            me.close()
                    return HttpResponse("Successfully printed tickets.")
                return HttpResponse("No open tickets to print.")
            else:
                return HttpResponse("error")
        return HttpResponse("error")
    else:
        return HttpResponse("wrong place")

def print_label(request, type, value, **args):

    # default printer is saved. the backoffice main template picks up the default printer and shows
    # it in the settings. if there is now printer there is a modal popup when someone tries to print
    # asking for the printer IP address... to do..

    args['tag_code'] = id_generator()
    label_type = type
    printer_ip = request.POST.get("printer_ip")
    if type =='discrete_label':
        printer_ip = settings.INVENTORY_STATUS_STICKER

    t = Template(open(Path(__file__).parents[0].joinpath("templates/print/labels/" + label_type + ".zpl"),'r').read())
    label = t.render(Context(args))
    #print(label)
    # print label
    url = "http://" + printer_ip + "/pstprnt"

    try:
        r = requests.post(url,data=label)
        # save label if print is successful
        if r.status_code == '200':
            Labels.objects.create(meaning=value,label_text=label,label_type=label_type,print_source_ip=get_ip(request), printer_ip=printer_ip).save()

        return 'success'

    except:
        raise

# set defautl printers
def set_default_printer(request):
    if request.method == "POST":
        if 'printer_ip' in request.POST:

            # get IP address
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]
            else:
                ip = request.META.get('REMOTE_ADDR')

            # save default printer
            if ip is not None:

                if DefaultLabelPrinters.objects.filter(print_source_ip=ip).exists():
                    DefaultLabelPrinters.objects.filter(print_source_ip=ip).update( printer_ip=request.POST.get('printer_ip'))
                else:
                    DefaultLabelPrinters.objects.create(print_source_ip=ip , printer_ip=request.POST.get('printer_ip')).save()
                return HttpResponse("success")
    return("error")

def bom(request):

    html = 'print/bom.html'
    labels = LinkedPrinters.objects.all()

    if request.method == "POST":

        part_numbers = [x.label_number for x in labels]

        me = Database()
        me.oracle_connect()
        bom = me.run_url_f_r('get_bom.sql',[['jobname',request.POST.get('job_number')]]).fetchall()
        me.close()

        for item in bom:
            if item[0] in part_numbers:
                label_props = labels.filter(label_number = item[0])
                for label in label_props:

                    # print label
                    url = "http://" + label.printer_ip + "/pstprnt"
                    t = Template(label.label_code)
                    label = t.render(Context())

                    try:
                        r = requests.post(url,data=label)
                    except Exception as e:
                        print(str(e))

    return render(request, html, {'labels':labels})

def bom_update_printer(request):
    if request.method == "POST":
        if request.POST.get('id') is not None:
            ## delete row
            LinkedPrinters.objects.filter(id=request.POST.get('id')).delete()

        else:
            ## add row
            obj = LinkedPrinters.objects.create(
                label_number = request.POST.get('label_number'),
                printer_ip = request.POST.get('printer_ip'),
                label_code = request.POST.get('label_code'),
            )
            obj.save()

        return redirect('print:bom')

    return HttpResponse("error")


import numpy as np

#Fijamos semilla
np.random.seed(666)
from tensorflow import set_random_seed
set_random_seed(2)

from XMLData import *
from general import prepareData, writeOutput, prepareDataTest, padding_truncate, maxLength
from keras.layers import Dense, Dropout, LSTM, Embedding, Bidirectional, Flatten
from keras.models import Model
from keras.layers.core import Activation
from keras.layers import Embedding, BatchNormalization
from keras.layers import Input
from keras.layers.core import Dropout
from keras.layers.core import Dense
from keras.callbacks import EarlyStopping
from keras.initializers import glorot_normal, glorot_uniform
from gensim.models.keyedvectors import KeyedVectors
from keras import optimizers
from keras.utils import to_categorical
from keras import regularizers
import sklearn
import tensorflow as tf
import keras.backend as K

#Lectura de los datos
print("Leyendo datos de entrenamiento...")
xml_train = XMLData('../data/intertass-ES-train-tagged.xml',1)
data_train = xml_train.getData()
label_train = xml_train.getPolarity()

data_train_antiguo = data_train

print("Leyendo datos de desarrollo...")
xml_eval = XMLData('../data/intertass-ES-development-tagged.xml',1)
data_eval = xml_eval.getData()
label_eval = xml_eval.getPolarity()

print("Leyendo datos de test...")
xml_test = XMLData('../data/intertass-ES-test.xml',0)
data_test = xml_test.getData()
test_ids = xml_test.getIds()

print("Leyendo word embeddings...")
embeddings = KeyedVectors.load_word2vec_format('../data/fasttext_spanish_twitter_100d.vec', binary=False)

print("Transformamos las frases con los embeddings...")
data_train, data_eval, matrix_embeddings, vocab = prepareData(data_train, data_eval, embeddings)

data_test = prepareDataTest(data_test, vocab)

#PADDING-TRUNCATE
input_size = maxLength(data_train)

data_train = np.array(padding_truncate(data_train, input_size))
data_eval = np.array(padding_truncate(data_eval, input_size))
data_test = np.array(padding_truncate(data_test, input_size))

matrix_embeddings = np.array(matrix_embeddings)

print("Chequeo de dimensiones...")
print(data_train.shape)
print(label_train.shape)
print(data_eval.shape)
print(label_eval.shape)
print(data_test.shape)
print(matrix_embeddings.shape)

print(data_train_antiguo[1])
print(data_train[1])

 ###################### MODELO

sequence_input = Input(shape = (input_size, ), dtype = 'float64')
embedding_layer = Embedding(matrix_embeddings.shape[0], matrix_embeddings.shape[1], weights=[matrix_embeddings],trainable=False, input_length = input_size) #Trainable false
embedded_sequence = embedding_layer(sequence_input)

x = Dense(1)(embedded_sequence)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = Dropout(0.3)(x)
x = Flatten()(x)
x = Dense(4)(x)
x = BatchNormalization()(x)
x = Dropout(0.3)(x)
preds = Activation('softmax')(x)

model = Model(sequence_input, preds)
model.summary()

#Las clases NONE y NEU son minoritarias. Si utilizáramos accuracy, se despreciarían --> Usamos F1_score
def f1_score(y_true, y_pred):
	y_pred = K.round(y_pred)
	tp = K.sum(K.cast(y_true*y_pred, 'float'), axis=0)
	fp = K.sum(K.cast((1-y_true)*y_pred, 'float'), axis=0)
	fn = K.sum(K.cast(y_true*(1-y_pred), 'float'), axis=0)

	p = tp / (tp + fp + K.epsilon())
	r = tp / (tp + fn + K.epsilon())

	f1 = 2*p*r / (p+r+K.epsilon())
	f1 = tf.where(tf.is_nan(f1), tf.zeros_like(f1), f1)
	return K.mean(f1)

model.compile(loss='categorical_crossentropy', optimizer = 'adagrad', metrics=['accuracy', f1_score])

#earlyStopping = EarlyStopping('val_f1_score', patience=3, mode='min')

#modelo = model.fit(x = data_train, y = to_categorical(label_train,4), batch_size = 16, epochs = 30, validation_data=(data_eval, to_categorical(label_eval,4)), shuffle = False, callbacks=[earlyStopping])
modelo = model.fit(x = data_train, y = to_categorical(label_train,4), batch_size = 16, epochs = 30, validation_data=(data_eval, to_categorical(label_eval,4)), shuffle = False)
#loss, acc = model.evaluate(x=data_eval, y=to_categorical(label_eval,4), batch_size=16)

#Predecimos train
y_pred = model.predict(data_train, batch_size=16).argmax(axis=-1)
print("Accuracy train:")
print(sum(1 for x,y in zip(y_pred,label_train) if x == y) / len(y_pred))
print("F1 train:")
print(sklearn.metrics.f1_score(label_train, y_pred, average = "macro"))

#Predecimos evaluación
y_pred_eval = model.predict(data_eval, batch_size=16).argmax(axis=-1)
print("Accuracy eval:")
print(sum(1 for x,y in zip(y_pred_eval,label_eval) if x == y) / len(y_pred_eval))
print("F1 eval:")
print(sklearn.metrics.f1_score(label_eval, y_pred_eval, average = "macro"))

#Predecimos test y guardamos en archivo
y_pred_test = model.predict(data_test, batch_size=16)
writeOutput(y_pred_test, test_ids, "submision.csv")


#we can give filename as input and feed it to the file handle
#rememeber find gives position, startswith checks a condition and returns true/false
fhandle=open('C:\\Users\\Gopi\\Documents\\Exercise Files\\mbox-short.txt','r')
for line in fhandle:
    line=line.rstrip()#rstrip strips white space at end of every string which is present by default at end of each line in "files"
    #without which we will be priniting a gap between each line
    #rememeber with print statement there is already a new line added
    if line.startswith('From:'):
        print(line)
    #above can also be achiebed with the below code
    #if not line.startswith('From:'):
    #    continue
    #print(line)
fhandle.seek(0)
for line in fhandle:
    line=line.rstrip()
    if not '@uct.ac.za' in line:
        continue
    print(line)


# -*- coding: utf-8 -*-
import qondor
import logging, re, os.path as osp, datetime, os
from collections import OrderedDict
logger = logging.getLogger('qondor')

def preprocessing(filename):
    """
    Convenience function that returns a Preprocessor object
    """
    return Preprocessor(filename)

def iter_preprocess_lines(lines):
    _linebreak_cache = ''
    for line in lines:
        line = line.strip()
        if line.startswith('#$'):
            line = line.lstrip('#$').strip()
            if line.endswith('\\'):
                # Line continuation
                _linebreak_cache += line[:-1].strip() + ' '
                logger.debug('Line continuation: set _linebreak_cache to "%s"', _linebreak_cache)
                continue
            elif not _linebreak_cache == '':
                # If there was line continuation and this line does not
                # continue, it must be the last of the continuation
                yield _linebreak_cache + line
                _linebreak_cache = ''
                continue
            yield line

def get_preprocess_lines(lines):
    return list(iter_preprocess_lines(lines))

def iter_preprocess_file(filename):
    with open(filename, 'r') as f:
        # File object should support iteration
        for line in iter_preprocess_lines(f):
            yield line

def get_preprocess_file(filename):
    return list(iter_preprocess_file(filename))

class Preprocessor(object):
    """docstring for Preprocessor"""

    allowed_pip_install_instructions = [
        'module-install',
        'install'
        ]

    def __init__(self, filename=None):
        super(Preprocessor, self).__init__()
        if not(filename is None): self.filename = osp.abspath(filename)
        self.htcondor = {}
        self.pip = [
            # Always pip install qondor itself
            ('qondor', self.get_pip_install_instruction('qondor'))
            ]
        self.variables = {}
        self.files = {}
        self.env = {
            'gccsetup' : '/cvmfs/sft.cern.ch/lcg/contrib/gcc/7/x86_64-centos7/setup.sh',
            'pipdir' : '/cvmfs/sft.cern.ch/lcg/releases/pip/19.0.3-06476/x86_64-centos7-gcc7-opt',
            'rootsetup' : '/cvmfs/sft.cern.ch/lcg/releases/LCG_95/ROOT/6.16.00/x86_64-centos7-gcc7-opt/ROOT-env.sh',
            'SCRAM_ARCH' : 'slc7_amd64_gcc820',
            }
        self.split_transactions = []
        self.delayed_runtime = None
        self.allowed_lateness = None
        if not(filename is None): self.preprocess()

    def get_pip_install_instruction(self, package_name):
        """
        Checks whether a package is installed editable
        (i.e. via `pip install -e package`), and if so chooses
        the module-install instruction, which means the editable code will
        be tarred up and sent along with the job.
        """
        import sys, pkg_resources
        distribution = pkg_resources.get_distribution(package_name)
        if qondor.utils.dist_is_editable(distribution):
            return 'module-install'
        else:
            return 'install'

    def get_item(self):
        if not(len(self.split_transactions)):
            raise RuntimeError(
                '.get_item() should only be called if transactions are split. '
                'Either .preprocess() is not yet called, or there is no split_transactions '
                'directive.'
                )
        if qondor.BATCHMODE:
            return os.environ['QONDORITEM']
        else:
            logger.debug('Local mode: returning first item of %s', self.split_transactions)
            return self.split_transactions[0]

    def preprocess(self):
        for line in iter_preprocess_file(self.filename):
            self.preprocess_line(line)

    def preprocess_line(self, line):
        logger.debug('Processing line: %s', line)
        if   line.startswith('htcondor '):
            self.preprocess_line_htcondor(line)
        elif line.startswith('pip '):
            self.preprocess_line_pip(line)
        elif line.startswith('file '):
            self.preprocess_line_file(line)
        elif line.startswith('env '):
            self.preprocess_line_env(line)
        elif line.startswith('split_transactions '):
            self.preprocess_line_split_transactions(line)
        elif line.startswith('delay '):
            self.preprocess_line_delay(line)
        elif line.startswith('allowed_lateness '):
            self.preprocess_line_allowed_lateness(line)
        else:
            self.preprocess_line_variable(line)

    def preprocess_line_htcondor(self, line):
        # Remove 'htcondor' and assume 'key value' structure further on
        try:
            key, value = line.split(None, 2)[1:3]
        except ValueError:
            logger.error('line "%s" did not have expected structure', line)
            raise
        logger.debug('htcondor[%s] = %s', key, value)
        self.htcondor[key] = value

    def preprocess_line_pip(self, line):
        try:
            install_instruction, value = line.split(None, 2)[1:3]
        except ValueError:
            logger.error('line "%s" did not have expected structure', line)
            raise
        if not install_instruction in self.allowed_pip_install_instructions:
            logger.error('pip install_instruction %s is not valid', install_instruction)
            raise ValueError
        logger.debug('pip %s %s', install_instruction, value)
        self.pip.append((value, install_instruction))

    def preprocess_line_file(self, line):
        try:
            key, path = line.split(None, 2)[1:3]
        except ValueError:
            logger.error('line "%s" did not have expected structure', line)
            raise
        if qondor.BATCHMODE:
            logger.debug('BATCHMODE: %s --> %s', path, osp.basename(path))
            path = osp.basename(path)
        else:
            if not osp.isabs(path):
                # Make sure path is relative to the file that is preprocessed
                path = osp.abspath(osp.join(osp.dirname(self.filename), path))
        logger.debug('file[%s] = %s', key, path)
        self.files[key] = path

    def preprocess_line_env(self, line):
        try:
            key, value = line.split(None, 2)[1:3]
        except ValueError:
            logger.error('line "%s" did not have expected structure', line)
            raise
        logger.debug('(environment) %s = %s', key, value)
        self.env[key] = value

    def preprocess_line_split_transactions(self, line):
        self.split_transactions = line.split()[1:]
        if not len(self.split_transactions):
            logger.error('line "%s" did not have expected structure', line)
            raise ValueError
        logger.debug('Will split transactions per items: %s', self.split_transactions)

    def preprocess_line_variable(self, line):
        try:
            key, value = line.split(None, 1)
        except ValueError:
            logger.error('line "%s" did not have expected structure', line)
            raise
        logger.debug('%s = %s', key, value)
        self.variables[key] = value

    # Special keywords preprocessing

    def preprocess_line_delay_or_lateness(self, line):
        try:
            components = line.split()[1:]
        except ValueError:
            logger.error('line "%s" did not have expected structure', line)
            raise
        unit = 's' if len(components) <= 1 else components[1]
        conversion_to_seconds = {'s' : 1, 'm' : 60, 'h' : 3600}
        if not unit in conversion_to_seconds:
            raise ValueError(
                'Delay unit should be in %s', conversion_to_seconds.keys()
                )
        n_seconds = int(components[0]) * conversion_to_seconds[unit]
        return n_seconds

    def preprocess_line_delay(self, line):
        n_seconds_delay = self.preprocess_line_delay_or_lateness(line)
        self.delayed_runtime = qondor.utils.get_now_utc() + datetime.timedelta(seconds=n_seconds_delay)
        logger.debug('Jobs will sleep until %s (%s seconds in the future)', self.delayed_runtime, n_seconds_delay)

    def preprocess_line_allowed_lateness(self, line):
        self.allowed_lateness = self.preprocess_line_delay_or_lateness(line)
        logger.debug('Allowed lateness is set to %s seconds', self.allowed_lateness)


# -*- coding: utf-8 -*-
# @Time     : 2019/12/25 17:33
# @Author   : peanut
# @Email    : 619414118@qq.com
# File      : school_02_info_page.py
# Software  : PyCharm

import time
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from PageLocators.SchoolManagePageLoc.school_02_info_page_loc import SchoolInfoPageLoc as SIP
from Common.basepage import BasePage

class SchoolInfoPage(BasePage):

    ######二级页面（创建学校）
    # 输入学校名字
    def input_name(self, school_name):
        # WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(SIP.input_name_loc))
        # self.driver.find_element(*SIP.input_name_loc).send_keys(school_name)
        self.input_text(SIP.input_name_loc,school_name,'学校基本信息_输入学校名')

    # 选择地区
    def provinces_select(self):
        # WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(SIP.provinces_select_loc))
        # self.driver.find_element(*SIP.provinces_select_loc).click()
        # self.driver.find_element(*SIP.provinces_loc).click()
        # self.driver.find_element(*SIP.city_select_loc).click()
        # self.driver.find_element(*SIP.city_loc).click()
        # self.driver.find_element(*SIP.district_select_loc).click()
        # self.driver.find_element(*SIP.district_loc).click()

        self.click_element(SIP.provinces_select_loc,'学校基本信息_点击省份下拉框')
        self.click_element(SIP.provinces_loc, '学校基本信息_选择省份')
        self.click_element(SIP.city_select_loc, '学校基本信息_点击城市下拉框')
        self.click_element(SIP.city_loc, '学校基本信息_选择城市')
        self.click_element(SIP.district_select_loc, '学校基本信息_点击地区下拉框')
        self.click_element(SIP.district_loc, '学校基本信息_选择地区')

    # 填写详细信息
    def input_placeholder(self, input_placeholde):
        # self.driver.find_element(*SIP.input_placeholder_loc).send_keys(input_placeholde)

        self.input_text(SIP.input_placeholder_loc,input_placeholde,'学校基本信息_填写详细信息')

    # 选择日期
    def select_data(self, start_time, end_time):
        # # 开始时间
        # self.driver.find_element(*SIP.start_time_loc).send_keys(start_time)
        # self.driver.find_element(*SIP.click_start_loc).click()
        # # 截止时间
        # self.driver.find_element(*SIP.end_time_loc).send_keys(end_time)
        # self.driver.find_element(*SIP.click_end_loc).click()

        self.input_text(SIP.start_time_loc,start_time,'学校基本信息_选择开始日期')
        self.click_element(SIP.click_start_loc,'学校基本信息_点击选择开始日期输入框')

        self.input_text(SIP.end_time_loc,end_time, '学校基本信息_选择结束日期')
        self.click_element(SIP.click_end_loc, '学校基本信息_点击选择结束日期输入框')

    # 点击保存
    def save_button(self):
        # self.driver.find_element(*SIP.save_button_loc).click()

        self.click_element(SIP.save_button_loc,'学校基本信息_点击保存按钮')

    # 返回首页
    def return_home_page(self):
        time.sleep(3)
        # self.driver.find_element(*SIP.return_home_page_loc).click()
        self.click_element(SIP.return_home_page_loc,'学校基本信息_点击学校管理')

    # 设置学期日期
    def set_semester_dates(self, start_time, end_time):
        # WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(SIP.set_semester_dates_loc))
        # # 设置日期
        # self.driver.find_element(*SIP.set_semester_dates_loc).click()
        # time.sleep(1)
        # # 输入开始日期
        # self.driver.find_element(*SIP.semester_start_loc).send_keys(start_time)
        # self.driver.find_element(*SIP.semester_start_loc).click()
        # time.sleep(1)
        # # 输入结束日期
        # self.driver.find_element(*SIP.semester_end_loc).send_keys(end_time)
        # self.driver.find_element(*SIP.semester_end_loc).click()
        # time.sleep(1)

        self.click_element(SIP.set_semester_dates_loc,'学校校历_点击设置日期按钮')
        time.sleep(1)
        self.input_text(SIP.semester_start_loc,start_time,'学校校历_输入校历开始时间')
        time.sleep(1)
        self.click_element(SIP.semester_start_loc,'学校校历_点击输入开始日期框')
        time.sleep(1)
        self.input_text(SIP.semester_end_loc,end_time, '学校校历_输入校历结束时间')
        time.sleep(1)
        self.click_element(SIP.semester_end_loc, '学校校历_点击输入结束日期框')

    # 确定按钮
    def pure_button(self):
        # self.driver.find_element(*SIP.pure_button_loc).click()

        self.click_element(SIP.pure_button_loc,'学校校历_点击日期确定按钮')

    ######二级页面（编辑详情）
    # 清空学校名字
    def clear_school_name(self):
        WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(SIP.input_name_loc))
        self.driver.find_element(*SIP.input_name_loc).clear()

    # 编辑时，设置学期日期
    def edit_dates(self, start_time, end_time):
        WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(SIP.edit_semester_dates_loc))
        # 点击设置日期
        time.sleep(1)
        # self.driver.find_element(*SIP.edit_semester_dates_loc).click()
        self.click_element(SIP.edit_semester_dates_loc,'学校校历_点击设置日期按钮')

        # 清空开始日期，重新输入
        time.sleep(1)
        self.driver.find_element(*SIP.semester_start_loc).clear()
        # self.driver.find_element(*SIP.semester_start_loc).send_keys(start_time)
        # self.driver.find_element(*SIP.semester_start_loc).click()

        self.input_text(SIP.semester_start_loc,start_time,'学校校历_输入开始日期')
        self.click_element(SIP.semester_start_loc,'学校校历_点击开始日期输入框')

        # 清空结束日期，重新输入
        time.sleep(1)
        self.driver.find_element(*SIP.semester_end_loc).clear()
        # self.driver.find_element(*SIP.semester_end_loc).send_keys(end_time)
        # self.driver.find_element(*SIP.semester_end_loc).click()

        self.input_text(SIP.semester_end_loc,end_time, '学校校历_输入结束日期')
        self.click_element(SIP.semester_end_loc, '学校校历_点击结束日期输入框')


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import socket
from lineup import Step, Queue
from lineup.framework import Node
from redis import StrictRedis

class DummyStep(Step):
    def consume(self, instructions):
        self.produce({'cool': instructions})

def test_queue_adopt_producer_step():
    ("Queue#adopt_producer should take a step and know about its id and")

    # Given a dummy manager
    manager = Node()

    # Given a Queue with maximum size of 10
    queue = Queue('test-queue', maxsize=10)
    q1 = Queue('name1')
    q2 = Queue('name2')
    # And a running step (so it gains a thread id)
    step = DummyStep(q1, q2, manager)
    step.start()

    # When that queue adopts the step as a producer
    consumers, producers = queue.adopt_producer(step)

    # And the redis key should contain the step id
    hostname = socket.gethostname()
    pid = os.getpid()
    tid = step.ident
    value = '{hostname}|{pid}|{tid}|tests.functional.test_queue.DummyStep|lineup.framework.Node'.format(**locals())

    redis = StrictRedis()
    members = redis.smembers('lineup:test-queue:producers')
    members.should.contain(value)
    queue.deactivate()
    q1.deactivate()
    q2.deactivate()

def test_put_waits_to_consume():
    ("Queue#put should wait until someone consumes")
    # Given a dummy manager
    manager = Node()

    consume = Queue('consume')
    produce = Queue('produce')

    step = DummyStep(consume, produce, manager)
    step.start()

    consume.put({'foo': 'Bar'})
    produce.get().should.equal({'cool': {'foo': 'Bar'}})
    consume.deactivate()
    produce.deactivate()


# import os(作業系統模組)
# 檢查檔案是否存在 os.path.isfile()

import os

products = []
# 不管是否有現存檔案，都需要這個清單
# 所以清單需要在最外圍

if os.path.isfile('products.csv'):
# 只寫檔名就檢查同一個資料夾底下有沒有這個檔案 =相對路徑
# 如果不在同一個資料夾中，就需要寫 “絕對路徑”

	# 讀取檔案
	with open('products.csv', 'r', encoding='utf-8') as f:
		for line in f:
			if '商品,價格' in line:
				continue # 在for loop 中跳到下一個回圈，必須只在for 底下
			name, price = line.strip().split(',')
			products.append([name, price])
		print(products)

else:
	print('找不到檔案...')

# 讓使用者輸入
while True:
	name = input('請輸入商品名稱：')
	if name == 'q':
		break
	price = input('請輸入商品價格：')
	price = int(price)
	products.append([name, price])
print(products)

# 印出所有購買記錄
for p in products:
	print(p[0], '的價格是', p[1])

# 寫入檔案
with open('products.csv', 'w', encoding='utf-8') as f:
	f.write('商品,價格\n')
	for p in products:
		f.write(p[0] + ',' + p[1] + '\n')


"""
PowerMod
from cs161 ntoe 12

exponentiation
1. comuting x^y (or in Python notation: x**y)
cannot be a polynomial time operation.
Why?
- answer is too big
- it has ylog_2 (x) bits, so just writing it down takes more than polynomial time

 2. instead: using powermod

RSA public key system
1. yolu chose big random prime numbers p and q
	* notice that we can check if they are prime in polynomial times
2. choose random number e
3. public e and p*q, keep secret p,q
4. calculate d=1/e mod((p-1)(q-1)), so that:
	if encrypt(m): return m^e mod(p*q)
	if decrypt(m): return m^d mod(p*q)
5. works for any message m that can be encoded as a
	binary number 0<= m <= p*q
"""

# m^e mod n

def pMod(m, e, n):
	if e == 0: return 1
	if e == 1: return m % n
	a = pMod(m, e // 2, n)

	if (e % 2 == 0):
		return (a * a) % n
	else:
		return (a * a * m) % n

e = 5
# p = 17, q = 19, n = 17*19
n = 17 * 19

# calculate the power mod when m is in range 10 to 29
for m in range(10, 21):
	print("m = ", m, " c = ", pMod(m, e, n))


# -*- coding: utf-8 -*-
import datetime
import re
import json
import settings
import BeautifulSoup
import logging

logging.basicConfig(format=u'%(levelname)-8s [%(asctime)s] %(message)s',
                    level=logging.ERROR, filename=settings.LOG_PATH)

class HtmlParser(object):
    """
    Class HtmlParser perform parsing of html code.
    """

    def __init__(self):
        self.exist_urls = None
        self.site_name = None
        self.patterns = None
        self.block = None
        self.block_params = None
        self.soup = None

    def prepare_to_parse(self, domain, exist_urls=None):
        """
        Set all vars. Get parse patterns from config file.
        site_name - regex of site name
        :param basestring domain: domain url
        :param list exist_urls: list of exist urls
        """
        # Get site from constants.py
        self.exist_urls = exist_urls if exist_urls else []
        self.site_name = re.search('//[A-Za-z.-]+/', domain).group()

        for site, params in settings.RE_SITE_DICT.items():
            if self.site_name in site:
                self.patterns = params.get('patterns')
                self.block = params.get('block')
                self.block_params = params.get('block_params')
                self.site_name = site
                break

    def parse_collection(self, collection, domain, exist_urls=None):
        """
        Main parse method.
        :param dict collection: collection to parse
        :param basestring domain: domain url
        :param list exist_urls: list of exist urls, that will be skipped
        :return: dict with new collection
        """
        self.exist_urls = exist_urls if exist_urls else []
        self.prepare_to_parse(domain, exist_urls)

        new_collection = {}
        for url, params in collection.items():
            new_params = {}

            if url not in self.exist_urls:

                # Get, compose and run all methods from patterns dict
                for pattern, value in self.patterns.items():
                    call = getattr(self, 'get_' + pattern)
                    params.update({pattern: call(params.get("source"), value)})

                # If patterns contain p_code and page has no p_code
                if self.patterns.get('p_code') and not params.get('p_code'):
                    continue

                # If patterns do not contain p_code and and page has no price
                if not self.patterns.get('p_code') and not params.get('price'):
                    continue

                # If patterns contain p_code and page has p_code
                # or patterns don't contain p_code at all and we check all pages
                # if they have block with regex
                if self.patterns.get('p_code') and params.get('p_code') or self.block_params:
                    new_params = self.parse_block(params.get("source"))

                params = self.update_params(params, new_params)
                params = self.convert_to_json(params)
                new_collection.update({url: params})
                logging.info("{} parsed".format(url))

        return new_collection

    def get_p_code(self, url, patterns):
        """
        Get p-code from url using regex pattern
        :param str url: current url
        :param tuple patterns: regex patterns
        :return: p-code or None
        """
        result = self.get_param(url, patterns)
        result = result.replace("/", "")
        return result

    def get_price(self, source, patterns):
        """
        Get price from page source using regex pattern
        :param str source: page source
        :param tuple patterns: regex patterns
        :return: product price or zero(not on stock)
        """
        result = self.get_param(source, patterns)
        result = result.replace(" ", "")
        if result: return float(result)
        else: return 0.0

    def get_image(self, source, patterns):
        """
        Get image from page source using regex pattern
        :param str source: page source
        :param tuple patterns: regex patterns
        :return: product image or None
        """
        result = self.get_param(source, patterns)
        result = result.replace("'", "")
        result = result.replace('"', '')
        return result

    def get_title(self, source, patterns):
        """
        Get title from page source using regex pattern
        :param str source: page source
        :param tuple patterns: regex patterns
        :return: product title or None
        """

        result = self.get_param(source, patterns)
        result = result[1:-1]
        result = result.replace("/", "")
        result = result.replace(">", "")
        result = result.replace("<", "")
        return result

    def get_weight(self, source, patterns):
        """
        Get weight from page source using regex pattern
        :param str source: page source
        :param tuple patterns: regex patterns
        :return: product weight value or None
        """

        result = self.get_param(source, patterns)
        result = result[1:-1]
        result = result.replace("/", "")
        result = result.replace(">", "")
        result = result.replace("<", "")
        try:
            return float(result)
        except ValueError:
            return 0.0

    def get_cpu(self, source, patterns):
        """
        Get cpu from page source using regex pattern
        :param str source: page source
        :param tuple patterns: regex patterns
        :return: product cpu value or None
        """

        result = self.get_param(source, patterns)
        result = result[1:-1]
        result = result.replace("/", "")
        result = result.replace(">", "")
        result = result.replace("<", "")
        return result

    def get_ram(self, source, patterns):
        """
        Get ram from page source using regex pattern
        :param str source: page source
        :param tuple patterns: regex patterns
        :return: product ram value or None
        """
        result = self.get_param(source, patterns)
        result = result[1:-1]
        result = result.replace("/", "")
        result = result.replace(">", "")
        result = result.replace("<", "")
        return result

    def get_hdd(self, source, patterns):
        """
        Get hdd from page source using regex pattern
        :param str source: page source
        :param tuple patterns: regex patterns
        :return: product hdd value or None
        """
        result = self.get_param(source, patterns)
        result = result[1:-1]
        result = result.replace("/", "")
        result = result.replace(">", "")
        result = result.replace("<", "")
        return result

    def get_description(self, source, patterns):
        """
        Get hdd from page source using regex pattern
        :param str source: page source
        :param tuple patterns: regex patterns
        :return: product hdd value or None
        """
        result = self.get_param(source, patterns)
        result = result[1:-1]
        result = result.replace("/", "")
        result = result.replace(">", "")
        result = result.replace("<", "")
        return result

    def get_display(self, source, patterns):
        """
        Get display from page source using regex pattern
        :param str source: page source
        :param tuple patterns: regex patterns
        :return: product display value or None
        """
        result = self.get_param(source, patterns)
        result = result[1:-1]
        result = result.replace("/", "")
        result = result.replace(">", "")
        result = result.replace("<", "")
        result = result.replace(",", ".")
        return result

    def get_param(self, source, patterns):
        result = u''
        for pattern in patterns:
            try:
                if not result:
                    result = re.search(pattern, source).group()
                else:
                    result = re.search(pattern, result).group()

            except AttributeError:
                return u''

        if len(result) > 500: return u''
        else: return result

    def parse_block(self, source):
        parse_result = {}
        self.soup = BeautifulSoup.BeautifulSoup(source)
        tables = self.soup.findAll(self.block.get('name'), {u'class': self.block.get('class')})

        for table in tables:
            rows = table.findAll(u'tr')
            for row in rows[1:]:
                column_name = row.find(u'th')
                column_value = row.find(u'td')

                # Some rows have no header tag 'th'
                if not column_name:
                    column_name, column_value = row.findAll(u'td')[:2]

                # Some rows may be spanned and have no value
                if not column_value:
                    continue

                param = self.get_cell_content(column_name)
                value = self.get_cell_content(column_value)

                # Some rows may different structure
                if not param or not value:
                    continue

                for p, v in self.block_params.items():
                    if v in param:
                        parse_result.update({p: value})

        return parse_result

    def get_cell_content(self, cell):
        for item in cell.contents:

            if hasattr(item, 'contents') and item.contents:
                item = self.get_cell_content(item)

            item = unicode(item)
            item = item.replace('\t', '')
            item = item.replace('\n', '')
            item = item.replace('\r', '')
            item = item.strip()

            if self.get_param(item, ['[a-zA-Z0-9,.]']):
                return item

        return u''

    def update_params(self, params, new_params):
        params.update(new_params)
        params.update({"actual_date": datetime.datetime.now(),
                       "on_stock": params.get('price') > 0})
        return params

    def convert_to_json(self, params):
        converted = {}
        attrs = {}

        for param, value in params.items():
            if param in settings.MAIN_PARAMS:
                converted.update({param: value})
            elif param in settings.IGNORE_PARAMS:
                continue
            elif value:
                attrs.update({param: value})

        converted.update({'attrs': json.dumps(attrs)})
        return converted

    def re_parse_collection(self, old_collection, domain, responses):
        """
        Update url data after expire of check period(in config file)
        :param dict old_collection: collection from DB
        :param basestring domain: site domain
        :param responses: list of url responses
        :return: updated collection
        """
        if not old_collection or not responses:
            return old_collection
        self.prepare_to_parse(domain)

        for response in responses:
            if not response:
                logging.info("banned for {} domain.".format(domain))
                return {}

            if response:
                params = old_collection.get(response.url)
                params.update({"price": self.get_price(response.text, self.patterns.get('price')),
                               "on_stock": self.get_price(response.text, self.patterns.get('price')) > 0,
                               "actual_date": datetime.datetime.now()})
                old_collection.update({response.url: params})
                logging.info("{} reparsed".format(response.url))

        return old_collection


import os
import json
import cv2
import argparse
import numpy as np
from matplotlib import pyplot as plt

from PIL import ImageDraw
from PIL import Image

meter2pixel = 20
border_pad = 20*3
ALLOWED_ROOM_TYPES = {'indoor':3, 'kitchen':4, 'dining_room':5, 'living_room':6,
                      'bathroom':7, 'bedroom':8, 'office':9, 'hallway':10}
beds_meter = [[2.0,2.0],[1.8, 2.0], [1.5, 2.0], [1.2 ,2.0]]
beds_pixels = [[int(bed_meter[0]*meter2pixel), int(bed_meter[1]*meter2pixel)] for bed_meter in beds_meter]

barriers_meter = [[0.5, 0.5],[0.4, 0.4],[0.3 ,0.3],[0.5, 0.4],[0.5,0.3],[0.4,0.3]]
# barriers_meter = [[0.3, 0.3],[0.2, 0.2],[0.1 ,0.1],[0.3, 0.2],[0.3,0.1],[0.2,0.1]]
barriers_pixels = [[int(barrier_meter[0]*meter2pixel), int(barrier_meter[1]*meter2pixel)] for barrier_meter in barriers_meter]

height, width = 512, 512

bx1 = int(0.95*width)
by1 = int(0.95*height)
bx0 = int(0.05*width)
by0 = int(0.05*height)

def get_cloest_pt(x,y):
    pt0 = np.array((x,y))
    pts = [np.array((x, by0)), np.array((x, by1)), np.array((bx0, y)), np.array((bx1, y))]
    dis = [np.linalg.norm(pt0-pt) for pt in pts]
#     print(np.amin(dis))
    return pts[np.argmin(dis)]

def check_closest_pt(x, y, bx, by, ref_image):
    cnt = 0
    if x == bx:
        for _y in range(min(y, by), max(y,by)):
            if ref_image[x, _y] != 0:
                cnt += 1;
    elif y == by:
        for _x in range(min(x, bx), max(x,bx)):
            if ref_image[_x, y] != 0:
                cnt += 1;
    if cnt > 5:
        return False
    return True

def darw_poly(draw, height, width, fil_col, ref_image, coinf=50, draw_pts=True):
    x_array, y_array=np.where(ref_image==2)
    px0,py0 = 0,0
    cpx, cpy = 511, 511
    while ref_image[px0,py0] != 1 or check_closest_pt(px0, py0, cpx, cpy, ref_image):
        idx = np.random.randint(x_array.shape[0])
        px0 = x_array[idx]
        py0 = y_array[idx]
        px0 = px0+np.random.randint(20)-10
        py0 = py0+np.random.randint(20)-10

        cpx, cpy = get_cloest_pt(px0, py0)

    rand_num = np.random.rand()
    px1, py1 = int(coinf*(np.random.rand()-0.5) + cpx), int(-coinf*(np.random.rand()-0.5) + cpy)
    px2, py2 = int(coinf*(np.random.rand()-0.5) + cpx), int(-coinf*(np.random.rand()-0.5) + cpy)

    for i in range(np.random.randint(1,40)):
        rand_x = np.random.rand()
        rand_y = np.random.rand()
        x, y = rand_x*px1+(1-rand_x)*px2, rand_y*py1+(1-rand_y)*py2
        draw.line((px0, py0, x, y), fil_col)

        if draw_pts:
            draw.point([(x, y)], 2)
            dot_enhance_num = np.random.randint(2,15)
            for _ in range(dot_enhance_num):
                add_x, add_y = np.random.rand(2)-0.5
                if rand_num < 0.5:
                    add_x, add_y = int(add_x*2), int(add_y*3)
                else:
                    add_x, add_y = int(add_x*3), int(add_y*2)
                draw.point([(x+add_x, y+add_y)], 2)
    return px0, py0, px1, py1, px2, py2

def _get_room_tp_id(room):
    room = room.lower()
    if room == 'toilet':
        room = 'bathroom'
    # elif room == 'guest_room':
    #     room = 'bedroom'
    if room not in ALLOWED_ROOM_TYPES:
        return ALLOWED_ROOM_TYPES['indoor']
    return ALLOWED_ROOM_TYPES[room]

def draw_map(file_name, json_path, save_path):
    print("Processing ", file_name)

    with open(json_path + '/' + file_name + '.json') as json_file:
        json_data = json.load(json_file)

    # Draw the contour
    verts = (np.array(json_data['verts']) * meter2pixel).astype(np.int)
    x_max, x_min, y_max, y_min = np.max(verts[:, 0]), np.min(verts[:, 0]), np.max(verts[:, 1]), np.min(verts[:, 1])

    if not os.path.exists(save_path):
        os.mkdir(save_path)
    ######################################
    raw_vis_map = np.ones((y_max - y_min + border_pad * 2,
                        x_max - x_min + border_pad * 2))*127
    if raw_vis_map.shape[0]>512 or raw_vis_map.shape[1]>512:
        return

    verts[:, 0] = verts[:, 0] - x_min + border_pad
    verts[:, 1] = verts[:, 1] - y_min + border_pad
    cv2.drawContours(raw_vis_map, [verts], -1, 255, -1)
    cv2.drawContours(raw_vis_map, [verts], -1, 0, 1)
    # Save map
    if not os.path.exists(save_path + "/raw_vis"):
        os.mkdir(save_path + "/raw_vis")
    cv2.imwrite(save_path + "/raw_vis/" + file_name + '.png', raw_vis_map)
    ######################################
    raw_map = np.zeros((y_max - y_min + border_pad * 2,
                        x_max - x_min + border_pad * 2))
    cv2.drawContours(raw_map, [verts], -1, 1, -1)
    cv2.drawContours(raw_map, [verts], -1, 2, 1)
    # Save map
    if not os.path.exists(save_path + "/raw"):
        os.mkdir(save_path + "/raw")
    cv2.imwrite(save_path + "/raw/" + file_name + '.png', raw_map)
    ######################################
    seg_map = np.zeros((y_max - y_min + border_pad * 2,
                        x_max - x_min + border_pad * 2))

    cv2.drawContours(seg_map, [verts], -1, 1, -1)
    cv2.drawContours(seg_map, [verts], -1, 2, 1)

    for room_cate in json_data['room_category']:
        room_id = _get_room_tp_id(room_cate)
        for box in json_data['room_category'][room_cate]:
            x0 = int(box[0]*meter2pixel)+border_pad-x_min
            y0 = int(box[1]*meter2pixel)+border_pad-y_min
            x1 = int(box[2]*meter2pixel)+border_pad-x_min
            y1 = int(box[3]*meter2pixel)+border_pad-y_min
            tmp_map = np.zeros(seg_map.shape)
            tmp_map[y0:y1, x0:x1] = 1
            seg_map[np.where((seg_map!=0)*(seg_map!=2)*(tmp_map==1))] = room_id

    # Save map
    if not os.path.exists(save_path + "/seg"):
        os.mkdir(save_path + "/seg")
    cv2.imwrite(save_path + "/seg/" + file_name + '.png', seg_map)
    ######################################
    inp_map = np.zeros((y_max - y_min + border_pad * 2,
                        x_max - x_min + border_pad * 2)).astype(np.uint8)

    cv2.drawContours(inp_map, [verts], -1, 1, -1)
    cv2.drawContours(inp_map, [verts], -1, 2, 1)

    # for room_cate in json_data['room_category']:
    #     room_id = _get_room_tp_id(room_cate)
    #     if room_id not in [4,5,6,9,8]:
    #         for box in json_data['room_category'][room_cate]:
    #             x0 = int(box[0]*meter2pixel)+border_pad-x_min
    #             y0 = int(box[1]*meter2pixel)+border_pad-y_min
    #             x1 = int(box[2]*meter2pixel)+border_pad-x_min
    #             y1 = int(box[3]*meter2pixel)+border_pad-y_min
    #             tmp_map = np.zeros(inp_map.shape)
    #             tmp_map[y0:y1, x0:x1] = 1
    #             inp_map[np.where((inp_map!=0)*(inp_map!=2)*(tmp_map==1))] = room_id

    for room_cate in json_data['room_category']:
        room_id = _get_room_tp_id(room_cate)
        # if room_id in [4,5,6,9,8]:
            # add
        # if room_id == 8:
        #     idx = np.random.randint(len(beds_pixels))
        #     scale_pixels = beds_pixels
        # else:
        idx = np.random.randint(len(barriers_pixels))
        scale_pixels = barriers_pixels
        for box in json_data['room_category'][room_cate]:
            x0 = int(box[0]*meter2pixel)+border_pad-x_min
            y0 = int(box[1]*meter2pixel)+border_pad-y_min
            x1 = int(box[2]*meter2pixel)+border_pad-x_min
            y1 = int(box[3]*meter2pixel)+border_pad-y_min
            try:
                tmp_map = np.zeros(inp_map.shape)
                tmp_map[y0:y1, x0:x1] = 1
                y_array, x_array = np.where((inp_map!=0)*(tmp_map==1))
                x00_lim = x_array.min()
                x11_lim = x_array.max()
                y00_lim = y_array.min()
                y11_lim = y_array.max()

                if np.random.randn()<0:
                    # bed ver
                    bed_w = scale_pixels[idx][0]
                    bed_h = scale_pixels[idx][1]
                else:
                    # bed hor
                    bed_w = scale_pixels[idx][1]
                    bed_h = scale_pixels[idx][0]
                # case = np.random.randint(4)
                add_bed_flag = False
                if not add_bed_flag:
                    x00 = x00_lim+np.random.randint(x11_lim-x00_lim-bed_h)
                    y00 = y00_lim
                    x11 = x00+bed_h
                    y11 = y00+bed_w
                    if (inp_map[y00:y11, x00:x11] != 0).all():
                        inp_map[y00-1:y11+1, x00-1:x11+1] = 19
                        add_bed_flag = True
                if not add_bed_flag:
                    x00 = x00_lim
                    y00 = y00_lim+np.random.randint(y11_lim-y00_lim-bed_w)
                    x11 = x00+bed_h
                    y11 = y00+bed_w
                    if ((inp_map[y00:y11, x00:x11] != 0) * \
                    (inp_map[y00:y11, x00:x11] != 2)).all():
                        inp_map[y00-1:y11+1, x00-1:x11+1] = 19
                        add_bed_flag = True
                if not add_bed_flag:
                    x11 = x11_lim-np.random.randint(x11_lim-x00_lim-bed_h)
                    y11 = y11_lim
                    x00 = x11-bed_h
                    y00 = y11-bed_w
                    if (inp_map[y00:y11, x00:x11] != 0).all():
                        inp_map[y00-1:y11+1, x00-1:x11+1] = 19
                        add_bed_flag = True
                if not add_bed_flag:
                    x11 = x11_lim
                    y11 = y11_lim-np.random.randint(y11_lim-y00_lim-bed_w)
                    x00 = x11-bed_h
                    y00 = y11-bed_w
                    if (inp_map[y00:y11, x00:x11] != 0).all():
                        inp_map[y00-1:y11+1, x00-1:x11+1] = 19
                        add_bed_flag = True

                if add_bed_flag:
                    # if room_id == 8:
                        # print("=============== add bed: {}".format(file_name))
                    # else:
                    print("=============== add barry: {}".format(file_name))
                    # print(x00, y00, x11, y11)
                    # print(case)
                    # print(bed_h, bed_w)
                    # print(x0, y0, x1, y1)
            except:
                pass

            tmp_map = np.zeros(inp_map.shape)
            tmp_map[y0:y1, x0:x1] = 1
            inp_map[np.where((inp_map!=19)*(inp_map!=0)*(inp_map!=2)*(tmp_map==1))] = room_id
            inp_map[np.where(inp_map==19)] = 0

    inp_map = (inp_map != 0).astype(np.uint8)
    contours, hierarchy = cv2.findContours(inp_map, 2, 1)
    cv2.drawContours(inp_map, contours, -1, 2)
    x_boundary, y_boundary = np.where(inp_map == 2)
    abandoned_boundary_idx = np.random.random(x_boundary.shape)<0.1
    x_boundary = x_boundary[abandoned_boundary_idx]
    y_boundary = y_boundary[abandoned_boundary_idx]
    inp_map[(x_boundary,y_boundary)] = 0
    x_boundary, y_boundary = np.where(inp_map == 2)
    abandoned_boundary_idx = np.random.random(x_boundary.shape)<0.1
    x_boundary = x_boundary[abandoned_boundary_idx]
    y_boundary = y_boundary[abandoned_boundary_idx]
    inp_map[(x_boundary,y_boundary)] = 1

    inp = np.zeros((height, width)).astype(np.uint8)
    inp[(height-inp_map.shape[0])//2:(height-inp_map.shape[0])//2+inp_map.shape[0],\
         (width-inp_map.shape[1])//2:(width-inp_map.shape[1])//2+inp_map.shape[1]] = inp_map

    tar = np.zeros((height, width)).astype(np.uint8)
    tar[(height-raw_map.shape[0])//2:(height-raw_map.shape[0])//2+raw_map.shape[0],\
         (width-raw_map.shape[1])//2:(width-raw_map.shape[1])//2+raw_map.shape[1]] = raw_map

    # freespace enhance
    dot_num = 100
    cnt = 0
    cnt2 = 0

    bx1 = int(0.95*width)
    by1 = int(0.95*height)
    bx0 = int(0.05*width)
    by0 = int(0.05*height)

    for _ in range(2500):
        randcoinf = np.random.random()
        if randcoinf<0.01:
            x,y = np.random.rand(2)
            x = int(x*height)
            y = int(y*width)
            w = np.random.randint(2,10)
            h = np.random.randint(2,10)
            x = max(min(x, bx1), bx0)
            y = max(min(y, by1), by0)
            # if np.unique(inp[x-h//2:x+h//2, y-h//2:y+h//2]).shape[0]>1:
            if inp[x,y] in [1,2]:
                inp[x-w//2:x+w//2,y-h//2:y+h//2] = np.zeros((w//2*2,h//2*2))
        elif randcoinf<0.1:
            x,y = np.random.rand(2)
            x = int(x*height)
            y = int(y*width)
            w = np.random.randint(2,5)
            h = np.random.randint(2,5)
            x = max(min(x, bx1), bx0)
            y = max(min(y, by1), by0)
            # if np.unique(inp[x-h//2:x+h//2, y-h//2:y+h//2]).shape[0]>1:
            if inp[x,y] in [1,2]:
                inp[x-w//2:x+w//2,y-h//2:y+h//2] = np.ones((w//2*2,h//2*2))*2
        else:
            x,y = np.random.rand(2)
            x = int(x*height)
            y = int(y*width)
            w = np.random.randint(2,5)
            h = np.random.randint(2,5)
            x = max(min(x, bx1), bx0)
            y = max(min(y, by1), by0)
            if np.unique(inp[x-h//2:x+h//2, y-h//2:y+h//2]).shape[0]>1:
            # if inp[x,y] in [1,2]:
                inp[x-w//2:x+w//2,y-h//2:y+h//2] = np.ones((w//2*2,h//2*2))*2

    for _ in range(dot_num):
        x,y = np.random.rand(2)
        x = int(x*height)
        y = int(y*width)
        if inp[x,y] == 2:
            w = np.random.randint(2,5)
            h = np.random.randint(2,5)
            random_num = np.random.rand()
            if random_num<0.8:
                inp[x-w//2:x+w//2,y-h//2:y+h//2] = np.ones((width,height))[x-w//2:x+w//2,y-h//2:y+h//2]*2
            elif random_num<0.9:
                inp[x-w*2:x+w*2,y-h*2:y+h*2] = np.ones((width,height))[x-w*2:x+w*2,y-h*2:y+h*2]*1
            else:
                inp[x-w*2:x+w*2,y-h*2:y+h*2] = np.zeros((width,height))[x-w*2:x+w*2,y-h*2:y+h*2]

        if inp[x,y] == 1:
            if cnt <20:
                if cnt2 < 10:
                    cnt2 += 1
                    w = np.random.randint(1,5)
                    h = np.random.randint(1,5)
                    inp[x-w//2:x+w//2,y-h//2:y+h//2] = np.zeros((width,height))[x-w//2:x+w//2,y-h//2:y+h//2]
                else:
                    cnt += 1
                    w = np.random.randint(1,3)
                    h = np.random.randint(1,3)
                    inp[x-w//2:x+w//2,y-h//2:y+h//2] = np.ones((width,height))[x-w//2:x+w//2,y-h//2:y+h//2]*2
    #             else:
    #                 inp[x,y] = 0
    image =  Image.fromarray(inp.copy())
    draw = ImageDraw.Draw(image)

    #     绘制飞线
    rect_num = 10
    for i in range(rect_num):
        darw_poly(draw, height, width, 1, inp, 50)
    inp = np.array(image)

    inp_map = np.concatenate([tar, inp], 1)

    inp_map[np.where(inp_map==0)] = 127
    inp_map[np.where(inp_map==1)] = 255
    inp_map[np.where(inp_map==2)] = 0

    # Save map
    if not os.path.exists(save_path + "/inp"):
        os.mkdir(save_path + "/inp")
    cv2.imwrite(save_path + "/inp/" + file_name + '.png', inp_map)
    #####################################

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Visualize the subset of maps in .png.")
    parser.add_argument("map_id_set_file", help="map id set (.txt)")
    parser.add_argument("--json_path", type=str, default="./HouseExpo/json/", help="json file path")
    parser.add_argument("--save_path", type=str, default='./png')
    result = parser.parse_args()

    json_path = os.path.abspath(os.path.join(os.getcwd(), result.json_path))
    map_file = os.path.abspath(os.path.join(os.getcwd(), result.map_id_set_file))
    save_path = os.path.abspath(os.path.join(os.getcwd(), result.save_path))
    print("---------------------------------------------------------------------")
    print("|map id set file path        |{}".format(map_file))
    print("---------------------------------------------------------------------")
    print("|json file path              |{}".format(json_path))
    print("---------------------------------------------------------------------")
    print("|Save path                   | {}".format(save_path))
    print("---------------------------------------------------------------------")

    map_ids = np.loadtxt(map_file, str)

    for map_id in map_ids:
        draw_map(map_id, json_path, save_path)

    print("Successfully draw the maps into {}.".format(save_path))


# -*- coding: utf-8 -*-
import unittest
# 单元测试是程序的重要部分之一，python内置了测试模块，unittest
from closure import createCounter

class Nametest(unittest.TestCase):
    # 这部分成为说明文档，用于对方法，属性或者类的说明，鼠标悬浮能够看到这部分内容
    """测试闭包是否通过测试"""

    def test_closure(self):
        counter = createCounter()
        self.assertEqual(
            [counter(), counter(),
             counter(), counter(),
             counter()], [1, 2, 3, 4])

unittest.main()
# 测试成功的结果
# .
# ----------------------------------------------------------------------
# Ran 1 test in 0.000s

# OK

# 失败时的结果
# F
# ======================================================================
# FAIL: test_closure (__main__.Nametest)
# ----------------------------------------------------------------------
# Traceback (most recent call last):
#   File "e:/PythonCharming/pythonTest.py", line 16, in test_closure
#     counter()], [1, 2, 3, 4])
# AssertionError: Lists differ: [1, 2, 3, 4, 5] != [1, 2, 3, 4]

# First list contains 1 additional elements.
# First extra element 4:
# 5

# - [1, 2, 3, 4, 5]
# ?            ---

# + [1, 2, 3, 4]

# ----------------------------------------------------------------------
# Ran 1 test in 0.001s

# FAILED (failures=1)


from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/store/user/', methods = ['GET'])
def index():
    return jsonify({
        "status": "OK",
        "result": {
            "method": "GET",
            "url": {},
            "body": {}
        }
    })

@app.route('/profile', methods = ['POST'])
def add():
    print('usao')
    data = request.get_json(force = True)

    return jsonify({
        "status": "OK",
        "result": {
            "method": "POST",
            "url": {},
            "body": data
        }
    })

@app.route('/profile/<profileId>', methods = ['DELETE'])
def delete(profileId):
    return jsonify({
        "status": "OK",
        "result": {
            "method": "DELETE",
            "url": {
                "param": profileId
            },
            "body": {}
        }
    })

@app.route('/store/user/<profileId>', methods = ['PUT'])
def edit(profileId):
    data = request.get_json(force = True)

    return jsonify({
        "status": "OK",
        "result": {
            "method": "PUT",
            "url": {
                "param": profileId
            },
            "body": data
        }
    })

if __name__ == '__main__':
    app.run(host = '127.0.0.1', port = 8000)


#!/usr/bin/python3
import sys
import numpy as np
from scipy.interpolate import InterpolatedUnivariateSpline
from scipy.special import sph_harm
import aux_analysis as aux

class state(object):

    E1ssg = -0.12840107E+01
    r = 1.4
    Ip = E1ssg + 1 / r

    def __init__(self, str_in, indx0):
        self.sym_str = str_in.split()[0]

        self.state_type = self.sym_str[0]
        self.m_sym = self.sym_str[2]
        self.m_val = aux.get_m(self.sym_str)
        self.isym = self.sym_str[3]

        if self.state_type == "B":
            self.n_bound = int(str_in.split()[1])
            self.wf_ind_i = indx0 - self.n_bound
        if self.state_type == "Q":
            self.n_res = int(str_in.split()[1])
            self.wf_ind_i = indx0 - self.n_res
        if self.state_type == "C":
            self.n_thres = int(self.sym_str[1])
            self.n_gridE = int(str_in.split()[3])
            self.n_chan = int(str_in.split()[2])
            self.n_cont = self.n_chan * self.n_gridE
            self.wf_ind_i = indx0 - self.n_cont
            self.l_chan = self.get_l_channels()
            self.phase_log = False
            if str_in.split()[4].lower() == "ph":
                self.phase_log = True
                self.read_phase()

    def get_l_channels(self):
        thres_dict = {1: "g", 2: "u", 3: "u", 4: "g"}

        thres_sym = thres_dict[self.n_thres]
        if (self.isym == "g" and thres_sym == "g") or (self.isym == "u" and thres_sym == "u"):
            l_sym = "g"
        elif (self.isym == "g" and thres_sym == "u") or (self.isym == "u" and thres_sym == "g"):
            l_sym = "u"

        res1 = np.zeros((self.n_chan), dtype=np.int)
        if l_sym == "g" and self.m_sym == "S":
            for l in range(0, self.n_chan):
                res1[l] = 2 * l
        if l_sym == "g" and self.m_sym == "P":
            for l in range(0, self.n_chan):
                res1[l] = 2 * (l + 1)
        elif l_sym == "u":
            for l in range(0, self.n_chan):
                res1[l] = 2 * l + 1

        return res1

    def read_sol_file(self, ener_vec, coef_vec):

        if self.state_type == "B":
            self.coef = np.zeros((self.n_bound), dtype=np.complex128)
            self.ener = np.zeros((self.n_bound), dtype=np.float64)

            for n in range(0, self.n_bound):
                self.coef[n] = coef_vec[self.wf_ind_i + n]
                self.ener[n] = ener_vec[self.wf_ind_i + n]

            self.dens_prob(self.ener, self.coef)

        elif self.state_type == "Q":
            self.coef = np.zeros((self.n_res), dtype=np.complex128)
            self.ener = np.zeros((self.n_res), dtype=np.float64)

            for r in range(0, self.n_res):
                self.coef[n] = coef_vec[self.wf_ind_i + r]
                self.ener[n] = ener_vec[self.wf_ind_i + r]

            self.dens_prob(self.ener, self.coef)

        elif self.state_type == "C":
            global Ip
            self.coef = np.zeros((self.n_gridE, self.n_chan), dtype=np.complex128)
            self.ener = np.zeros((self.n_gridE), dtype=np.float64)
            self.dens_cont = np.zeros((self.n_gridE), dtype=np.float64)

            i = self.wf_ind_i
            for l in range(0, self.n_chan):
                for k in range(0, self.n_gridE):
                    if k == 0:
                        self.dens_cont[k] = 1.0 / abs(ener_vec[i + 1] - ener_vec[i])
                    elif k == (self.n_gridE - 1):
                        self.dens_cont[k] = 1.0 / abs(ener_vec[i] - ener_vec[i - 1])
                    else:
                        self.dens_cont[k] = 2.0 / abs(ener_vec[i + 1] - ener_vec[i - 1])
                    self.coef[k][l] = coef_vec[i] * np.sqrt(self.dens_cont[k])
                    self.ener[k] = ener_vec[i] - self.Ip
                    i += 1

            self.dens_prob(self.ener, self.coef)

        return

    def dens_prob(self, ener_vec, coef_vec):

        if self.state_type == "B":
            self.dens = np.zeros((len(ener_vec)), dtype=np.float64)

            for n in range(0, len(ener_vec)):
                self.dens[n] = np.abs(coef_vec[n])**2

        elif self.state_type == "Q":
            self.dens = np.zeros((len(ener_vec)), dtype=np.float64)

            for r in range(0, len(ener_vec)):
                self.dens[r] = np.abs(coef_vec[r])**2

        elif self.state_type == "C":
            self.dens = np.zeros((len(ener_vec)), dtype=np.float64)
            self.dens_lchan = np.zeros((len(ener_vec), coef_vec.shape[1]), dtype=np.float64)

            for k in range(0, len(ener_vec)):
                for l in range(0, coef_vec.shape[1]):
                    self.dens[k] += np.abs(coef_vec[k][l])**2
                    self.dens_lchan[k][l] = np.abs(coef_vec[k][l])**2
        return

    def read_phase(self):
        file_phase = self.sym_str + ".desf"
        file = open(file_phase, "r")

        str_tmp = file.readline().split()
        self.n_gridE_phase = int(str_tmp[0])
        self.n_chan_phase = int(str_tmp[1])

        self.ener_phase = np.zeros((self.n_gridE_phase), dtype=np.float64)
        self.phaseshift = np.zeros((self.n_gridE_phase, self.n_chan_phase), dtype=np.float64)

        for k in range(0, self.n_gridE_phase):
            str_tmp = file.readline().split()
            self.ener_phase[k] = np.float64(str_tmp[1]) - self.Ip
            self.phaseshift[k, :] = np.array((str_tmp[2:]), dtype=np.float64)
        file.close()

        return

    def interpolate_coef(self, vec_ener, case):

        self.n_gridE_interp = len(vec_ener)
        self.ener_interp = vec_ener
        self.coef_interp = np.zeros((self.n_gridE_interp, self.n_chan), dtype=np.complex128)

        for l in range(0, self.n_chan):
            spl_re = InterpolatedUnivariateSpline(self.ener, np.real(self.coef[:, l]))
            spl_im = InterpolatedUnivariateSpline(self.ener, np.imag(self.coef[:, l]))

            for k, e in enumerate(self.ener_interp):
                if e >= self.ener[0] and e <= self.ener[-1]:
                    self.coef_interp[k][l] = spl_re(e) + spl_im(e) * 1j

        if case == "photoelectron_spectra":
            self.dens_prob(self.ener_interp, self.coef_interp)

        return

    def angular_distribution(self, theta_vec, phi_vec):

        print("Calculating angular distributin of state ", self.sym_str)

        if self.phase_log is False:
            print("No phases defined for this state", self.sym_str)
            return

        ntheta = len(theta_vec)
        nphi = len(phi_vec)
        self.damp_dangle = np.zeros((len(self.ener_phase), ntheta, nphi), dtype=np.complex128)

        self.interpolate_coef(self.ener_phase, "angular_distribution")

        for k, ener in enumerate(self.ener_phase):
            for p, phi in enumerate(phi_vec):
                for t, theta in enumerate(theta_vec):
                    for l, lval in enumerate(self.l_chan):
                        il = 1j**(-lval)
                        ephacou = np.exp(1j * aux.coul_phase(lval, ener))
                        # ephashift = np.exp(-1j * phase_shift[alpha][k][l])
                        ephashift = self.phaseshift[k][l]
                        Ylm = sph_harm(self.m_val, lval, phi, theta)
                        self.damp_dangle[k][t][p] += il * ephacou * ephashift * self.coef_interp[k][l] * Ylm

        return


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

"""
wiki.py
A very simple Wiki, now more striclty separeted according to the mvc pattern

@author: Tobias Thelen
@contact: tobias.thelen@uni-osnabrueck.de
@licence: public domain
@status: completed
@version: 2 (04/2015)

modified by: Falk Wilke
             Jan-Philip Schleutker
"""

import os

from blatt04.server import webserver
from blatt04.server.middleware.static import StaticMiddleware
from blatt04.server.log import log
from blatt04 import wikimodel

class WikiApp:
    def __init__(self, datadir=None):
        # global var for the wiki
        self.wiki = wikimodel.Wiki(datadir)

    def show(self, request, response, pathmatch=None):
        """Evaluate request and construct response."""
        modified = ""
        try:
            pagename = pathmatch.group('pagename') or "main"
        except IndexError:
            pagename = "main"  # default pagename

        try:
            page = self.wiki.get_page(pagename)
            text = page.as_html()
            modified = page.modifiedTime
        except wikimodel.NoSuchPageError:
            # redirect to edit view if page does not exist
            response.send_redirect("/edit/" + pagename)
            return

        # show page
        response.send_template('templates/wiki.tmpl',
                               {'text': text,
                                'mode': 'show',
                                'pagelist': self.wiki.pagelist(),
                                'pagename': pagename,
                                'modified': modified})

    def edit(self, request, response, pathmatch=None):
        """Display wiki page for editing."""
        modified = ""
        try:
            pagename = pathmatch.group('pagename') or "main"
        except IndexError:
            pagename = "main"

        try:
            page = self.wiki.get_page(pagename)
            text = page.wikitext
            modified = page.modifiedTime
        except wikimodel.NoSuchPageError:
            # use default text if page does not yet exist
            text = "This page is still empty. Fill it."

        # fill template and show
        response.send_template('templates/wiki.tmpl',
                               {'text': text,
                                'mode': 'edit',
                                'pagelist': self.wiki.pagelist(),
                                'pagename': pagename,
                                'modified': modified
                                })

    def save(self, request, response, pathmatch=None):
        """Evaluate request and construct response."""

        try:
            pagename = pathmatch.group('pagename')
        except IndexError:
            # no pagename given: error
            response.send_template("templates/wiki.tmpl",
                                   {'error': 'No pagename given.',
                                    'pagename': "Error",
                                    'pagelist': self.wiki.pagelist(),
                                    'mode': 'error',
                                    'text': 'save action needs pagename'}, code=500)
            return

        try:
            wikitext = request.params['wikitext']
        except KeyError:
            # no text given: error
            response.send_template("templates/wiki/wikierror.html",
                                   {'error': 'No wikitext given.',
                                    'pagename': "Error",
                                    'pagelist': self.wiki.pagelist(),
                                    'mode': 'error',
                                    'text': 'save action needs wikitext'}, code=500)
            return

        # ok, save text
        self.wiki.store_page(pagename, wikitext)

        response.send_redirect("/show/" + pagename)

    def remove(self, request, response, pathmatch=None):
        try:
            pagename = pathmatch.group('pagename')
        except IndexError:
            # no pagename given: error
            response.send_template("templates/wiki.tmpl",
                                   {'error': 'No pagename given.',
                                    'pagename': "Error",
                                    'pagelist': self.wiki.pagelist(),
                                    'mode': 'error',
                                    'text': 'delete action needs pagename'}, code=500)
            return
        if pagename.strip() == "main":
            response.send_template("templates/wiki.tmpl",
                                   {'error': '"main" cannot be deleted',
                                    'pagename': "Error",
                                    'pagelist': self.wiki.pagelist(),
                                    'mode': 'error',
                                    'text': 'main cannot be deleted'}, code=500)
            return;
        try:
            page = self.wiki.get_page(pagename)
            page.remove()
        except wikimodel.NoSuchPageError:
            response.send_template("templates/wiki.tmpl",
                                   {'error': 'page not found',
                                    'pagename': "Error",
                                    'pagelist': self.wiki.pagelist(),
                                    'mode': 'error',
                                    'text': 'only existing pages can be deleted'}, code=500)
            return

        response.send_redirect("/show/main")

if __name__ == '__main__':
    w = WikiApp('data')
    s = webserver.Webserver()
    s.add_route(r"^/$", w.show)
    s.add_route(r"^/show(/(?P<pagename>\w+))?$", w.show)
    s.add_route(r"^/edit/(?P<pagename>\w+)$", w.edit)
    s.add_route(r"^/save/(?P<pagename>\w+)$", w.save)
    s.add_route(r"^/delete/(?P<pagename>\w+)$", w.remove)
    s.add_middleware(StaticMiddleware(urlpattern='', path=os.getcwd() + '/static'))

    log(0, "Server running.")
    s.serve()