import numpy as np
import pandas as pd
from collections import defaultdict
from config import Config
import re
import time

#Core Functions

def throw_ini_error(err_type):
    print(err_type)

def read_ini(ini_path, v_name='nickname', filter_str=None):
    with open(ini_path, 'r') as ini:
        ini_lines = list(filter(None, [ln.strip() for ln in re.split(r'^(\[[A-Za-z]*\])', ini.read(), flags=re.M)]))
        ds = next(i for i, string in enumerate(ini_lines) if '[' in string)
        i_comments = ini_lines[:ds]
        i_keys = ini_lines[ds::2]
        i_values = ini_lines[ds+1::2]
        ini_dict = dict()

        for i in range(len(i_keys)):
            if filter_str and filter_str.lower() not in i_keys[i].lower():
                continue

            value_name = i_keys[i]
            i_tuples = list()

            try:
                i_props = list(filter(None, [ip for ip in i_values[i].split('\n') if ';' not in ip]))
            except IndexError:
                throw_ini_error(IndexError)
                continue

            if not i_props:
                continue

            for ip in i_props:
                i_tuples.append(tuple([i_tup.strip() for i_tup in ip.split('=')]))

            if not i_tuples:
                continue

            partial_dict = defaultdict(list)
            try:
                for k, v in i_tuples:
                    if v_name in k:
                        value_name = v
                    partial_dict[k].append(v)
            except ValueError:
                print('ERR: Invalid INI entry in file {0}'.format(ini_path))

            ini_dict[value_name] = partial_dict

    return ini_dict

def get_data(comm_markets_path, distances_path):
    '''
    A function that pulls in the data from marketcommodities.ini and the flc dump file and scrapes it.
    +++++++++
    Parameters:
    comm_markets_path (str): the path of market_commodities.ini
    distances_path (str): the path of the flc dump file
    +++++++++
    Returns
    distances (Dataframe): pandas dataframe of all the viable distances between bases
    bases(nested dict): dictionary structure keys internal name to a dictionary containing every commodity bought and sold
    comm_set (list): list of all commodities bought or sold on all bases
    base_names (dict): all base names keyed to their internal name
    sys_names (dict): all system names keyed to their internal name
    '''

    #distances = pd.read_csv(distances_path, names = ['start', 'end', 'time'])
    #distances = distances[distances['start']!=distances['end']]
    #distances = distances[distances['time']!=-1]

    distances = pd.read_csv(distances_path, names = ['start', 'end', 'time'])
    distances = distances.set_index(['start', 'end'])
    distances['time'] = distances['time'].apply(lambda x: x + 20000) # adding dock time because that's not exported for some reason

    commodities = dict()
    bases = dict()
    infocards = dict()
    sys_ids = dict()
    system_files = dict()
    systems = dict()

    # TODO: Separate out into helper functions; make a specialized class for this and generalize config parsing

    with open(Config.FILEPATH + 'SERVICE/infocards.txt', 'r', encoding='utf8') as i:
        for line in i:
            if line.strip().isdigit():
                next(i, None)
                infocards[line.strip()] = next(i, None)

    select_equip = read_ini(Config.FILEPATH + 'DATA/EQUIPMENT/select_equip.ini', filter_str="commodity")
    goods = read_ini(Config.FILEPATH + 'DATA/EQUIPMENT/goods.ini')
    market_commodities = read_ini(comm_markets_path, 'base')
    u_systems = read_ini(Config.FILEPATH + 'DATA/UNIVERSE/universe.ini', filter_str="system")
    u_bases = read_ini(Config.FILEPATH + 'DATA/UNIVERSE/universe.ini', filter_str="base")

    for k, v in select_equip.items():
        commodities[k.lower()] = {
            "nickname": k.lower(),
            "ids_name": v['ids_name'],
            "display_name": "",
            "base_price": 0.0,
            "consumed_by": [],
            "produced_by": []
            }

    for k, v in goods.items():
        if k.lower() not in commodities.keys():
            continue
        commodities[k.lower()]["base_price"] = float(v['price'][0])

    for k, v in market_commodities.items():
        bases[k.lower()] = {
            "nickname": k.lower(),
            "ids_name": "",
            "display_name": "",
            "archetype": "",
            "system": "",
            "commodities": {}
        }

        for mgs in v['MarketGood']:
            mg = mgs.split(', ')
            raw_data = [m for m in mg]
            commo = mg.pop(0).lower()
            base = bases[k.lower()]['commodities']
            base[commo] = {
                'raw_data': raw_data,
                'price_mult': float(mg.pop()),
                'consumer': int(mg.pop()),
                'max': int(mg.pop()),
                'min': int(mg.pop()),
                'rep': float(mg.pop()),
                'rank': int(mg.pop()),
                'display_name': infocards[commodities[commo]["ids_name"][0]].strip()
            }

            base[commo]['actual_price'] = base[commo]['price_mult'] * commodities[commo]['base_price']

            if base[commo]['price_mult'] > 1.0 or base[commo]['consumer']:
                commodities[commo]['consumed_by'].append(bases[k.lower()])
            if not base[commo]['consumer']:
                commodities[commo]['produced_by'].append(bases[k.lower()])

    for k, v in u_systems.items():
        sys_ids[k.lower()] = v['strid_name'][0]
        if 'file' in v.keys(): # thanks multiuniverse plugin, very cool
            system_files[k.lower()] = v['file'][0]

    for k, v in u_bases.items():
        try:
            bases[k.lower()]["ids_name"] = v['strid_name'][0].lower()
            bases[k.lower()]["system"] = v['system'][0].lower()
        except KeyError:
            pass

    for b_name, b_dict in bases.items():
        strid_name = b_dict['ids_name']
        system = b_dict['system']
        try:
            sys_strid_name = sys_ids[system]
        except KeyError:
            print(b_dict)
        system_path = ""

        try:
            system_path = system_files[system]
        except KeyError:
            print("WARN: Path not found for system '{0}'.".format(system))
        if system not in systems.keys():
            systems[system] = read_ini(Config.UNIPATH + system_path)

        if strid_name == "0":
            b_dict["display_name"] = strid_name
            continue
        try:
            b_dict["display_name"] = infocards[strid_name].strip()
        except KeyError:
            b_dict["display_name"] = strid_name
            print("ERR: No IDS {0} found in infocards.txt for {1}!".format(strid_name, b_name))

        try:
            b_dict["system_dis"] = infocards[sys_strid_name].strip()
        except KeyError:
            b_dict["system_dis"] = sys_strid_name
            print("ERR: No IDS {0} found in infocards.txt for {1}!".format(sys_strid_name, system))

    for c_name, c_dict in commodities.items():
        strid_name = c_dict["ids_name"][0]
        try:
            c_dict["display_name"] = infocards[strid_name].strip()
        except KeyError:
            c_dict["display_name"] = c_name
            print("ERR: No IDS {0} found in infocards.txt for {1}".format(strid_name, c_name))

    with open('help.txt', 'w') as w:
        w.write(str(commodities['commodity_credit1']['produced_by']))

    return distances, bases, commodities

def sort_by_closest_base(list_of_bases, distances):
    '''
    a function that takes the distances dataframe and any list of bases and sorts all the other bases out into the lists of bases closest to those bases in the list of bases.
    Its got a lot of fuckery, and maybe can be given aother pass for better algorithmic complexity. I'm so sorry.

    Parameters
    list_of_bases (list): a list of string base codes
    distances (DataFrame): the base to base travel times from flcomp formatted as a DataFrame by get_data()

    Returns:
    sorted_l (list of lists) list of list of bases, sorted in the same shape as the list of bases fed in,
    with each list containing those bases that are closest to the base listed at the same index in list_of_bases
    '''
    k = [distances[distances['start'] == i] for i in list_of_bases] # makes a list of dataframes of routes starting from the bases in question
    k = [i[~i['end'].isin(list_of_bases)].reset_index() for i in k] # gets rid of routes between bases in the  list

    df = pd.DataFrame()
    for idx, i in enumerate(list_of_bases): #peices the list k back together into a larger thing
        df[i]=k[idx]['time']
    df['base'] = k[0]['end']
    df = df.set_index('base')

    sorted_bases = df.idxmin(axis=1)
    sorted_bases = sorted_bases.reset_index()
    sorted_l =[]

    for i in list_of_bases:
        sorted_l.append(sorted_bases[sorted_bases[0]==i]['base'].to_list())

    return sorted_l


"""
# Definition for a Node.
class Node:
    def __init__(self, val, prev, next, child):
        self.val = val
        self.prev = prev
        self.next = next
        self.child = child
"""
class Solution:
    def flatten(self, head: 'Node') -> 'Node':
        self.recurse(head)
        return head

    def recurse(self, root: 'Node') -> 'Node':
        if root is None:
            return root

        child = self.recurse(root.child)
        next = self.recurse(root.next)

        if child is not None and next is not None:
            root.child = None
            root.next = child
            child.prev = root

            temp_child = child
            while temp_child is not None and temp_child.next is not None:
                temp_child = temp_child.next

            temp_child.next = next
            next.prev = temp_child
        elif child is not None:
            root.child = None
            root.next = child
            child.prev = root
        elif next is not None:
            root.child = None
            root.next = next
            next.prev = root

        return root


# Dedicated to the public domain under CC0: https://creativecommons.org/publicdomain/zero/1.0/.

'Sequence utilities.'

from bisect import bisect_left, bisect_right
from typing import Iterator, Sequence, Tuple, TypeVar

_T = TypeVar('_T')

