from __future__ import absolute_import, division, print_function
import sys
import time

from libtbx.utils import Sorry
from mmtbx.conformation_dependent_library.rdl_database import \
  get_rdl_database
from mmtbx.validation import rotalyze

substitute_residue_lookup = {
  "MSE" : "MET",
  }

rdl_database = get_rdl_database()

def get_rotamer_data(atom_group,
                     sa,
                     rotamer_evaluator,
                     rotamer_id,
                     all_dict,
                     sites_cart,
                     ):
  resname=substitute_residue_lookup.get(atom_group.resname,
                                        atom_group.resname,
                                        )
  if resname not in rdl_database.keys(): return None
  if resname in ["PRO", "GLY"]: return None
  model_rot, m_chis, value = rotalyze.evaluate_rotamer(
    atom_group=atom_group,
    sidechain_angles=sa,
    rotamer_evaluator=rotamer_evaluator,
    rotamer_id=rotamer_id,
    all_dict=all_dict,
    sites_cart=sites_cart,
    )
  return model_rot, m_chis, value

def setup_restraints():
  return None

def generate_rotamer_data(pdb_hierarchy,
                          exclude_outliers=True,
                          data_version="8000",
                          ):
  assert data_version == "8000","data_version not recognized."
  r = rotalyze.rotalyze(pdb_hierarchy=pdb_hierarchy,
                        data_version=data_version)
  for rot in r.results:
    #if rot.outlier:
    #  print (rot.resname,
    #       rot.id_str(),
    #       rot.chain_id,
    #       rot.altloc,
    #       rot.rotamer_name)
    #  assert 0
    if exclude_outliers and rot.outlier: continue
    yield (rot.resname,
           rot.id_str(),
           rot.chain_id,
           rot.altloc,
           rot.rotamer_name)

def update_restraints(hierarchy,
                      geometry, # restraints_manager,
                      current_geometry=None, # xray_structure!!
                      sites_cart=None,
                      rdl_proxies=None,
                      esd_factor=1.,
                      exclude_backbone=False,
                      assert_rotamer_found=False,
                      rdl_selection=None,
                      log=None,
                      verbose=False,
                      data_version="8000",
                      ):
  assert data_version == "8000","data_version not recognized."
  assert not exclude_backbone
  loud=True and False
  if loud:
    verbose=1
  from mmtbx.rotamer.sidechain_angles import SidechainAngles
  from mmtbx.rotamer import rotamer_eval
  from mmtbx.validation import rotalyze
  #
  def _set_or_reset_angle_restraints(geometry,
                                     lookup,
                                     use_rdl_weights=False,
                                     verbose=False,
                                     ):
    count = 0
    for angle_proxy in geometry.angle_proxies:
      if angle_proxy.i_seqs in lookup:
        if verbose: print(" i_seqs %-15s initial %12.3f %12.3f" % (
          angle_proxy.i_seqs,
          angle_proxy.angle_ideal,
          angle_proxy.weight,
          ))
        assert angle_proxy.angle_ideal<181
        angle_proxy.angle_ideal = lookup[angle_proxy.i_seqs][0]
        if use_rdl_weights: angle_proxy.weight = esd_factor/lookup[angle_proxy.i_seqs][1]**2
        if verbose: print(" i_seqs %-15s final   %12.3f %12.3f" % (
          angle_proxy.i_seqs,
          angle_proxy.angle_ideal,
          angle_proxy.weight,
          ))
        count += 1
    return count
  #
  def _set_or_reset_dihedral_restraints(geometry,
                                        lookup,
                                        use_rdl_weights=False,
                                        verbose=False,
                                        ):
    count = 0
    for angle_proxy in geometry.dihedral_proxies:
      if angle_proxy.i_seqs in lookup:
        if verbose: print(" i_seqs %-15s initial %12.3f %12.3f %s %d" % (
          angle_proxy.i_seqs,
          angle_proxy.angle_ideal,
          angle_proxy.weight,
          angle_proxy.alt_angle_ideals,
          angle_proxy.periodicity,
          ))
        angle_proxy.angle_ideal = lookup[angle_proxy.i_seqs][0]
        if use_rdl_weights: angle_proxy.weight = esd_factor/lookup[angle_proxy.i_seqs][1]**2
        angle_proxy.alt_angle_ideals=None
        angle_proxy.periodicity = lookup[angle_proxy.i_seqs][2]
        if verbose: print(" i_seqs %-15s final   %12.3f %12.3f %s %d" % (
          angle_proxy.i_seqs,
          angle_proxy.angle_ideal,
          angle_proxy.weight,
          angle_proxy.alt_angle_ideals,
          angle_proxy.periodicity,
          ))
        count += 1
    return count
  #
  t0=time.time()
  sa = SidechainAngles(False)
  rotamer_id = rotamer_eval.RotamerID()
  rotamer_evaluator = rotamer_eval.RotamerEval(data_version=data_version)
  sites_cart = None
  if current_geometry:
    sites_cart = current_geometry.sites_cart()
  #
  if rdl_proxies is None:
    rdl_proxies = []
  i_seqs_restraints = {}
  i_seqs_restraints_reverse = {}
  #
  def _alt_loc_atom_generator(residue_group, atom_group):
    atoms = []
    for ag in residue_group.atom_groups():
      if ag.altloc.strip()=="" or ag.altloc.strip()==atom_group.altloc.strip():
        for atom in ag.atoms(): yield atom
  #
  for model in hierarchy.models():
    #if verbose: print 'model: "%s"' % model.id
    for chain in model.chains():
      #if verbose: print 'chain: "%s"' % chain.id
      for residue_group in chain.residue_groups():
        all_dict = rotalyze.construct_complete_sidechain(residue_group)
        for atom_group in residue_group.atom_groups():
          if rdl_selection is None: pass
          elif 'all' in rdl_selection: pass
          elif atom_group.resname in rdl_selection: pass
          else: continue
          rc = get_rotamer_data(atom_group,
                                sa,
                                rotamer_evaluator,
                                rotamer_id,
                                all_dict=all_dict,
                                sites_cart=sites_cart,
            )
          if rc is None: continue
          rotamer_name, chis, value = rc
          if verbose:
            chis_str = "["
            if chis:
              for chi in chis:
                chis_str += " %6.1f," % chi
              chis_str = chis_str[:-1]+']'
            try:
              print("  %s %s %s %-5s %-60s %0.1f" % (
                chain.id,
                atom_group.resname,
                residue_group.resseq,
                rotamer_name,
                chis_str,
                value,
              ), file=log)
            except TypeError as e:
              print("  %s %s %s %-5s %-60s %s" % (
                chain.id,
                atom_group.resname,
                residue_group.resseq,
                rotamer_name,
                chis_str,
                value,
              ), file=log)
          if loud: print('exclude_backbone',exclude_backbone)
          if rotamer_name in ["OUTLIER"]: continue
          resname_lookup = substitute_residue_lookup.get(atom_group.resname,
                                                         atom_group.resname,
                                                         )
          if rotamer_name not in rdl_database[resname_lookup]:
            if assert_rotamer_found:
              raise Sorry("rotamer %s not found in db" % rotamer_name)
            else:
              continue
          if loud: print('not outlier')
          if rotamer_name not in rdl_database[resname_lookup]:
            if loud: print("rotamer_name %s not in RDL db" % rotamer_name)
            continue
          if loud: print('rotamer_name %s found' % rotamer_name)
          restraints = rdl_database[resname_lookup][rotamer_name]
          defaults = rdl_database[resname_lookup]["default"]
          rdl_proxies.append(atom_group.id_str())
          for names, values in restraints.items():
            i_seqs = []
            if exclude_backbone and names[1] in ["N", "CA", "C"]: continue
            for name in names:
              for atom in _alt_loc_atom_generator(residue_group, atom_group):
                if name.strip()==atom.name.strip():
                  i_seqs.append(atom.i_seq)
                  break
            if len(i_seqs)!=len(names): continue
            i_seqs_restraints[tuple(i_seqs)] = values
            i_seqs.reverse()
            i_seqs_restraints[tuple(i_seqs)] = values
            if names in defaults:
              i_seqs_restraints_reverse[tuple(i_seqs)] = defaults[names]
              i_seqs.reverse()
              i_seqs_restraints_reverse[tuple(i_seqs)] = defaults[names]
  #
  if loud:
    for i, atom in enumerate(hierarchy.atoms()):
      print(i, atom.quote())
  count = _set_or_reset_dihedral_restraints(geometry,
                                            i_seqs_restraints_reverse,
                                            #verbose=loud,
                                            )
  count_d = _set_or_reset_dihedral_restraints(geometry,
                                            i_seqs_restraints,
                                            verbose=loud,
                                            )
  count = _set_or_reset_angle_restraints(geometry,
                                         i_seqs_restraints_reverse,
                                         #verbose=loud,
                                         )
  count_a = _set_or_reset_angle_restraints(geometry,
                                         i_seqs_restraints,
                                         verbose=loud,
                                         )
  #
  print("    Number of angles, dihedrals RDL adjusted : %d, %d" % (
    count_a,
    count_d,
    ), file=log)
  print("    Time to adjust                           : %0.1fs" % (
    time.time()-t0), file=log)
  return rdl_proxies

def run(pdb_filename):
  from iotbx import pdb
  print(pdb_filename)
  pdb_inp = pdb.input(pdb_filename)
  pdb_hieratchy = pdb_inp.construct_hierarchy()
  for residue_group in pdb_hieratchy.residue_groups():
    rotamer_name, chis, value = get_rotamer_data(residue_group,
                                                 sa,
                                                 rotamer_evaluator,
                                                 rotamer_id,
      )
    print(rotamer_name)

if __name__=="__main__":
  run(sys.argv[1])


#!/usr/bin/env python3

import numpy as np
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt

def fit_line(x, y):
    reg = LinearRegression()
    X = x.reshape((-1, 1))
    reg.fit(X, y)
    return reg.coef_[0], reg.intercept_

def main():
    x = np.array([1, 2, 3])
    y = np.array([1, 2.5, 3]) + 1
    slope, intercept = fit_line(x, y)
    print("Slope:", slope)
    print("Intercept:", intercept)
    plt.scatter(x, y)
    x1 = np.linspace(min(x)-1, max(x)+1, 10)
    plt.plot(x1, x1*slope + intercept, 'red')
    plt.show()

if __name__ == "__main__":
    main()


#!/usr/bin/env python

###################
# plot_Compare2Histos.py
# description: compares two histograms from one root file
# instructions:
#  python -i plot_Compare2Histos.py
###################

from ROOT import *
import glob,sys

gROOT.Reset()
gStyle.SetOptStat(0)

histos = { 'massRecoBjetsCSVM':'step1plots1D',
		'avgMassRecoBjetsCSVM':'step1plots1D',
		'massdijetWORecoBjetsCSVM':'step2plots1D',
		'massdijetWORecoBjetsCSVM_cutDiagStop1jj50':'step2plots1D',
		'massdijetWORecoBjetsCSVM_cutDiagStop1jj100':'step2plots1D',
		'massdijetWORecoBjetsCSVM_cutDiagStop1jj150':'step2plots1D',
		'massRecoDiBjetDiJet':'step3plots1D',
		'massRecoDiBjetDiJet_cutDiagStop1jj50':'step3plots1D',
		'massRecoDiBjetDiJet_cutDiagStop1jj100':'step3plots1D',
		'massRecoDiBjetDiJet_cutDiagStop2bbjj50':'step3plots1D',
		'massRecoDiBjetDiJet_cutDiagStop2bbjj100':'step3plots1D',
		'massRecoDiBjetDiJetSmallestDeltaM':'step4plots1D'
		}

#print "Options: ", sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]
outputDir = "/uscms_data/d3/algomez/files/Stops/Results/Plots/"

input2 = "/uscms_data/d3/algomez/files/Stops/Results/data_4jet120_plots.root"
input3 = "/uscms_data/d3/algomez/files/Stops/Results/data_4jet80_plots.root"
input1 = "/uscms_data/d3/algomez/files/Stops/Results/data_4jet60_plots.root"
input4 = "/uscms_data/d3/algomez/files/Stops/Results/data_4jet80_6jet60_plots.root"

f1 = TFile(input1)
f2 = TFile(input2)
f3 = TFile(input3)
f4 = TFile(input4)

