"""Copy management entries from CSCAP to TD"""
import gdata.spreadsheets.data
import isudatateam.cscap_utils as util

CSCAP_ID = "1CdPi6IEnO3T35t-OFQajKYzFLpu7hwOaWdL2FG1_kVA"
TD_ID = "1m797EoMbtAvasqum-pB5ykVMeHsGWwcVvre8MbvE-xM"

sprclient = util.get_spreadsheet_client(util.get_config())

cscap_spread = util.Spreadsheet(sprclient, CSCAP_ID)
cscap_spread.get_worksheets()
td_spread = util.Spreadsheet(sprclient, TD_ID)
td_spread.get_worksheets()

WANTED = {"SERF": "SERF_IA", "DPAC": "DPAC", "STJOHNS": "STJOHNS"}

def get_cscap_sheet(sheetname):
    sheet = cscap_spread.worksheets[sheetname]
    return sheet.get_list_feed()

def get_td_sheet(sheetname):
    sheet = td_spread.worksheets[sheetname]
    return sheet.get_list_feed()

def one2one(inname, outname, operations):
    sheetin = get_cscap_sheet(inname)
    for entry in sheetin.entry:
        d = entry.to_dict()
        if (
            d["uniqueid"] not in WANTED
            or d.get("operation", "all") not in operations
        ):
            continue
        entry = gdata.spreadsheets.data.ListEntry()
        for key in d.keys():
            entry.set_value(key, d[key])
        entry.set_value("uniqueid", WANTED[d["uniqueid"]])
        entry.set_value("calendaryear", d["cropyear"])
        sprclient.add_list_entry(
            entry, TD_ID, td_spread.worksheets[outname].id
        )

def do_notes():
    spread = util.Spreadsheet(
        sprclient, "1tQvw-TQFtBI6xcsbZpaCHtYF7oKZEXNXy-CZHBr8Lh8"
    )
    sheet = spread.worksheets["Research Site Metadata"]
    for entry in sheet.get_list_feed().entry:
        d = entry.to_dict()
        if d["uniqueid"] not in WANTED:
            continue
        for year in range(2011, 2016):
            entry = gdata.spreadsheets.data.ListEntry()
            entry.set_value("uniqueid", WANTED[d["uniqueid"]])
            entry.set_value("calendaryear", str(year))
            entry.set_value("cropyear", str(year))
            entry.set_value("notes", d["notes%s" % (year,)])
            entry.set_value("editedby", "akrherz@gmail.com")
            entry.set_value("updated", "4/20/2016 14:00")
            sprclient.add_list_entry(
                entry, TD_ID, td_spread.worksheets["Notes"].id
            )

if __name__ == "__main__":
    # do_notes()
    # one2one('Field Operations', 'Soil & Fert', ['fertilizer_synthetic',
    #                                            'soiladmend_lime'])
    # one2one('Field Operations', 'Plant & Harvest',
    #        ['harvest_corn', 'harvest_other', 'harvest_soy', 'harvest_wheat',
    #         'plant_corn', 'plant_other', 'plant_rye', 'plant_rye-corn-res',
    #         'plant_rye-soy-res', 'plant_soy', 'plant_wheat'])
    # one2one('Management', 'Residue Mngt', ['all'])
    # one2one('Pesticides', 'Pesticides', ['herbicide', ])
    one2one(
        "DWM",
        "DWM",
        [
            "all",
        ],
    )


#! /usr/bin/env python3
# written by Matthias Schmal
# distributed under GNU GPLv3
# trains and evaluates a CPAT model

# import required libraries and modules
import argparse
import subprocess
import custom_functions as cf

from sklearn.model_selection import KFold

# generate parser to read in different arguments
parser = argparse.ArgumentParser()
parser.add_argument('--coding', '-c', help='give sequence file in fasta format for coding sequences')
parser.add_argument('--noncoding', '-n', help='give sequence file in fasta format for noncoding sequences')
parser.add_argument('--cpc-coding', '-cpc', help='give sequence file in fasta format for cpc test set')
parser.add_argument('--test-coding', '-ct', help='give sequence file in fasta format for test sequences')
parser.add_argument('--test-noncoding', '-nt', help='give sequence file in fasta format for test sequences')
parser.add_argument('--cod-cod-ids', '-cc', help='give file with ids of predicted coding transcripts of coding RNAs')
parser.add_argument('--non-cod-ids', '-nc', help='give file with ids of predicted noncoding transcripts of coding RNAs')
parser.add_argument('--cod-non-ids', '-cn', help='give file with ids of predicted coding transcripts of noncoding RNAs')
parser.add_argument('--non-non-ids', '-nn', help='give file with ids of predicted noncoding transcripts of noncoding RNAs')
parser.add_argument('--outname', '-o', help='give prefix for filenames generated')
parser.add_argument('--weight', '-w', help='give weight for false-positive rate')
args = parser.parse_args()

# read in data from arguments
train_cod = cf.fasta_reader(args.coding)
train_cpc_cod = cf.fasta_reader(args.cpc_coding)
train_noncod = cf.fasta_reader(args.noncoding)

# initialize arrays for later use
cc_ids = []
nc_ids = []
cn_ids = []
nn_ids = []
cutoff = []

# read in trnascript IDs from CPC2 output
with open(args.cod_cod_ids) as file:
    for line in file:
        cc_ids.append(">"+line.strip())

with open(args.non_cod_ids) as file:
    for line in file:
        nc_ids.append(">"+line.strip())

with open(args.cod_non_ids) as file:
    for line in file:
        cn_ids.append(">"+line.strip())

with open(args.non_non_ids) as file:
    for line in file:
        nn_ids.append(">"+line.strip())

# generate tuples of fasta header and sequence
cc = [(x,train_cpc_cod[x]) for x in cc_ids]
nc = [(x,train_cpc_cod[x]) for x in nc_ids]
cn = [(x,train_noncod[x]) for x in cn_ids]
nn = [(x,train_noncod[x]) for x in nn_ids]
train_cod = list(train_cod.items())

# merge nn and nc to generate one dataset of predicted noncoding RNAs
nn += nc

# write files for final training set
cf.list_fasta_writer(cc, args.outname + "_cc.fna")
cf.list_fasta_writer(nc, args.outname + "_nc.fna")
cf.list_fasta_writer(cn, args.outname + "_cn.fna")
cf.list_fasta_writer(nn, args.outname + "_nn.fna")

# create balanced training set
if (len(nn) >= len(train_cod)):
    nn = nn[:len(train_cod)]
else:
    train_cod = train_cod[:len(nn)]

# perform 10-fold cross-validation to determine optimal cutoff according to weighted Youden's Index
direc = args.outname+"_roc_curves"
subprocess.run(["mkdir", direc])
iter = 1
kf = KFold(n_splits=10, shuffle=True)
# train and evaluate for each split
for train, test in kf.split(nn):
    train_noncod_trans = [nn[i] for i in train]
    train_cod_trans = [train_cod[i] for i in train]
    test_noncod_trans = [nn[i] for i in test]
    test_cod_trans = [train_cod[i] for i in test]
    cf.list_fasta_writer(train_noncod_trans, "train_noncod_trans.fasta")
    cf.list_fasta_writer(test_noncod_trans, "test_noncod_trans.fasta")
    cf.list_fasta_writer(train_cod_trans, "train_cod_trans.fasta")
    cf.list_fasta_writer(test_cod_trans, "test_cod_trans.fasta")

    with open("hexamer.tsv", "w+") as file:
        subprocess.run(["make_hexamer_tab.py", "-c", "train_cod_trans.fasta", "-n", "train_noncod_trans.fasta"], stdout=file)

    subprocess.run(["make_logitModel.py", "-x", "hexamer.tsv", "-c", "train_cod_trans.fasta", "-n", "train_noncod_trans.fasta", "-o", "train"])

    subprocess.run(["cpat.py", "-x", "hexamer.tsv", "-d", "train.logit.RData", "--top-orf=5", "--min-orf=24", "--antisense", "-g", "test_cod_trans.fasta", "-o", "cod_genes"])
    subprocess.run(["cpat.py", "-x", "hexamer.tsv", "-d", "train.logit.RData", "--top-orf=5", "--min-orf=24", "--antisense", "-g", "test_noncod_trans.fasta", "-o", "noncod_genes"])

    cutoff.append(cf.find_cutoff("cod_genes.ORF_prob.best.tsv", "noncod_genes.ORF_prob.best.tsv", float(args.weight), iter, direc))

    iter += 1

# write file with calculated cutoff as well as ROC auc-score for each iteration
with open(args.outname+"_cutoff_data.tsv", 'w+') as file:
    file.write("number\tcutoff\tauc_score\n")
    for i, split in enumerate(cutoff):
        file.write("Iteration"+str(i)+"\t"+str(split[0]) +"\t" + str(split[1]) + "\n")
    file.write("mean\t" + str(sum([x[0] for x in cutoff])/len(cutoff)) + "\t"+ str(sum([x[1] for x in cutoff])/len(cutoff)))

# do final training with complete dataset
with open(args.outname + "_hexamer.tsv", "w+") as file:
    subprocess.run(["make_hexamer_tab.py", "-c", args.coding, "-n", args.noncoding], stdout=file)

subprocess.run(["make_logitModel.py", "-x", args.outname + "_hexamer.tsv", "-c", args.coding, "-n", args.noncoding, "-o", args.outname])

subprocess.run(["cpat.py", "-x", args.outname + "_hexamer.tsv", "-d", args.outname + ".logit.RData", "--top-orf=5", "--min-orf=0", "--antisense", "-g", args.test_coding, "-o", args.outname+"_coding"])
subprocess.run(["cpat.py", "-x", args.outname + "_hexamer.tsv", "-d", args.outname + ".logit.RData", "--top-orf=5", "--min-orf=0", "--antisense", "-g", args.test_noncoding, "-o", args.outname+"_noncoding"])


from PySide2 import QtWidgets

class GoalLabel(QtWidgets.QLabel):
    """Convenience class for describing the goal
    number of photos per person.
    """

    def __init__(self):
        super().__init__()
        sizePolicy: QtWidgets.QSizePolicy = self.sizePolicy()
        sizePolicy.setVerticalPolicy(QtWidgets.QSizePolicy.Maximum)
        self.setSizePolicy(sizePolicy)
        self.setToolTip(
            "Drag and drop transects from one person to another"
            " to create the perfect balance among your team.\n"
            " In an ideal world, all members would have the same number"
            " of photos to go through.\nHowever, since the photos are grouped"
            " by transect, this is a rare outcome."
        )
        self.setStyleSheet(
            "GoalLabel { font-weight: bold; text-decoration: underline; }"
            "QToolTip { font-weight: normal }"
        )

    def setGoal(self, goal: float):
        self.setText(f"The target number of photos per person is {round(goal, 1)}.")


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 19 12:52:12 2022