def sorted_seq_index(seq:Sequence[_T], el:_T) -> int:
  '''
  Locate the leftmost element exactly equal to `el`.
  From stdlib bisect documentation.
  '''
  i = bisect_left(seq, el)
  if i != len(seq) and seq[i] == el:
    return i
  raise ValueError(el)

def sorted_seq_find_lt(seq:Sequence[_T], el:_T) -> _T:
  '''
  Find rightmost element less than `el`.
  From stdlib bisect documentation.
  '''
  i = bisect_left(seq, el)
  if i:
    return seq[i-1]
  raise ValueError

def sorted_seq_find_le(seq:Sequence[_T], el:_T) -> _T:
  '''
  Find rightmost element less than or equal to `el`.
  From stdlib bisect documentation.
  '''
  i = bisect_right(seq, el)
  if i:
    return seq[i-1]
  raise ValueError

def sorted_seq_find_gt(seq:Sequence[_T], el:_T) -> _T:
  '''
  Find leftmost element greater than `el`.
  From stdlib bisect documentation.
  '''
  i = bisect_right(seq, el)
  if i != len(seq):
    return seq[i]
  raise ValueError

def sorted_seq_find_ge(seq:Sequence[_T], el:_T) -> _T:
  '''Find leftmost element greater than or equal to `el`.
  From stdlib bisect documentation.
  '''
  i = bisect_left(seq, el)
  if i != len(seq):
    return seq[i]
  raise ValueError

def iter_pairs_of_el_is_last(seq:Sequence[_T]) -> Iterator[Tuple[_T, bool]]:
  last = len(seq) - 1
  return ((el, i==last) for i, el in enumerate(seq))


from django.db import models
import datetime
from django.utils.timezone import now

class Chat(models.Model):
	title = models.CharField('заголовок', max_length=255, default='')
	is_group_chat = models.BooleanField('групповой чат', default=False)
	topic = models.CharField('топик', max_length=255, default='')
	avatar = models.ImageField('аватар', upload_to='images/', null=True)
	last_message_text = models.CharField('текст последнего сообщения', max_length=255, default='')
	last_message_date = models.DateTimeField('дата создания', default=now)

	def __str__(self):
		return self.title

	class Meta:
		verbose_name = "Чат"
		verbose_name_plural = "Чаты"
		ordering = ["-last_message_date"]

class Message(models.Model):
	content = models.TextField('контент', default='')
	date = models.DateTimeField('дата создания', default=now)
	chat = models.ForeignKey(Chat, on_delete=models.SET_NULL, null=True, related_name='messages', verbose_name="чат")
	user = models.ForeignKey('user_profile.User', on_delete=models.SET_NULL, null=True, related_name='messages', verbose_name="пользователь")

	def __str__(self):
		return self.content

	class Meta:
		verbose_name = "Сообщение"
		verbose_name_plural = "Сообщения"
		ordering = ["date", "content"]

class Attachment(models.Model):
	chat = models.ForeignKey(Chat, on_delete=models.SET_NULL, null=True, related_name='attachments', verbose_name="чат")
	user = models.ForeignKey('user_profile.User', on_delete=models.SET_NULL, null=True, related_name='attachments', verbose_name="пользователь")
	content_type = models.CharField('MIME тип', max_length=255, default='image/png')
	url = models.ImageField('адрес', upload_to='uploads/', null=True)
	message = models.OneToOneField(Message, on_delete=models.SET_NULL, null=True, related_name='attachment', unique=True, verbose_name="сообщение")

	class Meta:
		verbose_name = "Прикрепление"
		verbose_name_plural = "Прикрепления"
		ordering = ["content_type"]


from django.urls import path

from . import views,deploy,chart,attendance,penality

urlpatterns = [
    path('showpenality/', penality.showpenality, name="showpenality"),
    path('takepenality/',  penality.takepenality, name="takepenality"),

    path('showattendance/', attendance.showattendance, name="showattendance"),
    path('takeattendance/', attendance.takeattendance, name="takeattendance"),

    path('report', chart.report, name='report'),
    path('report-chart/', chart.report_chart, name='report-chart'),
    path('', views.index, name='index'),

    path('vehicle_location', views.vehicle_location,name='vehicle_location'),
    path('location/<str:mid>', views.location,name='location'),

    path('deployment', deploy.deploy,name="deploy"),
    path('driver/register', views.driver_register, name='driver_register'),
    path('driver/new', views.driver_register_save, name='driver_save'),
    path('driver/', views.driver_list, name='driver_list'),

    path('subcity/register', views.subcity_register, name='subcity_register'),
    path('subcity/new', views.subcity_save, name='subcity_save'),
    path('subcity/', views.subcity_list, name='subcity_list'),
    path('subcity/edit/<int:id>', views.subcity_edit,name='subcityEdit'),
    path('subcity/update/<int:id>', views.subcity_update,name='subcityUpdate'),
    path('subcity/delete/<int:id>', views.subcity_destroy,name='subcityDelete'),

    path('station/register', views.station_register, name='station_register'),
    path('station/new', views.station_save, name='station_save'),
    path('station/', views.station_list, name='station_list'),
    path('station/edit/<int:id>', views.station_edit,name='stationEdit'),
    path('station/update/<int:id>', views.station_update,name='stationUpdate'),
    path('station/delete/<int:id>', views.station_destroy,name='stationDelete'),

    path('route/register', views.route_register, name='route_register'),
    path('route/new', views.route_save, name='route_save'),
    path('route/', views.route_list, name='route_list'),
    path('route/edit/<int:id>', views.route_edit,name='routeEdit'),
    path('route/update/<int:id>', views.route_update,name='routeUpdate'),
    path('route/delete/<int:id>', views.route_destroy,name='routeDelete'),

    path('vehicle/register', views.vehicle_register, name='vehicle_register'),
    path('vehicle/new', views.vehicle_save, name='vehicle_save'),
    path('vehicle/', views.vehicle_list, name='vehicle_list'),
    path('Assigned_vehicle_list/', views.Assigned_vehicle_list, name='Assigned_vehicle_list'),
    path('vehicle/edit/<int:id>', views.vehicle_edit,name='vehicleEdit'),
    path('vehicle/update/<int:id>', views.vehicle_update,name='vehicleUpdate'),
    path('vehicle/delete/<int:id>', views.vehicle_destroy,name='vehicleDelete'),

    path('machine/register', views.machine_register, name='machine_register'),
    path('machine/new', views.machine_save, name='machine_save'),
    path('machine/', views.machine_list, name='machine_list'),
    path('machine/edit/<int:id>', views.machine_edit,name='machineEdit'),
    path('machine/update/<int:id>', views.machine_update,name='machineUpdate'),
    path('machine/delete/<int:id>', views.machine_destroy,name='machineDelete'),
    path('machine/data', views.machine_data_list, name='machine_data_list'),

]


import numpy as np

array1 = np.array(range(30))
array2 = np.array([2,3,5])

with open('array.npz','wb') as f:
    np.savez(f,array1,array2)

load_array=np.load('array.npz')
array3=np.array([[4,5,6],[1,2,3]])
np.savez('new_array.npz',load_array,array3)


#!/usr/bin/python3
import socket

recv_ip='197.168.43.41'
recv_port=4444

s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind((recv_ip,recv_port))

q=0
while q==0:
	data=s.recvfrom(150)
	ndata=data[0].decode('ascii')
	print("From Sender :",ndata )
	rpl=input("Your reply : ")
	if len(rpl)>150:
		print("reply should be less then 150 characters")
		rpl=input("Your reply :")
	send=rpl.encode('ascii')
	s.sendto(send,data[1])
	q=int(input("Press 1 to quit the chat and 0 for continue :"))


# -*- coding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1463637607.218917
_enable_loop = True
_template_filename = 'G:/public_html/iutvalence-python-mangacollection/View/template/dessinateur_new.html'
_template_uri = 'dessinateur_new.html'
_source_encoding = 'utf-8'
_exports = ['container']

def _mako_get_namespace(context, name):
    try:
        return context.namespaces[(__name__, name)]
    except KeyError:
        _mako_generate_namespaces(context)
        return context.namespaces[(__name__, name)]
def _mako_generate_namespaces(context):
    pass
def _mako_inherit(template, context):
    _mako_generate_namespaces(context)
    return runtime._inherit_from(context, 'base.html', _template_uri)
def render_body(context,**pageargs):
    __M_caller = context.caller_stack._push_frame()
    try:
        __M_locals = __M_dict_builtin(pageargs=pageargs)
        def container():
            return render_container(context._locals(__M_locals))
        __M_writer = context.writer()
        __M_writer('\r\n')
        if 'parent' not in context._data or not hasattr(context._data['parent'], 'container'):
            context['self'].container(**pageargs)

        return ''
    finally:
        context.caller_stack._pop_frame()

def render_container(context,**pageargs):
    __M_caller = context.caller_stack._push_frame()
    try:
        def container():
            return render_container(context)
        __M_writer = context.writer()
        __M_writer('\r\n
\r\n    <form action="/dessinateur/add/" method="post">\r\n
\r\n            Dessinateur :\r\n            <input type="text" class="form-control" id="dessinateur" name="dessinateur" required>\r\n
\r\n        <input type="submit" class="btn btn-success">\r\n    </form>\r\n
\r\n')
        return ''
    finally:
        context.caller_stack._pop_frame()

"""
__M_BEGIN_METADATA
{"filename": "G:/public_html/iutvalence-python-mangacollection/View/template/dessinateur_new.html", "line_map": {"56": 50, "34": 2, "27": 0, "44": 3, "50": 3}, "uri": "dessinateur_new.html", "source_encoding": "utf-8"}
__M_END_METADATA
"""


#!/usr/bin/python
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
from torch.autograd import Variable
import time

from descriminator import D
from generator import G

#takes as parameter a neural network and defines its weights
def weights_init(m):
    classname = m.__class__.__name__
    if classname.find('Conv') != -1:
        m.weight.data.normal_(0.0, 0.02)
    elif classname.find('BatchNorm') != -1:
        m.weight.data.normal_(1.0, 0.02)
        m.bias.data.fill_(0)

print("""\n\tA simple example of a:
\t+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+
\t|G|e|n|e|r|a|t|i|v|e| |A|d|v|e|r|s|a|r|i|a|l| |N|e|t|w|o|r|k|
\t+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+
\tCode created by Davidson Mizael based on the course:
\t'Computer Vision A-Z'
\thttps://www.udemy.com/computer-vision-a-z""")

print("\n")
print("# Starting...")

#sets the size of the image (64x64) and the batch
batchSize = 64
imageSize = 64

#creating the transformations
transform = transforms.Compose([transforms.Scale(imageSize),transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),])