for hist1, folder in histos.iteritems():
	h1 = f1.Get(folder+'/' + hist1)
	h2 = f2.Get(folder+'/' + hist1)
	h3 = f3.Get(folder+'/' + hist1)
	h4 = f4.Get(folder+'/' + hist1)

	h1clone = h1.Clone("h1")
	h2clone = h2.Clone("h2")
	h3clone = h3.Clone("h3")
	h4clone = h4.Clone("h4")

	h1clone.SetLineColor(1)
	h2clone.SetLineColor(2)
	h3clone.SetLineColor(3)
	h4clone.SetLineColor(4)
	h1clone.SetLineWidth(2)
	h2clone.SetLineWidth(2)
	h3clone.SetLineWidth(2)
	h4clone.SetLineWidth(2)

	c = TCanvas('c_' + hist1, 'c_' + hist1,  10, 10, 750, 500 )
	#c.SetLogy()
	h1clone.SetTitle("")
	h1clone.GetXaxis().SetTitle("Invariant Mass [GeV]")
	if "avg" in hist1: h1clone.GetYaxis().SetTitle("Events / 10 GeV")
	elif "DiJet" in hist1: h1clone.GetYaxis().SetTitle("QuadJet / 10 GeV")
	else: h1clone.GetYaxis().SetTitle("Dijet / 10 GeV")
	h1clone.GetYaxis().SetTitleOffset(1.2)
	h1clone.Draw("hist")
	h2clone.Draw("histsame")
	h3clone.Draw("histsame")
	h4clone.Draw("histsame")

	textBox=TLatex()
	textBox.SetNDC()
	textBox.SetTextSize(0.05)
	textBox.SetTextColor(50)
	textBox.DrawText(0.10,0.91,"CMS Preliminary")

	legend=TLegend(0.70,0.7,0.90,0.9)
	legend.SetFillColor(0);
	legend.AddEntry(h2clone, "4jet120", "l")
	legend.AddEntry(h3clone, "4jet80", "l")
	legend.AddEntry(h1clone, "4jet60", "l")
	legend.AddEntry(h4clone, "4jet80_6jet60", "l")
	legend.Draw()

	c.SaveAs(outputDir + hist1 + "_data_DiffAllTriggers.pdf")
	del c


#Idea behind social distance detecting - detect a person
# and based on the bounding boxes of those persons, calculate the centroid of 2 people.
#if the distance between centroid person1 and person2 is less than a threshold value(required social distance), then
#mark their bounding boxes as red else mark their boxes as green

import cv2
import datetime
import imutils
import numpy as np
from centroidtracker import CentroidTracker #includes the tracker
import math
from itertools import combinations  #for creating combinations btw persons (say person 0,1,2,3, this would
#create a combination btw person 1 and 3 or 2 and 3 or 2, 4, 6)

#mention the path to your detection file -> protopath
#and the modelpath - path to your model
protopath = "model files/generic object detection model/MobileNetSSD_deploy.prototxt"
modelpath = "model files/generic object detection model/MobileNetSSD_deploy.caffemodel"

#initialize the detector and have it read from caffemodel
detector = cv2.dnn.readNetFromCaffe(prototxt=protopath, caffeModel=modelpath)

#if running your code through openVino env, include these 2 lines
#they simply say, use the Backend_inference for inferencing and use my cpu
# detector.setPreferableBackend(cv2.dnn.BACKEND_INFERENCE_ENGINE)
# detector.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)

#define the classes. Our model is a generic detection model; it can detect any object around us
#it can detect a car, cat, dog, person etc
#here we are mentioning all the classes it has and while inferencing, we'll only choose the one which has a person
CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat",
           "bottle", "bus", "car", "cat", "chair", "cow", "diningtable",
           "dog", "horse", "motorbike", "person", "pottedplant", "sheep",
           "sofa", "train", "tvmonitor"]

#initialize the tracker
#maxDisappeared is how long the tracker should wait for a frame to appear in a certain location so that it assign it the same id
tracker = CentroidTracker(maxDisappeared=80, maxDistance=90)

#non max suppression algorithm to remove noise like multiple bounding boxes around an object
def non_max_suppression_fast(boxes, overlapThresh):
    try:
        if len(boxes) == 0:
            return []

        if boxes.dtype.kind == "i":
            boxes = boxes.astype("float")

        pick = []

        x1 = boxes[:, 0]
        y1 = boxes[:, 1]
        x2 = boxes[:, 2]
        y2 = boxes[:, 3]

        area = (x2 - x1 + 1) * (y2 - y1 + 1)
        idxs = np.argsort(y2)

        while len(idxs) > 0:
            last = len(idxs) - 1
            i = idxs[last]
            pick.append(i)

            xx1 = np.maximum(x1[i], x1[idxs[:last]])
            yy1 = np.maximum(y1[i], y1[idxs[:last]])
            xx2 = np.minimum(x2[i], x2[idxs[:last]])
            yy2 = np.minimum(y2[i], y2[idxs[:last]])

            w = np.maximum(0, xx2 - xx1 + 1)
            h = np.maximum(0, yy2 - yy1 + 1)

            overlap = (w * h) / area[idxs[:last]]

            idxs = np.delete(idxs, np.concatenate(([last],
                                                   np.where(overlap > overlapThresh)[0])))

        return boxes[pick].astype("int")
    except Exception as e:
        print("Exception occurred in non_max_suppression : {}".format(e))

#fps(frames per second) - how many frames your hardware is able to process in 1s. 30fps means the hardware is able to process 30 frames per second
#fps is dependednt on the type of h/w you have, good laptops have high fps, bad laptops have low fps

def main():
    # get the video file and store it in cap
    cap = cv2.VideoCapture('video/testvideo2.mp4')

    #calculating fps - params -> start and end time value
    #To get fps = total frames/(start time - end time)
    fps_start_time = datetime.datetime.now()
    fps = 0
    total_frames = 0
    centroid_dict = dict()      #where the centroid will be saved at

    while True:
        #read frames from video file
        ret, frame = cap.read()

        #resize the frame
        frame = imutils.resize(frame, width=800)

        #increase total frames-> when going through the while loop, go to 1st frame, 2nd, etc
        total_frames = total_frames + 1

        #calculate the height and the width from the frame
        (H, W) = frame.shape[:2]

        # create a blob out of our image which will the used for infrencing
        blob = cv2.dnn.blobFromImage(frame, 0.007843, (W, H), 127.5)

        # pass this blob into our detector
        detector.setInput(blob)

        # get all the results from the detector
        # person_detections has all the results from our model file
        person_detections = detector.forward()

        #a list where all the coordinates are saved
        rects = []

        # iterate over all the detections
        for i in np.arange(0, person_detections.shape[2]):
            # calculate the confidence of the detection -> if the confidence is above threshold, we accept that result
            confidence = person_detections[0, 0, i, 2]
            if confidence > 0.5:  # 0.5 is the threshold
                # calculate the index of the detection
                idx = int(person_detections[0, 0, i, 1])

                # based on this index, check which class it belongs to. If it isn't a person, continue
                # iterating, if it is person, calculate the bounding box
                if CLASSES[idx] != "person":
                    continue
                # the bounding box has cordinates like start x & y
                person_box = person_detections[0, 0, i, 3:7] * np.array([W, H, W, H])
                # calculating the start x&y and end x&y
                (startX, startY, endX, endY) = person_box.astype("int")
                #all person bounding boxes cordinates are saved here
                rects.append(person_box)

        #apply the non max suppression algorithm here to remove all noise(unwanted bounding boxes) from the persons in the image/video
        boundingBoxes = np.array(rects)
        boundingBoxes = boundingBoxes.astype(int) #convert bounding boxes to integer
        rects = non_max_suppression_fast(boundingBoxes, 0.3)  #pass all the bounding boxes to nonmaxsuppression & give it a threshold value of 0.3

        #above rects has the correct bounding boxes(right coordinates for the objects) & doesnt have noise in them
        #pass the bounding boxes(cordinates) to the tracker which will keep track of the bounding boxes(objects inside the boundingboxes)
        #after the tracker has taken all the cordinates it returns objects id
        objects = tracker.update(rects)

        #objects variable contains the bounding box and the object id of an object
        for (objectId, bbox) in objects.items():
            #assign bounding box values, the cordinates, to x1,y1,x2,y2
            x1, y1, x2, y2 = bbox

            #convert them to integers
            x1 = int(x1)
            y1 = int(y1)
            x2 = int(x2)
            y2 = int(y2)

            #calculating the centroids
            cX = int((x1 + x2)/2.0)
            cY = int((y1 + y2) / 2.0)

            #save the centroids and the bounding boxes of each person a dictionary
            centroid_dict[objectId] = (cX, cY, x1, y1, x2, y2)

            #display the object id given by the tracker
            #use cv2.putText to put the text(below string) to the frame
            text = "ID: {}".format(objectId)
            cv2.putText(frame, text, (x1, y1-5), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)

        #list of persons who come on the red zone
        red_zone_list = []
        #this for loop iterates contents of the dictionary
        for(id1, p1), (id2, p2) in combinations(centroid_dict.items(), 2):
            #calculate centroid, taking centroid of p1 - centroid of p2
            dx, dy = p1[0] -p2[0], p1[1] - p2[1]

            #calculate the real distance
            distance = math.sqrt(dx * dx + dy * dy)

            #check if social dist(75) is observed, if not, put their id in a list
            if distance < 75.0:
                if id1 not in red_zone_list:
                    red_zone_list.append(id1)
                if id2 not in red_zone_list:
                    red_zone_list.append(id2)

        #iterate the centroids again and display those ids in green or red bounding boxes
        for id, box in centroid_dict.items():
            if id in red_zone_list:
                # display these cordinates using red rectangle/bounding boxes
                cv2.rectangle(frame, (box[2], box[3]), (box[4], box[5]), (0, 0, 255), 2)
            else:
                # display these cordinates using green rectangle/bounding boxes
                cv2.rectangle(frame, (box[2], box[3]), (box[4], box[5]), (0, 255, 0), 2)

        #get fps end time
        fps_end_time = datetime.datetime.now()

        #get time difference
        time_diff = fps_end_time - fps_start_time

        #get fps
        #N/B: at the start the time diff will be very small, comp will interpret as zero.
        #since we can't divide by zero, use this if else so that if the time diff is zero we display nothing
        if time_diff.seconds == 0:
            fps = 0
        else:
            fps = (total_frames/time_diff.seconds)

        #display the fps value through text
        #first round it to 2 dps
        fps_text = "FPS: {:.2f}".format(fps)
        cv2.putText(frame, fps_text, (5, 30), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 255, 255), 1)

        #display the video
        cv2.imshow('Application', frame)

        #stop the while loop
        key = cv2.waitKey(1)
        if key == ord('q'):
            break

#after breaking destroy all windows
cv2.destroyAllWindows()

#call the main function
main()


from src.utils import *
import plot as PLOT

affirmative = ['yes', 'ye', 'y', 'yey', 'yeah', 'yay', 'yess']

SHOW = True
SAVEPUSH = False

'''
--------------------------
SIMPLE REGRESSION ANALYSIS
--------------------------
'''

files0 = ["plain_GD.txt", "momentum_GD.txt", "adagrad_GD.txt", "rmsprop_GD.txt", "adam_GD.txt"]
labels0 =  ["plain GD", "momentum GD", "AdaGrad", "RMSProp", "Adam"]

files = ["plain_SGD.txt", "momentum_SGD.txt", "adagrad_SGD.txt", "rmsprop_SGD.txt", "adam_SGD.txt"]
labels =  ["plain SGD", "momentum SGD", "AdaGrad", "RMSProp", "Adam"]

if input('Show plots for: SIMPLE REGRESSION ANALYSIS? [y/n][yes/no]').lower().strip() in affirmative:
    PLOT.simple_regression_errors(files0, labels0, pdfname="errors_gradient_descent_nonstochastic", savepush=SAVEPUSH, show=SHOW)

    PLOT.simple_regression_errors(files, labels, pdfname="errors_gradient_descent", savepush=SAVEPUSH, show=SHOW)

    PLOT.simple_regression_polynomial(files, labels, pdfname="polynomial_gradient_descent", savepush=SAVEPUSH, show=SHOW)

    PLOT.simple_regression_errors(["ridge_"+file for file in files], labels, pdfname="ridge_errors_gradient_descent",savepush=SAVEPUSH, show=SHOW)