@author: trinath
"""
from pathlib import Path
import os
import re
from collections import Counter
import nltk
nltk.download('stopwords')
from nltk.corpus import stopwords

def BOW(dataset,trainORtest):
    dataset_path= Path(Path.cwd(),dataset)
    if (trainORtest=='train'):
        dataset_path=Path(dataset_path,'train')
    else:
        dataset_path=Path(dataset_path,'test')

    spam_path=Path(dataset_path, 'spam')
    ham_path=Path(dataset_path, 'ham')
    spam_files=[]
    ham_files=[]
    no_of_spamfiles=0
    no_of_hamfiles=0
    no_of_totalfiles=0

    for file in os.listdir(spam_path):
    # check only text files
        if file.endswith('.txt'):
            spam_files.append(Path(spam_path,file))
            no_of_spamfiles+=1

    for file in os.listdir(ham_path):
    # check only text files
        if file.endswith('.txt'):
            ham_files.append(Path(ham_path,file))
            no_of_hamfiles+=1

    no_of_totalfiles=no_of_hamfiles+no_of_spamfiles

    #print(no_of_totalfiles)

    spam_data=[]
    ham_data=[]
    total_data=""
    for i in spam_files:
        spam_data.append(open(i, "r", encoding='utf-8', errors='ignore').read())
        total_data=total_data+" "+open(i, "r", encoding='utf-8', errors='ignore').read()

    for i in ham_files:
        ham_data.append(open(i, "r", encoding='utf-8', errors='ignore').read())
        total_data=total_data+" "+open(i, "r", encoding='utf-8', errors='ignore').read()

    #Vocabulary of total data
    Vocab={}
    Vocab_freq={}
    allWords = re.findall("[a-zA-Z]+", total_data)

    #set of words that doesn't contribute to classification
    stopword = set(stopwords.words('english'))

    for w in allWords:
        w = w.lower()
        if (w not in Vocab) and (w not in stopword):
            Vocab[w] = 0
        if w in Vocab_freq and (w not in stopword):
            Vocab_freq[w] = Vocab_freq[w] + 1
        else:
            if w not in stopword:
                Vocab_freq[w] = 1

    spam_bow = []
    spam_allwords_freq = {}
    for mail in spam_data:
        t = dict(Vocab)
        words_mail = re.findall("[a-zA-Z]+", mail)

        for w in words_mail:
            w = w.lower()
            if w not in stopword:
                t[w] = t[w] + 1

        spam_allwords_freq = Counter(spam_allwords_freq) + Counter(t)
        spam_bow.append(t)

    ham_allwords_freq = {}
    ham_bow = []
    for mail in ham_data:

        temp1 = dict(Vocab)
        words_mail = re.findall("[a-zA-Z]+", mail)
        for word in words_mail:
            word = word.lower()
            if word not in stopword:
                temp1[word] = temp1[word] + 1

        ham_allwords_freq = Counter(ham_allwords_freq) + Counter(temp1)
        ham_bow.append(temp1)

    return spam_bow, ham_bow, Vocab_freq, spam_allwords_freq, ham_allwords_freq, no_of_totalfiles, no_of_spamfiles, no_of_hamfiles, Vocab


import pathlib
import tempfile
from typing import Dict, List, Optional

import tensorflow as tf

def save_model(
    path: pathlib.Path,
    model: tf.keras.Model,
    labels_vocab: List[str],
    serving_func: tf.function = None,
    serving_func_kwargs: Optional[Dict] = None,
    **kwargs,
):
    """
    Save the model and labels, with an optional custom serving function.

    Parameters
    ----------
    path: pathlib.Path
        Path where the model will be saved.

    model: tf.keras.Model
        Keras model instance to be saved.

    labels_vocab: List[str]
        Label vocabulary.

    serving_func: tf.function, optional
        Custom serving function.
        If passed, `serving_func` will be the default endpoint in tensorflow serving.

    **kwargs: dict, optional
        Additional keyword arguments passed to `tf.keras.Model.save`.
    """
    tmp_dir = tempfile.TemporaryDirectory()
    labels_path = pathlib.Path(tmp_dir.name).joinpath("labels_vocab.txt")
    with labels_path.open("w") as w:
        w.writelines([f"{label}\n" for label in labels_vocab])
    model.labels_file = tf.saved_model.Asset(str(labels_path))

    signatures = None
    if serving_func:
        serving_func_kwargs = serving_func_kwargs or {}
        concrete_func = serving_func.get_concrete_function(
            model, model.save_spec(), **serving_func_kwargs
        )
        signatures = {"serving_default": concrete_func}

    model.save(str(path), signatures=signatures, **kwargs)

    # must occur after model.save, so Asset source is still around for save
    tmp_dir.cleanup()

def load_model(path: pathlib.Path, **kwargs):
    """
    Load the model and labels.

    Parameters
    ----------
    path: pathlib.Path
        Path to the saved model.

    **kwargs: dict, optional
        Additional keyword arguments passed to `tf.keras.models.load_model`.

    Returns
    -------
    (tf.keras.Model, List[str])
        Model and labels.
    """
    model = tf.keras.models.load_model(str(path), **kwargs)
    labels_file = model.labels_file.asset_path.numpy()
    labels = open(labels_file).read().splitlines()
    return model, labels


"""
@author: Riccardo Soldini
"""

import math,pprint
import FreeCAD,Part
import g2
import makEasy
from FreeCAD import Placement,Rotation

POSSIBLE_THK=[1.0,1.5,2.0,2.5,3.0,4.0,5.0,6.0,8.0,10.0,12.0,15.0,20.0,25.0,30.0,35.0,40.0]

class FCObject(object):
    def __init__(self,FCObj=None,):
        self.FCObj=FCObj
        self.Faces={}
        self.FacesMap={}
        self.Weight=round(FCObj.Shape.Volume*0.0000079,1)
        self.PartName='indefinito'
        self.Classified=False
        self.meItem=None

    def parse(self):
        self.Faces=self.FCObj.Shape.Faces
        self.FacesByArea=get_faces_by_area(self.Faces)
        self.FaceRoot=self.FacesByArea[sorted(self.FacesByArea,reverse=True)[:1][0]][0]
        self._getFacesMap()
        self._setEightBiggerFaces()
        self.FacesTree=build_faces_tree(self.Faces,self.FacesMap['Faces'])
        #self.FacesTree=build_faces_tree(self.FacesMap['Faces'])
        ### costruire facemap qui ???

    def _setEightBiggerFaces(self):
        self.EightBiggerFaces=[]
        eight_top_areas=sorted(self.FacesByArea,reverse=True)[:8]
        count=0
        index=0
        while (count<8) and (index<len(eight_top_areas)):
           for i in range (0,len(self.FacesByArea[eight_top_areas[index]])):
               self.EightBiggerFaces.append(self.FacesByArea[eight_top_areas[index]][i])
               count+=1
           index+=1

    def _getThickness(self):
        thk=0
        same_geometry=False
        group=list(self.EightBiggerFaces)

        if (group[0] in self.FacesTree['Plane']) and (group[1] in self.FacesTree['Plane']):
            f1=self.FacesTree['Plane'][group[0]]
            f2=self.FacesTree['Plane'][group[1]]
            same_geometry=True
        if (group[0] in self.FacesTree['Cylinder']) and (group[1] in self.FacesTree['Cylinder']):
            f1=self.FacesTree['Cylinder'][group[0]]
            f2=self.FacesTree['Cylinder'][group[1]]
            same_geometry=True

        if same_geometry:
            thk=round(f1.distToShape(f2)[0],1)

        if thk in POSSIBLE_THK:
            self.Thk=thk
            print('... thickness is ',self.Thk)

    def _getAnyBends(self):
        c_surf=list(self.FacesTree['Cylinder'])
        self.BendedFaces=[]
        self.NumberOfBend=0
        while len(c_surf)>0:
            s1=c_surf.pop(0)
            not_found=True
            ind=0
            while ind<len(c_surf) and not_found:
                c1=self.FacesTree['Cylinder'][s1]
                c2=self.FacesTree['Cylinder'][c_surf[ind]]
                bend_thk=round(c1.distToShape(c2)[0],2)
                cc1=c1.Surface.Axis
                cc2=c2.Surface.Axis
                eqX=round(abs(cc1.x), 4)==round(abs(cc2.x), 4)
                eqY=round(abs(cc1.y), 4)==round(abs(cc2.y), 4)
                eqZ=round(abs(cc1.z), 4)==round(abs(cc2.z), 4)
                equal_center= eqX and eqY and eqZ
                if (equal_center) and (abs(bend_thk)==self.Thk):
                    self.NumberOfBend+=1
                    not_found=False
                    self.BendedFaces.append([s1,c_surf[ind]])
                ind+=1
        print('... found ',self.NumberOfBend,' bend')

    def _getFacesMap(self):
        self.FacesMap=faces_map(self.Faces,self.FaceRoot)

    def _isHProfile(self):
        result=False
        return result

    def _isRectTube(self):
        result=False
        return result

    def _isCommonComponent(self,comm_comp):
        result=False
        for c in comm_comp:
            if c in self.FCObj.Label:
              self.PartName=comm_comp[c]['name']
              self.Classified=True
              self.meItem=makEasy.Item(Id=self.PartName)
              result=True
        return result

def normalized_degrees(angle):
     accuracy=7
     a=math.degrees(round(angle,accuracy))
     n=a-int(a/360)*360
     if n<0:n=n+360
     return n

def angle_between_planes(face1,face2):
    vns1 = face1.normalAt(0,0)
    vns2 = face2.normalAt(0,0)
    alpha = math.degrees( vns1.getAngle( vns2 ) )
    print ('angle between faces:',alpha)
    return alpha

def align_face_to_Zplane(face):
    vns1 = FreeCAD.Vector(0,1,0)
    n=face.normalAt(0,0)
    if abs(n.z)!=1.0:
        vns2 = FreeCAD.Vector(n.x,n.y,0).normalize()
        alpha = math.degrees( vns1.getAngle( vns2 ))
        face.rotate(FreeCAD.Vector(0,0,0),FreeCAD.Vector(0,0,1),alpha)
        #print ('angle to YZ plane:',alpha)
    vns1 = FreeCAD.Vector(0,0,1)
    n=face.normalAt(0,0)
    if abs(n.x)!=1.0:
        vns2 = FreeCAD.Vector(0,n.y,n.z).normalize()
        alpha = math.degrees( vns1.getAngle( vns2 ))
        face.rotate(FreeCAD.Vector(0,0,0),FreeCAD.Vector(1,0,0),alpha)
        #print ('angle to ZX plane:',alpha)
    return face

def angle_to_Z(face):
    vns1 = FreeCAD.Vector(0,0,1)
    vns2 = face.normalAt(0,0)
    alpha = math.degrees( vns1.getAngle( vns2 ))
    print ('angle to Z axis:',alpha)
    return round(alpha,6)

def angle_to_Y(face):
    vns1 = FreeCAD.Vector(0,1,0)
    vns2 = face.normalAt(0,0)
    alpha = math.degrees( vns1.getAngle( vns2 ))
    print ('angle to Y axis:',alpha)
    return round(alpha,6)

def angle_to_X(face):
    vns1 = FreeCAD.Vector(1,0,0)
    vns2 = face.normalAt(0,0)
    alpha = math.degrees( vns1.getAngle( vns2 ))
    print ('angle to X axis:',alpha)
    return round(alpha,6)

def is_edges_parallels(edge1,edge2):
    result=False
    d1=edge1.Curve.Direction
    d2=edge2.Curve.Direction
    print (d1)
    print (d2)
    if abs(d1.x)==abs(d2.x) and abs(d1.y)==abs(d2.y) and abs(d1.z)==abs(d2.z):
        print ('paralleli')
        result=True
    return result

def get_parallel_edges(face):
    e_list=[]
    for i in range(0,len(face.OuterWire.Edges)):
        found=False
        e=face.OuterWire.Edges[i]
        for c in e_list:
           if is_edges_parallels(e,face.OuterWire.Edges[c[0]]):
               c.append(i)
               found=True
        if not found:
            e_list.append([i])

    dist={}
    for pe in e_list:
        if len(pe)>1:
            e1=face.OuterWire.Edges[pe.pop(0)]
            p1=g2.Point(e1.Vertexes[0].X,e1.Vertexes[0].Y)
            p2=g2.Point(e1.Vertexes[1].X,e1.Vertexes[1].Y)
            l1=g2.Line(p1,p2)
            for e in pe:
                e2=face.OuterWire.Edges[e]
                p1=g2.Point(e2.Vertexes[0].X,e2.Vertexes[0].Y)
                p2=g2.Point(e2.Vertexes[1].X,e2.Vertexes[1].Y)
                l2=g2.Line(p1,p2)
                print(l1)
                print(l2)

    return dist

def get_box_dimensions(obj):
    bb=obj.Shape.BoundBox
    return [round(bb.XLength,2),round(bb.YLength,2),round(bb.ZLength,2)]

def get_faces_by_area(faces,scope=None):
   if scope==None: scope=[*range(0,len(faces))]
   faces_by_area={}
   for i in scope:
      area=faces[i].Area
      if area in faces_by_area:
          faces_by_area[area].append(i)
      else:
          faces_by_area[area]=[i]
   return faces_by_area

def build_faces_tree(faces,scope=None):
    if scope==None: scope=[*range(0,len(faces))]
    faces_tree={"Plane":{},
                "Cylinder":{},
                "Cone":{}}
    ### Build faces's tree
    for i in scope:
       str_face=faces[i].Surface.__str__()
       if str_face=="<Cylinder object>":
           faces_tree['Cylinder'][i]=faces[i]
       elif str_face=="<Plane object>":
           faces_tree['Plane'][i]=faces[i]
       elif str_face=="<Cone object>":
           faces_tree['Cone'][i]=faces[i]
    return faces_tree

def is_planes_parallels(face1,face2):

    def plane_from_3points(p1,p2,p3):

       M=[float(p2.X-p1.X),float(p2.Y-p1.Y),float(p2.Z-p1.Z),
          float(p3.X-p1.X),float(p3.Y-p1.Y),float(p3.Z-p1.Z)]
       K=[M[1]*M[5]-M[2]*M[4],
          M[2]*M[3]-M[0]*M[5],
          M[0]*M[4]-M[1]*M[3]]
       P=[K[0],K[1],K[2],-(K[0]*p1.X+K[1]*p1.Y+K[2]*p1.Z)]
       return P

    result=False
    v1=face1.OuterWire.Vertexes
    p1=plane_from_3points(v1[0],v1[1],v1[2])

    v2=face2.OuterWire.Vertexes
    p2=plane_from_3points(v2[0],v2[1],v2[2])

    n=p1[0]*p2[0]+p1[1]*p2[1]+p1[2]*p2[2]
    sq1=math.sqrt(p1[0]**2+p1[1]**2+p1[2]**2)
    sq2=math.sqrt(p2[0]**2+p2[1]**2+p2[2]**2)
    if sq1*sq2!=0.0:
        cosP=n/(sq1*sq2)
    else:
        cosP=0
    #print 'cosP:',cosP
    if abs(cosP)==1: result=True

    return result

def faces_map(faces,root):
    #id_root=self.EightBiggerFaces[0]
    num_faces=len(faces)
    group=[root]
    map={}
    count_adjacents=0
    while len(group)>0:
        index_face=group.pop(0)
        if not index_face in map:
            map[index_face]={}
            e1=faces[index_face].OuterWire.Edges
            for index_compare in range(0,num_faces):
                if index_compare!=index_face:
                    e2=faces[index_compare].OuterWire.Edges
                    for geo1 in range(0,len(e1)):
                        for geo2 in range(0,len(e2)):
                            if e1[geo1].isSame(e2[geo2]):
                                count_adjacents+=1
                                map[index_face][geo1]=[index_compare,geo2]
                                if index_compare not in group:
                                    group.append(index_compare)

    print (len(map),' linked faces found:')
    return {'Root':root,'Map':map,'Faces':list(map.keys())}

def min_faces_distance(faces,planes):
    dist=1000.0
    while len(faces)>0:
        f=faces.pop()
        for i in faces:
            d=round(planes[f].distToShape(planes[i])[0],1)
            if d<dist:dist=d
    return dist

def max_faces_distance(faces,planes):
    dist=0
    while len(faces)>0:
        f=faces.pop()
        for i in faces:
            d=round(planes[f].distToShape(planes[i])[0],1)
            if d>dist:dist=d
    return dist

def max_found_len(faces,planes):
    l=0
    for f in faces:
        for e in planes[f].OuterWire.Edges:
         if e.Length>l:
             l=e.Length
    return round(l,0)

def min_found_len(faces,planes):
    l=1000000
    for f in faces:
        for e in planes[f].OuterWire.Edges:
         if e.Length<l:
             l=e.Length
    return round(l,2)

def geos_from_face(_face):

    def indexNode(x,y):
        i=0
        notfound=True
        while (notfound) and i<len(nodes):
            if (x==nodes[i].x) and (y==nodes[i].y):
                notfound=False
                i=i-1
            i=i+1
        if notfound:
            nodes.append(g2.Point(x,y))
        return i

    # create a copy of the selected face
    face = Part.Face(_face.Wires)
    align_face_to_Zplane(face)

    edges=face.Edges
    nodes=[]
    geos=[]
    for edge in edges:
        ind_nd=0
        type_edge=type(edge.Curve).__name__
        vertexes=edge.Vertexes
        if type_edge=='GeomLineSegment'or type_edge=='Line' :
            txt='line'
            n1=indexNode(vertexes[0].X,vertexes[0].Y)
            n2=indexNode(vertexes[1].X,vertexes[1].Y)
            geos.append(['Line',n1,n2])
        elif type_edge=='GeomCircle' or type_edge=='Circle':
            if len(edge.Vertexes)==1:
                txt='circle'
                n1=indexNode(edge.Curve.Center.x,edge.Curve.Center.y)
                n2=indexNode(vertexes[0].X,vertexes[0].Y)
                geos.append(['Circle',n1,n2])
            if len(edge.Vertexes)==2:
                    txt='arc'
                    n1=indexNode(vertexes[0].X,vertexes[0].Y)
                    n3=indexNode(vertexes[1].X,vertexes[1].Y)
                    mdldgr=edge.ParameterRange[0]+(edge.ParameterRange[1]-edge.ParameterRange[0])/2
                    middle=edge.valueAt(mdldgr)
                    n2=indexNode(middle.x,middle.y)
                    geos.append(['Arc',n1,n2,n3])
        elif type_edge=="GeomEllipse":
            txt='ellipse'
            n1=indexNode(vertexes[0].X,vertexes[0].Y)
            n2=indexNode(vertexes[1].X,vertexes[1].Y)
            f1=e.Curve.Focus1
            rM=e.Curve.MajorRadius
            rm=e.Curve.MinorRadius
            #geos.append(['Ellipse',n1,n2,f1,f2,rM])????
    return dict(geos=geos,nodes=nodes)

def changeColor(object,scope,new_color):
	actual_color=object.ViewObject.DiffuseColor[0]
	num_faces=len(object.Shape.Faces)
	col_array=[actual_color]*num_faces

	for c in scope:
		col_array[c]=new_color

	object.ViewObject.DiffuseColor=col_array

def face_to_g2Shape(face):

    def indexNode(x,y):
        i=0
        notfound=True
        while (notfound) and i<len(nodes):
            if (x==nodes[i][0]) and (y==nodes[i][1]):
                notfound=False
                i=i-1
            i=i+1
        if notfound:
            nodes.append([x,y])
            all_nodes.append(g2.Point(x,y))
        return i

    copy_face = Part.Face(face.Wires)

    # align face on Z plane
    vns1 = face.normalAt(0.0,0.0)
    print ('Face normal vect: ',vns1.normalize(),'...')
    zdeg=vns1.getAngle(FreeCAD.Vector(0.0,0.0,1.0))
    print ('...Rotation degree to Z plane: ',math.degrees(zdeg),'...')
    rAxis=FreeCAD.Rotation(FreeCAD.Vector(0.0,0.0,1.0),vns1.normalize()).Axis
    rDegree=-math.degrees(zdeg)
    rCenter=copy_face.CenterOfMass
    copy_face.Placement=FreeCAD.Placement(FreeCAD.Vector(0.0,0.0,0.0),
                                     FreeCAD.Rotation(rAxis,rDegree),
                                     rCenter).multiply(copy_face.Placement)

    # find all paths
    edges=copy_face.Edges
    nodes=[]
    closed_paths={}
    geos=[]
    all_nodes=[]
    all_geos=[]

    #chains=[]
    for edge in edges:
        ind_nd=0
        type_edge=type(edge.Curve).__name__
        vertexes=edge.Vertexes
        if type_edge=='GeomLineSegment'or type_edge=='Line' :
            txt='line'
            n1=indexNode(vertexes[0].X,vertexes[0].Y)
            n2=indexNode(vertexes[1].X,vertexes[1].Y)
            geos.append(['Line',n1,n2])
        elif type_edge=='GeomCircle' or type_edge=='Circle':
            if len(edge.Vertexes)==1:
                txt='circle'
                n1=indexNode(edge.Curve.Center.x,edge.Curve.Center.y)
                n2=indexNode(vertexes[0].X,vertexes[0].Y)
                geos.append(['Circle',n1,n2])
            if len(edge.Vertexes)==2:
                    txt='arc'
                    n1=indexNode(vertexes[0].X,vertexes[0].Y)
                    n3=indexNode(vertexes[1].X,vertexes[1].Y)
                    mdldgr=edge.ParameterRange[0]+(edge.ParameterRange[1]-edge.ParameterRange[0])/2
                    middle=edge.valueAt(mdldgr)
                    n2=indexNode(middle.x,middle.y)
                    geos.append(['Arc',n1,n2,n3])
        elif type_edge=="GeomEllipse":
            txt='ellipse'
            n1=indexNode(vertexes[0].X,vertexes[0].Y)
            n2=indexNode(vertexes[1].X,vertexes[1].Y)
            f1=e.Curve.Focus1
            rM=e.Curve.MajorRadius
            rm=e.Curve.MinorRadius
            #geos.append(['Ellipse',n1,n2,f1,f2,rM])????
    while len(geos)>0:
        empty_search=False
        trovato=False
        act=geos.pop()
        chain=[act[1],act[0]]
        if act[0]=='Arc':
            chain.append(act[2])
        chain.append(act[-1])
        node_to_find=act[-1]
        while not empty_search:
            i=0
            empty_search=True
            while i<len(geos):
                if geos[i][1]==node_to_find:
                    trovato=True
                    chain.append(geos[i][0])
                    if geos[i][0]=='Arc':
                        chain.append(geos[i][2])
                    chain.append(geos[i][-1])
                    node_to_find=geos[i][-1]
                elif geos[i][-1]==node_to_find:
                    trovato=True
                    chain.append(geos[i][0])
                    if geos[i][0]=='Arc':
                        chain.append(geos[i][2])
                    chain.append(geos[i][1])
                    node_to_find=geos[i][1]
                if trovato:
                    empty_search=False
                    act=geos[i]
                    geos.pop(i)
                    trovato=False
                else:
                    i=i+1

        #chains.append(chain)
        path=g2.Path(all_nodes,chain)
        if path.isClosed:
            closed_paths[path.area]=path

    ### create shape
    areas=list(closed_paths.keys())
    outline_id=max(areas)
    shape=g2.Shape()
    shape.outline=closed_paths[outline_id]
    del(closed_paths[outline_id])
    shape.internal=[*closed_paths.values()]
    shape.update()

    return shape


###  CLIENT  ###

import address_info
from socket import *

# memorizzo le informazioni del server
server_name, server_port = address_info.get_server_name(), address_info.get_server_port()

# AF_INET -> la rete sottostante è di tipo IPv4.
# SOCK_STREAM -> il socket è di tipo UDP
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect((server_name, server_port))

# acquisisco una frase in input ..
sentence = input('frase in input: ')

# .. e la invio al server
client_socket.makefile('w').writelines(sentence + '\n')

# memorizzo la risposta del server
modified_sentence = client_socket.makefile().readline()

# stampo la risposta
print('frase in output: ', modified_sentence)

# termino la comunicazione
client_socket.close()


import os
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup
import pandas as pd
import time
from progress.bar import IncrementalBar
from pdfminer.converter import TextConverter
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfpage import PDFPage
from pdfminer.layout import LAParams
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
import io

class Converter:

    def __init__(self, pdf_path):# txt_path):
        self.pdf_path = pdf_path

    def get_text_from_pdf(self):

        resource_manager = PDFResourceManager()  # создаем resource manager
        str_file = io.StringIO()  # модуль StringIO позволяет работать со строкой как с файловым объектом
        laparams = LAParams()  # параметры по умолчанию char_margin=2.0 line_margin=0.5 word_margin=0.1
        converter = TextConverter(resource_manager, str_file, laparams=laparams)  # создаем сам конвертер
        page_interpreter = PDFPageInterpreter(resource_manager, converter)

        with open(self.pdf_path, "rb") as file:
            parser = PDFParser(file)
            try:
                PDFDocument(parser)
            except Exception as exept:
                print(self.pdf_path, 'is not a readable pdf')

            for page in PDFPage.get_pages(file, caching=True,
                                          check_extractable=True,
                                          maxpages=2):  # обрабатываем каждую страницу (max = 3)
                page_interpreter.process_page(page)

        text = str_file.getvalue()  # получаем все содержимое файла

        converter.close()
        str_file.close()   # Освождаем буфер памяти, в дальнейшем мы не сможем работать с StringIO и с TextConverter

        if text:
            return text

def pars_file(folder_location,url):
    if not os.path.exists(folder_location):os.mkdir(folder_location)
    response = requests.get(url)
    soup= BeautifulSoup(response.text, "html.parser")
    for link in soup.select("a[href$='.pdf']"):
        filename = os.path.join(folder_location,link['href'].split('/')[-1])
        with open(filename, 'wb') as f:
            f.write(requests.get(urljoin(url,link['href'])).content)

if __name__ == '__main__':
    patents = pd.read_csv("/content/gp-search-20210526-145223.csv", delimiter = ",",header= 1)
    for link in patents['result link']:
        folder_location = '/Users/kseniayakunina/Library/Mobile Documents/com~apple~CloudDocs/Patents'
        pars_file(folder_location,link)
    path = '/Users/kseniayakunina/Library/Mobile Documents/com~apple~CloudDocs/Patents'
    directory = os.listdir(path)
    patents_text = {}
    i = 0
    bar = IncrementalBar('Countdown', max = len(directory))

    for file_ in directory:
            bar.next()
            time.sleep(1)
            if file_ == '.DS_Store':
                continue
            if file_.endswith('.pdf'):
                text = (Converter(os.path.join(path, file_)).get_text_from_pdf())
                patents_text[i] = {'name' : file_, 'text': text}
                i+=1
    bar.finish()
    d = pd.DataFrame(patents_text)
    d = d.T
    d.to_csv('/Users/kseniayakunina/Documents')


from datetime import datetime
import json
import requests
from flask import Flask, request, make_response, jsonify

class TaskHandler:
    def __init__(self, response):
        self.responseId = response['responseId']
        self.queryText = response['queryResult']['queryText']
        self.parameters = response['queryResult']['parameters']
        self.taskType = response['queryResult']['intent']['displayName']
        with open('bot_config_private.json') as f:  # Use bot_config_private.json for development
            self.config = json.load(f)

    def handle(self):
        if self.taskType == 'weather' or self.taskType == 'weather - location':
            return self.handleWeather()
        elif self.taskType == 'waste classification':
            return self.hadnleWasteClassification()
        elif self.taskType == 'easter egg':
            return self.handleEasterEgg()
        else:
            return self._replyText("I don't know what to do.")

    # ==================================================================
    # Handling starts

    def handleWeather(self):

        def to_degree_celsius(degree_kelvin):
            return round(degree_kelvin - 273.1)

        if self.parameters['geo-city'] == '':
            return self._replyText('May I know which city we are talking about?')

        url = 'http://api.openweathermap.org/data/2.5/weather?q={}&APPID={}'.format(self.parameters['geo-city'],
                                                                                self.config['open_weather_appid'])

        try:
            res = requests.get(url).json()
            weather_description = res['weather'][0]['description']
            temp = res['main']['temp']
            temp_max = res['main']['temp_max']
            temp_min = res['main']['temp_min']
        except Exception:
            return self._replyText("Sorry. I had a problem retrieving weather information.")

        reply = "It is {} in {}. The temperature is {} °C. The high will be {} °C. The low will be {} °C.".format(
            weather_description,
            self.parameters['geo-city'],
            to_degree_celsius(temp),
            to_degree_celsius(temp_max),
            to_degree_celsius(temp_min)
        )
        return self._replyText(reply)

    def hadnleWasteClassification(self):

        if self.parameters['Garbage'] == '':
            return self._replyText("Please provide the waste name in your query.")

        url = 'https://sffc.sh-service.com/wx_miniprogram/sites/feiguan/trashTypes_2/Handler/Handler.ashx?a=GET_KEYWORDS&kw={}'.format(self.parameters['Garbage'])

        try:
            res = requests.get(url).json()
            print(res)
            if res['kw_list'] == None:
                return self._replyText("Sorry. I'm not sure.")
            else:
                reply = ''
                for item in res['kw_arr']:
                    reply += "{} belongs to {}.\n".format(item['Name'], item['TypeKey'])
                return self._replyText(reply.strip('\n'))

        except Exception:
            return self._replyText("Sorry. I had a problem retrieving data.")

    def handleEasterEgg(self):
        time1 = datetime(2018, 7, 7)
        time2 = datetime.now()
        delta = time2 - time1
        return self._replyText(u'🐶🐱面面和佳佳已经在一起{}天啦！❤❤❤'.format(delta.days))

    def _replyText(self, message):
        return jsonify({'fulfillmentText': message})


# Somewhat based on exercise 8.1.1
import sys
import os
dirname = os.path.dirname(__file__)

from matplotlib.pylab import (figure, semilogx, loglog, xlabel, ylabel, legend,
                           title, subplot, show, grid, rcParams)
import numpy as np
from scipy.io import loadmat
import sklearn.linear_model as lm
from sklearn import model_selection
from toolbox_02450 import rlr_validate

foldername = os.path.join(dirname, '../data')
sys.path.append(foldername)
import myData as d

foldername = os.path.join(dirname, '../features')
sys.path.append(foldername)
import standardize as stan
import numberedAttributes as no

# Data is imported:
md = d.myData()
X_ori = md.X
attr = md.attributeNames

# Data is standardized:
X=np.array(X_ori,dtype=np.float64)
X = stan.standardize(X, md.N)
X=np.array(X,dtype=np.float64)

#The attribute names are added numbers:
noAttr=no.addNumbers(attr)

#Definerer age kolonnen som egen array, vi vil forudse og
#fjerner age kolonnen fra dataen:
y=X[:,8]
X_del=np.delete(X,8,axis=1)
N, M = X_del.shape
X_ori=np.delete(X_ori,8,axis=1)

# Add offset attribute
X_del = np.concatenate((np.ones((X_del.shape[0],1)),X_del),1)
attributeNames = np.hstack((np.array([u'Offset']),np.delete(noAttr,8)))
M = M+1

# Values of lambda
lambdas=np.zeros(10)
for i in range(10):
    power=-1.2+0.3*(i+1)
    lambdas[i]=np.power(10.,power)
#lambdas = np.power(10.,range(-2,6))

# Since only cross-validation (not two level) the whole data set is used and
# the rlr_validate function uses 10-K-Fold cross validation.
X_train = X_del
y_train = y
internal_cross_validation = 10

# Crossvalidation on the 10 lambda models is executed:
gen_error, opt_lambda, mean_w_vs_lambda, train_err_vs_lambda, test_err_vs_lambda = rlr_validate(X_train, y_train, lambdas, internal_cross_validation)

# Then the weights are calculated with the best lambda:
Xty = X_train.T @ y_train
XtX = X_train.T @ X_train
lambdaI = opt_lambda * np.eye(M)
lambdaI[0,0] = 0 # Do no regularize the bias term
w_rlr= np.linalg.solve(XtX+lambdaI,Xty).squeeze()
w_rlr_deStand=stan.deStandardize(X_ori,w_rlr,N)

# Figures are plotted:
figure(1, figsize=(14,6))
#Formatting math style text to times
rc = {"font.family" : "serif",
      "mathtext.fontset" : "stix"}
rcParams.update(rc)
rcParams["font.serif"] = ["Times New Roman"] + rcParams["font.serif"]

subplot(1,2,1)
semilogx(lambdas,mean_w_vs_lambda.T[:,1:],'.-') # Don't plot the bias term
xlabel('Regularization factor', size=15)
ylabel('Mean Coefficient Values',size=15)
grid()
# You can choose to display the legend, but it's omitted for a cleaner
# plot, since there are many attributes
legend(attributeNames[1:], loc='upper left')

subplot(1,2,2)
title('Optimal lambda: 1e{:.2f}'.format(np.log10(opt_lambda)),size=20)
loglog(lambdas,train_err_vs_lambda.T,'b.-',lambdas,test_err_vs_lambda.T,'r.-')
xlabel('Regularization factor',size=15)
ylabel('Squared error (crossvalidation)',size=15)
legend(['Train error','Test error'])
grid()

show()

# Display results
print('Weights with optimal lambda:')
for m in range(M):
    print('{:>15} {:>15}'.format(attributeNames[m], np.round(w_rlr[m],2)))
print('Weights with optimal lambda de-standardized:')
for m in range(M):
    print('{:>15} {:>15}'.format(attributeNames[m], np.round(w_rlr_deStand[m],2)))
print('Generalization error:')
print(gen_error)

print('Finished regularized linear regression cross validation')


from dreampy3.redshift.netcdf import RedshiftNetCDFFile
import numpy
import matplotlib.pyplot as pl
from matplotlib.font_manager import FontProperties
try:
    from scipy.stats import nanmean
except:
    pass
import sys
import os.path
from genericFileSearch import genericFileSearch

class RSRRunTsys():

    def plot_tsys(self, pl, FontProperties, nc, board=None, hold=False,
                  set_subplot_title=True,
                  *args, **kwargs):
        """Plots the redshift Tsys data. This is to be obtained
        from the CalObsNum scan in a prescribed way. If the Cal data is not
        available in the scan, it will produce an error"""
        if isinstance(nc, RedshiftNetCDFFile):
            hdu = nc.hdu
        elif isinstance(nc, RedshiftScan):
            hdu = nc
        else:
            raise LMTRedshiftError("plot tsys", "Argument nc should be of type RedshiftNetCDFFile or RedshiftScan")
        if not hasattr(hdu, 'cal'):
            raise LMTRedshiftError("plot tsys", "hdu does not have cal object. Process first with get_cal()")
        if board is None:
            boards = hdu.header.BoardNumber
        else:
            boards = [board]
        y_max = 0
        y_min = 300
        for board in boards:
            y_min = numpy.min([y_min, numpy.min(hdu.cal.Tsys[board, :])])
            y_max = numpy.max([y_max, numpy.max(hdu.cal.Tsys[board, :])])
            pl.plot(hdu.frequencies[board, :], hdu.cal.Tsys[board, :],
                      linestyle='steps-mid', label='%d.%d' % (int(hdu.header.ChassisNumber), board))
        y_min = numpy.max([y_min*1.1, 0])
        y_max = numpy.min([y_max*1.1, 300])
        print('min/max = ', y_min, y_max)
        pl.set_ylim(y_min, y_max)
        pl.legend(loc='best', prop=FontProperties(size="xx-small"))
        pl.set_ylabel("Tsys (K)")

    def decode_chassis_string(self,chassis_arg):
        """Decodes the argument provided with the -c flag."""
        if chassis_arg[0] == 'a' or chassis_arg[0] == 'n':
            self.chassis_list = [0,1,2,3]
        elif chassis_arg[0] == '[':
            self.chassis_list = eval(chassis_arg)
        else:
            p = chassis_arg.partition(':')
            if p[1] == ':':
                self.chassis_list = list(range(int(p[0]),int(p[2])+1))
            else:
                self.chassis_list = list(range(int(p[0]),int(p[0])+1))

    def run(self, argv, obsNum):

        self.chassis_list = [0, 1, 2, 3]
        for i,arg in enumerate(argv):
            if arg in ("-c","--chassis"):
                self.decode_chassis_string(argv[i+1])
        pl.clf()
        #pl.figure(figsize=(6,12))
        for i,use_chassis in enumerate(self.chassis_list):
            print(use_chassis)
            ax = pl.subplot(len(self.chassis_list), 1, i+1)
            filename = genericFileSearch ('RedshiftChassis%d'%use_chassis, obsNum)
            if i == 0:
                pl.title('ObsNum %s' % (obsNum))
            try:
                nc = RedshiftNetCDFFile(filename)
            except:
                ax.annotate("File not found for Chassis %d"%(use_chassis), [0.2,0.5], fontsize=13, fontweight='bold', stretch='250', horizontalalignment='left', verticalalignment='top')
                continue
            nc.hdu.get_cal()
            #tsys = nanmean(nc.hdu.cal.Tsys.flatten())
            tsys_data = nc.hdu.cal.Tsys.flatten()
            tsys_data = tsys_data[numpy.where(numpy.isfinite(tsys_data))]
            tsys = numpy.median (tsys_data)
            print('Average Tsys = %6.2f K' % tsys)
            self.plot_tsys(ax, FontProperties, nc)
            #pl.ylim(0.0,3*tsys)
            if tsys < 1000:
                ax.hlines(tsys,70,115)
                ax.annotate("Average Tsys =%6.2fK on  Chassis %d"%(tsys,use_chassis), [71,tsys-1], fontsize=13, fontweight='bold', stretch='250', horizontalalignment='left', verticalalignment='top')

        pl.xlabel("Frequency (GHz)")
        pl.savefig('rsr_summary.png', bbox_inches='tight')

if __name__ == '__main__':
    #obsNumList = [65970]
    obsNumList = [91180]
    obsNumList = [95233]
    obsNumList = [106904]
    rsr = RSRRunTsys()
    M = rsr.run(sys.argv,obsNumList[-1])


from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
from flask import session
from flask import make_response
from flask import send_file
from flask import flash
from model.condition import Conditon
from Util import mongoUtil
from Util import exportUtil
from Util import util
import shutil
import os
import time
from urllib.parse import quote

app=Flask(__name__)

@app.route("/",methods=["GET","POST"])
def index():
    return render_template("main.html")

@app.route("/result",methods=["POST","GET"])
def search():
    if request.method=="POST":
        ajmc = request.form["ajmc"]
        ah = request.form["ah"]
        gjc = request.form["gjc"]
        fycj = request.form["fycj"]
        fydy = request.form["fydy"]
        spcx = request.form["spcx"]
        sprqS = request.form["sprqS"]
        sprqE = request.form["sprqE"]
        fbrqS = request.form["fbrqS"]
        fbrqE = request.form["fbrqE"]
        con=Conditon(ajmc,ah,gjc,fycj,fydy,spcx,sprqS,sprqE,fbrqS,fbrqE)
        session["Condition"]=con.toDict()
        session["TotalNumber"]=mongoUtil.getCaseNumber(con)
        return redirect("/result?page=1") #重定向到加了个参数的url

    else:
        ajmc=session["Condition"]["ajmc"]
        ah=session["Condition"]["ah"]
        gjc=session["Condition"]["gjc"]
        fycj=session["Condition"]["fycj"]
        fydy=session["Condition"]["fydy"]
        spcx=session["Condition"]["spcx"]
        sprqS=session["Condition"]["sprqS"]
        sprqE=session["Condition"]["sprqE"]
        fbrqS=session["Condition"]["fbrqS"]
        fbrqE=session["Condition"]["fbrqE"]
        con=Conditon(ajmc,ah,gjc,fycj,fydy,spcx,sprqS,sprqE,fbrqS,fbrqE)

        currentPage=int(request.args.get("page",1))
        currentCaseList=mongoUtil.getOnePageCase(con,currentPage)
        totalnumber=mongoUtil.getCaseNumber(con)
        buttonHtmlStr=util.toButtonHtml(con,currentPage,"/result")

        return render_template("response.html",caseList=currentCaseList,
                               count=len(currentCaseList),
                               currentPage=currentPage,
                               buttonHtmlStr=buttonHtmlStr,
                               totalnumber=totalnumber) #模板支持把list传入
@app.route("/download")
def download():
    ajmc=session["Condition"]["ajmc"]
    ah=session["Condition"]["ah"]
    gjc=session["Condition"]["gjc"]
    fycj=session["Condition"]["fycj"]
    fydy=session["Condition"]["fydy"]
    spcx=session["Condition"]["spcx"]
    sprqS=session["Condition"]["sprqS"]
    sprqE=session["Condition"]["sprqE"]
    fbrqS=session["Condition"]["fbrqS"]
    fbrqE=session["Condition"]["fbrqE"]
    con=Conditon(ajmc,ah,gjc,fycj,fydy,spcx,sprqS,sprqE,fbrqS,fbrqE)
    #把上一次的搜索结果删除
    try:#没删除成功说明temp文件夹不存在
        shutil.rmtree("temp")
    except Exception:
        pass
    try:#不要打开temp文件夹 不然删不掉
        os.mkdir("temp")
    except Exception:
        flash("请关闭temp文件夹")
        time.sleep(1)
        os.mkdir("temp")
    #把搜出来的文档存成txt再打包。rar
    exportUtil.exportAndToRar(con)
    response = make_response(send_file("temp/%s.zip" % con.toString().strip(),as_attachment=True))
    #因为中文文件名在header中不支持 所以必须用以下写法来编码
    filenameUtf=quote(con.toString().strip()+".zip")
    response.headers["Content-Disposition"] = "attachment; filename=%s;" % filenameUtf +" filename*=utf-8''%s" % filenameUtf

    return response

if(__name__=="__main__"):
    app.secret_key='A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
    app.run()


import glob
from json import load
from util.util import TextNormalizationUtils
RECIPES_GLOB_PATTERN = './recipes/'

def load_key_from_dataset(dataset_path, key, _type, normalize_units=False):
    data_list = []
    sets = glob.glob('{}/{}_data/*.json'.format(dataset_path, _type))
    for fname in sets:
        with open(fname, 'r') as file:
            json = load(file)
            data_list.extend(json[key])

    if normalize_units:
        data_list = map(TextNormalizationUtils().normalize_unit_abbreviations, data_list)

    return data_list

def save_data(data_list, data_path, fname):
    with open('{}/{}.txt'.format(data_path, fname), 'w') as file:
        file.writelines(map(lambda str: str + '\n', data_list))

if __name__ == '__main__':
    for _type in ['training', 'test']:
        for key in ['ingredients', 'directions']:
            data = load_key_from_dataset(RECIPES_GLOB_PATTERN, key, _type, normalize_units=True)
            save_data(data, key, '{}_hits'.format(_type))


import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

data = {
    "P1": [7, 7, 3, 1],
    "P2": [7, 4, 4, 4],
    "Class": ["False", "False", "True", "True"]
}

df = pd.DataFrame(data)

x = df.iloc[:,:-1].values
y = df.iloc[:,2].values

x_train, x_test, y_train, y_test = train_test_split(x, y)

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(x_train)
x_train = scaler.transform(x_train)

from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors = 3)

knn.fit(x_train,y_train)

print(knn.predict([[3,7]]))


from sklearn.preprocessing import MinMaxScaler
import pandas as pd
import yfinance as yf
import plotly.graph_objs as go
import requests, datetime
import time
import numpy as np

endpoint = "http://127.0.0.1:8500"
tickerSymbol = 'GC=F' # prediction asset
pred_col = 'Close' # prediction column
input_len = 60 # length of input sequence
output_len = 60 # length into future to predict
scaler = MinMaxScaler()

def get_start_date(end_date, input_len):
    '''
    get the start date from end date
    '''
    return end_date - datetime.timedelta(days=(input_len+40))

def get_data(tickerSymbol):
    '''
    Args:
        tickerSymbol (string) - ticker Symbol

    Returns:
        df (Dataframe) - raw data
    '''
    #get data on this ticker
    tickerData = yf.Ticker(tickerSymbol)

    #get the historical prices for this ticker
    end_date = datetime.date.today()
    start_date = get_start_date(end_date, input_len)
    df = tickerData.history(period='1d', start=start_date, end=end_date)
    df.drop(columns=['Dividends', 'Stock Splits'], inplace=True)
    return df.tail(input_len)

def preprocess_input_data(df):
    df[pred_col] = scaler.fit_transform(df[pred_col].values.reshape(-1,1))
    return df.values.tolist()

def get_preds(df):
    data = preprocess_input_data(df)
    json_data = {"data": {"input": [data]}}
    result = requests.post(endpoint, json=json_data)
    output = np.array(result.json()['output'][0]).reshape(-1,1)
    output = scaler.inverse_transform(output)
    return output.reshape(1,-1)

def return_figures():
    """Creates plotly visualizations

    Args:
        None

    Returns:
        list (dict): list containing the four plotly visualizations

    """
    df = get_data(tickerSymbol)
    # Gold chart plot
    # as a line chart
    graph_one = []

    x_val = df.index
    y_val = df[pred_col].values
    graph_one.append(
          go.Scatter(
          x = x_val,
          y = y_val,
          mode = 'lines',
          name = 'Gold Price'
          )
    )
    x_preds = pd.date_range(datetime.datetime.today().date(), periods=output_len, freq='D')
    y_preds = get_preds(df)[0]

    # Gold price action prediction
    # as a line chart
    graph_one.append(
          go.Scatter(
          x = x_preds,
          y = y_preds,
          mode = 'lines',
          name = 'Gold Price Prediction'
          )
      )

    layout_one = dict(
              title = 'Gold price chart and price prediction for the next day',
                xaxis = dict(title = 'Day', autotick=True),
                yaxis = dict(title = 'Gold Price in Dollar'),
                )

    # append all charts to the figures list
    figures = []
    figures.append(dict(data=graph_one, layout=layout_one))

    return figures


from xivo_dao.helpers.db_manager import Session
from xivo_dao.resources.user import dao as user_dao
from xivo_dao.resources.voicemail import dao as voicemail_dao

class UserVoicemailMiddleware:
    def __init__(self, service, middleware_handle):
        self._service = service
        self._middleware_handle = middleware_handle

    def associate(self, user_id, voicemail_id, tenant_uuids):
        user = user_dao.get_by_id_uuid(user_id, tenant_uuids=tenant_uuids)
        voicemail = voicemail_dao.get(voicemail_id, tenant_uuids=tenant_uuids)
        self._service.associate(user, voicemail)

    def create_voicemail(self, user_id, body, tenant_uuids):
        voicemail_middleware = self._middleware_handle.get('voicemail')
        voicemail = voicemail_middleware.create(body, tenant_uuids)
        self.associate(user_id, voicemail['id'], tenant_uuids)
        return voicemail

    def dissociate(self, user_id, tenant_uuids):
        user = user_dao.get_by_id_uuid(user_id, tenant_uuids=tenant_uuids)
        self._service.dissociate_all_by_user(user)

    def delete_voicemail(self, user_id, tenant_uuids):
        user = user_dao.get_by_id_uuid(user_id, tenant_uuids=tenant_uuids)
        voicemail_middleware = self._middleware_handle.get('voicemail')
        voicemail_id = user.voicemailid

        self.dissociate(user_id, tenant_uuids)
        Session.expire(user, ['voicemail'])

        voicemail = voicemail_middleware.get(voicemail_id, tenant_uuids)
        if not voicemail['users']:
            voicemail_middleware.delete(voicemail['id'], tenant_uuids)


import os
from shutil import copyfile

import numpy as np
import pytest
from numpy.testing import assert_allclose
from scipy import sparse

from mne import read_morph_map
from mne.datasets import testing
from mne.utils import _record_warnings, catch_logging

data_path = testing.data_path(download=False)
subjects_dir = data_path / "subjects"

@pytest.mark.slowtest
@testing.requires_testing_data
def test_make_morph_maps(tmp_path):
    """Test reading and creating morph maps."""
    pytest.importorskip("nibabel")
    # make a new fake subjects_dir
    for subject in ("sample", "sample_ds", "fsaverage_ds"):
        os.mkdir(tmp_path / subject)
        os.mkdir(tmp_path / subject / "surf")
        regs = ("reg", "left_right") if subject == "fsaverage_ds" else ("reg",)
        for hemi in ["lh", "rh"]:
            for reg in regs:
                copyfile(
                    subjects_dir / subject / "surf" / f"{hemi}.sphere.{reg}",
                    tmp_path / subject / "surf" / f"{hemi}.sphere.{reg}",
                )

    for subject_from, subject_to, xhemi in (
        ("fsaverage_ds", "sample_ds", False),
        ("fsaverage_ds", "fsaverage_ds", True),
    ):
        # trigger the creation of morph-maps dir and create the map
        with catch_logging() as log:
            mmap = read_morph_map(
                subject_from, subject_to, tmp_path, xhemi=xhemi, verbose=True
            )
        log = log.getvalue()
        assert "does not exist" in log
        assert "Creating" in log
        mmap2 = read_morph_map(subject_from, subject_to, subjects_dir, xhemi=xhemi)
        assert len(mmap) == len(mmap2)
        for m1, m2 in zip(mmap, mmap2):
            # deal with sparse matrix stuff
            diff = (m1 - m2).data
            assert_allclose(diff, np.zeros_like(diff), atol=1e-3, rtol=0)

    # This will also trigger creation, but it's trivial
    with _record_warnings():
        mmap = read_morph_map("sample", "sample", subjects_dir=tmp_path)
    for mm in mmap:
        assert (mm - sparse.eye(mm.shape[0], mm.shape[0])).sum() == 0


#!/usr/bin/python
#coding:utf-8
#@ZHOU_YING
#2020-5-29
#遍历检索所有的.docx和pdf，将搜索到的所有文件路径拆分成csv记录

import os
import shutil
import pandas as pd
from collections import defaultdict

'''遍历docx报告'''
rootpath='/mnt/e/NGS/二代测序第三REVIEW资料/'
os.chdir(rootpath)
paths_docx=pd.DataFrame()

for roots, dirs, files in os.walk(rootpath):
    filelists=os.listdir()
    for file in files:
        temp=defaultdict(list)
        if os.path.splitext(file)[1]=='.docx' and file.split('_')[0]=='NGS':
            path=os.path.join(roots,file).split('/')
            path_num=len(path)
            #temp['filename'].append(path[path_num-1])
            n=0
            for i in range(path_num-1,0,-1):
                n+=1
                temp[str(n)].append(path[i])
            temp=pd.DataFrame(temp)
            paths_docx=pd.concat([paths_docx,temp],axis=0)

paths_docx.to_csv('paths_docx.csv',index=False,encoding='utf_8_sig')


import h5py
import scipy.io as sio
import numpy as np
filepath = 'dod.mat'
arrays = {}

def main():

    A=sio.loadmat('dod.mat')

    volume=0;

    for i in range(0,len(A["dod"])):
        for j in range(0,len(A["dod"][i])):
            volume=volume+A["dod"][i][j];
    volume=volume/14.63;
    print('volume is',volume,'m3')

    return

if __name__ == "__main__":
    main()


from CbieudoPIE import *
from XulyFile import *

class CThietLapHu(QWidget):
    def __init__(self):
        super().__init__()

        self.setup()
        self.show()

    def setup(self):
        self.setWindowTitle("Thiết lập các hũ")
        self.setGeometry(300, 200, 450, 600)
        self.setMinimumSize(450,600)
        self.setMaximumSize(450,600)

        self.spin_box1()
        self.spin_box2()
        self.spin_box3()
        self.spin_box4()
        self.spin_box5()
        self.spin_box6()
        self.ButtonLuu()

        vbox=QVBoxLayout()

        vbox.addWidget(self.groupbox1)
        vbox.addWidget(self.groupbox2)
        vbox.addWidget(self.groupbox3)
        vbox.addWidget(self.groupbox4)
        vbox.addWidget(self.groupbox5)
        vbox.addWidget(self.groupbox6)
        vbox.addWidget(self.groupbox7)

        self.setLayout(vbox)

    #--------------------------------------------------------------
    def spin_box1(self):
        self.groupbox1 = QGroupBox('Đơn vị: vnđ')
        self.groupbox1.setFont(QFont("Times", 10))
        self.groupbox1.setAlignment(Qt.AlignRight)

        gridLayout = QGridLayout()

        self.label = QLabel("Thiết yếu")
        self.label.setFont(QFont('#9Slide03 Cabin Bold',13))
        icon1 = QIcon('thietyeu.png')
        label1 = QLabel(self)
        label1.setMaximumWidth(60)
        pixmap1 = icon1.pixmap(40, 40)
        label1.setPixmap(pixmap1)

        self.text1 = QLineEdit()
        self.text1.setFont(QFont("Arial",10))
        self.text1.setMaximumWidth(200)
        self.text1.setAlignment(Qt.AlignHCenter)
        file=XulyFile
        ptu=file.docfile(self,'Gia_tri_cac_hu.txt')
        self.text1.setText(ptu[0])

        gridLayout.addWidget(label1,0,0)
        gridLayout.addWidget(self.label, 0, 1)
        gridLayout.addWidget(self.text1,0,2)

        self.groupbox1.setLayout(gridLayout)
    def spin_box2(self):
        self.groupbox2 = QGroupBox()

        gridLayout = QGridLayout()

        self.label = QLabel("Giáo dục")
        self.label.setFont(QFont('#9Slide03 Cabin Bold', 13))
        icon1 = QIcon('education.png')
        label1 = QLabel(self)
        label1.setMaximumWidth(60)
        pixmap1 = icon1.pixmap(40, 40)
        label1.setPixmap(pixmap1)

        self.text2 = QLineEdit()
        # self.spinbox.setMaximum(100)
        self.text2.setFont(QFont("Arial", 10))
        self.text2.setMaximumWidth(200)
        self.text2.setAlignment(Qt.AlignHCenter)
        file = XulyFile
        ptu = file.docfile(self, 'Gia_tri_cac_hu.txt')
        self.text2.setText(ptu[1])

        gridLayout.addWidget(label1, 0, 0)
        gridLayout.addWidget(self.label,0,1)
        gridLayout.addWidget(self.text2,0,2)

        self.groupbox2.setLayout(gridLayout)
    def spin_box3(self):
        self.groupbox3 = QGroupBox()

        gridLayout = QGridLayout()

        self.label = QLabel("Tiết kiệm")
        self.label.setFont(QFont('#9Slide03 Cabin Bold', 13))
        icon1 = QIcon('save.png')
        label1 = QLabel(self)
        label1.setMaximumWidth(60)
        pixmap1 = icon1.pixmap(40, 40)
        label1.setPixmap(pixmap1)

        self.text3 = QLineEdit()
        # self.spinbox.setMaximum(100)
        self.text3.setFont(QFont("Arial", 10))
        self.text3.setMaximumWidth(200)
        self.text3.setAlignment(Qt.AlignHCenter)
        file = XulyFile
        ptu = file.docfile(self, 'Gia_tri_cac_hu.txt')
        self.text3.setText(ptu[2])

        gridLayout.addWidget(label1,0,0)
        gridLayout.addWidget(self.label,0,1)
        gridLayout.addWidget(self.text3,0,2)

        self.groupbox3.setLayout(gridLayout)
    def spin_box4(self):
        self.groupbox4 = QGroupBox()

        gridLayout = QGridLayout()

        self.label = QLabel("Hưởng thụ")
        self.label.setFont(QFont('#9Slide03 Cabin Bold', 13))
        icon1 = QIcon('enjoy.png')
        label1 = QLabel(self)
        label1.setMaximumWidth(60)
        pixmap1 = icon1.pixmap(40, 40)
        label1.setPixmap(pixmap1)

        self.text4 = QLineEdit()
        # self.spinbox.setMaximum(100)
        self.text4.setFont(QFont("Arial", 10))
        self.text4.setMaximumWidth(200)
        self.text4.setAlignment(Qt.AlignHCenter)
        file = XulyFile
        ptu = file.docfile(self, 'Gia_tri_cac_hu.txt')
        self.text4.setText(ptu[3])

        gridLayout.addWidget(label1,0,0)
        gridLayout.addWidget(self.label,0,1)
        gridLayout.addWidget(self.text4,0,2)

        self.groupbox4.setLayout(gridLayout)
    def spin_box5(self):
        self.groupbox5 = QGroupBox()

        gridLayout = QGridLayout()

        self.label = QLabel("Đầu tư")
        self.label.setFont(QFont('#9Slide03 Cabin Bold', 13))
        icon1 = QIcon('investment.png')
        label1 = QLabel(self)
        label1.setMaximumWidth(60)
        pixmap1 = icon1.pixmap(40, 40)
        label1.setPixmap(pixmap1)

        self.text5 = QLineEdit()
        self.text5.setFont(QFont("Arial", 10))
        self.text5.setMaximumWidth(200)
        self.text5.setAlignment(Qt.AlignHCenter)
        file = XulyFile
        ptu = file.docfile(self, 'Gia_tri_cac_hu.txt')
        self.text5.setText(ptu[4])

        gridLayout.addWidget(label1,0,0)
        gridLayout.addWidget(self.label,0,1)
        gridLayout.addWidget(self.text5,0,2)

        self.groupbox5.setLayout(gridLayout)
    def spin_box6(self):
        self.groupbox6 = QGroupBox()

        gridLayout = QGridLayout()

        self.label = QLabel("Thiện tâm")
        self.label.setFont(QFont('#9Slide03 Cabin Bold', 13))
        icon1 = QIcon('care.png')
        label1 = QLabel(self)
        label1.setMaximumWidth(60)
        pixmap1 = icon1.pixmap(40, 40)
        label1.setPixmap(pixmap1)

        self.text6 = QLineEdit()
        # self.spinbox.setMaximum(100)
        self.text6.setFont(QFont("Arial", 10))
        self.text6.setMaximumWidth(200)
        self.text6.setAlignment(Qt.AlignHCenter)
        file = XulyFile
        ptu = file.docfile(self, 'Gia_tri_cac_hu.txt')
        self.text6.setText(ptu[5])

        gridLayout.addWidget(label1,0,0)
        gridLayout.addWidget(self.label,0,1)
        gridLayout.addWidget(self.text6,0,2)

        self.groupbox6.setLayout(gridLayout)
    def ButtonLuu(self):
        self.groupbox7 = QGroupBox()
        grid=QGridLayout()

        self.btnLuu=QPushButton('Lưu')
        self.btnLuu.setMinimumSize(20,50)
        self.btnLuu.setFont(QFont('9Slide03 Cabin Bold',15))
        self.btnLuu.clicked.connect(self.luuAction)

        grid.addWidget(self.btnLuu)
        self.groupbox7.setLayout(grid)

    def spin_value(self):
        self.label.setText("Current Value Is : " + str(self.spinbox.value()))
    def luuAction(self):
        a1 = eval(self.text1.text())
        a2 = eval(self.text2.text())
        a3 = eval(self.text3.text())
        a4 = eval(self.text4.text())
        a5 = eval(self.text5.text())
        a6 = eval(self.text6.text())
        arr=[a1,a2,a3,a4,a5,a6]

        if (a1 + a2 + a3 + a4 + a5 + a6) == 0:
            QMessageBox.warning(self, "Thông báo",
                                "Lỗi! Không được để trống toàn bộ.", QMessageBox.Ok)
            #myapp.quit()
        else:
            file = XulyFile()
            file.xoads('Gia_tri_cac_hu.txt', '')
            for i in range(len(arr)):
                file.luufile('Gia_tri_cac_hu.txt', str(arr[i]))
            self.goi = giaodienPCCT(a1, a2, a3, a4, a5, a6)

if __name__ == '__main__':
    myapp = QApplication(sys.argv)
    window = CThietLapHu()
    myapp.exec_()
    sys.exit()


from odoo import models, api, fields
from datetime import datetime

class MukDmsExt(models.Model):
    _inherit = "muk_dms.file"

    object = fields.Text(string="Predmet")
    sub_number = fields.Integer(string="Pod Broj",store=True, compute='number_onchange')
    create_date = fields.Datetime(string="Datum")
    contact_id = fields.Many2one('res.partner',string="Posiljaoc")
    document_class_id = fields.Many2one('irvas.edoc.document.class', string="Klasa Dokumenta")
    date_receive = fields.Datetime(string="Datum Prijema")
    date_shipped = fields.Datetime(string="Datum Otpreme")
    digital_signature = fields.Binary(string="Digital Signature")
    document_number = fields.Text(string="Document Number", compute='get_document_number', store=True, readonly=True)
    #received_type = fields.Selection([('on_hands', 'On Booking'),
     #                                ('manual', 'On Check In'),
      #                               ('picking', 'On Checkout')], description='The way document was received', string="Receive Type")
    def _get_number_id(self):
        file = self.env['muk_dms.file'].search([])
        a=[]
        max_number= 0
        for f in file:
            a.append(f.basic_number)
        for i in range(len(a)):
            if a[i]> max_number:
                max_number = a[i]
        if max_number == 0:
            return 1
        else:
            return max_number + 1

    basic_number = fields.Integer(string="Osnovni Broj", default=_get_number_id, store=True, readonly=False)

    @api.one
    @api.depends('document_class_id')
    def _get_document_state(self):
        if self.document_class_id.document_type == 'izlazni':
            self.document_state = 'otprema'
            print('asd')
        elif (self.document_class_id.document_type == 'ulazni') or (self.document_class_id.document_type == 'interni'):
            self.document_state = 'prijem'
            print('uso')
        else:
            return None
    document_state = fields.Selection([('prijem', 'Prijem'), ('otprema', 'Otprema')],store=True, compute=_get_document_state)

    @api.one
    @api.depends('basic_number')
    def number_onchange(self):
        file = self.env['muk_dms.file'].search([('basic_number', '=', self.basic_number)])
        if file is None:
            self.basic_number = 1
            self.sub_number = 1
        else:
            max_subnumber=0
            for f in file:
                if f.sub_number > max_subnumber:
                    max_subnumber = f.sub_number
            self.sub_number = max_subnumber + 1

    @api.one
    @api.depends('basic_number','sub_number')
    def get_document_number(self):
        self.document_number = str(self.basic_number) + "-" + str(self.sub_number) + '/' + str(datetime.now().year)

    def open_create_document_received(self,ctx, context=None):
        context=ctx
        print(context)
        print(context.get('izlazni'))
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'muk_dms.file',
            'view_mode': 'form',
            'target': 'current',
            'context': context,
            'flags': {'form': {'action_buttons': True, 'options': {'mode': 'create'}}}
        }

    def open_create_document_shipping(self,ctx, context=None):
        context=ctx

        return {
            'type': 'ir.actions.act_window',
            'res_model': 'muk_dms.file',
            'view_mode': 'form',
            'target': 'current',
            'context': context,
            'flags': {'form': {'action_buttons': True, 'options': {'mode': 'create'}}}
        }

    @api.multi
    def run_document_shipped_action_wizard(self):
        action = self.env.ref('irvas_muk_dms_extension.irvas_edoc_document_shipped_action_wizard').read()[0]
        return action

class DocumentShippingActionWizard(models.TransientModel):
    _name="muk_dms.file.shipping.wizard"

    contact_id = fields.Many2one('res.partner')
    date_shipped = fields.Datetime()
    basic_number = fields.Integer(related='muk_dms_file_id.basic_number')
    sub_number = fields.Integer(related='muk_dms_file_id.sub_number')

    def _get_number_id(self):
        file = self.env['muk_dms.file'].search([])
        a=[]
        max_number= 0
        for f in file:
            a.append(f.basic_number)
        for i in range(len(a)):
            if a[i]> max_number:
                max_number = a[i]
        if max_number == 0:
            return 1
        else:
            return max_number + 1

    new_basic_number = fields.Integer(string="Osnovni Broj", default=_get_number_id, store=True, readonly=False)

    new_sub_number = fields.Integer(store="True",compute='number_onchange')

    @api.one
    @api.depends('new_basic_number')
    def number_onchange(self):
        file = self.env['muk_dms.file'].search([('basic_number', '=', self.new_basic_number)])
        if file is None:
            self.new_basic_number = 1
            self.new_sub_number = 1
        else:
            max_subnumber = 0
            for f in file:
                if f.sub_number > max_subnumber:
                    max_subnumber = f.sub_number
            self.new_sub_number = max_subnumber + 1

    def _get_file_id(self):

        id = self.env.context.get('id')
        file_id = self.env['muk_dms.file'].search([('id','=',id)])
        return file_id

    muk_dms_file_id = fields.Many2one('muk_dms.file', default=_get_file_id)

    def set_document_shipping(self):
        print(self.env.context.get('contact_id'))
        print(self.env.context.get('muk_dms_file_id'))
    # self.date_receive = None
    #  self.document_state = 'otprema'
    # self.contact_id = self.env.context.get('contact_id')
    # self.date_shipped = self.env.context.get('date_shipped')

    # @api.onchange('location_dest_id')
    # def get_document_type(self, context=None):
    #     if self.location_dest_id:
    #         res = {}
    #         micro_list = []
    #
    #         if 'sit_prelociranje_form_action' in self._context:
    #             micro_location = self.env['stock.microlocation'].search(
    #                 [('stock_location_id', '=', self.location_dest_id.id)], limit=1)
    #             # self.micro_loc_dest_id = micro_location.id
    #             micro_location_obj = self.env['stock.microlocation']
    #             micro_location_ids = micro_location_obj.search([('stock_location_id', '=', self.location_dest_id.id)])
    #             for record in micro_location_ids:
    #                 micro_list.append(record.id)
    #             res = {'domain': {'micro_loc_dest_id': [('id', 'in', micro_list)]}}
    #             return res
    #
    #         if 'sit_trebovanje_form_action' in self._context:
    #             micro_location_obj = self.env['stock.microlocation']
    #             micro_location_ids = micro_location_obj.search([[u'stock_location_id.name', u'ilike', u'SI u upotrebi'],
    #                                                             ('stock_location_id.usage', '=', 'asset')])
    #             for record in micro_location_ids:
    #                 micro_list.append(record.id)
    #             res = {'domain': {'micro_loc_dest_id': [('id', 'in', micro_list)]}}


from rest_framework import serializers
from easyleasy2.models import *

class RelatedFieldAlternative(serializers.PrimaryKeyRelatedField):
    def __init__(self, **kwargs):
        self.serializer = kwargs.pop('serializer', None)
        if self.serializer is not None and not issubclass(self.serializer, serializers.Serializer):
            raise TypeError('"serializer" is not a valid serializer class')

        super().__init__(**kwargs)

    def use_pk_only_optimization(self):
        return False if self.serializer else True

    def to_representation(self, instance):
        if self.serializer:
            return self.serializer(instance, context=self.context).data
        return super().to_representation(instance)
class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'
        depth = 1

class PromoSerializer(serializers.ModelSerializer):
    product = RelatedFieldAlternative(queryset=Product.objects.all(), serializer=ProductSerializer)
    class Meta:
        model = Promo
        fields = '__all__'
        depth = 1

class SupportRequestSerializer(serializers.ModelSerializer):
    class Meta:
        model = Support_Request
        fields = '__all__'

class InterestRateSerializer(serializers.ModelSerializer):
    product = RelatedFieldAlternative(queryset=Product.objects.all(), serializer=ProductSerializer)
    class Meta:
        model = Interest_Rate
        fields = '__all__'
        depth = 1

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
class ClientProfileSerializer(serializers.ModelSerializer):

    user = RelatedFieldAlternative(queryset=User.objects.all(), serializer=UserSerializer)
    class Meta:
        model = ClientProfile
        fields = '__all__'
        depth = 1

class ApplicationSerializer(serializers.ModelSerializer):
    client_profile = RelatedFieldAlternative(queryset=ClientProfile.objects.all(), serializer=ClientProfileSerializer)
    product = RelatedFieldAlternative(queryset=Product.objects.all(), serializer=ProductSerializer)
    class Meta:
        model = Application
        fields = '__all__'
        depth = 1

class DealSerializer(serializers.ModelSerializer):
    client_profile = RelatedFieldAlternative(queryset=ClientProfile.objects.all(), serializer=ClientProfileSerializer)
    product = RelatedFieldAlternative(queryset=Product.objects.all(), serializer=ProductSerializer)
    class Meta:
        model = Deal
        fields = '__all__'
        depth = 1

class DocumentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Document
        fields = '__all__'
        depth = 1


# -*- coding: utf-8 -*-
"""
Spyder Editor