print("# Loading data...")
dataset = dset.CIFAR10(root = './data', download = True, transform = transform)
dataloader = torch.utils.data.DataLoader(dataset, batch_size = batchSize, shuffle = True, num_workers = 2)

print("# Starting generator and descriminator...")
netG = G()
netG.apply(weights_init)

netD = D()
netD.apply(weights_init)

#training the DCGANs
criterion = nn.BCELoss()
optimizerD = optim.Adam(netD.parameters(), lr = 0.0002, betas = (0.5, 0.999))
optimizerG = optim.Adam(netG.parameters(), lr = 0.0002, betas = (0.5, 0.999))

epochs = 25

timeElapsed = []
for epoch in range(epochs):
    print("# Starting epoch [%d/%d]..." % (epoch, epochs))
    for i, data in enumerate(dataloader, 0):
        start = time.time()
        time.clock()

        #updates the weights of the discriminator nn
        netD.zero_grad()

        #trains the discriminator with a real image
        real, _ = data
        input = Variable(real)
        target = Variable(torch.ones(input.size()[0]))
        output = netD(input)
        errD_real = criterion(output, target)

        #trains the discriminator with a fake image
        noise = Variable(torch.randn(input.size()[0], 100, 1, 1))
        fake = netG(noise)
        target = Variable(torch.zeros(input.size()[0]))
        ouput = netD(fake.detach())
        errD_fake = criterion(output, target)

        #backpropagating the total error
        errD = errD_real + errD_fake
        errD.backward()
        optimizerD.step()

        #updates the weights of the generator nn
        netG.zero_grad()
        target = Variable(torch.ones(input.size()[0]))
        output = netD(fake)
        errG  = criterion(output, target)

        #backpropagating the error
        errG.backward()
        optimizerG.step()

        if i % 50 == 0:
            #prints the losses and save the real images and the generated images
            print("# Progress: ")
            print("[%d/%d][%d/%d] Loss_D: %.4f Loss_G: %.4f" % (epoch, epochs, i, len(dataloader), errD.data[0], errG.data[0]))

            #calculates the remaining time by taking the avg seconds that every loop
            #and multiplying by the loops that still need to run
            timeElapsed.append(time.time() - start)
            avg_time = (sum(timeElapsed) / float(len(timeElapsed)))
            all_dtl = (epoch * len(dataloader)) + i
            rem_dtl = (len(dataloader) - i) + ((epochs - epoch) * len(dataloader))
            remaining =  (all_dtl - rem_dtl) * avg_time
            print("# Estimated remaining time: %s" % (time.strftime("%H:%M:%S", time.gmtime(remaining))))

        if i % 100 == 0:
            vutils.save_image(real, "%s/real_samples.png" % "./results", normalize = True)
            vutils.save_image(fake.data, "%s/fake_samples_epoch_%03d.png" % ("./results", epoch), normalize = True)

print ("# Finished.")


import math
from datetime import datetime, timedelta

import peewee
from consoleapp.settings import log, DATABASE_NAME

database = peewee.SqliteDatabase(DATABASE_NAME)

class BaseTable(peewee.Model):
    # В подклассе Meta указываем подключение к той или иной базе данных
    class Meta:
        database = database

class NamesCashItem(BaseTable):
    name = peewee.CharField()

    class Meta:
        verbose_name = u"Название статьи"
        verbose_name_plural = u"Названия статей статей"
        database = database

    def __str__(self):
        return self.name

class CashItem(BaseTable):
    name = peewee.ForeignKeyField(NamesCashItem)
    min_value = peewee.IntegerField(default=0, verbose_name="Минимальный порог")
    value = peewee.IntegerField(default=0, verbose_name=u"Значение")
    plan_value = peewee.IntegerField(default=0, verbose_name=u"Плановое значение")
    date = peewee.DateField(default=datetime.today(), verbose_name="Период")
    virtual_value = peewee.IntegerField(default=0, verbose_name=u"Плановый приход")
    active = peewee.BooleanField(default=True)

    class Meta:
        verbose_name = u"статья"
        verbose_name_plural = u"статьи"
        database = database

database.connect()
database.create_tables([NamesCashItem, CashItem])

#
# class NamesCashItem:
#
#     def __init__(self, name):
#         self.name = name
#
#     def __unicode__(self):
#         return self.name
#
#
# class CashItem:
#
#     def __init__(self,
#                  name=None,
#                  min_value=0,
#                  value=0,
#                  plan_value=0,
#                  date=datetime.today(),
#                  virtual_value=0):
#         self.name = name
#         self.min_value = min_value
#         self.value = value
#         self.plan_value = plan_value
#         self.date = date
#         self.virtual_value = virtual_value
#
#     def __str__(self):
#         return self.name