'''
-----------------------------
FRANKE NN REGRESSION ANALYSIS
-----------------------------
'''
if input('Show plots for: NEURAL NETWORK REGRESSION ANALYSIS? [y/n][yes/no]').lower().strip() in affirmative:
    PLOT.MSEheatmap_plot("EtaLmbdaMSE.pkl", pdfname="eta_lambda_analysis", savepush=SAVEPUSH, show=SHOW)

    PLOT.MSEheatmap_plot("LayerNeuron.pkl", pdfname="layer_neuron_analysis", savepush=SAVEPUSH, xlabel="$N_l$", ylabel=r"$L-1$", show=SHOW)

    PLOT.epoch_plot("actFuncPerEpoch1000.pkl", pdfname="actFuncPer1000Epoch", savepush=SAVEPUSH, show=SHOW)

    PLOT.epoch_plot("actFuncPerEpoch250.pkl", pdfname="actFuncPerEpoch", savepush=SAVEPUSH, show=SHOW)

    PLOT.MSEheatmap_plot("EpochMinibatch.pkl", pdfname="epoch_minibatch_analysis", savepush=SAVEPUSH, xlabel=r"$m$", ylabel=r"$\#$epochs", show=SHOW)

    PLOT.FrankePlot(pdfname='franke', savepush=SAVEPUSH, show=SHOW)

'''
---------------------------------
CANCER NN CLASSIFICATION ANALYSIS
---------------------------------
'''
if input('Show plots for: NEURAL NETWORK CLASSIFICATION ANALYSIS? [y/n][yes/no]').lower().strip() in affirmative:
    PLOT.CancerHeatmap_plot("EtaLmbdaMSECancer.pkl", pdfname="eta_lambda_analysisCancer", savepush=SAVEPUSH, show=SHOW)

    PLOT.CancerHeatmap_plot("LayerNeuronCancer.pkl", pdfname="layer_neuron_analysisCancer", savepush=SAVEPUSH, xlabel="$N_l$", ylabel=r"$L-1$", show=SHOW)

    PLOT.Cancerepoch_plot("actFuncPerEpochCancer1000.pkl", pdfname="actFuncPerEpoch1000Cancer", savepush=SAVEPUSH, show=SHOW)

    PLOT.Cancerepoch_plot("actFuncPerEpochCancer250.pkl", pdfname="actFuncPerEpochCancer", savepush=SAVEPUSH, show=SHOW)

    PLOT.CancerHeatmap_plot("EpochMinibatchCancer.pkl", pdfname="epoch_minibatch_analysisCancer", savepush=SAVEPUSH, xlabel=r"$m$", ylabel=r"$\#$epochs", show=SHOW)

'''
-----------------------------------
CANCER LOGISTIC REGRESSION ANALYSIS
-----------------------------------
'''
if input('Show plots for: LOGISTIC REGRESSION ANALYSIS? [y/n][yes/no]').lower().strip() in affirmative:
    PLOT.CancerHeatmap_plot("logistic.pkl", pdfname="logistic", savepush=SAVEPUSH, show=SHOW)

if SAVEPUSH:
    '''
    Update info.pkl and README.md:
    '''
    PLOT.update()


try:
    #nhap 2 số 2 a,b
    a=int(input())
    b=int(input())
    sum=0
    #nếu a<=b
    if a<=b:
        for i in range(a,b+1):
            sum+=i
    else:
        #nếu a>b thì nhập lại
        print("a lon hon b ?")
    print("tong cac so nguyen tu a den b: ",sum)