"""

"""
    Create a Queue using doubly linked list
"""

import re

class Node:

# initialize the node object
    def __init__(self,data):
        self.data = data
        self.next = None
        self.prev = None

class Queue:

# intialize the head
    def __init__(self):
        self.head = None
        self.last = None

    def enqueue(self,data):
        if self.last is None:
            self.head = Node(data)
            self.last = self.head
        else:
            self.last.next = Node(data)
            self.last.next.prev = self.last
            self.last = self.last.next
    def dequeue(self):
        if self.head is None:
            return None
        else:
            temp = self.head.data
            self.head.prev = None
            self.head = self.head.next
            return temp

    def printQueue(self,tag):
        print("\n")
        print(f'{tag} Queue elements :')
        temp = self.head
        while temp is not None:
            print(temp.data,end="->")
            temp = temp.next

def recursive_palindrome_check(word):
    if len(word) == 1:
        return True
    first_letter = word[0]
    last_letter = word[len(word) -1]
    if first_letter != last_letter:
        return False
    else:
        new_word = word[1:-1]
        return recursive_palindrome_check(new_word)

def is_palindrome(word):
    if len(word) == 1:
        return True
    else:
        return recursive_palindrome_check(word)

input_queue = Queue()
output_queue = Queue()
with open('inputPS15.txt', 'r') as reader:
    for line in reader.readlines():
        # remove punctuation
        cleaned_line = re.sub(r'[^\w\s]', '', line)
        for word in cleaned_line.split():
            input_queue.enqueue(word)

input_queue.printQueue("input")
# iterate over input queue
curr_word = input_queue.dequeue()
while curr_word is not None:
    if is_palindrome(curr_word):
        output_queue.enqueue(curr_word)
    curr_word = input_queue.dequeue()

output_queue.printQueue("output")

input_queue = Queue()
#populate input queue
palindrome = output_queue.dequeue()
while palindrome is not None:
    input_queue.enqueue(palindrome)
    palindrome = output_queue.dequeue()

print("input queue after population")
input_queue.printQueue("input")

"""
    TODO : check for empty string