class ManagerCashItems:

    def __init__(self):
        self.date_begin = None
        self.date_end = None
        self.cash_items = []

    def __str__(self):
        return f"{self.date_begin} - {self.date_end}"

    def set_period_manager(self, begin, end):
        """Установить период текущего менеджера

        :param begin: начало периода
        :param end: конец периода
        """
        self.date_begin = begin
        self.date_end = end
        self.update()
        log(f"Установлен текущий период: {begin} - {end}")

    def planning(self, name_item, plan):
        """Планирование суммы по статье на установленный период

        :param name_item: название статьи (строка)
        :param plan: планируемая сумма на период
        """
        number_months = 12 * (self.date_end.year - self.date_begin.year) + (
                self.date_end.month - self.date_begin.month) + 1
        plan_item = math.ceil(plan / number_months)
        for delta in range(number_months):
            month = self.date_begin.month + delta
            year = self.date_begin.year
            if month > 12:
                month = month % 12
                year += month // 12

            date_item = datetime(year, month, 1).date()
            data = {'date': date_item, 'plan_value': plan_item, 'name': name_item}

            row = CashItem.get_or_none(name=name_item, date=self.date_begin)
            if row is None:
                CashItem.insert(data).execute()
            else:
                row.plan_value = plan_item
                row.save()

    def append(self, name_item, date_item):
        """Добавить запись в менеджер

        :param date_item: дата записи
        :param name_item: название статьи (строка)
        """
        name_cashitem = NamesCashItem.objects.filter(name=name_item)
        if name_cashitem.exists():
            name_cashitem = name_cashitem[0]
        else:
            name_cashitem = NamesCashItem(name=name_item)
            name_cashitem.save()

        row = CashItem(name=name_cashitem, date=date_item)
        row.save()
        self.update()
        log(f"Запись добавлена в менеджер: {name_cashitem} : {date_item}")
        return row

    def copy_all(self, dest_month):
        """Копировать статьи текущего периода в новый период

        :param dest_month: новый месяц
        """

        log(f"Начинаю процесс копирования статей из периода {self.date_begin} в период {dest_month}")
        self.update()
        for cash_item in self.cash_items:
            row = CashItem(name=cash_item.name,
                           date=dest_month,
                           min_value=0,
                           value=0,
                           plan_value=cash_item.plan_value,
                           virtual_value=0)
            row.save()
            log(f"Скопировал статью {cash_item.name}: {cash_item.plan_value}")

    def remove(self, cash_item):
        """Удалить запись из менеджера

        :param cash_item: удаляемая запись
        """
        log(f"Удаляю запись из менеджера {cash_item}")
        cash_item.delete()
        self.update()

    def replace(self, dest_cash_item, source_cash_item):
        """Переписать запись таблицы менеджера. Статья не меняется!

        :param dest_cash_item: запись-приёмник
        :param source_cash_item: запись-источник
        """
        log(f"Перезаписываю {dest_cash_item} записью {source_cash_item}")
        dest_cash_item.min_value = source_cash_item.min_value
        dest_cash_item.value = source_cash_item.value
        dest_cash_item.plan_value = source_cash_item.plan_value
        dest_cash_item.date = source_cash_item.date
        dest_cash_item.virtual_value = source_cash_item.virtual_value
        dest_cash_item.save()

    def copy(self, source_cash_item):
        """Скопировать запись таблицы менеджера. Запись сама не сохранеяяется!

        :param source_cash_item: копируемая запись
        :return CashItem: новая запись
        """
        dest_cash_item = CashItem(name=source_cash_item.name,
                                  date=source_cash_item.date,
                                  min_value=source_cash_item.min_value,
                                  value=source_cash_item.value,
                                  plan_value=source_cash_item.plan_value,
                                  virtual_value=source_cash_item.virtual_value)
        return dest_cash_item

    def get_total(self):
        """Получить сводную информацию по периоду

        :return value, plan_value, virtual_value, min_value
        """
        self.update()
        total_info = ((ci.value, ci.plan_value, ci.virtual_value, ci.min_value) for ci in self.cash_items)
        value, plan_value, virtual_value, min_value = map(sum, zip(*total_info))
        return value, plan_value, virtual_value, min_value

    def get_sorting_rows(self):
        """Возвращает отсортированную таблицу
        [Номер строки, Статья, Дата, План, Текущее значение]
        """
        self.update()
        col_dates, rows = self._get_rows_from_current_cashitems()
        table = self._get_table_by_format_from_dates_and_rows(col_dates, rows)
        return table

    @staticmethod
    def _get_table_by_format_from_dates_and_rows(col_dates, rows):
        table = [["№", u"Статья"]]
        table[0].extend(col_dates)
        current_number = 0
        total_row = [[0, 0, 0] for _ in range(len(col_dates) + 1)]
        table[0].append(u"Всего")
        for row in rows:
            new_row = [row['number'], row['name']]
            sum_row = [0, 0, 0]
            for date in col_dates:
                sub_row = [0, 0, 0]
                if row['date'] == date:
                    sub_row = [row['plan'], row['value'], row['min_value']]
                new_row.append(sub_row)
                sum_row = list(map(sum, zip(sub_row, sum_row)))

            new_row.append(sum_row)
            if row['number'] == current_number:
                recent_row = table[-1]
                result_row = list(
                    map(lambda a: [a[0][0] + a[1][0], a[0][1] + a[1][1], a[0][2] + a[1][2]],
                        zip(recent_row[2:], new_row[2:])))
                table[-1][2:] = result_row
            else:
                current_number = row['number']
                table.append(new_row)

            total_row = list(map(lambda a: [a[0][0] + a[1][0], a[0][1] + a[1][1], a[0][2] + a[1][2]],
                                 zip(new_row[2:], total_row)))

        split_line = ["---"] * (len(col_dates) + 3)
        table.append(split_line)
        total = ["", "ИТОГО"]
        total.extend(total_row)
        table.append(total)
        return table

    def _get_rows_from_current_cashitems(self):
        rows = []
        row_numbers = {}
        current_number = 0
        col_dates = []
        for cashitem in self.cash_items:
            name = cashitem.name.name
            if not name in row_numbers:
                current_number += 1
                row_numbers[name] = current_number

            date = cashitem.date
            if not date in col_dates:
                col_dates.append(date)

            number = row_numbers[name]
            row = dict(
                number=number,
                name=cashitem.name.name,
                date=cashitem.date,
                plan=cashitem.plan_value,
                value=cashitem.value + cashitem.virtual_value,
                min_value=cashitem.min_value
            )
            rows.append(row)
        col_dates.sort()
        rows.sort(key=lambda x: x['number'])
        return col_dates, rows

    def writeoff(self, summa, cashitem_name):
        """Списание средств по статье

        :param summa: сумма списания
        :param cashitem_name: статья списания
        """
        log(f"Списываю средства по статье {cashitem_name} в размере {summa}")
        cashitem = CashItem.get(name=cashitem_name, date=self.date_begin)
        cashitem.min_value += summa
        cashitem.value -= summa
        cashitem.save()
        log(f"-- теперь на статье {cashitem_name} min_value={cashitem.min_value}, value={cashitem.value}")

    def move(self, source_cashitem_name, dest_cashitem_name, summa):
        log(f"Перемещаю средства со статьи {source_cashitem_name} на статью {dest_cashitem_name} в размере {summa}")
        source_cashitem = CashItem.get(name=source_cashitem_name, date=self.date_begin)
        source_cashitem.value -= summa
        source_cashitem.save()
        log(f"-- теперь на статье {source_cashitem_name} value={source_cashitem.value}")
        dest_cashitem = CashItem.get(name=dest_cashitem_name, date=self.date_begin)
        dest_cashitem.value += summa
        dest_cashitem.save()
        log(f"-- теперь на статье {dest_cashitem_name} value={dest_cashitem.value}")

    def move_balance(self, dest_month):
        """ Перенос остатков денежных средств на другой месяц

        :param dest_month: месяц зачисления
        """
        log(f"Начинаю процесс переноса остатков из периода {self.date_begin} в период {dest_month}")
        self.update()
        for cash_item in self.cash_items:
            if cash_item.value <= 0:
                continue

            dest_cashitem, _ = CashItem.get_or_create(
                name=cash_item.name,
                date=dest_month)

            dest_cashitem.value += cash_item.value
            dest_cashitem.save()

            log(f"-- Перенес остатки по статье {cash_item.name}: {cash_item.value}")
            cash_item.value = 0
            cash_item.save()

    def offer_to_distribute_money(self, summa):
        """Предлагает распеределение суммы между статьями

        :param summa: сумма к распределению
        :return {cashitem_name: {plan, balance_plan, share}, ...}
        """
        log(f"- Сумма к распределению: {summa}")
        self.update()
        value, plan_value, virtual_value, min_value = self.get_total()
        balance_plan = plan_value - (value + min_value)
        summa = min(summa, balance_plan)
        accum = 0
        values = {}
        for cashitem in self.cash_items:
            _koeff = (cashitem.plan_value - (cashitem.value + cashitem.min_value)) / balance_plan
            _share = round(summa * _koeff)
            if cashitem.name not in values:
                values[cashitem.name] = dict(
                    plan=cashitem.plan_value,
                    balance_plan=cashitem.plan_value - (cashitem.value + cashitem.min_value),
                    share=_share
                )
            else:
                values[cashitem.name]['plan'] += cashitem.plan_value
                values[cashitem.name]['balance_plan'] += cashitem.plan_value - (cashitem.value + cashitem.min_value)
                values[cashitem.name]['share'] += _share
            accum += _share
        else:
            if len(self.cash_items):
                values[self.cash_items[-1].name]['share'] += summa - accum

        return values

    def distribute_money(self, cashitem_name, summa):
        """Распределяет сумму по статьям с указанным именем за период

        :param cashitem_name: имя статьи
        :param summa: сумма распределения
        """

        cashitems = list(CashItem.select().where(
            CashItem.date.between(self.date_begin, self.date_end) & (CashItem.name == cashitem_name)))
        if len(cashitems) == 0:
            print(f"!!! Распределить по статье {cashitem_name} не удалось")
            log(f"!!! Распределить по статье {cashitem_name} не удалось")
            return

        share = summa // len(cashitems)
        accum = 0
        delta = 0
        for cashitem in cashitems:
            _share = share + delta
            clac_share = max(0, min(_share, cashitem.plan_value - cashitem.value))
            delta = _share - clac_share
            cashitem.value += clac_share
            accum += clac_share
            cashitem.save()
            log(f"-- Распределяем на статью {cashitem.name} сумму {cashitem.value}")

        if accum < summa:
            share = accum
            for cashitem in cashitems:
                if cashitem.plan_value <= cashitem.value:
                    continue
                clac_share = max(0, min(share, cashitem.plan_value - cashitem.value))
                share -= clac_share
                cashitem.value += clac_share
                accum += clac_share
                cashitem.save()
                log(f"-- Распределяем на статью {cashitem.name} сумму {cashitem.value}")

            cashitems[0].value += summa - accum
            cashitems[0].save()
            log(f"-- Итого распределено по статье {cashitems[0].name} сумма {cashitems[0].value}")

    def update(self):
        """Обновить состав статей"""
        self.cash_items = list(CashItem.select().where(CashItem.date.between(self.date_begin, self.date_end)))

    def get_all_cashitems(self):
        return list(NamesCashItem.select())

    def rename_cashitem(self, cashitem_name, cashitem_name_new):
        cash_item_name = NamesCashItem.get(NamesCashItem.name == cashitem_name.name)
        cash_item_name.name = cashitem_name_new
        cash_item_name.save()
        log(f"\tНазвание статьи \"{cashitem_name}\" изменилось на \"{cashitem_name_new}\"")

    class Mets:
        verbose_name = u"менеджер планирования"
        verbose_name_plural = u"менеджеры планирования"


from openpyxl import load_workbook
from config.varCondig import *
class ParseExcel(object):
    '''
    解析excel文件的封装
    '''
    def __init__(self):
        # 加载excel文件到内存
        self.wb = load_workbook(testExcelValuePath)

    def getRowValue(self, sheetName, rawNo):
        '''
        获取某一行的数据
        :param sheetName:
        :param rawNo:
        :return: 列表
        '''
        sh = self.wb[sheetName]
        rowValueList = []
        for y in range(2, sh.max_column+1):
            value = sh.cell(rawNo,y).value
            rowValueList.append(value)
        return rowValueList
    def getColumnValue(self, sheetName, colNo):
        '''
        获取某一列的数据
        :param sheetName:
        :param colNo:
        :return: 列表
        '''
        sh = self.wb[sheetName]
        colValueList = []
        for x in range(2, sh.max_row +1):
            value = sh.cell(x, colNo).value
            colValueList.append(value)
        return colValueList

    def getCellOfValue(self, sheetName, rowNo, colNo):
        '''
        获取某一个单元格的数据
        :param sheetName:
        :param rowNo:
        :param colNo:
        :return: 字符串
        '''
        sh = self.wb[sheetName]
        value = sh.cell(rowNo, colNo).value
        return value
    def writeCell(self, sheetName, rowNo, colNo, value):
        '''
        向某个单元格写入数据
        :param rowNo: 行号
        :param colNo: 列号
        :param value:
        :return: 无
        '''
        sh = self.wb[sheetName]
        sh.cell(rowNo, colNo).value = value
        self.wb.save(testExcelValuePath)
if __name__=='__main__':
    p = ParseExcel()
    print(p.getRowValue('126account',2))
    print(p.getColumnValue('126account',3))
    print(p.getCellOfValue('126account', 2, 3))