except:
    print("Data eror")


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Main script for the case study."""

from src import setup_logging
from src import init_dbs
from src import qa_staging
from src import etl_to_production
from src import generate_reports

def main():
    logger.info('Begin ETL process.')
    init_dbs.init_staging_database()
    init_dbs.init_prod_database()
    file_paths = init_dbs.validate_folder_and_files('data/input')
    file_path_dict = init_dbs.validate_file_header(file_paths)

    logger.info('Load content into *_stg tables begin.')
    for table_name, files in file_path_dict.items():
        for file_path in files:
            init_dbs.load_file_in_staging(file_path,
                                          table_name)

    logger.info('Initialize data QA and transfer to *_clean tables.')
    qa_staging.update_audit_table()

    qa_staging.run_qa_logins()
    qa_staging.run_qa_registration()
    qa_staging.run_qa_games()
    qa_staging.run_qa_lottery()

    logger.info('Initialize data transfer to production.')
    etl_to_production.prepare_customer_table()
    etl_to_production.prepare_discount_table()
    etl_to_production.prepare_login_table()
    etl_to_production.prepare_registration_table()
    etl_to_production.prepare_booking_table()
    etl_to_production.prepare_ticket_table()
    etl_to_production.prepare_product_table()

    logger.info('Concluded ETL process.')
    logger.info ('Generating quaterly reports.')

    generate_reports.generate_billing(by='type')
    generate_reports.generate_billing(by='name')
    generate_reports.generate_billing(by='website')
    generate_reports.generate_billing(by='booking_month')

    generate_reports.generate_active_customers(by='login_month')
    generate_reports.generate_active_customers(by='login_day')
    generate_reports.generate_active_customers(by='login_week')
    generate_reports.generate_active_customers(by='website')

    generate_reports.generate_avg_checkout()
    generate_reports.generate_monthly_diff()

    logger.info('Concluded generation of reports.')

if __name__ == "__main__":
    logger = setup_logging(logFile='etl-info.log', level='info')
    main()


import datetime
import io
import json
import logging
import os
import telebot
import time
import traceback

from PIL import Image
from termcolor import colored
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton

from local_settings import *

JSON_FILE = "dynamic_data/telegram.json"
PROFILE_PIC_DIR = "dynamic_data/telegram_profile_pics"

class FIABot:
    def __init__(self, api_key, admin_cid, admin_mode = False, blocklist = [], max_message_age = 5):
        self.admin_cid = admin_cid
        self.admin_mode = admin_mode
        self.blocklist = blocklist
        self.max_message_age = max_message_age

        self.bot = telebot.TeleBot(api_key, threaded=False)
        self.bot.set_update_listener(lambda msgs: self.listener_console_logging(msgs))
        self.bot.me = self.bot.get_me()
        logging.basicConfig()
        self.logger = logging.getLogger("FIABot")
        self.logger.setLevel(logging.INFO)

        # Abusing function decorators to enable me to use the code in a class
        self.bot.message_handler(commands=['start'])(lambda msg: self.handle_start(msg))
        self.bot.message_handler(commands=['delete'])(lambda msg: self.handle_delete(msg))
        self.bot.message_handler(commands=['deleteall'])(lambda msg: self.handle_deleteall(msg))
        self.bot.message_handler(content_types=['text'])(lambda msg: self.handle_text(msg))

    def run(self):
        exit = False
        while not exit:
            try:
                self.logger.info("Press Ctrl-C again within one second to terminate the bot")
                time.sleep(1)
                self.logger.info("Starting bot")
                self.bot.polling()
            except KeyboardInterrupt:
                self.logger.info("Goodbye!")
                exit = True
            except:
                traceback.print_exc()
                time.sleep(10)

    def filter_message_incoming(self, msg):
        # Discard any non-admin messages if in admin mode
        if self.admin_mode and msg.chat.id != self.admin_cid:
            return False
        # Discard messages from blacklisted users
        if msg.chat.id in self.blocklist:
            return False
        # Discard messages older than the limit
        if (time.time() - msg.date) > (60 * self.max_message_age):
            return False
        return True

    def listener_console_logging(self, messages):
        def _readable(msg):
            if msg.content_type == 'text':
                return msg.text
            else:
                if msg.content_type is not None:
                    return colored(msg.content_type.capitalize(), 'blue')
                else:
                    return colored("Unknown Message Type", 'blue')

        for msg in messages:
            #filtered = self.filter_message_incoming(msg)
            filtered = True
            self.logger.info("%(filtered)s[%(timestamp)s #%(mid)s %(firstname)s %(lastname)s @%(username)s #%(uid)s @ %(groupname)s #%(cid)s] %(text)s" % {
                'filtered': colored("[FILTERED]", 'red') if not filtered else "",
                'timestamp': datetime.datetime.fromtimestamp(msg.date).strftime("%d.%m.%Y %H:%M:%S"),
                'firstname': colored(msg.from_user.first_name, 'green'),
                'lastname': colored(msg.from_user.last_name, 'magenta'),
                'username': colored(msg.from_user.username, 'yellow'),
                'groupname': colored(msg.chat.title, 'red'),
                'mid': colored(str(msg.message_id), 'blue'),
                'uid': colored(str(msg.from_user.id), 'cyan'),
                'cid': colored(str(msg.chat.id), 'cyan'),
                'text': _readable(msg)
            })

    def load_data(self):
        try:
            with open(JSON_FILE, 'r', encoding='utf-8') as f:
                data = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError):
            data = {}
        return data

    def save_data(self, data):
        with open(JSON_FILE, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=2, sort_keys=True)

    def handle_start(self, msg):
        self.bot.reply_to(msg, "Hi! Just send me a text message and I'll display it.")

    def handle_delete(self, msg):
        data = self.load_data()
        if str(msg.chat.id) in data:
            del data[str(msg.chat.id)]
            self.save_data(data)
            self.bot.reply_to(msg, "Your message has been deleted.")
        else:
            self.bot.reply_to(msg, "Looks like you didn't have a message saved in the first place!")

    def handle_deleteall(self, msg):
        if msg.chat.id != self.admin_cid:
            self.bot.reply_to(msg, f"I'm sorry, {msg.from_user.first_name}. I can't let you do that.")
            return
        with open(JSON_FILE, 'w', encoding='utf-8') as f:
            json.dump({}, f)
        self.bot.reply_to(msg, "All messages cleared.")

    def handle_text(self, msg):
        profile_pics = self.bot.get_user_profile_photos(msg.chat.id)
        if profile_pics.total_count > 0:
            profile_pic = profile_pics.photos[0]
            for size in profile_pic:
                if size.width >= 48 and size.height >= 48:
                    f_info = self.bot.get_file(size.file_id)
                    f = io.BytesIO()
                    f.write(self.bot.download_file(f_info.file_path))
                    f.seek(0)
                    img = Image.open(f)
                    img = img.resize((48, 48))
                    img.save(os.path.join(PROFILE_PIC_DIR, f"{msg.chat.id}.png"))
                    img.close()
                    f.close()

        data = self.load_data()
        data.update({str(msg.chat.id): {
                'type': 'text',
                'text': msg.text,
                'timestamp': msg.date,
                'username': msg.from_user.username,
                'display_name': (msg.from_user.first_name or "") + " " + (msg.from_user.last_name or "")
            }})
        self.save_data(data)
        self.bot.reply_to(msg, "Your message has been saved! Use /delete to remove it.")

"""
MAIN LOOP
"""

def main():
    bot = FIABot(TELEGRAM_API_TOKEN, TELEGRAM_ADMIN_CID)
    bot.run()

if __name__ == "__main__":
    main()


from abc import ABC

import numpy as np
import scipy.stats as si
from scipy.stats import norm

from OpenFinPriGen.Pricer import Pricer

class AnalyticalExpressions(Pricer, ABC):

    def __init__(self, s0: float, vanilla_style: str, k: float, tau: float, rf: float = 0, q: float = 0):
        """
            This class aims to provide analytical expressions when models offer pricing tractability
            @param s0: stock price at time zero
            @param vanilla_style: call ("c") or put ("p").
            @param k: Strike price of your option.
            @param tau: Time until the end of life of the option.
            @param rf: Risk free rate to apply for the calculations.default=0.
            @param q: Dividend yield (if existing). Default=0.
        """
        self.s0 = s0
        self.vanilla_style = vanilla_style
        self.k = k
        self.tau = tau
        self.rf = rf
        self.q = q

    def getReturns(self, data):
        ret = data[1:] / data[:-1] - 1
        return ret

    def HistoricalVol(self, data):
        ret = self.getReturns(data)
        hist_vol = np.std(ret)*np.sqrt(250)
        return hist_vol


import random

print("Welcome to the game Guess the Number. You have maximum 5 attempts.")

max_num = int(input("Choose a maximum number in your game: "))
right_num = random.randint(1, max_num)

attempts = 0

while attempts < 5:
    guess = int(input("What's your guess? "))

    if guess == right_num:
        print("Congrats! This is the right number.")
        break
    else:
        print("Try again.")
        if guess > right_num:
            print("It's too much!")
        elif guess < right_num:
            print("It's not enough!")
        attempts += 1

if attempts == 5:
    print("Sorry, you've used all your attempts. The correct number was:", right_num)


from node_module import node
#A List Abstract Data Type

class ordered_list:

    def __init__(self):
        self.head = None

    def is_empty(self):
        return self.head == None

    def pop(self):
        pass

    def pos_pop():
        pass

    def add(self, item):
        current = self.head
        previous = None
        stop = False

        while current != None and not stop:
            if current.get_data() > item:
                stop = True
            else:
                previous = current
                current = current.get_next()

        temp = node(item)
        if previous == None:
            temp.set_next(self.head)
            self.head = temp
        else:
            temp.set_next(current)
            previous.set_next(temp)

    def size(self):
        current = self.head
        count = 0
        while current != None:
            count = count + 1
            current = current.get_next()

        return count

    def search(self, item):
        current = self.head
        found = False
        stop = False
        while current != None and not found and not stop:
            if current.get_data() == item:
                found = True
            else:
                if current.get_data() > item:
                    stop = True
                else:
                    current = current.get_next()

        return found

    def show(self):
        rep = "["
        current = self.head
        while current != None:
            rep = rep + str(current.get_data()) + ", "
            current = current.get_next()
        rep = rep[:-2] + "]"
        return rep

    def remove(self, item):
        current = self.head
        previous = None
        found = False
        while not found:
            if current.get_data() == item:
                found = True
            else:
                previous = current
                current = current.get_next()

        if previous == None:
            self.head = current.get_next()
        else:
            previous.set_next(current.get_next())


"""A module for water_edd.py that wrangles raw results into edd output"""

import pandas as pd
import numpy as np

def find_acts_orphans(
    results_ncrn_anc:pd.DataFrame
    ,results_ncrn_stream:pd.DataFrame
    ,results_ncrn_water:pd.DataFrame
    ,results:pd.DataFrame
    ,analysis_ready:bool
    ):
    """Find Activity_IDs that would be orphaned from not running sql_files/ncrn_db/qry_edd_ncrn_results_tbl_ANC.sql

    The records in tbl_ANC already exist in NPStoret. To avoid duplicating records, we don't want to add records in tbl_ANC.
    Simply not running the query could leave orphaned Activity_IDs if an activity produced only tbl_ANC results (and not
    in tbl_Core_Water_Data or tbl_Stream_Condition). Similarly, if any of those orphaned Activity_IDs were the only activities
    at a location, not running the query would leave orphaned Location_IDs. In theory, if an Activity_ID exists in
    tbl_ANC, the Activity_ID should always exist in tbl_Core_Water_Data and/or tbl_Stream_Condition. Likewise, it's an
    unlikely, but plausible edge-case that an Activity_ID that existed only in tbl_ANC would be the only
    activity at a Location_ID.

    This module finds the edge-cases described above and deletes them to avoid both duplicated and orphaned records.

    Args:
        results_ncrn_anc (pd.DataFrame): The dataframe returned by sql_files/ncrn_db/qry_edd_ncrn_results_tbl_ANC.sql
        results_ncrn_stream (pd.DataFrame): The dataframe returned by sql_files/ncrn_db/qry_edd_ncrn_tbl_Stream_Condition.sql
        results_ncrn_water (pd.DataFrame): The dataframe returned by sql_files/ncrn_db/qry_edd_ncrn_results_tbl_Core_Water_Data.sql

    Returns:
        acts_orphans (list): A list of would-be orphaned Activity_IDs.
    """
    acts_orphans = []

    # orphans that propagate from excluding tbl_ANC
    for act in results_ncrn_anc.Activity_ID.unique():
        if act not in results_ncrn_stream.Activity_ID.unique()\
        and act not in results_ncrn_water.Activity_ID.unique():
            acts_orphans.append(act)

    # orphans that propagate from excluding records with Activity_Start_Date < '2005-01-01'
    # possible_orphans = actvities_npstoret[actvities_npstoret['Activity_Start_Date'] < '2005-01-01'].Activity_ID.unique()
    # for poss in possible_orphans:
    #     acts_orphans.append(poss)

    if analysis_ready == True:
        # filtering out 'Not Reported' and 'Present <QL' records from results could orphan `Activity_ID`s, so we find those and append here
        mysub = results.groupby(['Activity_ID']).size().reset_index(name='count').sort_values(['count'], ascending=True)
        mysub = mysub[mysub['count'] == 1]
        mysub = mysub.Activity_ID.unique()
        for act in mysub:
            if results[results.Activity_ID == act].Result_Text.unique() == '*Not Reported':
                acts_orphans.append(act)
            elif results[results.Activity_ID == act].Result_Text.unique() == '*Present <QL':
                acts_orphans.append(act)

        # results = results.drop(results[(results['Result_Text'] == '*Not Reported')].index)
        # results = results.drop(results[(results['Result_Text'] == '*Present <QL')].index)

    return acts_orphans

def wrangle_results(results:pd.DataFrame, acts_orphans:list, blank_adjusted:list, field_duplicate:list, analysis_ready:bool):
    """Wrangle the dataframe of EDD-formatted results into one comprehensible analysis-ready dataframe

    Args:
        results (pd.DataFrame): The dataframe of results records from queries, concatenated.
        acts_orphans (list): A list of Activity_IDs that would yield orphaned results from filtering out
            npstoret records with Activity_Start_Date < '2005-01-01'

    Returns:
        results (pd.DataFrame): The input dataframe with light quality-control, and domain-limited values.
    """
    # delete results from npstoret where Activity_Start_Date < '2005-01-01'
    if len(acts_orphans) > 0:
        results = results[~results['Activity_ID'].isin(acts_orphans)]
    # delete junk records

    results.rename(columns={'Org_Code': '#Org_Code'}, inplace=True) # rename to match edd...
    results['#Org_Code'] = 'NCRN'

    # standardize results.Characteristic_Name
    results.loc[results['Characteristic_Name'] == 'ANC', 'Characteristic_Name'] = 'Acid Neutralizing Capacity (ANC)'
    results.loc[results['Characteristic_Name'] == 'Base flow discharge', 'Characteristic_Name'] = 'Discharge'
    results.loc[results['Characteristic_Name'] == 'Spec_Conductance', 'Characteristic_Name'] = 'Specific conductance'
    results.loc[results['Characteristic_Name'] == 'Water_Temp', 'Characteristic_Name'] = 'Temperature, water'
    results.loc[results['Characteristic_Name'] == 'Width', 'Characteristic_Name'] = 'Wetted width'
    results.loc[results['Characteristic_Name'] == 'Wetted_Width', 'Characteristic_Name'] = 'Wetted width'
    results.loc[results['Characteristic_Name'] == 'Stream width measure', 'Characteristic_Name'] = 'Wetted width'
    results.loc[results['Characteristic_Name'] == 'TDS', 'Characteristic_Name'] = 'Total dissolved solids'
    results.loc[results['Characteristic_Name'] == 'Percent_DO', 'Characteristic_Name'] = 'Dissolved oxygen saturation'
    results.loc[results['Characteristic_Name'] == 'Flow_Condition', 'Characteristic_Name'] = 'Flow, severity (choice list)'
    results.loc[results['Characteristic_Name'] == 'Flow', 'Characteristic_Name'] = 'Discharge'
    results.loc[results['Characteristic_Name'] == 'Dissolved oxygen (DO)', 'Characteristic_Name'] = 'Dissolved oxygen concentration'
    results.loc[results['Characteristic_Name'] == 'TDN', 'Characteristic_Name'] = 'Total dissolved Nitrogen concentration'
    results.loc[results['Characteristic_Name'] == 'TDP', 'Characteristic_Name'] = 'Total dissolved Phosphorus concentration'
    results.loc[results['Characteristic_Name'] == 'TN', 'Characteristic_Name'] = 'Total Nitrogen concentration'
    results.loc[results['Characteristic_Name'] == 'TP', 'Characteristic_Name'] = 'Total Phosphorus concentration'
    results.loc[results['Characteristic_Name'] == 'Chlorine', 'Characteristic_Name'] = 'Chlorine concentration'
    results.loc[results['Characteristic_Name'] == 'Algae_Cover', 'Characteristic_Name'] = 'Algae, substrate rock/bank cover'
    results.loc[results['Characteristic_Name'] == 'Algae, substrate rock/bank cover (choice list)', 'Characteristic_Name'] = 'Algae, substrate rock/bank cover'
    results.loc[results['Characteristic_Name'] == 'Algae_Appearance', 'Characteristic_Name'] = 'Epilithic algae color description'
    results.loc[results['Characteristic_Name'] == 'DO', 'Characteristic_Name'] = 'Dissolved oxygen concentration'
    results.loc[results['Characteristic_Name'] == 'Stream_Condition', 'Characteristic_Name'] = 'Stream Physical Appearance (choice list)'
    results.loc[results['Characteristic_Name'] == 'Stream Physical Appearance (choice list)', 'Characteristic_Name'] = 'Water appearance'
    results.loc[results['Characteristic_Name'] == 'Distance increment where measurements are taken from right bank', 'Characteristic_Name'] = 'Distance increment where measurements were taken from river-right bank'
    results.loc[results['Characteristic_Name'] == 'Description of sequential increment from right bank', 'Characteristic_Name'] = 'Sample sequence from river-right bank'
    results.loc[results['Characteristic_Name'] == 'Barometric pressure', 'Characteristic_Name'] = 'Barometric pressure, air'
    results.loc[results['Characteristic_Name'] == 'Depth', 'Characteristic_Name'] = 'Mean water depth across stream cross-section where discharge was measured'
    results.loc[results['Characteristic_Name'] == 'Nitrogen, ammonia (NH3) as NH3', 'Characteristic_Name'] = 'Nitrogen; ammonia (NH3) concentration'
    results.loc[results['Characteristic_Name'] == 'Nitrogen, Nitrate (NO3) as NO3', 'Characteristic_Name'] = 'Nitrogen; nitrate (NO3) concentration'
    results.loc[results['Characteristic_Name'] == 'Phosphorus as PO4', 'Characteristic_Name'] = 'Phosphorus; phosphate (PO4) concentration'
    results.loc[results['Characteristic_Name'] == 'Phosphorus, orthophosphate as PO4', 'Characteristic_Name'] = 'Phosphorus; orthophosphate concentration'
    results.loc[results['Characteristic_Name'] == 'Acid Neutralizing Capacity (ANC)', 'Characteristic_Name'] = 'Acid neutralizing capacity'
    results.loc[results['Characteristic_Name'] == 'RBP Stream Velocity', 'Characteristic_Name'] = 'Discharge velocity'
    results.loc[results['Characteristic_Name'] == 'RBP2, Watershed, Predominant Surrounding Landuse', 'Characteristic_Name'] = 'Predominant surrounding landuse'
    results.loc[results['Characteristic_Name'] == 'Bank erosion stability (choice list)', 'Characteristic_Name'] = 'Bank erosion stability'
    results.loc[results['Characteristic_Name'] == 'RBP2, Riparian Vegetation, Dominant Species Present', 'Characteristic_Name'] = 'Riparian vegetation, dominant terrestrial vegetation type present'
    results.loc[results['Characteristic_Name'] == 'RBP2, Low G, Riparian Vegetative Zone Width, Right Bank', 'Characteristic_Name'] = 'Riparian vegetative zone width, river-right bank'
    results.loc[results['Characteristic_Name'] == 'RBP2, Low G, Riparian Vegetative Zone Width, Left Bank', 'Characteristic_Name'] = 'Riparian vegetative zone width, river-left bank'
    results.loc[results['Characteristic_Name'] == 'RBP Channelized Y/N', 'Characteristic_Name'] = 'Stream is artificially channelized'
    results.loc[results['Characteristic_Name'] == 'Total dissolved Nitrogen concentration', 'Characteristic_Name'] = 'Nitrogen; total dissolved nitrogen concentration'
    results.loc[results['Characteristic_Name'] == 'Total dissolved Phosphorus concentration', 'Characteristic_Name'] = 'Phosphorus; total dissolved phosphorus concentration'
    results.loc[results['Characteristic_Name'] == 'Total Phosphorus concentration', 'Characteristic_Name'] = 'Phosphorus; total phosphorus concentration'
    results.loc[results['Characteristic_Name'] == 'Total Nitrogen concentration', 'Characteristic_Name'] = 'Nitrogen; total nitrogen concentration'
    results.loc[results['Characteristic_Name'] == 'Weather Condition (WMO Code 4501) (Choice List)', 'Characteristic_Name'] = 'Weather Condition (WMO Code 4501)'
    # standardize results.Result_Text
    results.loc[results['Result_Text'] == '1.CLEAR     ', 'Result_Text'] = 'CLEAR'
    results.loc[results['Result_Text'] == '2.MILKY     ', 'Result_Text'] = 'MILKY'
    results.loc[results['Result_Text'] == '3.FOAMY     ', 'Result_Text'] = 'FOAMY'
    results.loc[results['Result_Text'] == '4.TEA-COLOR ', 'Result_Text'] = 'TEA-COLOR'
    results.loc[results['Result_Text'] == '5.MUDDY     ', 'Result_Text'] = 'MUDDY'
    results.loc[results['Result_Text'] == '7.SCUM/ODOR ', 'Result_Text'] = 'SCUM/ODOR'
    results.loc[results['Result_Text'] == 'Lindsay Ashley lead, assisted by Amy Fowler.', 'Result_Text'] = ''
    results.loc[results['Result_Text'] == 'CLEAR AND NORMAL', 'Result_Text'] = 'CLEAR'
    results.loc[results['Result_Text'] == '1.CLEAR', 'Result_Text'] = 'CLEAR'
    results.loc[results['Result_Text'] == '2.MILKY', 'Result_Text'] = 'MILKY'
    results.loc[results['Result_Text'] == '3.FOAMY', 'Result_Text'] = 'FOAMY'
    results.loc[results['Result_Text'] == '4.TEA-COLOR', 'Result_Text'] = 'TEA-COLOR'
    results.loc[results['Result_Text'] == '5.MUDDY', 'Result_Text'] = 'MUDDY'
    results.loc[results['Result_Text'] == '6.GREEN', 'Result_Text'] = 'GREEN'
    results.loc[results['Result_Text'] == '7.SCUM/ODOR', 'Result_Text'] = 'SCUM/ODOR'
    results.loc[results['Result_Text'] == 'MDST', 'Result_Text'] = 'stable'
    results.loc[results['Result_Text'] == 'MDUS', 'Result_Text'] = 'unstable'
    results.loc[results['Result_Text'] == '2           ', 'Result_Text'] = '2'
    results.loc[results['Result_Text'] == '0           ', 'Result_Text'] = '0'
    results.loc[results['Result_Text'] == '1           ', 'Result_Text'] = '1'
    results.loc[results['Result_Text'] == '5           ', 'Result_Text'] = '5'
    results.loc[results['Result_Text'] == '6           ', 'Result_Text'] = '6'
    results.loc[results['Result_Text'] == '7           ', 'Result_Text'] = '7'
    results.loc[results['Result_Text'] == 'FIELD/PASTUR', 'Result_Text'] = 'FIELD/PASTURE'
    results.loc[results['Result_Text'] == 'N/A', 'Result_Text'] = ''
    results.loc[results['Result_Text'] == 'NO FLOW', 'Result_Text'] = 'DRY'
    results.loc[results['Result_Text'] == 'NORMAL      ', 'Result_Text'] = 'NORMAL'
    results.loc[results['Result_Text'] == 'LOW         ', 'Result_Text'] = 'LOW'
    results.loc[results['Result_Text'] == 'FLOOD       ', 'Result_Text'] = 'FLOOD'
    results.loc[results['Result_Text'] == '100%        ', 'Result_Text'] = '100%'
    results.loc[results['Result_Text'] == '.', 'Result_Text'] = '' # Phosphorus; total phosphorus concentration from 'NPS_NCR_041018.xlsx

    # standardize results.Result_Unit
    results.loc[results['Characteristic_Name'] == 'Discharge', 'Result_Unit'] = 'cubic feet per second'
    results.loc[results['Characteristic_Name'] == 'Flow, severity (choice list)', 'Result_Unit'] = 'qualitative estimation of creek stage relative to normal'
    results.loc[results['Characteristic_Name'] == 'Mean water depth across stream cross-section where discharge was measured', 'Result_Unit'] = 'feet'
    results.loc[results['Characteristic_Name'] == 'Discharge velocity', 'Result_Unit'] = 'feet per second'
    results.loc[results['Characteristic_Name'] == 'Epilithic algae color description', 'Result_Unit'] = 'comments; appearance of algae on rocks in stream'
    results.loc[results['Characteristic_Name'] == 'Algae, substrate rock/bank cover', 'Result_Unit'] = 'Bins of percentages: 0%|1-20%|21-40%|41-60%|61-80%|81-99%|100%'
    results.loc[results['Characteristic_Name'] == 'Water appearance', 'Result_Unit'] = 'Choice list: CLEAR|MILKY|FOAMY|TEA-COLOR|MUDDY|GREEN|SCUM/ODOR'
    results.loc[results['Characteristic_Name'] == 'Wetted width', 'Result_Unit'] = 'feet'
    results.loc[results['Characteristic_Name'] == 'Total dissolved solids', 'Result_Unit'] = 'milligrams per liter'
    results.loc[results['Characteristic_Name'] == 'Barometric pressure, air', 'Result_Unit'] = 'millimeters of mercury'
    results.loc[results['Characteristic_Name'] == 'Distance increment where measurements were taken from river-right bank', 'Result_Unit'] = 'meter'
    results.loc[results['Characteristic_Name'] == 'Dissolved oxygen concentration', 'Result_Unit'] = 'milligrams per liter'
    results.loc[results['Characteristic_Name'] == 'Salinity', 'Result_Unit'] = 'parts per thousand'
    results.loc[results['Characteristic_Name'] == 'Temperature, water', 'Result_Unit'] = 'degrees celsius'
    results.loc[results['Characteristic_Name'] == 'Temperature, air', 'Result_Unit'] = 'degrees celsius'
    results.loc[results['Characteristic_Name'] == 'Sample sequence from river-right bank', 'Result_Unit'] = 'Sample order'
    results.loc[results['Characteristic_Name'] == 'Conductivity', 'Result_Unit'] = 'microohms per centimeter'
    results.loc[results['Characteristic_Name'] == 'Specific conductance', 'Result_Unit'] = 'microsiemens per centimeter'
    results.loc[results['Characteristic_Name'] == 'pH', 'Result_Unit'] = 'pH'
    results.loc[results['Characteristic_Name'] == 'Dissolved oxygen saturation', 'Result_Unit'] = 'milligrams per liter'
    results.loc[results['Characteristic_Name'] == 'Nitrogen; ammonia (NH3) concentration', 'Result_Unit'] = 'milligrams per liter'
    results.loc[results['Characteristic_Name'] == 'Nitrogen; nitrate (NO3) concentration', 'Result_Unit'] = 'milligrams per liter'
    results.loc[results['Characteristic_Name'] == 'Phosphorus; phosphate (PO4) concentration', 'Result_Unit'] = 'milligrams per liter'
    results.loc[results['Characteristic_Name'] == 'Bank erosion stability', 'Result_Unit'] = 'Choice list: stable, unstable'
    results.loc[results['Characteristic_Name'] == 'Stream is artificially channelized', 'Result_Unit'] = 'Choice list: NO|YES'
    results.loc[results['Result_Unit'] == 'ueq/L', 'Result_Unit'] = 'microequivalents per liter' # ANC
    results.loc[results['Result_Unit'] == 'meq/L', 'Result_Unit'] = 'milliequivalents per liter' # ANC
    results.loc[results['Characteristic_Name'] == 'Phosphorus; orthophosphate concentration', 'Result_Unit'] = 'milligrams per liter'
    results.loc[results['Characteristic_Name'] == 'Nitrogen; total dissolved nitrogen concentration', 'Result_Unit'] = 'milligrams per liter'
    results.loc[results['Characteristic_Name'] == 'Phosphorus; total dissolved phosphorus concentration', 'Result_Unit'] = 'milligrams per liter'
    results.loc[results['Characteristic_Name'] == 'Phosphorus; total phosphorus concentration', 'Result_Unit'] = 'milligrams per liter'
    results.loc[results['Characteristic_Name'] == 'Nitrogen; total nitrogen concentration', 'Result_Unit'] = 'milligrams per liter'
    results.loc[results['Characteristic_Name'] == 'Weather Condition (WMO Code 4501)', 'Result_Unit'] = 'WMO Code 4501'
    results.loc[results['Characteristic_Name'] == 'Predominant surrounding landuse', 'Result_Unit'] = 'Choice list: FIELD/PASTURE|FOREST|AGRICULTURAL|OTHER|RESIDENTIAL|COMMERCIAL'
    results.loc[results['Characteristic_Name'] == 'Riparian vegetation, dominant terrestrial vegetation type present', 'Result_Unit'] = 'Choice list: TREES|SHRUBS'
    results.loc[results['Characteristic_Name'] == 'Riparian vegetative zone width, river-right bank', 'Result_Unit'] = 'meters'
    results.loc[results['Characteristic_Name'] == 'Riparian vegetative zone width, river-left bank', 'Result_Unit'] = 'meters'
    results.loc[results['Result_Unit'] == 'mg P/L', 'Result_Unit'] = 'milliequivalents per liter' # ANC

    results['Activity_ID'] = results['Activity_ID'].str.replace('MCRN_ROCR_FEBR','NCRN_ROCR_FEBR')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRC_PRWI_BONE','NCRN_PRWI_BONE')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRC_PRWI_ORRU','NCRN_PRWI_ORRU')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_GWMP-MICR','NCRN_GWMP_MICR')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_MANA-YOBR','NCRN_MANA_YOBR')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_ROCR-PHBR','NCRN_ROCR_PHBR')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_PRWI-SORU','NCRN_PRWI_SORU')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_WORT_WOTR','NCRN_WOTR_WOTR')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_WORT_CHCK','NCRN_WOTR_CHCK')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_PWRI_ORRU','NCRN_PRWI_ORRU')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_CATO_OCWK','NCRN_CATO_OWCK')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_PWRI_SFQC','NCRN_PRWI_SFQC')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_MANA_NFQC','NCRN_PRWI_NFQC')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_PWRI_TARU','NCRN_PRWI_TARU')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_ROCK_HACR','NCRN_ROCR_R630')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_ROCR_CARU','NCRN_PRWI_CARU')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_GWMP_STCK','NCRN_NACE_STCK')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_GWMP_HECR','NCRN_NACE_HECR')
    results['Activity_ID'] = results['Activity_ID'].str.replace('NCRN_CATO_WHST','NCRN_CATO_BLBZ')

    # identify field duplicates and blank adjusted records
    results.loc[results['Activity_ID'].isin(blank_adjusted), 'Result_Type'] = 'Blank adjusted'
    results.loc[results['Activity_ID'].isin(field_duplicate), 'Result_Type'] = 'Field duplicate'
    results = results[~results['Activity_ID'].isin(acts_orphans)]

    for act in field_duplicate:
        new_act_id = act.replace('_DUP', '')
        if act == new_act_id:
            new_act_id = act.replace('-DUP', '')
        results.loc[results['Activity_ID'] == act, 'Activity_ID'] = new_act_id

    if analysis_ready == True:
        results = results.drop(results[(results['Result_Text'] == '*Not Reported')].index)
        results = results.drop(results[(results['Result_Text'] == '*Present <QL')].index)

    results = results.fillna('')

    return results

def unify_act_ids(results:pd.DataFrame, activities:pd.DataFrame):
    """Reflect the definition of a sampling activity in `Activity_ID`

    There should be a one-to-many relationship between activities.Activity_ID and results.Activity_ID in which an "activity" is defined
    as a unique combination of a place (i.e., `activities.Location_ID`) and a time (i.e., `activities.Activity_Start_Date`).
    This function renames `results.Activity_ID` to reflect the previously-described definition of an "activity" to ensure
    data integrity among `activities` and `results` tables.

    Args:
        results (pd.DataFrame): A dataframe of pre-cleaned edd results records
        activities (pd.DataFrame): A dataframe of pre-cleaned edd activities records

    Returns:
        temp_results (pd.DataFrame): A dataframe of pre-cleaned results
    """
    temp_results = results.copy()
    before_columns = []
    for column in temp_results.columns:
        before_columns.append(column)

    temp_activities = activities[['Activity_ID', 'Location_ID', 'Activity_Start_Date']]
    temp_activities["dummy"] = temp_activities["Location_ID"] + ';' + temp_activities["Activity_Start_Date"].astype(str)
    temp_activities = temp_activities[['Activity_ID', 'dummy']]
    temp_results = temp_results.merge(temp_activities, on='Activity_ID', how='left')

    del temp_results['Activity_ID']

    temp_results.rename(columns={
        'dummy': 'Activity_ID'
        },
        inplace=True)
    temp_results = temp_results[before_columns]

    return temp_results

def update_noch(results:pd.DataFrame):
    results.loc[results['Activity_ID'] == 'NCRN_PRWI_NOBR;20050613', 'Activity_ID'] = 'should_be_NCRN_PRWI_NOCH;20050613'
    results.loc[results['Activity_ID'] == 'NCRN_PRWI_NOCH;20050613', 'Activity_ID'] = 'should_be_NCRN_PRWI_NOBR;20050613'
    results.loc[results['Activity_ID'] == 'should_be_NCRN_PRWI_NOCH;20050613', 'Activity_ID'] = 'NCRN_PRWI_NOCH;20050613'
    results.loc[results['Activity_ID'] == 'should_be_NCRN_PRWI_NOBR;20050613', 'Activity_ID'] = 'NCRN_PRWI_NOBR;20050613'


import numpy as np
import cv2
import pickle
from IntegralImage import to_integral_image
def subimg(h,w , minsz, maxsi, stride):
	l = []
	for size in range(minsz,maxsi,2):
		for i in range(0,h-size,int(size/3)):
			for j in range(0,w-size,int(size/3)):
				l.append([i,j,size,size])
	return l

path = "img_51.jpg"
img = cv2.imread(path, 0)

h = img.shape[0]
w = img.shape[1]

subwindw = subimg(h,w,50,150,5)
print(len(subwindw))
model = pickle.load(open("abc", 'rb'))
l = []
for y,x,h,w in subwindw:
	v = model.predict(to_integral_image(cv2.resize(img[y:y+h, x:x+w],(24,24))))
	if v:
		# if any((y_ > y and y_ < y + h and x_ > x and x_ < x + w) or (y_ + h_ > y and y_ + h_ < y + h and x_ + w_ > x and x_ + w_ < x + w) for y_,x_,h_,w_ in l):
		# 	continue
		l.append([y,x,h,w])
		print(y,x,h,w)
		# cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
		cv2.imshow('img',img[y:y+h, x:x+w])
		cv2.waitKey(0)
		cv2.destroyAllWindows()

# cv2.imshow('img',img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()


from behave import given, when, then
import math
import json
import time

from basic_websocket import ws_connect_retry
from tetra_constants import NUMBER_OF_PATIENTS, DESCRIPTORS

@given("A running Docker image on port {port}")
def step_impl(context, port):
    context.port = port
    context.client.containers.run(context.container_tag,
                                  name=context.container_name,
                                  detach=True,
                                  auto_remove=True,
                                  ports={f"{context.port}": context.port})
    time.sleep(2.0)  # give the container a moment to start up.
    # Has a bad code smell, but it takes a second or two for things to start.
    # Even so, further listening is done in the "I listen for packets" step to
    # make sure we have good timing once everything's running

@when("I listen for packets")
def step_impl(context):
    uri = f"ws://localhost:{context.port}/ws"
    context.ws = ws_connect_retry(uri)
    context.first_message = context.ws.recv()  # triggers waiting for the first
    # message to appear, rather than sleeping for it

@then("there will be a JSON packet sent every {t:f} seconds")
def step_impl(context, t):
    number_of_messages = 5
    start_time = time.time()
    print(start_time)  # leaving in print statements for later debugging if necessary
    for _ in range(number_of_messages):
        context.message = context.ws.recv()
        print(context.message, time.time())
    end_time = time.time()
    print(end_time)
    context.json = json.loads(context.message)
    context.client.containers.get(context.container_name).kill()
    print ((end_time-start_time)/number_of_messages)
    assert math.isclose((end_time - start_time)/number_of_messages, t,
                        rel_tol=0.15), \
        "Fails to send packets at 1 Hz"

@then("that JSON packet will have several keys named with "
      "'patient-{0-index}'")
def step_impl(context):
    for i in range(NUMBER_OF_PATIENTS):
        assert f"patient-{i}" in context.json, \
            ("JSON packet doesn't have top-level keys formatted as "
             "expected.")

@then("those keys will refer to the descriptors")
def step_impl(context):
    assert all(descriptor in context.json[f"patient-{i}"]
               for i in range(NUMBER_OF_PATIENTS)
               for descriptor in DESCRIPTORS), \
        "Patient descriptors aren't formatted as expected."


from itertools import combinations

MIN = 2
MAX = 4
WORDS = ""

while 1:
    try:
        line = input()
        WORDS += line + "\n"
    except EOFError:
        break

splitted = WORDS.split( '\n' )

for i in range( MIN, MAX + 1 ):
    combs = combinations(splitted, i)
    ress = [''.join(comb) for comb in combs]
    for res in ress:
        print(res)


import visualization.visualization as vis
import pandas as pd

import numpy as np
import os

from phoneme_recognition import *
from alphsistant import *

df = pd.read_csv('./alphsistant/data/ds_weights.csv')

vertice_file_path = "../fadg0/sk/sa1"
files=os.listdir(vertice_file_path)
for i in range(0,len(files)):
    os.remove(vertice_file_path+'/'+files[i])

basis = np.loadtxt('C:/Users/Enzo.Magal/Documents/Enzo2021/AlphSistant/shape_keys_v0/Basis.txt')
jaw_open = np.loadtxt('C:/Users/Enzo.Magal/Documents/Enzo2021/AlphSistant/shape_keys_v0/jaw_open.txt')
left_eye_closed = np.loadtxt('C:/Users/Enzo.Magal/Documents/Enzo2021/AlphSistant/shape_keys_v0/left_eye_closed.txt')
mouth_open = np.loadtxt('C:/Users/Enzo.Magal/Documents/Enzo2021/AlphSistant/shape_keys_v0/mouth_open.txt')
right_eye_closed = np.loadtxt('C:/Users/Enzo.Magal/Documents/Enzo2021/AlphSistant/shape_keys_v0/right_eye_closed.txt')
smile_left = np.loadtxt('C:/Users/Enzo.Magal/Documents/Enzo2021/AlphSistant/shape_keys_v0/smile_left.txt')
smile_right = np.loadtxt('C:/Users/Enzo.Magal/Documents/Enzo2021/AlphSistant/shape_keys_v0/smile_right.txt')
smile = np.loadtxt('C:/Users/Enzo.Magal/Documents/Enzo2021/AlphSistant/shape_keys_v0/smile.txt')

for i in range(len(df)):
    if df.loc[i, 'sequence'] == 'sa1':
        y = df.loc[i, ['Basis.txt', 'jaw_open.txt', 'left_eye_closed.txt', 'mouth_open.txt', 'right_eye_closed.txt', 'smile.txt', 'smile_left.txt', 'smile_right.txt']]
        output = y[0] * basis + y[1] * jaw_open + y[2] * left_eye_closed + y[3] * mouth_open + y[4] * right_eye_closed + y[5] * smile + y[6] * smile_left + y[7] * smile_right
        np.savetxt(vertice_file_path + "/" + df.loc[i, 'frame'] + ".txt", output)

for filename in os.listdir(vertice_file_path):
        filename_we = os.path.splitext(filename)[0]
        with open(vertice_file_path + "/" + filename_we + ".obj", 'w+') as obj_file:
            obj_file.write("# obj {:s}\n\n".format(filename_we))
            obj_file.write("o {:s}\n\n".format(filename_we))
            with open(vertice_file_path + "/" + filename, 'r') as v_file:
                for v in v_file:
                    array = [float(x) for x in v.split(' ')]
                    obj_file.write("v {:.4f} {:.4f} {:.4f}\n".format(array[0], array[1], array[2]))
            obj_file.write("\n")
            with open('./alphsistant/data/alphsistant_face_tris.txt', 'r') as f_file:
                for f in f_file:
                    array = [int(float(x)) for x in f.split(' ')]
                    obj_file.write("f {:d} {:d} {:d}\n".format(array[0]+1, array[1]+1, array[2]+1))
                f_file.close()
            obj_file.close()

folder1 = "../fadg0/face_mesh/sa1"

face_path = "C:/Users/Enzo.Magal/Documents/Enzo2021/AlphSistant/alphsistant_face_tris.txt"
audio_path = "../fadg0/audio/sa1.wav"

df = phoneme_csv_creation(audio_path)
X = input_creation(df)
print("Input created")

model = torch.load('C:/Users/Enzo.Magal/Documents/Enzo2021/models/sk_model.pth')
print("Model structure: ", model, "/n\n")
y = model(X)
print("Output computed")

vertice_file_path = "./prediction"
files=os.listdir(vertice_file_path)
for i in range(0,len(files)):
    os.remove(vertice_file_path+'/'+files[i])
output_extraction(y,vertice_file_path)
print("Output extracted !")

face_file_path = "./alphsistant/data/alphsistant_face_tris.txt"

for filename in os.listdir(vertice_file_path):
    filename_we = os.path.splitext(filename)[0]
    with open("./prediction/" + filename_we + ".obj", 'w+') as obj_file:
        obj_file.write("# obj {:s}\n\n".format(filename_we))
        obj_file.write("o {:s}\n\n".format(filename_we))
        with open(vertice_file_path + "/" + filename, 'r') as v_file:
            for v in v_file:
                array = [float(x) for x in v.split(' ')]
                obj_file.write("v {:.4f} {:.4f} {:.4f}\n".format(array[0], array[1], array[2]))
        obj_file.write("\n")
        with open(face_file_path, 'r') as f_file:
            for f in f_file:
                array = [int(float(x)) for x in f.split(' ')]
                obj_file.write("f {:d} {:d} {:d}\n".format(array[0]+1, array[1]+1, array[2]+1))
            f_file.close()
        obj_file.close()

title = ('Vidéo', 'Shape Keys', 'Prédiction', 'Vidéo retargeting', 'Shape Keys retargeting', 'Prédiction retargeting')
visu = vis.Visualization(2, 3, title)

visu.update_fig(1, 1, '../fadg0/face_mesh/sa1')
visu.update_fig(1, 2, '../fadg0/sk/sa1')
visu.update_fig(1, 3, './prediction')
visu.update_fig_retargeting(2, 1, './alphsistant/data/suzanne_test/video_retargeting.yml')
visu.update_fig_retargeting(2, 2, './alphsistant/data/suzanne_test/sk_retargeting.yml')
visu.update_fig_retargeting(2, 3, './alphsistant/data/suzanne_test/prediction_retargeting.yml')

visu.animate()
visu.set_camera()
visu.afficher()


from django.contrib.gis.db import models

class StopRoute(models.Model):
    class Meta:
        db_table = "stop_route"

    stop = models.ForeignKey("mystops.Stop", on_delete=models.CASCADE)
    route = models.ForeignKey("mystops.Route", on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.stop} : {self.route}"

class Stop(models.Model):
    class Meta:
        db_table = "stop"

    id = models.AutoField(primary_key=True)

    stop_id = models.PositiveIntegerField(unique=True)

    name = models.TextField()

    direction = models.CharField(
        max_length=255,
        blank=True,
        null=True,
        choices=(
            ("eastbound", "Eastbound"),
            ("northbound", "Northbound"),
            ("southbound", "Southbound"),
            ("westbound", "Westbound"),
        ),
    )

    location = models.PointField()

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    routes = models.ManyToManyField("mystops.Route", through=StopRoute)

    def __str__(self):
        string = f"Stop {self.stop_id} -> {self.name}"
        if self.direction:
            string = f"{string} -> {self.direction}"
        return string


'''
-Easy-

Given three integer arrays arr1, arr2 and arr3 sorted in strictly increasing order,
return a sorted array of only the integers that appeared in all three arrays.

Example 1:

Input: arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]
Output: [1,5]
Explanation: Only 1 and 5 appeared in the three arrays.

Constraints:

1 <= arr1.length, arr2.length, arr3.length <= 1000
1 <= arr1[i], arr2[i], arr3[i] <= 2000
Hints
Count the frequency of all elements in the three arrays.
The elements that appeared in all the arrays would have a frequency of 3.

'''

class Solution(object):
    def arraysIntersection(self, arr1, arr2, arr3):
        """
        :type arr1: List[int]
        :type arr2: List[int]
        :type arr3: List[int]
        :rtype: List[int]
        """
        # You may notice that Approach 1 does not utilize the fact that all arrays are sorted . Indeed,
        # instead of using a Hashmap to store the frequencies, we can use three pointers p1 , p2 ,
        # and p3 to iterate through arr1 , arr2 , and arr3 accordingly:

        #Each time, we want to increment the pointer that points to the smallest number, i.e.,
        # min(arr1[p1], arr2[p2], arr3[p3]) forward;
        #if the numbers pointed to by p1 , p2 , and p3 are the same, we should then store it and
        # move all three pointers forward.
        #Moreover, we don't have to move the pointer pointing to the smallest number - we only
        # need to move the pointer pointing to a smaller number. In this case, we avoid comparing
        # three numbers and finding the smallest one before deciding which one to move. You may
        # find the rationale behind this in the Algorithm.

        #!?!../Documents/1213_Intersection_of_Three_Sorted_Arrays.json:531,198!?!

        #Algorithm

        #Initiate three pointers p1 , p2 , p3 , and place them at the beginning of arr1 , arr2 , arr3 by initializing them to 0;
        #while they are within the boundaries:
        #if arr1[p1] == arr2[p2] && arr2[p2] == arr3[p3] , we should store it because it appears three times in arr1 , arr2 , and arr3 ;
        #else
        #if arr1[p1] < arr2[p2] , move the smaller one, i.e., p1 ;
        #else if arr2[p2] < arr3[p3] , move the smaller one, i.e., p2 ;
        #if neither of the above conditions is met, it means arr1[p1] >= arr2[p2] && arr2[p2] >= arr3[p3] , therefore move p3 .

        ans = []
        # prepare three pointers to iterate through three arrays
        # p1, p2, and p3 point to the beginning of arr1, arr2, and arr3 accordingly
        p1 = p2 = p3 = 0
        while p1 < len(arr1) and p2 < len(arr2) and p3 < len(arr3):
            if arr1[p1] == arr2[p2] == arr3[p3]:
                ans.append(arr1[p1])
                p1 += 1
                p2 += 1
                p3 += 1
            else:
                if arr1[p1] < arr2[p2]:
                    p1 += 1
                elif arr2[p2] < arr3[p3]:
                    p2 += 1
                else:
                    p3 += 1
        return ans

if __name__ == "__main__":
    print(Solution().arraysIntersection(arr1 = [1,2,3,4,5], arr2 = [1,2,5,7,9], arr3 = [1,3,4,5,8]))


#!/usr/bin/env python

from os.path import join
from string import lowercase, uppercase

def compare(a, b):
    if a in lowercase and b in uppercase:
        return a.upper() == b
    elif a in uppercase and b in lowercase:
        return a.lower() == b

def part1(input):
    ls = [c for c in input]

    while True:
        i = 0
        llen = len(ls)-1
        changed = False
        while i < llen:
            if compare(ls[i], ls[i+1]):
                ls.pop(i)
                ls.pop(i)
                changed = True
                llen -= 2
            else:
                i += 1
        if not changed:
            return "".join(ls)

def part2(input):
    letters = set()
    for c in input:
        letters.add(c.lower())
    lowest = len(input)
    for w in list(letters):
        ls = [c for c in input if c not in (w, w.upper())]
        slen = len(part1(ls))
        print("removing %s: %d => %d: %d" % (w, len(input), len(ls), slen))
        if slen < lowest:
            lowest = slen
    return lowest

if __name__ == "__main__":
    input = open(join("resources", "input.txt")).read().strip()
    print(len(part1(input)))
    print(part2(input))

# eof


from __future__ import print_function, division
import warnings; warnings.filterwarnings("ignore")

from nilmtk import DataSet
import pandas as pd
import numpy as np

import datetime
import time
import math
import glob

from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
from keras.models import Sequential
from keras.callbacks import ModelCheckpoint
from keras.models import load_model
from keras.optimizers import Adam, Nadam, RMSprop
from keras.regularizers import l2
from keras.callbacks import EarlyStopping

# Bring packages onto the path
import sys, os
sys.path.append(os.path.abspath('../bayesian_optimization/'))

from utils import metrics_np
from utils.metrics_np import Metrics

def array_layers(num_layer):
    """
    function to create array to be input for build_fc_model()
    eg. array_layers(5) --> [1, 256, 512, 1024, 1]
    """
    output_array = []
    current_hidden_nodes = 256
    for i in range(1,num_layer+1):
        # first layer
        if i == 1:
            output_array.append(1)
        elif i==(num_layer):
            output_array.append(1)
        else:
            output_array.append(current_hidden_nodes)
            current_hidden_nodes *= 2
    return output_array

def build_fc_model(layers, dropout_prob=0.5):
    fc_model = Sequential()
    for i in range(len(layers)-1):
        fc_model.add( Dense(input_dim=layers[i], output_dim= layers[i+1]) )#, W_regularizer=l2(0.1)) )
        fc_model.add( Dropout(dropout_prob) )
        if i < (len(layers) - 2):
            fc_model.add( Activation('relu') )
    fc_model.summary()
    return fc_model

def fcnn(dataset_path, train_building, train_start, train_end, val_building, val_start, val_end, test_building, test_start, test_end, meter_key, sample_period, num_epochs,
                    patience,
                    num_layers,
                    optimizer,
                    learning_rate,
                    dropout_prob,
                    loss):

    # Start tracking time
    start = time.time()

    # Prepare dataset and options
    dataset_path = dataset_path
    train = DataSet(dataset_path)
    train.set_window(start=train_start, end=train_end)
    val = DataSet(dataset_path)
    val.set_window(start=val_start, end=val_end)
    test = DataSet(dataset_path)
    test.set_window(start=test_start, end=test_end)
    train_building = train_building
    val_building = val_building
    test_building = test_building
    meter_key = meter_key

    sample_period = sample_period

    train_elec = train.buildings[train_building].elec
    val_elec = val.buildings[val_building].elec
    test_elec = test.buildings[test_building].elec

    try: # REDD
        X_train = next(train_elec.mains().all_meters()[0].load(sample_period=sample_period)).fillna(0)
        y_train = next(train_elec[meter_key].load(sample_period=sample_period)).fillna(0)
        X_test = next(test_elec.mains().all_meters()[0].load(sample_period=sample_period)).fillna(0)
        y_test = next(test_elec[meter_key].load(sample_period=sample_period)).fillna(0)
        X_val = next(val_elec.mains().all_meters()[0].load(sample_period=sample_period)).fillna(0)
        y_val = next(val_elec[meter_key].load(sample_period=sample_period)).fillna(0)

        # Intersect between two dataframe - to make sure same trining instances in X and y
        # Train set
        intersect_index = pd.Index(np.sort(list(set(X_train.index).intersection(set(y_train.index)))))
        X_train = X_train.ix[intersect_index]
        y_train = y_train.ix[intersect_index]
        # Test set
        intersect_index = pd.Index(np.sort(list(set(X_test.index).intersection(set(y_test.index)))))
        X_test = X_test.ix[intersect_index]
        y_test = y_test.ix[intersect_index]
         # Val set
        intersect_index = pd.Index(np.sort(list(set(X_val.index).intersection(set(y_val.index)))))
        X_val = X_val.ix[intersect_index]
        y_val = y_val.ix[intersect_index]

        # Get values from numpy array
        X_train = X_train.values
        y_train = y_train.values
        X_test = X_test.values
        y_test = y_test.values
        X_val = X_val.values
        y_val = y_val.values
    except AttributeError: # UKDALE
        X_train = train_elec.mains().power_series_all_data(sample_period=sample_period).fillna(0)
        y_train = next(train_elec[meter_key].power_series(sample_period=sample_period)).fillna(0)
        X_test = test_elec.mains().power_series_all_data(sample_period=sample_period).fillna(0)
        y_test = next(test_elec[meter_key].power_series(sample_period=sample_period)).fillna(0)

        # Intersect between two dataframe - to make sure same trining instances in X and y
        # Train set
        intersect_index = pd.Index(np.sort(list(set(X_train.index).intersection(set(y_train.index)))))
        X_train = X_train.ix[intersect_index]
        y_train = y_train.ix[intersect_index]
        # Test set
        intersect_index = pd.Index(np.sort(list(set(X_test.index).intersection(set(y_test.index)))))
        X_test = X_test.ix[intersect_index]
        y_test = y_test.ix[intersect_index]

        # X_train = X_train.reshape(-1, 1)
        # y_train = y_train.reshape(-1, 1)
        # X_test = X_test.reshape(-1, 1)
        # y_test = y_test.reshape(-1, 1)

        # Get values from numpy array - Avoid server error
        X_train = X_train.values.reshape(-1, 1)
        y_train = y_train.values.reshape(-1, 1)
        X_test = X_test.values.reshape(-1, 1)
        y_test = y_test.values.reshape(-1, 1)

    # Model settings and hyperparameters
    layers_array = array_layers(num_layers)
    fc_model = build_fc_model(layers_array, dropout_prob)
    # adam = Adam(lr = 1e-5)
    optimizer = optimizer(lr = learning_rate)
    fc_model.compile(loss=loss, optimizer=optimizer)

    # print("========== TRAIN ============")
    #checkpointer = ModelCheckpoint(filepath="results/fcnn-model-{}-{}epochs.h5".format(meter_key, num_epochs), verbose=0, save_best_only=True)

    # Early stopping when validation loss increases
    earlystop = EarlyStopping(monitor='val_loss',
                              min_delta=0,
                              patience=patience,
                              verbose=0, mode='auto')

    hist_fc_ = fc_model.fit( X_train, y_train,
                                batch_size=512, verbose=1, nb_epoch=num_epochs,
                                validation_split=0.2, shuffle=True, callbacks=[earlystop])#  , checkpointer])

    # Get number of earlystop epochs
    num_epochs = earlystop.stopped_epoch if earlystop.stopped_epoch != 0 else num_epochs

    # print("========== DISAGGREGATE ============")
    val_pred_fc = fc_model.predict(X_val).reshape(-1)
    test_pred_fc = fc_model.predict(X_test).reshape(-1)

    # print("========== RESULTS ============")
    # me = Metrics(state_boundaries=[10])
    on_power_threshold = train_elec[meter_key].on_power_threshold()
    me = Metrics(state_boundaries=[on_power_threshold])
    val_metrics_results_dict = Metrics.compute_metrics(me, val_pred_fc, y_val.flatten())
    test_metrics_results_dict = Metrics.compute_metrics(me, test_pred_fc, y_test.flatten())

    # end tracking time
    end = time.time()

    time_taken = end-start # in seconds

    # model_result_data = {
    #     'algorithm_name': 'FCNN',
    #     'datapath': dataset_path,
    #     'train_building': train_building,
    #     'train_start': str(train_start.date()) if train_start != None else None ,
    #     'train_end': str(train_end.date()) if train_end != None else None ,
    #     'test_building': test_building,
    #     'test_start': str(test_start.date()) if test_start != None else None ,
    #     'test_end': str(test_end.date()) if test_end != None else None ,
    #     'appliance': meter_key,
    #     'sampling_rate': sample_period,
    #
    #     'algorithm_info': {
    #         'options': {
    #             'epochs': num_epochs
    #         },
    #         'hyperparameters': {
    #             'sequence_length': None,
    #             'min_sample_split': None,
    #             'num_layers': num_layers
    #         },
    #         'profile': {
    #             'parameters': None
    #         }
    #     },
    #
    #     'metrics':  metrics_results_dict,
    #
    #     'time_taken': format(time_taken, '.2f'),
    # }

    model_result_data = {
        'val_metrics':  val_metrics_results_dict,
        'test_metrics':  test_metrics_results_dict,
        'time_taken': format(time_taken, '.2f'),
        'epochs': num_epochs,
    }

    # Close Dataset files
    train.store.close()
    val.store.close()
    test.store.close()

    return model_result_data
#
# def main():
#
#     # Take in arguments from command line
#     parser = argparse.ArgumentParser(description='FCNN')
#     parser.add_argument('--datapath', '-d', type=str,  required=True,
#                         help='hd5 filepath')
#
#     parser.add_argument('--train_building', type=int, required=True)
#     parser.add_argument('--train_start', type=str, default=None, help='YYYY-MM-DD')
#     parser.add_argument('--train_end', type=str, required=True, help='YYYY-MM-DD')
#
#     parser.add_argument('--test_building', type=int, required=True)
#     parser.add_argument('--test_start', type=str, required=True, help='YYYY-MM-DD')
#     parser.add_argument('--test_end', type=str, default=None, help='YYYY-MM-DD')
#
#     parser.add_argument('--appliance', type=str, required=True)
#     parser.add_argument('--sampling_rate', type=int, required=True)
#
#     # Model specific options and hyperparameters
#     parser.add_argument('--epochs', type=int, default=50)
#     parser.add_argument('--num_layers', type=int, default=5)
#     args = parser.parse_args()
#
#     hd5_filepath = args.datapath
#     train_building = args.train_building
#     train_start = pd.Timestamp(args.train_start) if args.train_start != None else None
#     train_end = pd.Timestamp(args.train_end)
#     test_building = args.test_building
#     test_start = pd.Timestamp(args.test_start)
#     test_end = pd.Timestamp(args.test_end) if args.test_end != None else None
#     appliance = args.appliance
#     downsampling_period = args.sampling_rate
#     epochs = args.epochs
#     num_layers = args.num_layers
#
#
#     model_result_data = fcnn(
#         dataset_path=hd5_filepath,
#         train_building=train_building, train_start=train_start, train_end=train_end,
#         test_building=test_building, test_start=test_start, test_end=test_end,
#         meter_key=appliance,
#         sample_period=downsampling_period,
#         num_epochs=epochs,
#         num_layers=num_layers)
#
#     # Write options and results to file
#     with open('results/fcnn_json.json', 'a+') as outfile:
#         json.dump(model_result_data, outfile, sort_keys=True,
#                  indent=4, separators=(',', ': '))
#     print(model_result_data)
#
# if __name__ == "__main__":
#     main()
#
#     # python fcnn.py --datapath ../data/REDD/redd.h5 --train_building 1 --train_building 1 --train_end 2011-05-10 --test_building 1 --test_start 2011-05-10 --appliance fridge --sampling_rate 20 --epochs 1 --num_layers 5
#     # python fcnn.py --datapath /mnt/data/datasets/wattanavaekin/REDD/redd.h5 --train_building 1 --train_end 2011-05-10 --test_building 1 --test_start 2011-05-10 --appliance fridge --sampling_rate 20 --epochs 1 --num_layers 5


import os
from collections import namedtuple
from radical.entk import Pipeline, Stage, Task, AppManager

class DeepDriveMD:
    """
    Implements an interface for the DeepDriveMD computational
    motif presented in: https://arxiv.org/abs/1909.07817
    """
    def __init__(self, md_sims, preprocs, ml_algs, outlier_algs, resources,
                 max_iter=1, pipeline_name='MD_ML', md_stage_name='MD',
                 pre_stage_name='Preprocess', ml_stage_name='ML',
                 outlier_stage_name='Outlier'):

        """
        Parameters
        ----------
        md_sims : list
            list of DeepDriveMD.taskmanager.TaskManager objects
            which manage simulations

        preprocs : list
            list of DeepDriveMD.taskmanager.TaskManager objects
            which manage data preprocessing

        ml_algs : list
            list of DeepDriveMD.taskmanager.TaskManager objects
            which manage representation learning

        outlier_algs : list
            list of DeepDriveMD.taskmanager.TaskManager objects
            which manage outlier detection

        resources : dict
            Configuration settings for running on Summit

        max_iter : int
            Max number of iterations through the pipeline

        pipeline_name : str
            Name of computational pipeline

        md_stage_name : str
            Name of MD stage

        pre_stage_name : str
            Name of preprocessing stage

        ml_stage_name : str
            Name of ML stage

        outlier_stage_name : str
            Name of outlier detection stage

        """
        # Checks environment variables are set
        self._validate_environment()

        # Number of iterations through the pipeline
        self.current_iter = 0
        self.max_iter = max_iter

        # Neatly stores stage name and taskmanagers
        StageData = namedtuple('StageData', ['name', 'taskmanagers'])

        # Dictionary storing name and taskmanagers for each stage
        self.stages = {'md': StageData(md_stage_name, md_sims),
                       'preprocess': StageData(pre_stage_name, preprocs),
                       'ml': StageData(ml_stage_name, ml_algs),
                       'outlier': StageData(outlier_stage_name, outlier_algs)}

        # Initialize pipeline
        self.__pipeline = Pipeline()
        self.__pipeline.name = pipeline_name

        # Sets pipeline stages
        self._pipeline()

        # Create Application Manager
        self.appman = AppManager(hostname=os.environ.get('RMQ_HOSTNAME'),
                                 port=int(os.environ.get('RMQ_PORT')))

        # Assign hardware resources to application
        self.appman.resource_desc = resources

        # Assign the workflow as a set of Pipelines to the Application Manager. In
        # this way, all the pipelines in the set will execute concurrently.
        self.appman.workflow = {self.__pipeline}

    def run(self):
        """
        Effects
        -------
        Runs the Application Manager.

        """
        self.appman.run()

    def _validate_environment(self):
        if not os.environ.get('RADICAL_ENTK_VERBOSE'):
            os.environ['RADICAL_ENTK_REPORT'] = 'True'

        # All envars must be set prior
        envars = ['RMQ_HOSTNAME', 'RMQ_PORT', 'RADICAL_PILOT_DBURL',
                  'RADICAL_PILOT_PROFILE', 'RADICAL_ENTK_PROFILE']

        for envar in envars:
            if not os.environ.get(envar):
                raise Exception(f'{envar} environment variable not set')

    def _generate_stage(self, stage_type):
        """
        Parameters
        ----------
        stage_type : str
            key into self.stages dictionary to retrieve stage name and taskmanagers.
        """
        stage = Stage()
        stage.name = self.stages[stage_type].name
        for taskman in self.stages[stage_type].taskmanagers:
            stage.add_tasks(set(taskman.tasks(self.current_iter)))
        return stage

    def _condition(self):
        if self.current_iter < self.max_iter:
            self._pipeline()
        print('Done')

    def _pipeline(self):
        """
        Effects
        -------
        Adds stages to pipeline.

        """
        if self.current_iter:
            print(f'Finished pipeline iteration {self.current_iter} of {self.max_iter}')

        # Add the first three stages to the pipeline
        for stage_type in ['md', 'preprocess', 'ml']:
            self.__pipeline.add_stages(self._generate_stage(stage_type))

        # Generate last stage seperate to add post execution step
        last_stage = self._generate_stage('outlier')

        # Set post execution for last stage
        last_stage.post_exec = self._condition

        self.current_iter += 1

        self.__pipeline.add_stages(last_stage)


from tkinter import *
import os.path

root = Tk()
root.geometry("500x250")
root.config(bg="#6D9886")
save_path = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')

file_name = "data.txt"

completeData = os.path.join(save_path, file_name)

# Accept Text After Submit Button

def getvals():
    # This function is invoked when button `submit` is clicked
    with open(completeData, 'w') as file:
        file.write(namevalue.get()),
        file.write('\n'),
        file.write(surnamevalue.get()),
        file.write('\n'),
        file.write(phonevalue.get()),
        file.write('\n'),
        file.write(adressvalue.get()),
        file.write('\n'),
        file.write(emailvalue.get())
    print("Accepted")

# Heading
Label(root, text="Please Enter Your Information Bellow", font="ar 15 bold", bg="#6D9886", fg="white").grid(row=0,
                                                                                column=3)

# Field Name
name = Label(root, text="Name", bg="#6D9886", fg="white", font="ar 12 bold")
surname = Label(root, text="Surname", bg="#6D9886", fg="white", font="ar 12 bold")
phone = Label(root, text="Phone", bg="#6D9886", fg="white", font="ar 12 bold")
adress = Label(root, text="Adress", bg="#6D9886", fg="white", font="ar 12 bold")
email = Label(root, text="Email", bg="#6D9886", fg="white", font="ar 12 bold")

# Packing Fields
name.grid(row=1, column=2)
surname.grid(row=2, column=2)
phone.grid(row=3, column=2)
adress.grid(row=4, column=2)
email.grid(row=5, column=2)

# Variable for Storing data
namevalue = StringVar()
surnamevalue = StringVar()
phonevalue = StringVar()
adressvalue = StringVar()
emailvalue = StringVar()
checkvalue = IntVar()

# Creating Entry Field
nameentry = Entry(root, textvariable=namevalue, width=30, fg="black", bg="#CEE5D0", font="italic 12")
surnameentry = Entry(root, textvariable=surnamevalue, width=30, fg="black", bg="#CEE5D0", font="italic 12")
phoneentry = Entry(root, textvariable=phonevalue, width=30, fg="black", bg="#CEE5D0", font="italic 12")
adressentry = Entry(root, textvariable=adressvalue, width=30, fg="black", bg="#CEE5D0", font="italic 12")
emailentry = Entry(root, textvariable=emailvalue, width=30, fg="black", bg="#CEE5D0", font="italic 12")

# Packing Entry Fields
nameentry.grid(row=1, column=3)
surnameentry.grid(row=2, column=3)
phoneentry.grid(row=3, column=3)
adressentry.grid(row=4, column=3)
emailentry.grid(row=5, column=3)

# Creating CheckBox
checkbtn = Checkbutton(text="Remember Text?", variable=checkvalue, fg="white", bg="#6D9886", font="italic 10 bold")
checkbtn.grid(row=8, column=3)

# Submit Button
Button(root, text="Submit", bg="#6D9886", fg="white", command=getvals).grid(row=9, column=3)

root.mainloop()


#python3
from itertools import product

class EnergyInf:
	def __init__(self):
		self.n = int(input())
		self.A = [list(map(float, input().split())) for _ in range(self.n)]
		self.pivot_col, self.pivot_row = 0, 0
		self.result = [0] * self.n

	# def __init__(self, lines):
	# 	self.n = int(lines[0])
	# 	self.A = [list(map(float, line.split())) for line in lines[1:]]
	# 	self.pivot_row = 0
	# 	self.pivot_col = 0
	# 	self.result = [0] * self.n

	def swap_rows(self):
		# print('swapping rows:', self.pivot_row, self.pivot_col)
		if self.A[self.pivot_row][self.pivot_col] == 0:
			row_range = range(self.pivot_row, self.n)
			col_range = range(self.pivot_col, self.n)
			for i, j in product(row_range, col_range):
				# print(j, i)
				if self.A[j][i] != 0:
					self.A[self.pivot_row], self.A[j] = self.A[j], self.A[self.pivot_row]
					# print('break')
					# print(self.A)
					self.pivot_col = i
					break

	def gaussian_elimination(self):
		while self.pivot_col < self.n and self.pivot_row < self.n:
			self.swap_rows()
			row = self.A[self.pivot_row]
			if row[self.pivot_col] != 1:
				factor = row[self.pivot_col]
				for i in range(self.pivot_col, self.n + 1):
					row[i] /= factor

			for row_ in self.A[self.pivot_row + 1:]:
				if row_[self.pivot_col] == 0:
					continue
				factor = -row_[self.pivot_col]
				for i in range(self.pivot_col, self.n + 1):
					row_[i] += factor * row[i]
			# print(self.A)
			self.pivot_row += 1
			self.pivot_col += 1

	def solve_eqs(self):
		if not self.result:
			return

		self.gaussian_elimination()
		# print(self.A)

		self.result[-1] = self.A[-1][-1] / self.A[-1][-2]
		for i in reversed(range(self.n - 1)):
			sum_ = sum([self.A[i][j] * self.result[j] for j in range(i + 1, self.n)])
			self.result[i] = (self.A[i][-1] - sum_) / self.A[i][i]

		for val in self.result:
			print('{:.6f}'.format(val), end=' ')

if __name__ == '__main__':
# 	lines = '''4
# 0 0 1 0 2
# 1 0 0 0 0
# 0 0 0 1 1
# 0 1 0 0 6'''.split('\n')
# 	energy_solver = EnergyInf(lines)

	energy_solver = EnergyInf()
	energy_solver.solve_eqs()