"""
#for line in all_lines:
#    for word in line.split():
#        words.append(word)
#
#word_size = len(words)
## Create input Queue
#
#

#
#
#for index in range(word_size):
#    word = words.popleft()
#
#    if is_palindrome(word):
#        words.append(word)
#
##Dump the output of queue to file
#output_file = open('outputPS15.txt','a')
#for index in range(len(words)):
#    pali_word =  words.popleft()
#    output_file.write(pali_word)
#    output_file.write(" ")
#output_file.close()


from flask import Flask, request
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from flask_jsonpify import jsonify
from flask_cors import CORS

db_connect = create_engine('sqlite:///forecast.db')
app = Flask(__name__)
CORS(app)
api = Api(app)

class Cities(Resource):
    def get(self):
        conn = db_connect.connect()  # connect to database
        query = conn.execute("select * from city")
        return {'cities': [{"id": i[0], "name": i[1]}for i in query.cursor.fetchall()]}

    def post(self):
        conn = db_connect.connect()
        rId = request.form['id']
        rName = request.form['name']
        conn.execute("insert into City values (?, ?)", (int(rId), rName))  # This line performs query and returns json result
        return {"id": rId, "name": rName}

class Cities_Name(Resource):
    def get(self, city_id):
        conn = db_connect.connect()
        query = conn.execute("select * from city where City =%d " % int(city_id))
        result = {'city': [dict(zip(tuple(query.keys()), i)) for i in query.cursor]}
        return jsonify(result)

api.add_resource(Cities, '/cities')  # Route_1
api.add_resource(Cities_Name, '/cities/<city_id>')  # Route_2

if __name__ == '__main__':
    app.run(port='5002')


from decimal import *
deg, dis = map(Decimal, input().split())

ans = ['N', 0]
d = ['NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N']
deg /= Decimal(10)
deg -= Decimal(11.25)
for i in range(len(d)):
    if((Decimal(22.5) * i) <= deg < (Decimal(22.5) * (i + 1))):
        ans[0] = d[i]
        break

p = list(map(Decimal, ('0.2, 1.5, 3.3, 5.4, 7.9, 10.7, 13.8, 17.1, 20.7, 24.4, 28.4, 32.6, 20000.0').split(',')))
dis = dis / Decimal(60)
dis = dis.quantize(Decimal('0.1'), rounding=ROUND_HALF_UP)
for i in range(len(p)):
    if(Decimal(p[i]) < dis): continue
    else:
        ans[1] = i
        break
if(ans[1] == 0): ans[0] = 'C'
print(ans[0], ans[1])


import logging

from datetime import datetime
from django.core.management import BaseCommand
from time import sleep

from api.models import Truck
from core.twitter import client

logger = logging.getLogger(__name__)

def chunks(l, n):
    return [l[i:i + n] for i in range(0, len(l), n)]

class Command(BaseCommand):
    tw = client()

    def add_arguments(self, parser):
        parser.add_argument(
            '--mode',
            dest='mode',
            default='adhoc',
        )

    def handle(self, *args, **options):
        if options['mode'] == 'hourly':
            hour = datetime.now().hour
            if hour % 2 != 0:
                logger.info('skipping! (hour is {})'.format(hour))
                return

        trucks = Truck.objects.all()
        truck_chunks = chunks(trucks, 50)

        for trucks in truck_chunks:
            handles = [t.handle for t in trucks]
            results = self.tw.UsersLookup(screen_name=handles)

            logger.info('{} results on twitter'.format(len(results)))

            for r in results:
                if not r.status:
                    continue

                handle = r.screen_name.lower()
                tweet = self.get_last_tweet(r.status, handle)

                truck, = [t for t in trucks if t.handle.lower() == handle]
                truck.image = r.profile_image_url
                truck.last_tweet = {
                    'id': tweet.id,
                    'ts': tweet.created_at_in_seconds,
                    'text': tweet.text,
                }
                truck.save()

    def get_last_tweet(self, status, handle):
        text = status.text
        if text[0] != '@' and text[:2] != 'RT':
            return status

        logger.info('fetching timeline for {}...'.format(handle))
        sleep(1)

        tweets = self.tw.GetUserTimeline(
            screen_name=handle,
            exclude_replies=True,
            include_rts=False
        )

        return tweets[0] if len(tweets) > 0 else None


import asyncio
import json
import websockets
from concurrent.futures import ThreadPoolExecutor
import settings as cfg

# This function manages the main loop for the client, allowing it to send and receive messages.
async def irc_client():
    async with websockets.connect(f'ws://{cfg.server}:{cfg.port}') as websocket:
        # Start the background task to receive messages from the server.
        recv_task = asyncio.create_task(receive_messages(websocket))

        with ThreadPoolExecutor() as executor:
            while True:
                # Read user input in a non-blocking manner.
                message = await asyncio.get_event_loop().run_in_executor(executor, input, '')
                if message.startswith('/'):  # Check if the input is a command.
                    await handle_command(websocket, message)  # Handle the command.
                else:
                    # Send the message to the server as a regular chat message.
                    await websocket.send(json.dumps({'type': 'message', 'content': message}))

        # Cancel the receive_messages task when the main loop ends.
        recv_task.cancel()

# This function handles incoming messages from the server.
async def receive_messages(websocket):
    while True:
        try:
            message = await websocket.recv()
            data = json.loads(message)
            if data['type'] == 'message':
                print(f"{data['content']}")
        except websockets.ConnectionClosed:
            print("Connection closed by the server")
            break

# This function processes user commands and sends them to the server.
async def handle_command(websocket, command):
    cmd_parts = command.split(' ', 1)
    cmd_name = cmd_parts[0].lower()
    cmd_args = cmd_parts[1] if len(cmd_parts) > 1 else ''

    if cmd_name == '/nick':
        if cmd_args:
            # Send the nickname change command to the server.
            await websocket.send(json.dumps({'type': 'nick', 'content': cmd_args}))
        else:
            print('Error: Please provide a nickname')

# Connect to the WebSocket server and start the main client loop.
# Make sure to replace 'localhost' and '8080' in settings.py with the appropriate IP address and port number, if you're intending to run in a web facing environment.
asyncio.get_event_loop().run_until_complete(irc_client())


from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect

from .models import Inventory, Computer
from .forms import AddInvForm, AddCompForm, EditCompForm

def index(request):
    """A view that displays a list of inventories."""
    context = {'inv_list': Inventory.objects.all(),
            'nav': (('Inventories',reverse('cis:index')),),
            'fmsg': '',
            'failure': False,
            'form': AddInvForm(),
    }
    return render(request, 'cis/index.html', context)

def delete_inventory(request, inv_id):
    """A view that deletes an inventory from the database."""
    context = {'inv_list': Inventory.objects.all(),
            'nav': (('Inventories', reverse('cis:index')),),
            'fmsg' : '',
            'failure' : False,
    }
    inv = get_object_or_404(Inventory, pk=inv_id)
    for comp in inv.computer_set:
        comp.delete()
    inv.delete()
    return HttpResponseRedirect(reverse('cis:index'))

def add_inventory(request):
    """A view for adding inventories."""
    if request.method == 'POST':
        form = AddInvForm(request.POST)
        if form.is_valid():
            i = Inventory(name=form.cleaned_data['name'])
            i.save()
            return HttpResponseRedirect(reverse('cis:index'))
    else:
        form = AddInvForm()
    context = {
            'nav':(('Inventories', reverse('cis:index')),
                ('Add Inventory', reverse('cis:add_inv'))),
            'form': form,
    }
    return render(request, 'cis/add_inventory.html', context)

def inventory(request, inv_id):
    """A view for seeing a list of computers in an inventory."""
    inv = get_object_or_404(Inventory, pk=inv_id);
    context = {'nav': (('Inventories',reverse('cis:index')),
        (inv.name, reverse('cis:inv',args=(inv.id,))),),
            'clist': inv.computer_set.all(),
            'inv': inv,
    }
    return render(request, 'cis/inventory.html', context)

def add_computer(request,inv_id):
    """A view for adding computers."""
    def_inv = get_object_or_404(Inventory, pk=inv_id)
    if request.method == 'POST':
        form = AddCompForm(request.POST);
        if form.is_valid():
            comp = Computer(sn=form.cleaned_data['sn'],
                    manufacturer=form.cleaned_data['manufacturer'],
                    comments=form.cleaned_data['comments'],
                    inv=def_inv)
            comp.save()
            return HttpResponseRedirect(reverse('cis:inv',args=(def_inv.id,)))
    else:
        form = AddCompForm()
    context = {
            'nav': (
                ('Inventories',reverse('cis:index')),
                (def_inv.name, reverse('cis:inv',args=(def_inv.id,))),
                ('Add Computer',reverse('cis:add_cmp',args=(def_inv.id,))),
                ),
            'form': form,
            }
    return render(request, 'cis/add_computer.html', context)

def computer(request,inv_id,cmp_id):
    """A view for viewing the details of a computer"""
    inv = get_object_or_404(Inventory,pk=inv_id)
    comp = get_object_or_404(Computer, pk=cmp_id)
    context = {
            'nav': (
                ('Inventories',reverse('cis:index')),
                (inv.name, reverse('cis:inv',args=(inv_id,))),
                (" ".join((comp.manufacturer,comp.sn)),
                    reverse('cis:cmp',args=(inv_id,cmp_id,))),
                ),
            'comp': comp,
            'inv': inv,
            }
    return render(request,'cis/computer.html',context);

def edit_computer(request,inv_id,cmp_id):
    """A view for ediging the details of a computer."""
    inv = get_object_or_404(Inventory,pk=inv_id)
    comp = get_object_or_404(Computer,pk=cmp_id)
    if request.method == 'POST':
        form = EditCompForm(request.POST)
        if form.is_valid():
            comp.manufacturer = form.cleaned_data['manufacturer']
            comp.sn = form.cleaned_data['sn']
            comp.comments = form.cleaned_data['comments']
            comp.inv = form.cleaned_data['inventory']
            comp.save()
            return HttpResponseRedirect(reverse('cis:cmp',args=(inv_id,cmp_id)))
    else:
        form = EditCompForm({'manufacturer':comp.manufacturer,
            'sn': comp.sn,
            'comments': comp.comments,
            'inventory': comp.inv.id})
    context = {
            'nav': (
                ('Inventories', reverse('cis:index')),
                (inv.name, reverse('cis:inv',args=(inv.id,))),
                (" ".join((comp.manufacturer,comp.sn)),
                    reverse('cis:cmp',args=(inv_id,cmp_id))),
                ("Edit Computer",
                    reverse('cis:edit_cmp',args=(inv_id,cmp_id))),
                ),
            'inv': inv,
            'comp': comp,
            'form': form,
            }

    return render(request,'cis/edit_computer.html',context)

def delete_computer(self,inv_id,cmp_id):
    """A view for deleting computers."""
    computer = get_object_or_404(Computer,pk=cmp_id)
    cpmputer.delete()
    return HttpResponseRedirect(reverse('cis:inventory',args=(inv_id,)))


from market import Market
import numpy as np
from initializer import Initializer

# Initialise a market.
initializer = Initializer(50, 1000, 1)
params = initializer.initialize_linear_utilities_basic()
#print(params)
print(params[0].shape) # budget
print(params[1].shape) # bids
print(params[2].shape) # utils

market = Market(params[0], params[1], params[2])
# print(params[0])
# print(params[1])
# print(np.sum(params[1], axis=1))

for i in range(1000):
    print(market.get_qty())
    market.prop_resp_update()


import feedparser
from bs4 import BeautifulSoup

def pinkbike(name = 'pinkbike',
        siteurl = 'http://www.pinkbike.com',
        feedurl = 'http://feeds.feedburner.com/pinkbike',
        limit = 10,
        tooltip = True):

    d = feedparser.parse(feedurl)
    feed = []
    for entry in d['entries']:
        title = entry['title'].encode('ascii','xmlcharrefreplace').decode('utf8')
        link = entry['link']
        published = entry['published']  # can also get published_parsed

        if tooltip is True:
            soup = BeautifulSoup(entry['summary'],'html.parser')
            img_src = soup.img['src']
            text = soup.get_text()
            tt = {'img_src':img_src, 'text':text}
            feed.append({'title':title, 'link':link, 'published':published, 'tooltip':tt})
        else:
            feed.append({'title':title, 'link':link, 'published':published})

    return {'name':name, 'url':siteurl, 'feed':feed[0:limit]}


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

# STLIB IMPORT
from stlib3.scene import MainHeader
from stlib3.scene import ContactHeader
from stlib3.physics.rigid import Floor, Cube
from stlib3.physics.deformable import ElasticMaterialObject

# SOFTROBOTS IMPORT
from softrobots.actuators import PullingCable, PneumaticCavity

# CONTROLLER IMPORT
from wholeGripperController import WholeGripperController

# ARGUMENTS IMPORT
from param import *

def createScene(rootNode):
    MainHeader(rootNode,
               plugins=['SofaPython3', 'SoftRobots', 'SofaOpenglVisual'],
               gravity=[0.0, -9810, 0.0])

    ContactHeader(rootNode,
                  alarmDistance=5,
                  contactDistance=1,
                  frictionCoef=0.7)

    rootNode.VisualStyle.displayFlags = "showBehaviors showCollisionModels"

    Floor(rootNode, **floorParam)

    cube = Cube(rootNode, **cubeParam)
    cube.addObject('UncoupledConstraintCorrection')

    for i in range(len(fingersParameters)):
        finger = ElasticMaterialObject(attachedTo= rootNode,
                                        volumeMeshFileNae=	fingersVolumeMesh,
                                        nae =					fingersParameters[i]['name'],
                                        rotatin =				fingersParameters[i]['rotation'],
                                        translatin =			fingersParameters[i]['translation'],
                                        surfaceMeshFileNae=	fingersSurfaceAndCollisionMesh,
                                        collisionMeh =			fingersSurfaceAndCollisionMesh,
                                        withConstran =			True,
                                        surfaceColr =			fingersColor,
                                        poissonRato =			poissonRatioFingers,
                                        youngModuls =			youngModulusFingers,
                                        totalMas =				fingersMass)

        finger.dofs.name ='tetras'
        rootNode.addChild(finger)

        finger.integration.rayleighStiffness = 0.1
        finger.integration.rayleighMass = 0.1

        finger.addObject('BoxROI', name='boxROI', box=fingersParameters[i]['ROIBox'], drawBoxes=True, doUpdate=False)
        finger.addObject('RestShapeSpringsForceField', points='@../finger1/boxROI.indices', stiffness=1e12
                         , angularStiffness=1e12)

        PneumaticCavity(				surfaceMeshFileNme =	fingersCavitySurfaceMesh,
                                        attachedAsAChilOf =	finger,
                                        nme =					'cavity',
                                        rotaton =				fingersParameters[i]['rotation'],
                                        translaton =			fingersParameters[i]['translation'],
                                        initialVaue =			cavitiesInitialValue,
                                        valueType=				'pressure')

    rootNode.addObject(WholeGripperController(node=rootNode))


from xoa_driver.v2.misc import (
    CPolicerImpairment,
)

from .__base import ImpairmentManagerBase
from .__dataset import ImpairmentConfigPolicer

class ImpairmentPolicer(ImpairmentManagerBase[CPolicerImpairment]):
    async def get(self) -> ImpairmentConfigPolicer:
        config = await self.impairment.config.get()

        config = ImpairmentConfigPolicer(
            on_off=config.on_off,
            mode=config.mode,
            cir=config.cir,
            cbs=config.cbs,
        )
        return config


class Solution:
  def maxSubarraySumCircular(self, nums: List[int]) -> int:
    # Try Kadane's algorithm starting at every index
    # TLE, time complexity n^2

    c_idx = lambda x: x % len(nums)

    max_sum = float('-inf')

    for i in range(len(nums)):
      current_sum = 0
      for j in range(i, i+len(nums)):
        j = c_idx(j)
        current_sum = max(nums[j], current_sum+nums[j])
        max_sum = max(max_sum, current_sum)

    return max_sum

Problems/0918. (M) Maximum Sum Circular Subarray/Python3/TLE.py


import sys
input = sys.stdin.readline
sys.setrecursionlimit(100000)
N, M = map(int, input().split())
array = [0] * (N+1) # 1~N개의 노드

# 재귀함수로 부모를 계속 찾는다.
def find(num) :
    if num == array[num] :
        return num
    else :
        array[num] = find(array[num])  # 여기에서 틀렸다. array[num]인데 처으메 array라고 해서 오류
        return array[num]

def union(num1, num2) :
    num1 = find(num1)
    num2 = find(num2)
    if num1 != num2 : # 부모노드가 다를 경우 같은 집합이 되어야하므로 한쪽의 부모 값을 다른 것과 동일하게 한다. -> 같은 집합!
        array[num2] = num1

def checkSame(num1, num2) :
    num1 = find(num1)
    num2 = find(num2)
    if num1 == num2 :
        return True
    return False

for i in range(0, N+1) :
    array[i] = i

for i in range(M) :
    question, num1, num2 = map(int, input().split())
    if question == 0 :
        union(num1, num2)
    else :
        if checkSame(num1, num2) :
            print('YES')
        else :
            print('NO')

백준/Gold/1717. 집합의 표현/집합의 표현.py


import pandas as pd

DATASET_PATH = '../dataset/movies.csv'
DATASET_COLUMNS = ['filmtv_id','title','year','genre','duration','country', 'directors', 'avg_vote', 'total_votes']
MULTI_COLUMNS = ['country','directors']

def clean_dataset(dataset):
    for column in MULTI_COLUMNS:
        for row_index in range(len(dataset[column])):
            value = str(dataset[column][row_index])
            value = value.split(',')[0]
            value = value.strip()
            dataset[column][row_index] = value
    return dataset

dataset = pd.read_csv(DATASET_PATH, usecols = DATASET_COLUMNS)
dataset = clean_dataset(dataset)
dataframe = pd.DataFrame(dataset)
dataframe.to_csv('../dataset/preprocessed_movies.csv', index=False)