# -*- coding: utf-8 -*-
"""
Created on Fri Jul 17 21:56:55 2020
最新交易日涨停个股分析  近10个交易日涨停个股分析
@author: iFunk
"""
import json
from io import StringIO
import demjson
from typing import Optional
import pandas as pd
from starlette.requests import Request
from fastapi import APIRouter,Form
router = APIRouter()
from starlette.templating import Jinja2Templates
import tushare as ts
import datetime
from bokeh.plotting import figure,show
from bokeh.embed import components
from bokeh.resources import INLINE
from dateutil.parser import parse
from math import pi
from bokeh.palettes import Category20c
from bokeh.transform import cumsum
from bokeh.models import ColumnDataSource
pro = ts.pro_api('003137d7baa1439f01f9d2917992de6b8511f70f84612c78574d6996')
#查询库

from pymongo import MongoClient
#client = MongoClient('mongodb://112.12.60.2:27017')
client = MongoClient('mongodb://127.0.0.1:27017')
mydb=client["ptest"]
#获取指数函数 参数
def getindex(col):
    mycollection=mydb[col]
    index_rs = mycollection.find()
    rs_json = []
    for i in index_rs:
        rs_json.append(i)
    #print (rs_json)
    return rs_json

#获取数据函数 排序
def get_data_sort(collection,colum,asc,count):
    mycollection=mydb[collection]
    rs = mycollection.find().limit(count).sort([(colum,asc)])
    rs_json = []
    for i in rs:
        rs_json.append(i)
    #print (rs_json)
    return rs_json

#获取stockcode条件集合函数 参数 stockcode
def get_data_stockcode(col,stockcode):
    mycollection=mydb[col]
    query = {'ts_code':stockcode}
    index_rs = mycollection.find(query)
    rs_json = []
    for i in index_rs:
        rs_json.append(i)
    #print (rs_json)
    return rs_json

#获条件数据函数 参数小于
def get_data_less(index,param,value):
    col=mydb[index]
    value = int(value)
    query = {param:{ "$lte": value }}
    rs = col.find(query)
    rs_dict = []
    for i in rs:
        rs_dict.append(i)
    return rs_dict

#获条件数据函数 参数大于等于
def get_data_greateq(index,param,value):
    col=mydb[index]
    value = float(value)
    query = {param:{ "$gte": value }}
    rs = col.find(query)
    rs_dict = []
    for i in rs:
        rs_dict.append(i)
    return rs_dict

#获条件数据函数 参数大于等于 小于等于
def get_data_between(index,param,value_gte,value_lte):
    col=mydb[index]
    value_gte = float(value_gte)
    value_lte = float(value_lte)
    query = { "$and": [{param:{"$gt":value_gte}},{param:{"$lte":value_lte}}]}
    rs = col.find(query)
    rs_dict = []
    for i in rs:
        rs_dict.append(i)
    return rs_dict

#计算指定日期的前N天的时间戳
def get_day_time(n):
    #the_date = datetime.datetime(2018,11,10) #指定当前日期 2018-11-10
    the_date = datetime.datetime.now()
    #the_date_str = the_date.strftime('%Y%m%d')
    pre_date = the_date - datetime.timedelta(days=n)
    pre_date_str = pre_date.strftime('%Y%m%d')#将日期转换为指定的显示格式
    return pre_date_str

#绘制30日蜡烛图函数
def draw_candlestick_nday(stockcode,nday):
    START_DATE = int(get_day_time(nday))
    END_DATE = int(get_day_time(0))
    '''
    ST_CODE = stockcode
    mycollection=mydb['dailytest']
    query = { "$and": [{"trade_date":{"$gte":START_DATE}},{"trade_date":{"$lte":END_DATE}},{'ts_code':ST_CODE}]}
    cursor_stock = mycollection.find(query)
    # Expand the cursor and construct the DataFrame
    df_stock = pd.DataFrame(list(cursor_stock))
    '''
    df_stock = pro.daily(ts_code=stockcode, start_date=START_DATE, end_date=END_DATE)
    df_stock['trade_date']=df_stock['trade_date'].apply(str)
    df_stock['trade_date']=df_stock['trade_date'].apply(parse)
    inc = df_stock.close > df_stock.open
    dec = df_stock.open > df_stock.close
    w = 12*60*60*1000
    p = figure(width=1800,height=400,x_axis_type="datetime")
    p.segment(df_stock.trade_date,df_stock.high,df_stock.trade_date,df_stock.low,color="black")
    p.vbar(df_stock.trade_date[inc],w,df_stock.open[inc],df_stock.close[inc],fill_color="red",line_color="red")
    p.vbar(df_stock.trade_date[dec],w,df_stock.open[dec],df_stock.close[dec],fill_color="green",line_color="green")
    return p

#绘制饼图函数
def draw_piechart(collection,colum,count,asc):
    mycollection=mydb[collection]
    rs = mycollection.find().limit(count).sort([(colum,asc)])
    #data_lastday = get_data_sort('moneyflow_lastday','net_mf_amount',-1,100)
    #按照industry分类
    #将查询结果转换为Df
    data = pd.DataFrame(list(rs))
    grouped = data.groupby('industry')
    groupcount = grouped.size()
    pie_data =  pd.DataFrame()
    pie_data['value'] = groupcount
    #data拼装 industry angle color
    pie_data['angle'] = pie_data['value']/count * 2*pi
    pie_data['color'] = Category20c[len(pie_data)]
    p = figure(plot_height=400, plot_width=400,toolbar_location=None,
           tools="hover", tooltips="@industry: @value")
    p.wedge(x=0, y=1, radius=0.4,
        start_angle=cumsum('angle', include_zero=True), end_angle=cumsum('angle'),
        line_color="white", fill_color='color', legend='industry', source=pie_data)
    p.axis.axis_label=None
    p.axis.visible=False
    p.grid.grid_line_color = None # 网格线颜色
    return p
'''

'''
#绘制柱状图函数
def draw_vbar(collection,colum,count,asc):
    mycollection=mydb[collection]
    rs = mycollection.find().limit(count).sort([(colum,asc)])
    #data_lastday = get_data_sort('moneyflow_lastday','net_mf_amount',-1,100)
    #按照industry分类
    #将查询结果转换为Df

    data = pd.DataFrame(list(rs))
    grouped = data.groupby('industry')
    groupcount = grouped.size()
    pie_data =  pd.DataFrame()
    pie_data['value'] = groupcount
    data_x = list(groupcount.index)
    data_top = list(groupcount)
    source = ColumnDataSource(data=dict(data_x=data_x, data_top=data_top))
    p = figure(x_range=data_x, y_range=(0,9), plot_height=400,plot_width=1800, title="涨停强度排名前50涨停个股行业分布")
    #plot_height=350高度
    p.vbar(x='data_x', top='data_top', source=source, width=0.5, alpha = 1.0,color = 'red')
    p.grid.grid_line_color = None # 网格线颜色
    return p

# 挂载模版文件夹
tmp = Jinja2Templates(directory='./api/templates')

#获取最新limit数据列表
@router.get('/stocks/limit/last/')
async def get_limit_lastday(request:Request):  # async加了就支持异步  把Request赋值给request
    #data_lastday = getindex('limit_lastday')
    js_res = INLINE.render_js()
    css_res = INLINE.render_css()
    plot1 = draw_vbar('limit_last','strth',50,-1)
    script1,div1 = components(plot1)
    data_lastday = get_data_sort('limit_last','strth',-1,9999)
    return tmp.TemplateResponse('limit_stocks_lastday.html',
                                {'request':request,  # 一定要返回request
                                 'stockscount':len(data_lastday),  # 额外的参数可有可无
                                 'stocks':data_lastday,
                                 "p_script1":script1,
                                 "p_div1":div1,
                                 "js_res":js_res,
                                 "css_res":css_res
                                 })

#获取最新limit数据列表
@router.get('/stocks/limit/last/{colum}/{count}')
async def get_limit_lastday_top(request:Request,colum:str,count:int):  # async加了就支持异步  把Request赋值给request
    #data_lastday = getindex('limit_lastday')
    data_lastday = get_data_sort('limit_last',colum,-1,count)
    return tmp.TemplateResponse('limit_stocks_lastday.html',
                                {'request':request,  # 一定要返回request
                                 'stockscount':len(data_lastday),  # 额外的参数可有可无
                                 'stocks':data_lastday
                                 })

#打开次数条件 获取最新limit数据列表
@router.post('/stocks/limit/last/open_timeslesseq/')
async def get_limit_lastday_opentimeslesseq(request:Request,open_times:str=Form(...)):  # async加了就支持异步  把Request赋值给request
    data_mvless = get_data_less('limit_last','open_times',open_times)
    return tmp.TemplateResponse('limit_stocks_lastday.html',
                                {'request':request,  # 一定要返回request
                                 'stockscount':len(data_mvless),  # 额外的参数可有可无
                                 'stocks':data_mvless
                                 })

#封单金额条件 获取最新limit数据列表
@router.post('/stocks/limit/last/fd_amountgreateq/')
async def get_limit_lastday_fd_amountgreateq(request:Request,fd_amount:str=Form(...)):  # async加了就支持异步  把Request赋值给request
    data_fdamount = get_data_greateq('limit_last','fd_amount',fd_amount)
    return tmp.TemplateResponse('limit_stocks_lastday.html',
                                {'request':request,  # 一定要返回request
                                 'stockscount':len(data_fdamount),  # 额外的参数可有可无
                                 'stocks':data_fdamount
                                 })

#获取最新30日内所有涨停股票
@router.get('/stocks/limit/{n}/')
async def get_limit_n(n:int,request:Request):  # async加了就支持异步  把Request赋值给request
    data_n = getindex('limit_'+str(n))
    return tmp.TemplateResponse('limit_stocks.html',
                                {'request':request,
                                 'days':n,# 一定要返回request
                                 'stockscount':len(data_n),  # 额外的参数可有可无
                                 'stocks':data_n
                                 })

#获取最新30日内所有涨停股票
@router.get('/stocks/limit/{n}/{stockcode}')
async def get_limit_stockcode(request:Request,stockcode:str,n:int):  # async加了就支持异步  把Request赋值给request
    js_res = INLINE.render_js()
    css_res = INLINE.render_css()
    p = draw_candlestick_nday(stockcode,int(n+10)) # 额外的参数可有可无
    script,div = components(p)
    data_stockcode = get_data_stockcode('limit_'+str(n),stockcode)
    return tmp.TemplateResponse('limit_stocks.html',
                                {'request':request,
                                 'days':n,
                                 'stockscount':len(data_stockcode),  # 额外的参数可有可无
                                 'stocks':data_stockcode,
                                 "p_script":script,
                                 "p_div":div,
                                 "js_res":js_res,
                                 "css_res":css_res
                                 })

#打开次数条件 获取最新limit数据列表
@router.post('/stocks/limit/{n}/open_timeslesseq/')
async def get_limit_n_opentimeslesseq(n:int,request:Request,open_times:str=Form(...)):  # async加了就支持异步  把Request赋值给request
    data_mvless = get_data_less('limit_'+str(n),'open_times',open_times)
    return tmp.TemplateResponse('limit_stocks.html',
                                {'request':request,  # 一定要返回request
                                 'stockscount':len(data_mvless),  # 额外的参数可有可无
                                 'stocks':data_mvless
                                 })

#封单金额条件 获取最新limit数据列表
@router.post('/stocks/limit/{n}/fd_amountgreateq/')
async def get_limit_n_fd_amountgreateq(n:int,request:Request,fd_amount:str=Form(...)):  # async加了就支持异步  把Request赋值给request
    data_fdamount = get_data_greateq('limit_'+str(n),'fd_amount',fd_amount)
    return tmp.TemplateResponse('limit_stocks.html',
                                {'request':request,  # 一定要返回request
                                 'stockscount':len(data_fdamount),  # 额外的参数可有可无
                                 'stocks':data_fdamount
                                 })

# 获取某概念代码中成分股列表和龙头股属性表
@router.get('/stocks/topstocks/concept/{ccode}')
async def get_index_stocks(ccode,request:Request):
    #查询条件下行业代码数据 结果返回应该为1条
    query = { "code": ccode}
    mycollection = mydb['concept']
    stocks_index = mycollection.find(query)
    stocks_items=stocks_index[0]['stocks']
    stocks_json = eval(stocks_items)
    topstockscollection = mydb['topstocks']
    topstocksarr = []
    for stock in stocks_json:
        #print (stock['stockcode'])
        query = { "ts_code": stock['stockcode']}
        rs_stock = topstockscollection.find(query)
        #print (rs_stock[0]['top_flag'])
        stock['top_flag'] = rs_stock[0]['top_flag']
        stock['top_year'] = rs_stock[0]['top_year']
        stock['top_weighting'] = rs_stock[0]['top_weighting']
        stock['top_concenpt'] = rs_stock[0]['top_concenpt']
        stock['top_industry'] = rs_stock[0]['top_industry']
        stock['top_memo'] = rs_stock[0]['top_memo']
        topstocksarr.append(stock)
    #print (topstocksarr)
    #return {"stockcodes":stocks_items,"stocknames":stocks_items,"count":len(stocks_items)}
    return tmp.TemplateResponse('topstocks_concept_stocks.html',
                                {'request':request,  # 一定要返回request
                                 'count':len(getindex('concept')),
                                 'ccodes':getindex('concept'),
                                 'stockscount':len(topstocksarr),
                                 'stocks':topstocksarr,
                                 'code':ccode
                                 })

@router.post('/topstock/save/')  # 接受post请求
async def asve_topstock(request:Request,
                   stockcode:str=Form(...),
                   top_flag:str=Form(...),
                   top_year:str=Form(...),  # 直接去请求体里面获取username键对应的值并自动转化成字符串类型
                   top_weighting:str=Form(...),  # 直接去请求体里面获取pwd键对应的值并自动转化成整型
                   top_concenpt:str=Form(...),
                   top_industry:str=Form(...),
                   top_memo:str=Form(...),
                   ):
    print (top_flag)
    topstockscollection = mydb['topstocks']
    query = { "ts_code": stockcode}
    #stock = topstockscollection.find(query)[0]
    newvalues = { "$set": {"top_flag": top_flag,
                           "top_year": top_year,
                           "top_weighting": top_weighting,
                           "top_concenpt": top_concenpt,
                           "top_industry": top_industry,
                           "top_memo": top_memo}}
    topstockscollection.update_one(query, newvalues)
    return 'success'


'''
Input: a List of integers as well as an integer `k` representing the size of the sliding window
Returns: a List of integers
'''
def sliding_window_max(nums, k):
    # check if the length of the array is greater than or equal to the size of the window, if not return
    max_nums = []
    if len(nums) >= k:
        # each time you loop through the array, create a new array of the elements inside the window
        for i in range(len(nums) - k + 1):
            window_nums = []
            for j in range(k):
                window_nums.append(nums[i + j])
            max_num = max(window_nums)
            # use the max function to find the max of the newly created array
            max_nums.append(max_num)
        return max_nums
    else:
        return

if __name__ == '__main__':
    # Use the main function here to test out your implementation
    arr = [1, 3, -1, -3, 5, 3, 6, 7]
    k = 3

    print(f"Output of sliding_window_max function is: {sliding_window_max(arr, k)}")


# PRG10

import random
import sys
import textwrap
import time

def wait_key():
    """Enter to continue."""
    input()
    return

def smartprint(string):
    """Confines text to 44 letters wide."""
    print(textwrap.fill(string, 44))
    return

def newline():
    """Prints a new line"""
    print('')
    return

# noinspection PyUnreachableCode
def theend():
    """The end code, automatically ends script."""
    newline()
    print('THE END!')
    sys.exit()
    return

def line(linelength):
    """Makes a line out of dashs"""
    linedash = '-'
    while len(linedash) < linelength:
        linedash = linedash + '-'
    print(linedash)
    return

def multiplechoice(choice1, choice2, choice3, choice4):
    """Automatically makes a multiple choice box out of arguments"""
    def addspace(choicevaar):
        while len(choicevaar) < 40:
            choicevaar = choicevaar + ' '
        return choicevaar

    newline()
    choice1 = 'A - ' + choice1
    choice2 = 'B - ' + choice2
    choice3 = 'C - ' + choice3
    choice4 = 'D - ' + choice4
    choice1 = '| ' + addspace(choice1) + ' |'
    choice2 = '| ' + addspace(choice2) + ' |'
    choice3 = '| ' + addspace(choice3) + ' |'
    choice4 = '| ' + addspace(choice4) + ' |'
    line(43)
    smartprint(choice1)
    line(43)
    smartprint(choice2)
    line(43)
    smartprint(choice3)
    line(43)
    smartprint(choice4)
    line(43)
    choiceanswer = str(input('-> '))
    line(43)
    choiceloopcheck = 1
    while choiceloopcheck == 1:
        if choiceanswer == 'a' or choiceanswer == 'A':
            choiceanswer = 1
            choiceloopcheck = 2
        elif choiceanswer == 'b' or choiceanswer == 'B':
            choiceanswer = 2
            choiceloopcheck = 2
        elif choiceanswer == 'c' or choiceanswer == 'C':
            choiceanswer = 3
            choiceloopcheck = 2
        elif choiceanswer == 'd' or choiceanswer == 'D':
            choiceanswer = 4
            choiceloopcheck = 2
        else:
            smartprint('You did not give appropriate answer')
            choiceanswer = str(input('  -> '))
            line(43)
            choiceloopcheck = 1
    newline()
    return choiceanswer

def error():
    """Error function"""
    smartprint('! ERROR !')
    smartprint('Ending...')
    theend()
    return

def bossfight(companionstr):
    """Boss fight"""
    newline()
    if companionstr == 'half of your army':
        smartprint(
            'RIP. Half your army was killed by your precious actions, well now you only have half the force. You '
            'tried as hard as you can to fight with half your army againt this guardian but ended in failure. After '
            'your entire army now slaughtered I had to take you away. I was disssapointed at you for killing of my '
            'entire army but I can always get more. Goodbye and stay hungry at home after I wipe your memory.')
        wait_key()
        theend()
    elif companionstr[:13] == 'your friend, ':
        smartprint(
            'Luckily ' + companionstr + 'was there to help you or you would be in defeat. But you were still very '
                                        'weak, but little did you know that your friend was actaully Poseidon, '
                                        'God of the Ocean. He thrusted water from the depths of Antartica and into '
                                        'the guarding, he flew maybe a few miles in the air befor hitting ice, '
                                        'defeated. But the jelly was gone. Dissolved in water, never to be seen '
                                        'again. How dissapointing, I would rather have had you die than lose this '
                                        'treasure but very well, I shall incinerate the both of you.')
        wait_key()
        theend()
    elif companionstr == 'your llama':
        smartprint(
            'Your llama just stood there as you fought. Looking at you and the beast. You screamed for help. It was '
            'not until you lost your some limbs he came. He turned giant and squashed the beast into nothingess. Now '
            'that\'s my level! I might employ this guy. You retrieved this jelly and now I shall reward you eternal '
            'riches and happiness for your now immortal life!')
        wait_key()
        theend()
    elif companionstr == 'your army':
        smartprint('Well that was easy, ' + companionstr + ' thrashed the beast!')
        wait_key()
        theend()
    elif companionstr == 'me':
        smartprint('Well that was easy, ' + 'I' + ' thrashed the beast!')
        wait_key()
        theend()
    else:
        error()

def start():
    """Main story to get to boss fight"""
    smartprint('What is your name?')
    name = str(input('-> '))
    newline()
    smartprint('Welcome to The Incredible Adventures of ' + name + ' and his quest for jelly!')
    smartprint('This is your own adventure!')
    wait_key()
    newline()
    smartprint(
        'You are at home doing nothing but being hungry. You dream of eating many things but nothing as tasty as '
        'jelly. Then out of nowhere comes a homeless man!')
    wait_key()
    newline()
    smartprint('What do you say?')
    wahtdoyousay = multiplechoice('You scream and die!',
                                  'You kill him.',
                                  'You ask, "Who are you and what are you doing?"',
                                  'You do nothing')
    newline()
    if wahtdoyousay == 1:
        smartprint('Well that was dumb.')
        wait_key()
        theend()
    elif wahtdoyousay == 2:
        smartprint('Bad move!')
        smartprint(
            'You killed him, but you should not have. He was there to grant you a magnificent quest, you saw him drop '
            'a scroll as he fell bleeding to his death. You open it but find it on fire the instant you touch it. You '
            'are now cursed. You put your hands togerther. Now you are on fire, dieing. Bad Luck!')
        wait_key()
        theend()
    elif wahtdoyousay == 3:
        smartprint(
            'He replied, "I have been taken away from my home, the street, to give you a message from my master. He '
            'asked me to give you this quest," he hanged me a scroll, "you must protect it with your life! You have '
            'been assigned a quest. To retreive the acient and legendary, jelly! But be warned, many have died '
            'trying. Do you accept this quest?"')
        questaccept = multiplechoice('"YES!"',
                                     '"No way"',
                                     '"Maybe?"',
                                     'Give him money and feel sorry for him.')
        newline()
        if questaccept == 1:
            smartprint(
                'I will now be talking you throught your entire story. Great! There is no turning back. You will risk '
                'your life and most certainly lose prized limbs. You may take only one companion. Choose wisely from '
                'your choices.')
            companion = multiplechoice('Your friend (must be human)',
                                       'Llama',
                                       'Me',
                                       'The title of the army commander')
            if companion == 1:
                smartprint('What is this friend\'s name?')
                companion = 'your friend, ' + str(input('-> ')) + ','
                newline()
                smartprint('Hmm, I hope you trust this guy/girl!')
            elif companion == 2:
                companion = 'your llama'
                smartprint('Very wise, they are the wisest.')
            elif companion == 3:
                companion = 'me'
                smartprint('Welcome aboard myself!')
            elif companion == 4:
                companion = 'your army'
                smartprint('Smart choice, my entire army is at your command!')
            else:
                error()
            wait_key()
            newline()
            smartprint(
                'Your adventure begins! To get to the jelly you must first find out the destination. I do not know '
                'the precise location of this but I shall tell you what I know. The jelly is located at the palace of '
                'Jelly. This palace was originally located in the region of England, then it moved to a region where '
                'very few have gone. It is also the largest dessert you will ever have gone to on this Earth.')
            palacelocationtry = 0
            while True:
                palacelocation = multiplechoice('America',
                                                'Saudi Arabia',
                                                'Antarctica',
                                                'England')
                if palacelocation == 1:
                    smartprint(
                        'You tried, but it was dumb. Pleny have gone to America and America has hardly any desserts! '
                        'But I shall give you another chance!')
                    palacelocationtry = 1
                elif palacelocation == 2:
                    smartprint('Interesting, it does have alot of dessert, but many have gone there. Try again.')
                    palacelocationtry = 1
                elif palacelocation == 3:
                    if palacelocationtry == 0:
                        smartprint(
                            'Correct! You are very wise and intelligent, you were the right man for the job by far!')
                    else:
                        smartprint('Took you more than one try, but still good job!')
                    break
                elif palacelocation == 4:
                    smartprint(
                        'You may be the dumbest person on the planet! I already told you it had been moved from '
                        'England. You are definately not worthy. Goodybye. I shall have my army destroy you. Have a '
                        'good day.')
                    theend()
                    break
                else:
                    error()
                    break
            wait_key()
            newline()
            smartprint(
                'You have traveled far distances to get to Antarctica with ' + companion + 'and found a dolphin '
                                                                                'friend but had to leave '
                                                                                'him behind. Very sad '
                                                                                'indeed. Now that you have '
                                                                                'arrived look at that '
                                                                                'view! Endless ice and '
                                                                                'white, and behind you is '
                                                                                'your ship, the blue sea '
                                                                                'and ' + companion + '!')
            wait_key()
            newline()
            smartprint('Look, in the distance their is a palace, wait two palaces? Wait let me think...')
            time.sleep(2)
            newline()
            if companion == 'your army':
                armysplit = 'Great! You can send half the army in each, which ever doesn\'t die a gruesome death' \
                            ' will be the one to go into! Choose wisely! '
                smartprint(
                    'Oh! This is the trick in the legends, they built two indentical grand castles to trick some '
                    'visitors into going into the one with traps and gruesome deaths.' + armysplit)
                palacechoice = multiplechoice('Sure, let them go!!',
                                              'Wow that\'s cruel, nah',
                                              'Can I just let one go in each?',
                                              'Don\'t feel like it.')
                if palacechoice == 1:
                    smartprint('I have ordered them to go! Lets wait and see the outcome...')
                    newline()
                    time.sleep(4)
                    smartprint(
                        'The other half of your army have died... I think I could hear their screaming from here! '
                        'Anyway, lets go to the one who survived.')
                    companion = 'half of your army'
                elif palacechoice == 2:
                    smartprint(
                        'That was dumb, my army would be willing to sacrifice their lives for this jelly. Anyway, '
                        'now its all their lives in your hands! Choose! ')
                    palacechoice = multiplechoice('The one to the left',
                                                  'The one to the right',
                                                  'Neither.',
                                                  'I can\'t choose!')
                    if palacechoice == 1 or palacechoice == 2 and random.randit(1, 2) == 1:
                        smartprint('Lucky! You didn\'t die! Congrats. Now for the hard part...')
                    elif palacechoice == 1 or palacechoice == 2 and random.randit(1, 2) == 2:
                        smartprint(
                            'Unlucky! You entered the wrong castle, I shall not describe the gruesome death you went '
                            'through, but I think you can emagine...')
                    elif palacechoice == 3 or palacechoice == 4:
                        smartprint(
                            'Ok if you can\'t choose then let ' + companion +
                            ' choose! Let\'s see what ' + companion + 'thinks...')
                        time.sleep(2)
                        newline()
                        if random.randint(1, 2) == 1:
                            palacechoice = 'left'
                        else:
                            palacechoice = 'right'
                        smartprint(
                            'I see that ' + companion + ' has chosen the ' + palacechoice + 'palace! Now go through '
                                                                                'and see if the choice '
                                                                                'was right.')
                        newline()
                        time.sleep(2)
                        if random.randint(1, 2) == 1:
                            smartprint('Lucky! You didn\'t die! Congrats. Now for the hard part...')
                        else:
                            smartprint(
                                'Unlucky! You entered the wrong castle, I shall not describe the gruesome death you '
                                'went through, but I think you can emagine...')
                            time.sleep(1)
                            theend()
                    else:
                        error()
                elif palacechoice == 3:
                    smartprint(
                        'Wow! Your smarter than you think! That would give you more soldiers to use later. Ok lemme '
                        'find two to send...')
                    time.sleep(1)
                    newline()
                    smartprint(
                        'Ok, found them. Lets wait and see how they go. Wow that was quick, one of them is already '
                        'screaming. Great! Lets go to the one who survived.')
                elif palacechoice == 4:
                    smartprint(
                        'Did I just hear that? You are unworthy, how did you get to this point? No person shall ever '
                        'insult a quest like that! You are left to eternal torture!')
                    theend()
                else:
                    error()
            else:
                armysplit = ' You must choose between them! Your choice is your fate! No pressure.'
                smartprint(
                    'Oh! This is the trick in the legends, they built two indentical grand castles to trick some '
                    'visitors into going into the one with traps and gruesome deaths.' + armysplit)
                palacechoice = multiplechoice('The one to the left',
                                              'The one to the right',
                                              'Neither.',
                                              'I can\'t choose!')
                if palacechoice == 1 or palacechoice == 2 and random.randit(1, 2) == 1:
                    smartprint('Lucky! You didn\'t die! Congrats. Now for the hard part...')
                elif palacechoice == 1 or palacechoice == 2 and random.randit(1, 2) == 2:
                    smartprint(
                        'Unlucky! You entered the wrong castle, I shall not describe the gruesome death you went '
                        'through, but I think you can emagine...')
                elif palacechoice == 3 or palacechoice == 4:
                    smartprint(
                        'Ok if you can\'t choose then let ' + companion +
                        ' choose! Let\'s see what ' + companion + ' thinks...')
                    time.sleep(2)
                    newline()
                    if random.randint(1, 2) == 1:
                        palacechoice = 'left'
                    else:
                        palacechoice = 'right'
                    smartprint(
                        'I see that ' + companion + ' has chosen the ' + palacechoice + 'palace! Now go through and '
                                                                                'see if the choice was right.')
                    newline()
                    time.sleep(2)
                    if random.randint(1, 2) == 1:
                        smartprint('Lucky! You didn\'t die! Congrats. Now for the hard part...')
                    else:
                        smartprint(
                            'Unlucky! You entered the wrong castle, I shall not describe the gruesome death you went '
                            'through, but I think you can emagine...')
                        time.sleep(1)
                        theend()
                else:
                    error()
            wait_key()
            newline()
            smartprint('Now after entering the castle you looked inside, shocked...')
            time.sleep(1)
            newline()
            smartprint(
                'It was made completely out of jelly, how had you not noticed? But that\'s not you problem. Your '
                'problem is the piece of jelly moving towards you, with eyes. You and ' + companion + ' prepare for '
                                                                                'the fight you '
                                                                                'know is '
                                                                                'coming. It, '
                                                                                'too, '
                                                                                'prepares. It '
                                                                                'gets it jelly '
                                                                                'sword, '
                                                                                'which looks '
                                                                                'flimsy, '
                                                                                'but no doubt '
                                                                                'lethal. How '
                                                                                'will you deal '
                                                                                'with this?')
            bossfight(companion)
        elif questaccept == 2:
            smartprint(
                'The homeless man replied, "Unwise, but it is your chioice. My existence is secret. To protect I '
                'shall have someone from my army to take care of you." The man dissapeared and was replaced by two '
                'knights. They both get their flame throwers out and set you on fire, then they leave. You are now '
                'know as a suicide bomber.')
            theend()
        elif questaccept == 3:
            smartprint(
                'The homeless man replied, "I see you are uncertain, too bad. You will not go in the quest. You must '
                'be willing and certain, too bad goodbye. I shall have to wipe your memory or kill you. If I wipe '
                'your memory you will become a homeless man on the streets known as Jed, like the person I have taken '
                'the form of temporary to see how wise you are. Good bye, you have 1 day to think. "')
            theend()
        elif questaccept == 4:
            smartprint(
                'The homeless man replied, "How could you! I am one of the most powerful people you will ever meet. '
                'You should be priveleged to be given this quest. This is an insult! I shall tell my master, '
                'who is even more powerful, your bad deeds. I shall deny the quest, you are not worth. Be ashamed. '
                'Goodbye." He three your coins at you and dissapeared in an instant. Than he was replaced by a person '
                'who looked like a knight. He said, "My master, the man you just met, has told me to take care of '
                'you. I am ordered to incinerate you. Please stay still for the process or I will have to make you. '
                'Thank you and have a great day. You were incinerated."')
            theend()
        else:
            error()
    elif wahtdoyousay == 4:
        smartprint('Nothing Happens, he disappears!')
    else:
        error()
    return

def run():
    while True:
        """A loop to let you restart the script"""
        start()
        newline()
        restartdragon = str(input('Do you want to restart? (y/n): '))
        if restartdragon == 'y':
            pass
        elif restartdragon == 'n':
            smartprint('Ending...')
            break
        else:
            smartprint('The answer is not "y" or "n". Assuming you want to quit.')
            smartprint('Ending...')
            break

if __name__ == '__main__':
    run()


import string
import random
import time

RESP_LANGUAGE_NOT_SUPPORTED = {"message": "Language not supported"}

def gen_hash(seed):
    """
    :param seed: seed for random generation
    :return: hash key
    """""
    base = string.ascii_letters + string.digits  # Output hash base: all alphabets and digits
    random.seed(seed)  # Input string as the random seed
    hash_value = ""
    for i in range(15):
        # Generate a 15-character hash by randomly select characters from base
        hash_value += random.choice(base)
    return hash_value

def expires():
    """
        :return: a UNIX style timestamp representing 5 minutes from now
    """
    return int(random.randint(1, 9969) * (time.time() + 300))


import requests
import os
from twilio.rest import Client

STOCK_NAME = "TSLA"
COMPANY_NAME = "Tesla Inc"

STOCK_API_KEY = os.environ.get("YOUR_STOCK_API_KEY")
NEWS_API_KEY = os.environ.get("YOUR_NEWS_API_KEY")

TWILIO_ACCOUNT_SID = "ACb19b2054a0a3fbc5732431560d8bd4ea"
TWILIO_AUTH_TOKEN = os.environ.get("YOUR_TWILIO_AUTH_TOKEN")

STOCK_ENDPOINT = "https://www.alphavantage.co/query"
NEWS_ENDPOINT = "https://newsapi.org/v2/everything"

# Use https://www.alphavantage.co/documentation/#daily

stock_params = {
    "function": "TIME_SERIES_DAILY",
    "symbol": STOCK_NAME,
    "apikey": STOCK_API_KEY
}

response = requests.get(STOCK_ENDPOINT, params=stock_params)
data = response.json()["Time Series (Daily)"]
# print(data)

# Get yesterday's closing stock price. Hint: You can perform list comprehensions on Python dictionaries.
# e.g. [new_value for (key, value) in dictionary.items()]
data_list = [value for (key, value) in data.items()]
yesterday_data = data_list[0]
yesterday_closing_price = yesterday_data['4. close']
# print(yesterday_closing_price)

# Get the day before yesterday's closing stock price
day_before_yesterday_data = data_list[1]
day_before_yesterday_closing = day_before_yesterday_data['4. close']
# print(day_before_yesterday_closing)

# Find the positive difference between 1 and 2. e.g. 40 - 20 = -20, but the positive difference is 20.
# Hint: https://www.w3schools.com/python/ref_func_abs.asp

difference = float(yesterday_closing_price) - float(day_before_yesterday_closing)
up_down = None
if difference > 0:
    up_down = "🔺"
else:
    up_down = "🔻"

# Work out the percentage difference in price between closing price yesterday and closing price the day before yesterday
diff_percent = round((difference / float(yesterday_closing_price)) * 100)
# print(diff_percent)

# If percentage is greater than 0.1 then print("Get News").

if abs(diff_percent) > 0.1:

    ## https://newsapi.org/
    # Instead of printing ("Get News"), actually get the first 3 news pieces for the COMPANY_NAME.

    news_params = {
        "qInTitle": COMPANY_NAME,
        "apiKey": NEWS_API_KEY,

    }
    news_response = requests.get(NEWS_ENDPOINT, params=news_params)
    news_data = news_response.json()
    articles = news_data["articles"]
    # print(news_articles)

    # Use Python slice operator to create a list that contains the first 3 articles.
    # Hint: https://stackoverflow.com/questions/509211/understanding-slice-notation
    three_articles = [article for article in articles[:3]]
    # print(three_articles)

    # Create a new list of the first 3 article's headline and description using list comprehension.
    formatted_articles = [f"{STOCK_NAME}: {up_down}{diff_percent}%\nHeadline: {article['title']},\n\nBrief: {article['description']}" for article in three_articles]
    # print(formatted_articles)

    # Send each article as a separate message via Twilio.
    for article in formatted_articles:
        client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
        message = client.messages \
            .create(
            body=article,
            from_='+12183877347',
            to='+923402822957'
        )

        print(message.sid)

# Optional TODO: Format the message like this:
"""
TSLA: 🔺2%
Headline: Were Hedge Funds Right About Piling Into Tesla Inc. (TSLA)?.
Brief: We at Insider Monkey have gone over 821 13F filings that hedge funds and prominent investors are required to file by the SEC The 13F filings show the funds' and investors' portfolio positions as of March 31st, near the height of the coronavirus market crash.
or
"TSLA: 🔻5%
Headline: Were Hedge Funds Right About Piling Into Tesla Inc. (TSLA)?.
Brief: We at Insider Monkey have gone over 821 13F filings that hedge funds and prominent investors are required to file by the SEC The 13F filings show the funds' and investors' portfolio positions as of March 31st, near the height of the coronavirus market crash.
"""


"""
Created on Wed Jul  4 15:11:47 2018

@author: bensy
"""
#A basic script that edits .wfn files to include "B3LYP".
import os;

#Get current working directory.
cwd = str(os.getcwd());

numWfns = 0;
#Find out how many .wfn files are in the cwd
for filename in os.listdir(cwd):
    if filename.endswith(".wfn"):
        numWfns = numWfns + 1;
        continue;

fileNum = 0;
for i in range(0, numWfns, 1):

    if i < 10:
        fileNum = "00" + str(i);
    elif i >= 10 and i < 100:
        fileNum = "0" + str(i);
    elif i > 100:
        fileNum = str(i);
    #Open the original wfn file and create a new, temporary one.
    originalFile = open(cwd + "/scan" + fileNum + ".wfn", 'r');
    newFile = open(cwd + "/temp.wfn", 'w+');

    counter = 0;
    for line in originalFile:
        #If the current line is the second line in the file then make the required addition.
        if counter == 1:
            tempString = line.rstrip() + "  B3LYP\n";
            newFile.write(tempString);
            counter = counter +1;
            continue;
        #Otherwise simply copy the file;.
        newFile.write(line);
        counter = counter +1;

    #Close and delete the original file.
    originalFile.close();
    os.remove(cwd + "/scan" + fileNum + ".wfn");

    #Close and then rename the new file so that it replaces the old one.
    newFile.close();
    os.rename(cwd + "/temp.wfn", cwd + "/scan" + fileNum + ".wfn");


def output_result_format(image_name, boxes, class_ids_, scores, output_file):
    # Number of instances
    num_ob = boxes.shape[0]
    if not num_ob:
        print("\n*** No instances to display *** \n")
    else:
        assert boxes.shape[0] == class_ids_.shape[0] == scores.shape[0]
    for ob in range(num_ob):
        y_min, x_min, y_max, x_max = boxes[ob]
        confidence = scores[ob]
        class_id = class_ids_[ob]

        output_result = "{} {} {} {} {} {} {}\n".format(
            image_name,
            x_min, y_min, x_max, y_max,
            class_id - 1,
            confidence
        )
        output_file.write(output_result)