branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package winda.logic; import java.util.ArrayList; import java.util.List; /** * * @author Tomek */ public class Pietro { public List<Pasazer> pasazerowieWsiadający = new ArrayList(); public List<Pasazer> pasazerowieWysiadajacy = new ArrayList(); public int numerPietra; } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package winda.logic; /** * * @author Tomek */ public class Pasazer { private int start; private int stop; private int name; public Pasazer(int name, int start, int stop) { this.name = name; this.start = start; this.stop = stop; } public int GetName() { return this.name; } public int GetStart() { return this.start; } public int GetStop() { return this.stop; } public void SetStart(int start) { this.start = start; } public void SetStop(int stop) { this.stop = stop; } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package winda.logic; import java.util.ArrayList; import java.util.List; /** * * @author Tomek */ public class AlgorytmNajblizszeWezwanie implements IAlgorytm{ private int aktualnePietro = 0; private int maxPietro; private boolean kierunekJazdy = true; //true - gora, false - dol private List<Pasazer> pasazerowie; private List<Pasazer> pozostaliPasazerowie = new ArrayList<Pasazer>(); private List<Pietro> trasa = new ArrayList<Pietro>(); public List<Pietro> Trasa(List<Pasazer> pasazerowie) { this.pasazerowie = pasazerowie; for (Pasazer p : pasazerowie) this.pozostaliPasazerowie.add(new Pasazer(p.GetName(), p.GetStart(), p.GetStop())); while (this.pozostaliPasazerowie.size() > 0) { Pietro pietro = new Pietro(); pietro.numerPietra = this.aktualnePietro; List<Pasazer> tmpPasazerowie = new ArrayList<Pasazer>(); for(Pasazer p : this.pasazerowie) for(Pasazer pp : this.pozostaliPasazerowie) { boolean isIn = false; for(Pietro pi : this.trasa) for(Pasazer pw : pi.pasazerowieWsiadający) if(pw.GetName() == p.GetName()) isIn = true; if(!isIn && p.GetName() == pp.GetName() && p.GetStart() == this.aktualnePietro) tmpPasazerowie.add(p); } pietro.pasazerowieWsiadający = tmpPasazerowie; tmpPasazerowie = new ArrayList<Pasazer>(); List<Pasazer> doUsuniecia = new ArrayList<Pasazer>(); for(Pietro p : this.trasa) for(Pasazer pasazer : p.pasazerowieWsiadający) for(Pasazer pp : this.pozostaliPasazerowie) if(pasazer.GetName() == pp.GetName() && pasazer.GetStop() == this.aktualnePietro) { tmpPasazerowie.add(pasazer); doUsuniecia.add(pp); } pietro.pasazerowieWysiadajacy = tmpPasazerowie; this.pozostaliPasazerowie.removeAll(doUsuniecia); this.trasa.add(pietro); int nastepnePietro; boolean pustaWinda = true; if(this.kierunekJazdy) nastepnePietro = this.maxPietro; else nastepnePietro = 0; for(Pietro p : this.trasa) for(Pasazer pasazer : p.pasazerowieWsiadający) for(Pasazer pp : this.pozostaliPasazerowie) if(pasazer.GetName() == pp.GetName()){ pustaWinda = false; if(this.kierunekJazdy && pasazer.GetStop() > this.aktualnePietro && pasazer.GetStop() < nastepnePietro) nastepnePietro = pasazer.GetStop(); else if(!this.kierunekJazdy && pasazer.GetStop() < this.aktualnePietro && pasazer.GetStop() > nastepnePietro) nastepnePietro = pasazer.GetStop(); } if(pustaWinda){ for(Pasazer pp : this.pozostaliPasazerowie) if(this.kierunekJazdy && pp.GetStart() > this.aktualnePietro && pp.GetStart() < nastepnePietro) nastepnePietro = pp.GetStart(); else if(!this.kierunekJazdy && pp.GetStart() < this.aktualnePietro && pp.GetStart() > nastepnePietro) nastepnePietro = pp.GetStart(); } this.aktualnePietro = nastepnePietro; if(this.aktualnePietro == this.maxPietro) this.kierunekJazdy = false; else if(this.aktualnePietro == 0) this.kierunekJazdy = true; } for(int i = 1; i < trasa.size()-1; i++){ if(trasa.get(i).pasazerowieWsiadający.isEmpty() && trasa.get(i).pasazerowieWysiadajacy.isEmpty()){ trasa.remove(i); } } return trasa; } public void SetMaxPietro(int maxPietro) { this.maxPietro = maxPietro; } public static void main(String [] args){ List<Pasazer> pasazerowie = new ArrayList(); Parser p = new Parser(); //pasazerowie = p.Wczytaj("c:\\DemoDane.txt"); AlgorytmNajblizszeWezwanie anw = new AlgorytmNajblizszeWezwanie(); anw.SetMaxPietro(12); Pasazer p1=new Pasazer(1,2,7); Pasazer p2=new Pasazer(2,8,2); Pasazer p3=new Pasazer(3,6,3); Pasazer p4=new Pasazer(4,2,6); Pasazer p5=new Pasazer(5,11,5); Pasazer p6=new Pasazer(6,10,2); pasazerowie.add(p1);pasazerowie.add(p2);pasazerowie.add(p3); pasazerowie.add(p4);pasazerowie.add(p5);pasazerowie.add(p6); AlgorytmNajblizszeWezwanie nw = new AlgorytmNajblizszeWezwanie(); nw.trasa = anw.Trasa(pasazerowie); nw.SetMaxPietro(12); for(int i = 0; i<nw.trasa.size(); i++){ System.out.println("P: "+nw.trasa.get(i).numerPietra); for(int j=0; j < nw.trasa.get(i).pasazerowieWsiadający.size();j++){ System.out.print("Ws: "+nw.trasa.get(i).pasazerowieWsiadający.get(j).GetName()); } for(int j=0; j < nw.trasa.get(i).pasazerowieWysiadajacy.size();j++){ System.out.print("Wy: "+nw.trasa.get(i).pasazerowieWysiadajacy.get(j).GetName()); } System.out.println(); } List<List<Pietro>> tr = nw.TrasaDwieWindy(pasazerowie); } public List<List<Pietro>> TrasaDwieWindy(List<Pasazer> pasazerowie) { this.pasazerowie = pasazerowie; List<List<Pietro>> tr = new ArrayList<List<Pietro>>(); List<Pietro> trasa1 = new ArrayList<Pietro>(); //trasa windy pierwszej List<Pietro> trasa2 = new ArrayList<Pietro>(); //trasa windy drugiej List<Pasazer> pozostaliPasazerowie1 = new ArrayList<Pasazer>(); List<Pasazer> pozostaliPasazerowie2 = new ArrayList<Pasazer>(); int aktualnePietro1 = 0; int aktualnePietro2 = 0; boolean kierunekJazdy1 = true; boolean kierunekJazdy2 = true; for (Pasazer p : pasazerowie) this.pozostaliPasazerowie.add(new Pasazer(p.GetName(), p.GetStart(), p.GetStop())); for (Pasazer p : pasazerowie) pozostaliPasazerowie1.add(new Pasazer(p.GetName(), p.GetStart(), p.GetStop())); for (Pasazer p : pasazerowie) pozostaliPasazerowie2.add(new Pasazer(p.GetName(), p.GetStart(), p.GetStop())); while (this.pozostaliPasazerowie.size() > 0) { Pietro pietro1 = new Pietro(); pietro1.numerPietra = aktualnePietro1; List<Pasazer> tmpPasazerowie1 = new ArrayList<Pasazer>(); List<Pasazer> weszli1 = new ArrayList<Pasazer>(); for(Pasazer p : this.pasazerowie) for (Pasazer pp1 : pozostaliPasazerowie1) for(Pasazer pp : this.pozostaliPasazerowie) { boolean isIn = false; for(Pietro pi : trasa1) for(Pasazer pw : pi.pasazerowieWsiadający) if(pw.GetName() == p.GetName()) isIn = true; if(!isIn && p.GetName() == pp.GetName() && p.GetName() == pp1.GetName() && p.GetStart() == aktualnePietro1) tmpPasazerowie1.add(p); } for (Pasazer pp : pozostaliPasazerowie2) for (Pasazer p : tmpPasazerowie1) if(p.GetName() == pp.GetName()) weszli1.add(pp); pietro1.pasazerowieWsiadający = tmpPasazerowie1; pozostaliPasazerowie2.removeAll(weszli1); tmpPasazerowie1 = new ArrayList<Pasazer>(); List<Pasazer> doUsuniecia1 = new ArrayList<Pasazer>(); for(Pietro p : trasa1) for(Pasazer pasazer : p.pasazerowieWsiadający) for(Pasazer pp : this.pozostaliPasazerowie) if(pasazer.GetName() == pp.GetName() && pasazer.GetStop() == aktualnePietro1) { tmpPasazerowie1.add(pasazer); doUsuniecia1.add(pp); } pietro1.pasazerowieWysiadajacy = tmpPasazerowie1; this.pozostaliPasazerowie.removeAll(doUsuniecia1); trasa1.add(pietro1); int nastepnePietro1; boolean pustaWinda1 = true; if(kierunekJazdy1) nastepnePietro1 = this.maxPietro; else nastepnePietro1 = 0; for(Pietro p : trasa1) for(Pasazer pasazer : p.pasazerowieWsiadający) for(Pasazer pp : this.pozostaliPasazerowie) if(pasazer.GetName() == pp.GetName()){ pustaWinda1 = false; if(kierunekJazdy1 && pasazer.GetStop() > aktualnePietro1 && pasazer.GetStop() < nastepnePietro1) nastepnePietro1 = pasazer.GetStop(); else if(!kierunekJazdy1 && pasazer.GetStop() < aktualnePietro1 && pasazer.GetStop() > nastepnePietro1) nastepnePietro1 = pasazer.GetStop(); } if(pustaWinda1){ for(Pasazer pp : this.pozostaliPasazerowie) if(kierunekJazdy1 && pp.GetStart() > aktualnePietro1 && pp.GetStart() < nastepnePietro1) nastepnePietro1 = pp.GetStart(); else if(!kierunekJazdy1 && pp.GetStart() < aktualnePietro1 && pp.GetStart() > nastepnePietro1) nastepnePietro1 = pp.GetStart(); } aktualnePietro1 = nastepnePietro1; if(aktualnePietro1 == this.maxPietro) kierunekJazdy1 = false; else if(aktualnePietro1 == 0) kierunekJazdy1 = true; Pietro pietro2 = new Pietro(); pietro2.numerPietra = aktualnePietro2; List<Pasazer> tmpPasazerowie2 = new ArrayList<Pasazer>(); for(Pasazer p : this.pasazerowie) for(Pasazer pp2 : pozostaliPasazerowie2) for(Pasazer pp : this.pozostaliPasazerowie) { boolean isIn = false; for(Pietro pi : trasa2) for(Pasazer pw : pi.pasazerowieWsiadający) if(pw.GetName() == p.GetName()) isIn = true; if(!isIn && p.GetName() == pp.GetName() && p.GetName() == pp2.GetName() && p.GetStart() == aktualnePietro2) tmpPasazerowie2.add(p); } List<Pasazer> weszli2 = new ArrayList<Pasazer>(); for (Pasazer pp : pozostaliPasazerowie2) for (Pasazer p : tmpPasazerowie1) if(p.GetName() == pp.GetName()) weszli2.add(pp); pietro2.pasazerowieWsiadający = tmpPasazerowie2; pozostaliPasazerowie1.removeAll(weszli2); tmpPasazerowie2 = new ArrayList<Pasazer>(); List<Pasazer> doUsuniecia2 = new ArrayList<Pasazer>(); for(Pietro p : trasa2) for(Pasazer pasazer : p.pasazerowieWsiadający) for(Pasazer pp : this.pozostaliPasazerowie) if(pasazer.GetName() == pp.GetName() && pasazer.GetStop() == aktualnePietro2) { tmpPasazerowie2.add(pasazer); doUsuniecia2.add(pp); } pietro2.pasazerowieWysiadajacy = tmpPasazerowie2; this.pozostaliPasazerowie.removeAll(doUsuniecia2); trasa2.add(pietro2); int nastepnePietro2; boolean pustaWinda2 = true; if(kierunekJazdy2) nastepnePietro2 = this.maxPietro; else nastepnePietro2 = 0; for(Pietro p : trasa2) for(Pasazer pasazer : p.pasazerowieWsiadający) for(Pasazer pp : this.pozostaliPasazerowie) if(pasazer.GetName() == pp.GetName()){ pustaWinda2 = false; if(kierunekJazdy2 && pasazer.GetStop() > aktualnePietro2 && pasazer.GetStop() < nastepnePietro2) nastepnePietro2 = pasazer.GetStop(); else if(!kierunekJazdy2 && pasazer.GetStop() < aktualnePietro2 && pasazer.GetStop() > nastepnePietro2) nastepnePietro2 = pasazer.GetStop(); } if(pustaWinda2){ for(Pasazer pp : this.pozostaliPasazerowie) if(kierunekJazdy2 && pp.GetStart() > aktualnePietro2 && pp.GetStart() < nastepnePietro2) nastepnePietro2 = pp.GetStart(); else if(!kierunekJazdy2 && pp.GetStart() < aktualnePietro2 && pp.GetStart() > nastepnePietro2) nastepnePietro2 = pp.GetStart(); } aktualnePietro2 = nastepnePietro2; if(aktualnePietro2 == this.maxPietro) kierunekJazdy2 = false; else if(aktualnePietro2 == 0) kierunekJazdy2 = true; } List<Pietro> toRemove1 = new ArrayList<Pietro>(); for(int i = 1; i < trasa1.size()-1; i++) if(trasa1.get(i).pasazerowieWsiadający.isEmpty() && trasa1.get(i).pasazerowieWysiadajacy.isEmpty()) toRemove1.add(trasa1.get(i)); List<Pietro> toRemove2 = new ArrayList<Pietro>(); for(int i = 1; i < trasa2.size()-1; i++) if(trasa2.get(i).pasazerowieWsiadający.isEmpty() && trasa2.get(i).pasazerowieWysiadajacy.isEmpty()) toRemove2.add(trasa2.get(i)); trasa1.removeAll(toRemove1); trasa2.removeAll(toRemove2); tr.add(trasa1); tr.add(trasa2); return tr; } }<file_sep>package winda.animation; import java.awt.ScrollPane; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import winda.gui.WindaApp; import winda.logic.Pietro; /** * * @author Przemo */ public class ElevatorMovement extends Thread{ private ElevatorAnimation ea; Elevator first; Elevator second; private int floor_count; private final int floor_size = 50; private int time_for_floor; // Tymczasowo /* Miliseconds */ private int actual_floor; private double jump_time; private double speed; private int enter_exit_time; private boolean second_elevator; private ArrayList<Pietro> pietro; private ArrayList<Pietro> second_pietro; @Override public void run(){ this.first.setPietro(this.pietro); this.first.start(); if(this.second_elevator){ this.second.setPietro(this.second_pietro); this.second.start(); } } public ElevatorMovement(int floor_count){ this.floor_count = floor_count; this.init(); this.speed = 1; } public ElevatorAnimation getElevatorAnimation(){ return this.ea; } public void setPassangersOnFloor(int floor, int number){ this.ea.floor_passangers[floor]=number; } public void setPassangersOnFloors(int []passangers){ if(passangers.length == this.ea.floor_passangers.length) this.ea.floor_passangers = passangers; else for(int i=0;i<passangers.length;i++) this.ea.floor_passangers[i] = passangers[i]; } public void setPassangersInElevator(int passangers){ System.out.println("setPassangersInElevator("+passangers+")"); this.ea.elevator_passangers = passangers; } public int getPassangersInElevator(){ return this.ea.elevator_passangers; } public int getPassangersOnFloor(int floor){ return this.ea.floor_passangers[floor]; } public void setTimeForFloor(int time){ this.time_for_floor = time; this.jump_time = ((double)time)/((double)(this.floor_size)); this.first.setTimeForFloor(time); if(this.second_elevator) this.second.setTimeForFloor(time); } public double getSpeed(){ return this.speed; } public void setSpeed(int speed){ if(speed == 50) this.speed = 1; else if(speed >50){ speed = 100-speed; this.speed = (((double)speed+50)/2)/100; } else{ speed = 100-speed; this.speed = (((double)speed+50)*2)/100; } this.first.setSpeed(this.speed); if(this.second_elevator) this.second.setSpeed(this.speed); } public void setFloorsCount(int floors){ this.floor_count = floors; this.first.setFloorsCount(floors); if(this.second_elevator) this.second.setFloorsCount(floors); this.init(); } public void setEnterExitTime(int time){ this.enter_exit_time = time; this.first.setEnterExitTime(time); if(this.second_elevator) this.second.setEnterExitTime(time); } private void init(){ this.time_for_floor = 1000; this.actual_floor = 0; this.ea = new ElevatorAnimation(this.floor_count, this.second_elevator); /* Start z parteru */ this.ea.shift = this.floor_size * (this.floor_count-1); this.ea.shift2 = this.floor_size * (this.floor_count-1); this.jump_time = ((double)this.time_for_floor)/((double)(this.floor_size)); this.second_elevator = false; this.first = new Elevator(this.ea, this.floor_count, 1); } public void setPietro(ArrayList pietro, int elevator){ if(elevator == 1){ this.pietro = pietro; this.first.setPietro(pietro); } else{ this.second_pietro = pietro; this.second.setPietro(pietro); } } public void enableSecondElevator(){ this.second_elevator = true; this.second = new Elevator(this.ea, this.floor_count, 2); this.second.setSpeed(this.speed); this.ea.repaint(); } public void disableSecondElevator(){ this.second_elevator = false; this.second.interrupt(); this.second = null; this.ea.repaint(); } } <file_sep>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package winda.logic; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * * @author Tomek */ public class Logger { public Logger (List<Pietro> trasa){ for(Pietro pietro : trasa) { for(Pasazer pasazer : pietro.pasazerowieWysiadajacy) log.add("Na Piętrze " + pietro.numerPietra + " wysiadł pasażer " + pasazer.GetName()); for(Pasazer pasazer : pietro.pasazerowieWsiadający) log.add("Na Piętrze " + pietro.numerPietra + " wsiadł pasażer " + pasazer.GetName()); } } public void SaveLog(String filename){ FileWriter fw = null; try { fw = new FileWriter(filename); for (String s : log) fw.write(s+'\r'+'\n'); fw.close(); } catch (IOException ex) { java.util.logging.Logger.getLogger(Parser.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } } private List<String> log = new ArrayList<String>(); }
645caefa05ba1ad558c8646ae2b74cba12097f28
[ "Java" ]
5
Java
pgrondek/winda-ee2011
c2c2232011fb670a5bd953e69679bce9465a15db
a87b1d2c71c7c965cf27fe4ecdc0a24ab0bd9958
refs/heads/master
<repo_name>thaivinhtoan/App-Crush<file_sep>/README.md # App Crush ### Language: WinForm ### Display ![Display Image](Display/display.png) <file_sep>/AppCrush/Crush.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace AppCrush { public partial class Form : System.Windows.Forms.Form { string fileContent = "content.conf"; string[] lines = { "Anh đồng ý làm người yêu em nhé <3","Em biết anh sẽ đồng ý mà <3"}; public Form() { InitializeComponent(); if (!File.Exists(fileContent)) { using (File.Create(fileContent)) { }; } else { string[] readFile = File.ReadAllLines(fileContent); MessageBox.Show(readFile.Count().ToString()); if (readFile.Count() == 2) readFile.CopyTo(lines, 0); } lbCaption.Text = lines[0]; } private void bt_kdy_MouseHover(object sender, EventArgs e) { bt_kdy.Text = "Đồng ý"; bt_kdy.ForeColor = Color.Red; } private void bt_kdy_MouseLeave(object sender, EventArgs e) { bt_kdy.ForeColor = Color.Black; bt_kdy.Text = "Không đồng ý"; } private void bt_dy_Click(object sender, EventArgs e) { MessageBox.Show(lines[1]); } private void bt_kdy_Click(object sender, EventArgs e) { MessageBox.Show(lines[1]); } } }
c74d1824764745cd872c84197d5ea481c73ef426
[ "Markdown", "C#" ]
2
Markdown
thaivinhtoan/App-Crush
cbaa5ec00506180b1c9b310fef3c3be6c5b1311d
e018a5d3aa3a556c413c5fb13d8ac8032340d3f3
refs/heads/master
<file_sep>__author__ = 'nst8ft' from Crypto.PublicKey import RSA from Crypto.Cipher import AES from Crypto import Random from Crypto.Hash import SHA256 pad = 0 pad_total = 0 def secret_string(string, pub_key): bytes_obj = string.encode() enc_data = pub_key.encrypt(bytes_obj, 32) return enc_data def encrypt_file(file_name, sym_key): file_out = file_name + '.enc' cipher = AES.new(sym_key) global pad global pad_total with open(file_name, 'r') as in_file: with open(file_out, 'w') as out_file: while True: chunk_size = in_file.__sizeof__() chunk = in_file.read(chunk_size) padding = (16 - len(chunk) % 16) # print('enc pad is ' + str(padding)) hash = SHA256.new(sym_key) key_size16 = hash.digest()[0:16] cipher = AES.new(key_size16) if len(chunk) == 0: # print('enc pad_total is ' + str(pad_total)) break elif len(chunk) % 16 != 0: chunk += ' ' * padding pad_total += padding # print('enc pad_total is ' + str(pad_total)) out_file.write(str(cipher.encrypt(chunk))) return True def decrypt_file(file_name, sym_key): file_out = 'DEC_' + file_name.split('.enc')[0] hash = SHA256.new(sym_key) hash.digest() key_size16 = hash.digest()[0:16] cipher = AES.new(key_size16) # print('dec padding is ' + str(pad)) with open(file_name, 'r') as in_file: with open(file_out, 'w') as out_file: while True: chunk_size = in_file.__sizeof__() chunk = in_file.read(chunk_size) if len(chunk) == 0: break out_file.write(str(cipher.decrypt(chunk * 0))) return True def main(): str = "abcdefgh" # print(str) random_generator = Random.new().read key = RSA.generate(1024) sym = b'sixteen byte key' public_key = key.publickey() encoded = secret_string(str, key) # print(encoded) # print(key.decrypt(encoded)) test_file = 'helloworld.txt' enc_file = test_file + '.enc' dec_file = 'DEC_' + test_file.split('.enc')[0] with open(test_file, 'r') as f: print(test_file + ': %s' % f.read()) encrypt_file(test_file, sym) with open(enc_file, 'r') as f: print(enc_file + ': %s' % f.read()) decrypt_file(enc_file, sym) with open(dec_file, 'r') as f: print('DEC_helloworld.txt: %s' % f.read()) if __name__ == '__main__': main()
94a67419a49a209a71d0dfd3c70bc38f2854c9ef
[ "Python" ]
1
Python
nst8ft/hw4
1464b76b6557659fecdb8a540b0bcccc1aad6e5d
2158cdca96fb35cbf71c10af8c181ee3b0141780
refs/heads/master
<file_sep>from django.contrib.gis.db import models from django.contrib.postgres.fields import HStoreField from django.db import connections import json #gazetteer id format - type:id #country:"2 character ISO 3166-1 alpha-2 code" e.g. country:us #state:"2 character state fips code" e.g. state:33 #county:"2 character state fips code""3 character county fips code" e.g. county:33001 #municipality: "2 character state fips code""3 character county fips code"-"variable length GNIS ID" e.g. municipality:33003-873526 # in rare cases where no GNIS ID is available, the name is used in lower case and with underscores substituting spaces e.g. municipality:23025-t3_r5_bkp_wkr class GeneratedGeometry(models.Model): gazetteer_id = models.TextField(unique=True) geometry = models.GeometryField() osm_id = models.IntegerField(null=True) #optional OSM id for searches stemming from nominatim objects = models.GeoManager() def __unicode__(self): return self.gazetteer_id class Meta: db_table = "gazetteer_generatedgeometry" class State(models.Model): name = models.TextField() geometry = models.GeometryField() state_fips = models.CharField(max_length=2, unique=True) abbreviation = models.TextField(blank=True) def __unicode__(self): return self.name @property def identifier(self): return self.state_fips or self.name.lower().replace(" ", "_") @property def counties(self): return County.objects.filter(state_fips=self.state_fips) class County(models.Model): name = models.TextField() geometry = models.GeometryField() state_fips = models.CharField(max_length=2) county_fips = models.CharField(max_length=3) def __unicode__(self): return self.name @property def identifier(self): return "%s%s" % (self.state_fips, self.county_fips) or self.name.lower().replace(" ", "_") @property def municipalities(self): return Municipality.objects.filter(state_fips = self.state_fips, county_fips = self.county_fips).order_by("name") class Municipality(models.Model): name = models.TextField() geometry = models.GeometryField() place_id = models.TextField(null=True, blank=True) state_fips = models.CharField(max_length=2) county_fips = models.CharField(max_length=3) def __unicode__(self): return self.name @property def identifier(self): return self.place_id or self.name.lower().replace(" ", "_") @property def bbox(self): with connections["default"].cursor() as c: m = self c.execute("select ST_AsGeoJSON(Box2D(gazetteer_municipality.geometry)) from gazetteer_municipality where state_fips=%s and county_fips=%s and name=%s", [m.state_fips, m.county_fips, m.name]) r = c.fetchone() return json.loads(r[0])["coordinates"][0] class Meta: db_table = "gazetteer_municipality" class GNIS(models.Model): feature_id = models.IntegerField(primary_key=True) feature_name = models.TextField(null=True, blank=True) feature_class = models.TextField(null=True, blank=True) state_alpha = models.TextField(null=True, blank=True) state_numeric = models.TextField(null=True, blank=True) county_name = models.TextField(null=True, blank=True) county_numeric = models.TextField(null=True, blank=True) primary_latitude_dms = models.TextField(null=True, blank=True) primary_longitude_dms = models.TextField(null=True, blank=True) primary_latitude_dec = models.FloatField(null=True, blank=True) primary_longitude_dec = models.FloatField(null=True, blank=True) source_latitude_dms = models.TextField(null=True, blank=True) source_longitude_dms = models.TextField(null=True, blank=True) source_latitude_dec = models.FloatField(null=True, blank=True) source_longitude_dec = models.FloatField(null=True, blank=True) elevation_meters = models.FloatField(null=True, blank=True) elevation_feet = models.FloatField(null=True, blank=True) map_name = models.TextField(null=True, blank=True) date_created = models.TextField(null=True, blank=True) date_modified = models.TextField(null=True, blank=True) def __unicode__(self): return self.feature_name class FIPS55(models.Model): state = models.CharField(max_length=2) state_fips = models.CharField(max_length=2) place_fips = models.CharField(max_length=5) place_name = models.TextField() place_type = models.TextField() status = models.CharField(max_length=1) county = models.TextField() def __unicode__(self): return "%s: %s" % (self.state, self.place_name) class ShapeFileData(models.Model): geometry = models.GeometryField() record = HStoreField() state = models.CharField(max_length=2) name = models.TextField() state_fips = models.CharField(max_length=2) county_fips = models.CharField(max_length=3, blank=True, null=True) def __unicode__(self): return "%s, %s" % (self.name, self.state) <file_sep>from django.contrib import admin from gazetteer.models import FIPS55 # Register your models here. admin.site.register(FIPS55) <file_sep>from django.contrib.gis.geos import Polygon, Point, WKBReader from django.db import connections from django.db.models import Q from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, HttpResponseRedirect, Http404 from django.shortcuts import render from django.template.loader import render_to_string from django.views.decorators.csrf import csrf_exempt import httplib2 import json import os from osgeo import gdal from PIL import Image import re import requests from urllib2 import Request, urlopen from gazetteer.models import GeneratedGeometry from nominatim.models import Placex from ogp.importing import import_map, query_solr from ogp.models import BoundedItem, Category, ItemCollection, DownloadRequest from utilities.misc import name_from_filepath from utilities.conversion import fgdc_to_ogp_csv, latlng_to_srs from django.conf import settings def map(request): return render(request, "map.html") def solr_select(request): query_string = request.META['QUERY_STRING'] response = query_solr(query_string) return completed_request([response]) def query_solr(query_string): solr_url = "%s/select?%s" % (settings.SOLR_REPO["URL"], query_string) request = Request(solr_url) response = urlopen(request) return response.read() def download_items(request): layers = request.POST.get("layers") email_address = request.POST.get("email") wfs_format = request.POST.get("wfsFormat") if not email_address: return bad_request(["MISSING: email"]) if not layers and not external_layers: return bad_request(["MISSING: layers"]) if wfs_format == "shapefile": wfs_format = "shape-zip" elif wfs_format == "gml": wfs_format = "GML3" elif wfs_format == "kml": wfs_format = "KML" else: wfs_format = "application/json" layers = layers.split(",") if layers else [] if (len(layers)) > 10: return completed_request(["Please select 10 or fewer items to download"]) items = [] for layer in layers: items.append(BoundedItem.objects.get(LayerId=layer)) dr = DownloadRequest(email_address=email_address, wfs_format=wfs_format) dr.save() dr.items = items dr.active = True dr.save() return completed_request(["An email with your download link will be sent to %s" % (email_address)]) def originators(request): name_start = request.GET.get("name") gazetteer_id = request.GET.get("polygon") bbox = request.GET.get("bbox") geometry = None statement = "" parameters = [] if gazetteer_id: geometry = GeneratedGeometry.objects.get(gazetteer_id=gazetteer_id).geometry elif bbox: #would also need to set srs pass if name_start and geometry: pass elif name_start and not geometry: pass elif not name_start and geometry: pass else: #no parameters statement = 'SELECT DISTINCT "Originator", COUNT("Originator") FROM ogp_item GROUP BY "Originator" ORDER BY "Originator"' originators = [] with connections["default"].cursor() as c: c.execute(statement, parameters) for row in c.fetchall(): originators.append({"name": row[0], "count": row[1]}) return completed_request(originators) @csrf_exempt def nominatim_request(request): url = "http://epscor-pv-2.sr.unh.edu%s?%s" % (request.path, request.META['QUERY_STRING']) return external_request(url) @csrf_exempt def external_request(url, content_type = None, method="GET"): if not url.startswith("http://"): url = "http://%s" % (url) connection = httplib2.Http() headers, content = connection.request(url, method) response = HttpResponse(content, content_type = content_type or headers["content-type"]) return response_with_headers(response) @csrf_exempt def geoserver_request(request): path = request.path url = "%s%s?%s" % (settings.TOMCAT_BASE_URL, path, request.META['QUERY_STRING']) return external_request(url) @csrf_exempt def solr_request(request): if not request.META.get("REMOTE_ADDR").startswith("132.177"): return bad_request(["Remote Solr access is currently unavailable pending the finalization of metadata."]) path = request.path query = request.META['QUERY_STRING'] url = "%s%s?%s" % (settings.TOMCAT_BASE_URL, path, query) content_type = None if "wt=json" in url: content_type = "application/json" return external_request(url, content_type) @csrf_exempt def ogp_request(request): path = request.path query = request.META['QUERY_STRING'] url = "%s%s?%s" % (settings.TOMCAT_BASE_URL, path, query) return external_request(url) @csrf_exempt def external_solr_request(request): hostname = request.GET.get("hostname") path = request.GET.get("path", "solr") query = request.GET.get("query") errors = [] if not hostname: errors.append("MISSING: hostname") if not path: errors.append("MISSING: path") if errors: return bad_request(errors) if hostname.startswith("place"): hostname = "place.sr.unh.edu:8080" url = "http://%s/%s/select?%s" % (hostname,path,query) content_type = None if "wt=json" in url: content_type = "application/json" return external_request(url, content_type) @csrf_exempt def external_wfs_request(request, hostname): wfs_query = request.META["QUERY_STRING"] url = "%s/wfs?%s" % (hostname, wfs_query) return external_request(url, method=request.method) @csrf_exempt def external_wms_request(request, hostname): wms_query = request.META["QUERY_STRING"] url = "%s/wms?%s" % (hostname, wms_query) return external_request(url, method=request.method) @csrf_exempt def external_reflect_request(request, hostname): wms_query = request.META["QUERY_STRING"] url = "%s/wms/reflect?%s" % (hostname, wms_query) return external_request(url, method=request.method) def find_items(request): bounds_string = request.GET.get("bbox") point_string = request.GET.get("coord") gazetteer_polygon_id = request.GET.get("polygon") osm_id = request.GET.get("osm_id") field_string = request.GET.get("return") years_string = request.GET.get("years") keyword_string = request.GET.get("keyword") originator_string = request.GET.get("originator") datatype_string = request.GET.get("datatype") start = int(request.GET.get("start", 0)) end = int(request.GET.get("end", 0)) grouped = request.GET.get("grouped") group_id = request.GET.get("id") if not (bounds_string or gazetteer_polygon_id or point_string or osm_id) or not field_string: errors = [] if not (bounds_string or gazetteer_polygon_id or point_string or osm_id): errors.append("MISSING: osm_id, bbox, polygon, point") if not field_string: errors.append("MISSING: return") return bad_request(errors) query = Q() if gazetteer_polygon_id: query &= Q(bounds__intersects=GeneratedGeometry.objects.get(gazetteer_id=gazetteer_polygon_id).geometry) elif osm_id: polygon = None try: polygon = Placex.objects.get(osm_id=osm_id).geometry except MultipleObjectsReturned: with connections["nominatim"].cursor() as c: c.execute('select ST_Collect("placex"."geometry") from "placex" where "placex"."osm_id"=%s', [osm_id]) polygon = WKBReader().read(c.fetchone()[0]) query &= Q(bounds__intersects=polygon) if point_string: (lng, lat) = [float(x) for x in point_string.split(",")] point = Point(lat,lng) elif bounds_string: (minX, minY, maxX, maxY) = (float(b) for b in bounds_string.split(",")) bounds_polygon = Polygon(((minX, minY), (minX, maxY), (maxX, maxY), (maxX, minY), (minX, minY))) query &= Q(bounds__intersects=bounds_polygon) if keyword_string: keyword_query = Q(LayerDisplayName__icontains=keyword_string) # keyword_query = Q(Name__icontains=keyword_string) keyword_query |= Q(PlaceKeywords__icontains=keyword_string) keyword_query |= Q(ThemeKeywords__icontains=keyword_string) keyword_query |= Q(collection__full_name__icontains=keyword_string) query &= keyword_query if originator_string: query &= Q(Originator__icontains=originator_string) if datatype_string: datatype_query = Q() for datatype in datatype_string.split(","): datatype_query |= Q(DataType=datatype) query &= datatype_query #dates are strings in the format %Y-%m-%dT%H:%M:%SZ if years_string: (start_year, end_year) = years_string.split("-") date_query = Q() if (start_year): date_query &= Q(ContentDate__gt=start_year) if (end_year): date_query &= Q(ContentDate__lt=end_year) query &= date_query if grouped == "collection": groups = [] collections = [ItemCollection.objects.get(Q(short_name = group_id) | Q(full_name = group_id))] if group_id else ItemCollection.objects.all().order_by("external", "short_name") for ic in collections: items = BoundedItem.objects.filter(query & Q(collection=ic, collection__enabled = True)).order_by("LayerDisplayName") if items.count() == 0: continue total_number = items.count() items = items[start:end] if end else items name = ic.short_name if not ic.external else ic.full_name groups.append({"name": name, "id": ic.id, "items": [x.as_dictionary(field_string) for x in items], "totalNumber": total_number}) return completed_request({"groups": groups}) elif grouped == "datatype": groups = [] data_types = {} if group_id == "Maps and Images": data_types["Maps and Images"] = Q(DataType="Raster") | Q(DataType="Paper Map") elif group_id: data_types[group_id] = Q(DataType=group_id) else: data_types["Book"] = Q(DataType="Book") data_types["Line"] = Q(DataType="Line") data_types["Maps and Images"] = Q(DataType="Raster") | Q(DataType="Paper Map") data_types["Point"] = Q(DataType="Point") data_types["Polygon"] = Q(DataType="Polygon") for data_type in data_types: data_type_query = data_types[data_type] items = BoundedItem.objects.filter(query & data_type_query).order_by("LayerDisplayName") total_number = items.count() items = items[start:end] if end else items groups.append({"name": data_type, "items": [x.as_dictionary(field_string) for x in items], "totalNumber": total_number, "id": data_type}) return completed_request({"groups": groups}) elif grouped == "category": groups = [] if not group_id: misc_query = Q() for c in Category.objects.all().order_by("name"): items = c.items.filter(query).order_by("LayerDisplayName") total_number = items.count() items = items[start:end] if end else items groups.append({"name": c.name, "items": [x.as_dictionary(field_string) for x in items], "totalNumber": total_number, "id": c.id}) misc_query = misc_query & ~Q(ThemeKeywords__icontains=c.keyword) misc_items = BoundedItem.objects.filter(query & misc_query).order_by("LayerDisplayName") misc_total = misc_items.count() misc_items = misc_items[start:end] if end > 0 else misc_items groups.append({ "name": "Uncategorized", "items": [x.as_dictionary(field_string) for x in misc_items], "totalNumber": misc_total, "id": "misc" }) elif group_id == "Uncategorized": misc_query = Q() for c in Category.objects.all().order_by("name"): misc_query = misc_query & ~Q(ThemeKeywords__icontains=c.keyword) misc_items = BoundedItem.objects.filter(query & misc_query).order_by("LayerDisplayName") misc_total = misc_items.count() misc_items = misc_items[start:end] if end > 0 else misc_items groups.append({ "name": "Uncategorized", "items": [x.as_dictionary(field_string) for x in misc_items], "totalNumber": misc_total, "id": "misc" }) elif group_id: c = Category.objects.get(name=group_id) items = c.items.filter(query).order_by("LayerDisplayName") total_number = items.count() items = items[start:end] if end else items groups.append({"name": c.name, "items": [x.as_dictionary(field_string) for x in items], "totalNumber": total_number, "id": c.id}) return completed_request({"groups": groups}) elif grouped == "year": groups = [] years = {} items = BoundedItem.objects.filter(query).order_by("LayerDisplayName") for item in items: year = item.ContentDate[0:4] if not year in years: years[year] = [] years[year].append(item) for year in years: groups.append({"name": unicode(year), "items": [x.as_dictionary(field_string) for x in years[year]]}) return completed_request({"groups": groups}) else: items = BoundedItem.objects.filter(query).order_by("LayerDisplayName") total_number = items.count() items = items[start:end] if end else items groups = [{"name": "All Items Alphabetically", "items": [x.as_dictionary(field_string) for x in items], "totalNumber": total_number, "id": "all"}] return completed_request({"groups": groups}) def items_for_layers(request): layers = request.GET.get("layers") field_string = request.GET.get("return") if not layers: return bad_request(["MISSING: layers"]) if not field_string: return bad_request(["MISSING: return"]) layers = layers.split(",") items = BoundedItem.objects.filter(LayerId__in=layers) return completed_request([x.as_dictionary(field_string, include_collection=True) for x in items]) @csrf_exempt def minimal_ogp_import(request): image_path = request.GET.get("image_path") srs = request.GET.get("srs", "EPSG:3445") units = request.GET.get("units", "ft") no_image = request.GET.get("no_image") if not image_path or not srs or not units: errors = [] if not image_path: errors.append("MISSING: image_path") if not srs: errors.append("MISSING: srs") if not units: errors.append("MISSING: units") return bad_request(errors) extraData = { "DataType": "Raster", "Originator": "Unknown", "Publisher": "Unknown", "Abstract": "No Abstract" } if request.GET.get("bbox"): (minX, minY, maxX, maxY) = request.GET.get("bbox").split(",") extraData["MinX"] = minX extraData["MinY"] = minY extraData["MaxX"] = maxX extraData["MaxY"] = maxY extraData["ContentDate"] = request.GET.get("ContentDate") extraData["LayerDisplayName"] = request.GET.get("LayerDisplayName") else: for f in ["MinX", "MaxX", "MinY", "MaxY", "ContentDate", "LayerDisplayName"]: extraData[f] = request.GET.get(f) xml_string = render_to_string("fgdc_stub.xml", extraData) fgdc_file_path = "%s.xml" % (os.path.splitext(image_path)[0]) fgdc_file = open(fgdc_file_path, "w") fgdc_file.write(xml_string) fgdc_file.close() return import_to_ogp(request) def import_item(request): import_type = request.GET.get("type") if not import_type: return bad_request(["MISSING: type"]) if type in ("Scanned+Map", "Scanned Map", "Paper+Map", "Paper Map"): return import_to_ogp(request) elif type == "Book": return import_pdf(request) @csrf_exempt def import_to_ogp(request): image_path = request.GET.get("image_path") srs = request.GET.get("srs") units = request.GET.get("units") if None in [image_path, srs, units]: errors = [] if not image_path: errors.append("MISSING: image_path") if not srs: errors.append("MISSING: srs") if not units: errors.append("MISSING: units") return bad_request(errors) (saved, response) = import_map(image_path, srs, units) if saved: return completed_request() else: return bad_request([response]) @csrf_exempt def import_pdf(request): pdf_path = request.GET.get("pdf_path") bbox = request.GET.get("bbox") errors = [] if not pdf_path: errors.append("MISSING: pdf_path") if not bbox: errors.append("MISSING: bbox") if errors: return bad_request(errors) directory_path = os.path.split(pdf_path)[0] file_name = os.path.split(pdf_path)[1] name = os.path.splitext(file_name)[0] year = name.split("_")[0].replace("neigc","") section = int(name.split("_")[1].replace("sec", "")) section_title = None if section == 0: section_title = "Intro" else: section_title = "Section %d" % section (MinX, MinY, MaxX, MaxY) = bbox.split(",") fields = { "Onlink": "", "DataType": "Book", "MinX": MinX, "MaxX": MaxX, "MinY": MinY, "MaxY": MaxY, "ContentDate": year, "Originator": "New England Intercollegiate Geological Conference", "Publisher": "New England Intercollegiate Geological Conference", "Abstract": "No abstract", "LayerDisplayName": "NEIGC %s Excursion - %s" % (year, section_title), "Institution": "UNH" } xml_string = render_to_string("fgdc_stub.xml", fields) fgdc_file_path = "%s/%s.xml" % (directory_path, name) csv_file_path = "%s/%s.csv" % (directory_path, name) fgdc_file = open(fgdc_file_path, "w") fgdc_file.write(xml_string) fgdc_file.close() (h,r) = fgdc_to_ogp_csv(fgdc_file_path, True) csv_file = open(csv_file_path, "w") csv_file.writelines([h,r]) csv_file.close() url = "%s/update/csv?commit=true&stream.file=%s&stream.contentType=text/csv;charset=utf-8&overwrite=true" % (settings.SOLR_REPO["URL"], csv_file_path) response = requests.get(url=url) os.remove(csv_file_path) if response.status_code == 200: item_name = name # solrData = json.loads(query_solr("q=Name:%s&wt=json" % (itemName)).read())["response"]["docs"][0] solrData = json.loads(requests.get("%s/select?q=Name:%s&wt=json" % (settings.SOLR_REPO["URL"], item_name)).text) solrData = solrData["response"]["docs"][0] del solrData["_version_"] del solrData["PlaceKeywordsSynonyms"] del solrData["OriginatorSort"] solrData["srs"] = 4326 if len(BoundedItem.objects.filter(Name=item_name)) == 0: b = BoundedItem(**solrData) b.directory_path = directory_path b.collection = ItemCollection.objects.get(full_name__contains="Intercollegiate") b.save() else: b = BoundedItem.objects.get(Name=item_name) b.update_from_dictionary(solrData) b.directory_path = directory_path b.save() return completed_request() return completed_request([response.status_code]) @csrf_exempt def link_for_layer(request): (item, error_response) = item_from_request(request) if error_response: return error_response try: url = "%s/%s/%s" % (settings.ONLINK_BASE, item.collection.abbreviated_name, item.Name) return HttpResponseRedirect(url) except: pass url = re.findall("\<onlink\>.*\<\/onlink\>", item.FgdcText)[0] url = re.sub("<\/?onlink\>|&..;|URL:", "", url) if url: return HttpResponseRedirect(url) else: raise Http404 @csrf_exempt def abstract_for_layer(request): (item, error_response) = item_from_request(request) if error_response: return error_response return response_with_headers(HttpResponse(item.Abstract, content_type="text/plain")) @csrf_exempt def metadata_for_layer(request): (item, error_response) = item_from_request(request) if error_response: return error_response if not item.collection.metadata_available: return HttpResponse("Metadata is not available for this item.", content_type="text/plain") return response_with_headers(HttpResponse(item.FgdcText, content_type="text/xml")) def item_from_request(request): layerID = request.GET.get("id") if not layerID: return (None, bad_request(["MISSING: id"])) item = None try: item = BoundedItem.objects.get(LayerId=layerID) except: return (None, bad_request(["INVALID: %s" % (layerID)])) return (item, None) def bbox_for_layers(request): layers = request.GET.get("layers") if not layers: return bad_request(["MISSING: layers"]) layers = layers.split(",") c = connections["default"].cursor() c.execute('select ST_AsGeoJSON(Box2d(ST_Collect("ogp_boundeditem"."bounds"))) from "ogp_boundeditem","ogp_item" where "ogp_item"."LayerId" like any(%s) and "ogp_boundeditem"."item_ptr_id" = "ogp_item"."id"', [layers]) return completed_request(json.loads(c.fetchone()[0])) def items_at_coord(request): coord = request.GET.get("coord") fields = request.GET.get("fields") if not coord: return bad_request(["MISSING: coord"]) (lng,lat) = [float(x) for x in coord.split(",")] point = Point(lng,lat) items = BoundedItem.objects.filter(bounds__intersects=point, Institution = "UNH").order_by("ContentDate", "LayerDisplayName") return completed_request([b.as_dictionary(fields,True) for b in items]) def display_page(request, page, content_type="text/html"): if page.endswith(".json"): content_type = "application/json" try: return response_with_headers(render(request, page, content_type=content_type)) except: raise Http404 def bad_request(errors): return HttpResponseBadRequest(json.dumps({"version": 1, "completed": False, "errors": errors}), content_type="application/json") def completed_request(response=[]): http_response = HttpResponse(json.dumps({"version": 1, "completed": True, "response": response}), content_type="application/json") return response_with_headers(http_response) def plain_json_request(response = {}): return response_with_headers(HttpResponse(json.dumps(response), content_type="application/json")) def response_with_headers(response): response["Cache-Control"] = "max-age=3600" return response <file_sep>//MAYBE //layer adjustment //TableViewDelegate //functions // numberOfSections() -> int // numberOfRowsInSection(section) -> int // cellForRowInSection(row,section) -> Cell // hoverStartedForRowInSection(row, section) -> nothing // hoverEndedForRowInSection(row, section) -> nothing // selectedCellForRowInSection(row, section) -> nothing // headerForSection(section) -> SectionHeader (null for no header) // footerForSection(section) -> SectionFooter (null for no footer) // sectionSortable(section) -> bool // orderingForSection(section) -> int (1 asc, -1 desc) // orderChangedForSection(section) -> nothing // //GenericCellDelegate (?) //functions // onAdd() -> nothing (called after the cell is added to the table) // //ColorPickerDelegate //function // selectedColor(color) -> nothing (as [r,g,b,a]) // //LocationDelegate //functions // locationFound(latlng, accuracy) // locationError(error) //TimeSliderDelegate //functions // enableTimeSlider() // disableTimeSlider() // numberOfTimeSliderItems() // itemForTimeSliderPosition(position) // setTimeSliderPosition(position) // yearsForTimeSlider() //OGPDelegate //attributes // proxyURL - the address of the OGP proxy server // itemProperties - an array of item properties to download and store // //SearchDelegate //attributes // searchOptions - a dictionary of values to use when searching //functions // searchRequested() -> nothing // //MapViewDelegate //functions // mapViewMoveEnded() -> nothing // mapViewClicked(latlng) -> nothing // //PaginatingCellDelegate //functions // paginatingCellSetPageForSection(page,section) -> nothing // //DownloadFooterDelegate //functions // downloadRequested(email_address) -> nothing // clearLayers() -> nothing // //CollapsingSectionHeaderDelegate //functions // collapseStateForSection(section) -> bool (true: collapsed) // collapseStateChangedForSection(section, collapsed) -> nothing //GazetteerMenuDelegate // gazetteerPolygonSelected(polygonID, type, name) -> nothing // gazetteerPolygonUnSelected() -> nothing //CategoryChangeDelegate // selectedCategoryForIndex(index) -> nothing //Search Options Dictionary Key Constants SO_KEYWORD_TEXT = "keywordText" SO_LIMIT_TO_LOCATION = "limitToLocation" SO_LOCATION_TEXT = "locationText" SO_SHOW_POLYGON = "showPolygon" SO_ORIGINATOR_TEXT = "originatorText" SO_DATATYPE_TEXT = "datatypeText" SO_START_YEAR = "startYear" SO_END_YEAR = "endYear" //OSM Response Key Constants OSM_BBOX = "boundingbox" OSM_DISPLAY_NAME = "display_name" OSM_GEOJSON = "geojson" OSM_ID = "osm_id" //specific sections SECTION_SELECTED = 0 SECTION_LOADING = 1 //Other constants ENTER_KEY_CODE = 13 HTTP_OK = 200 XHR_DONE = 4 function OGPController(map_id, map_options, proxyURL, institutionID) { this.proxyURL = proxyURL this.institutionID = institutionID this.solrFieldString = "ContentDate,DataType,Institution,LayerDisplayName,LayerId,Location,Name,MinX,MaxX,MinY,MaxY,Originator,WorkspaceName" //also exposed as itemProperties this.nominatimURL = "/nominatim" this.loadingItems = false this.currentRequest = null this.searchOptions = {} this.searchData = {} this.openSection = 1 this.selectedGazetteerPolygon = null this.selectedItems = [] this.internalItems = {} this.internalItemTotals = {} this.timeSliderItems = [] this.mapView = new MapView(map_id, map_options, this) this.searchView = new SearchView("searchview", "search-field", ["location", "keyword", "showpolygon", "startyear", "endyear", "originator", "datatype"], this) this.gazetteerMenu = new GazetteerMenu("search-button-gazetteer", "/gazetteer", this) this.selectedItemsTableView = new TableView("selected-items-tableview") this.selectedItemsDelegate = new SelectedItemsDelegate(this.selectedItems, this.selectedItemsTableView, this.mapView, this) this.selectedItemsTableView.delegate = this.selectedItemsDelegate this.internalItemsTableView = new TableView("internal-items-tableview") this.internalItemsDelegate = new InternalItemsDelegate(this.internalItems, this.internalItemsTableView, this.mapView, this) this.internalItemsTableView.delegate = this.internalItemsDelegate this.categoryOptions = ["Collection", "Category", "Data Type", "All Items"] this.categoryIndex = 0 this.categoryChangeTableView = new TableView("category-change-tableview") this.categoryChangeDelegate = new CategoryChangeTableViewDelegate(this.categoryOptions, this) this.categoryChangeTableView.delegate = this.categoryChangeDelegate this.tableViews = new TableViewCollection([ this.selectedItemsTableView, this.internalItemsTableView, this.categoryChangeTableView ]) this.mapView.timeSliderButton = new TimeSliderButton({delegate: this}) this.mapView.map.addControl(this.mapView.timeSliderButton) this.mapView.showNHButton = new ShowNHButton({"mapView": this.mapView}) this.mapView.map.addControl(this.mapView.showNHButton) this.gazetteerLayers = new L.LayerGroup() this.enteredLocationLayers = new L.LayerGroup() this.mapView.map.addLayer(this.gazetteerLayers) this.mapView.map.addLayer(this.enteredLocationLayers) //modify the default leaflet vector styles this.setDefaultLeafletStyle() // //menu dialog set up plus general dialog parameters var dialogSetup = function(url, title, extraDialogClass, extraSetup) { $.ajax(url).done(function(data) { var element = $(data) var settings = { title: title, position: { my: "top", at: "top+100px", of: window }, buttons: [{ text: "Close", click: function() { $(this).dialog("close") } }] } if (extraDialogClass) { settings.dialogClass = extraDialogClass} var dialog = $(element).dialog(settings) if (extraSetup) { extraSetup() } }) } var controller = this $("#contact-button").click(function() { dialogSetup("/contact.html", "Contact Info") }) $("#help-button").click(function(e) { dialogSetup("/help.html", "Help") }) $("#about-button").click(function() { dialogSetup("/welcome.html", "Welcome to the UNH PLACE Geoportal", "ui-dialog-wide-dialog") }) if (location.search.includes("layers=")) { this.loadEnteredLayers() } else { // dialogSetup("/welcome.html", "Welcome to the UNH PLACE Geoportal", "ui-dialog-wide-dialog", function() { // controller.loadDataForMapBounds() // }) controller.setSearchViewPlaceholder() controller.loadDataForMapBounds() } } Object.defineProperty(OGPController.prototype, "groupNames", { get: function() { return Object.keys(this.internalItems) } }) Object.defineProperty(OGPController.prototype, "itemProperties", { get: function() { return this.solrFieldString.split(",") } }) Object.defineProperty(OGPController.prototype, "lastInternalSection", { //because "selected items" is section 0, this section number ends up being the same as the number of collections get: function() { return this.groupNames.length } }) Object.defineProperty(OGPController.prototype, "urlWithLayers", { get: function() { var layersParameter = sprintf("layers=%s", this.selectedItems.map(function(i) { return i.LayerId})) var url = sprintf("%s?%s", location.href.replace(/\?.*/,""), layersParameter) return url } }) Object.defineProperty(OGPController.prototype, "noResultsFound", { get: function() { return Object.keys(this.internalItems).length == 0 } }) OGPController.prototype.setDefaultLeafletStyle = function() { var vectorStyle = { color: "rgb(0,102,255)", fillOpacity: 0.2, opacity: 1, weight: 1 } L.GeoJSON.prototype.options = {} L.GeoJSON.mergeOptions(vectorStyle) DeferredGeoJSON.prototype.options = {} DeferredGeoJSON.mergeOptions(vectorStyle) L.Rectangle.mergeOptions(vectorStyle) ClickPassingGeoJSON.mergeOptions(vectorStyle) AntimeridianAdjustedGeoJSON.mergeOptions(vectorStyle) } OGPController.prototype.loadEnteredLayers = function() { var layers = this.getURLParameter("layers").split(",") var controller = this var internalPromise = null if (layers.length > 0) { internalPromise = new Promise(function(resolve, reject) { $.ajax(sprintf("/ogp/items?layers=%s&return=%s", layers, controller.solrFieldString)).done(function(data) { resolve(data.response) }) }) } else { internalPromise = Promise.resolve() } this.loadingItems = true this.tableViews.reloadData() Promise.all([internalPromise]).then(function(results) { var internalItems = results[0] || [] for (var i = internalItems.length - 1; i >= 0; --i) { var item = internalItems[i] var boundedItem = new BoundedItem(item, item.collection) boundedItem.selected = true controller.mapView.visibleLayers.addLayer(boundedItem.mapLayer) controller.selectedItems.push(boundedItem) } if (controller.selectedItems.length > 1) { controller.selectedItems.reverse() } controller.mapView.map.fitBounds(controller.getBBoxForItems(controller.selectedItems)) }) } OGPController.prototype.loadInternalItemsForMapBounds = function(groupID) { var bbox = this.mapView.map.getBounds().toBBoxString() var keyword = this.searchOptions[SO_KEYWORD_TEXT] var originator = this.searchOptions[SO_ORIGINATOR_TEXT] var startYear = this.searchOptions[SO_START_YEAR] || "" var endYear = this.searchOptions[SO_END_YEAR] var datatype = this.searchOptions[SO_DATATYPE_TEXT] //the search end year needs to be increased by one to be inclusive of the entered end year //since there might be no value entered, end year is first checked for existence endYear = parseInt(endYear) ? endYear + 1 : "" var groupType = this.categoryOptions[this.categoryIndex].replace(" ", "").toLowerCase() var url = sprintf("/ogp/find?grouped=%s&return=%s", groupType, this.solrFieldString) if (this.searchData[OSM_ID] && this.searchOptions[SO_LIMIT_TO_LOCATION]) { url += sprintf("&osm_id=%s", this.searchData[OSM_ID]) } else if (this.selectedGazetteerPolygon && this.searchOptions[SO_LIMIT_TO_LOCATION]) { url += sprintf("&polygon=%s:%s", this.selectedGazetteerPolygon.type, this.selectedGazetteerPolygon.id) } else { url += sprintf("&bbox=%s", bbox) } if (startYear || endYear) { var yearRange = sprintf("%s-%s", startYear, endYear) url = sprintf("%s&years=%s", url, yearRange) } if (keyword) { url = sprintf("%s&keyword=%s", url, keyword) } if (originator) { url = sprintf("%s&originator=%s", url, originator) } if (datatype) { url = sprintf("%s&datatype=%s", url, datatype) } var number = 20 // if (groupType == "allitems") { // if (!this.allItemsNumber) { // var tvs_h = Number($("#tableviews").css("height").replace("px", "")) // var sit_h = Number($("#selected-items-tableview").css("height").replace("px","")) // var cct_h = Number($("#category-change-tableview").css("height").replace("px", "")) // // var iit_h = (tvs_h - sit_h - cct_h) - 48 //get height of header and page control programatically // this.allItemsNumber = Math.floor(iit_h/20) - 1 // } // number = this.allItemsNumber // } var pageNumber = this.internalItemsDelegate.sectionCurrentPages[groupID] || 1 var start = (pageNumber - 1) * number var end = (pageNumber) * number url += sprintf("&start=%d&end=%d", start, end) if (groupID) { url += sprintf("&id=%s", groupID) } var controller = this var promise = new Promise(function(resolve, reject) { $.ajax(url).done(function(response) { resolve(response) }) }) promise.then(function(data) { if (!groupID) { Object.replace(controller.internalItems, {}) Object.replace(controller.internalItemTotals, {}) Object.replace(controller.internalItemsDelegate.sectionCurrentPages, {}) } var groups = data.response.groups var selectedItemNames = controller.selectedItems.map(function(i) { return i.Name }) for (var i = 0; i < groups.length; ++i) { var group = groups[i] controller.internalItemTotals[group.name] = group.totalNumber controller.internalItems[group.name] = group.items.map(function(i) { var itemIndex = selectedItemNames.indexOf(i.Name) if (itemIndex == -1) { return new BoundedItem(i, group.name) } else { return controller.selectedItems[itemIndex] } }) controller.internalItems[group.name].removeNulls() } controller.loadingItems = false controller.currentRequest = null }).then(null, function(error) { throw error }) return promise } OGPController.prototype.loadDataForMapBounds = function(groupID, section) { var controller = this if (!groupID) { controller.loadingItems = true controller.tableViews.reloadData() } var internalItemsPromise = this.loadInternalItemsForMapBounds(groupID, section) return Promise.all([internalItemsPromise]).then(function() { controller.loadingItems = false controller.searchView.enableSearch() if (section) { controller.internalItemsTableView.reloadSection(section) } else { controller.tableViews.reloadData() } }) } OGPController.prototype.loadOSMPolygon = function(location_string) { location_string = location_string.replace(/\s/g, "+") var polygonURL = sprintf("%s/search?q=%s&format=json&polygon_geojson=1", this.nominatimURL, location_string) var controller = this var promise = new Promise(function(resolve, reject) { $.ajax(polygonURL).done(function(data) { resolve(data) }) }) promise.then(function(data) { var polygon = data[0][OSM_GEOJSON] var layer = new ClickPassingGeoJSON(polygon, { "mapViewDelegate": controller }) controller.gazetteerLayers.clearLayers() controller.enteredLocationLayers.clearLayers() controller.enteredLocationLayers.addLayer(layer) }) return promise } OGPController.prototype.loadGazetteerPolygon = function(polygonID, type) { var map = this.mapView.map var controller = this var id = sprintf("%s:%s", type, polygonID) var polygonObject = (id == "state:02" || id == "county:02016" ? AntimeridianAdjustedGeoJSON : ClickPassingGeoJSON) var promise = new Promise(function(resolve, reject) { $.ajax(sprintf("/gazetteer/%s?id=%s", type, polygonID)).done(function(data) { resolve(data) }) }) promise.then(function(data) { var l = new polygonObject(data, {"mapViewDelegate": controller}) controller.selectedGazetteerPolygon["bounds"] = l.getBounds().toBBoxString() controller.enteredLocationLayers.clearLayers() controller.gazetteerLayers.clearLayers() controller.gazetteerLayers.addLayer(l) var oldBounds = controller.mapView.map.getBounds() controller.mapView.map.fitBounds(l.getBounds()) var newBounds = controller.mapView.map.getBounds() if (oldBounds.equals(newBounds)) { controller.loadDataForMapBounds() } }) return promise } OGPController.prototype.getBBoxForItems = function(items) { if (items && items.length > 0) { var bounds = items[0].bounds for (var i = 1; i < items.length; ++i) { bounds = bounds.union(items[i].bounds) } return bounds } } OGPController.prototype.setSearchViewPlaceholder = function() { if (this.searchOptions[SO_LIMIT_TO_LOCATION] && this.selectedGazetteerPolygon) { this.searchView.placeholderText = sprintf("Enter a location (Showing Gazetteer Entry: %s)", this.selectedGazetteerPolygon.name) } else { var center = this.mapView.map.getCenter() var mapZoom = this.mapView.map.getZoom() var osmSearchURL = sprintf("%s/reverse?format=json&lat=%f&lon=%f&zoom=%d", this.nominatimURL, center.lat, center.lng, mapZoom > 13 ? 13 : mapZoom) var nominatimPromise = new Promise(function(resolve, reject) { $.ajax(osmSearchURL).done(function(response) { resolve(response) }) }) var searchView = this.searchView nominatimPromise.then(function(data) { var displayName = data.display_name searchView.placeholderLocation = displayName }) } } //MISC UTILITY OGPController.prototype.getURLParameter = function(parameter) { if (!location.search.includes(parameter)) { return null } var queryString = location.search var r = new RegExp(sprintf("%s=.*?($|&)", parameter)) var value = r.exec(queryString)[0].replace(sprintf("%s=", parameter),"").replace("&","") return value } function SelectedItemsDelegate(selectedItems, tableView, mapView, controller) { this.selectedItems = selectedItems this.tableView = tableView this.mapView = mapView this.controller = controller this.proxyURL = controller.proxyURL } _sid = SelectedItemsDelegate.prototype _sid.itemForRowInSection = function(row, section) { if (row > this.selectedItems.length) { return null } else { return this.selectedItems[row] } } _sid.numberOfSections = function() { return 1 } _sid.numberOfRowsInSection = function(section) { return this.selectedItems.length || 1 } _sid.cellForRowInSection = function(row, section) { if (this.selectedItems.length == 0) { return new NoSelectedItemsCell() } else { var item = this.selectedItems[row] var delegate = this var allowSelection = !this.controller.timeSliderEnabled return new BoundedItemCell(item, row, section, delegate, delegate, allowSelection, this.mapView) } } _sid.headerForSection = function(section) { var headerText = "Selected Items" var subheaderText = sprintf("<span class='drag-help'>Click and drag %s to order layers</span>", "<img src='/media/img/sort_handle.png'>") return new SectionHeader(headerText, subheaderText, section) } _sid.footerForSection = function(section) { if (this.selectedItems.length > 0) { return new DownloadFooter(this.controller) } else { return null } } _sid.hoverStartedForRowInSection = function(row, section) { var item = this.selectedItems[row] this.mapView.previewLayers.addLayer(item.previewOutline) } _sid.hoverEndedForRowInSection = function(row, section) { this.mapView.previewLayers.clearLayers() } _sid.sectionSortable = function(section) { return true } _sid.orderingForSection = function(section) { return -1 } _sid.orderChangedForSection = function(section) { var sectionElementID = sprintf("#selected-items-tableview-section-%d", section) var sectionElement = $(sectionElementID) var rows = sectionElement.children(".tableview-row") var newSelectedItems = [] var currentSelectedItems = this.selectedItems $(rows).each(function() { var rowNum = parseInt($(this).attr("data-row")) newSelectedItems.push(currentSelectedItems[rowNum]) }) newSelectedItems.reverse() this.selectedItems.replaceValues(newSelectedItems) this.tableView.reloadSection(section) $(this.selectedItems).each(function() { this.mapLayer.bringToFront() }) } _sid.selectedCellForRowInSection = function(row, section) { var item = this.selectedItems[row] var controller = this.controller controller.mapView.previewLayers.removeLayer(item.previewOutline) if (item.selected) { item.selected = false controller.mapView.visibleLayers.removeLayer(item.mapLayer) controller.selectedItems.remove(this.selectedItems.indexOf(item)) controller.tableViews.reloadData() } } function InternalItemsDelegate(internalItems, tableView, mapView, controller) { this.internalItems = internalItems this.tableView = tableView this.mapView = mapView this.controller = controller this.proxyURL = controller.proxyURL this.collapseStates = {} this.sectionCurrentPages = {} } _iid = InternalItemsDelegate.prototype _iid.collectionKeyForSection = function(section) { return Object.keys(this.internalItems)[section] } _iid.collectionForSection = function(section) { var key = this.collectionKeyForSection(section) return this.internalItems[key] } _iid.collectionTotalForSection = function(section) { var key = this.collectionKeyForSection(section) return this.controller.internalItemTotals[key] } _iid.itemForRowInSection = function(row, section) { var index = row - 1 return this.collectionForSection(section)[index] } _iid.numberOfSections = function() { if (this.controller.loadingItems) { return 1 } if (this.controller.noResultsFound) { return 1 } return Object.keys(this.internalItems).length } _iid.numberOfRowsInSection = function(section) { if (this.controller.loadingItems) { return 1 } if (this.controller.noResultsFound) { return 1 } var numberOfItems = this.collectionForSection(section).length return numberOfItems + 1 } _iid.cellForRowInSection = function(row, section) { if (this.controller.loadingItems) { return new LoadingCell() } if (this.controller.noResultsFound) { return new NoResultsCell() } if (row == 0) { var collection = this.collectionKeyForSection(section) var totalNumber = this.controller.internalItemTotals[collection] var numberPerPage = 20 // var key = Object.keys(this.controller.internalItems)[section] // var numberPerPage = this.controller.internalItems[key].length var start = this.sectionCurrentPages[collection] || 1 var pages = Math.ceil(totalNumber / numberPerPage) return new PaginatingCell(start, pages, section, this) } var item = this.itemForRowInSection(row, section) var delegate = this var allowSelection = true return new BoundedItemCell(item, row, section, delegate, delegate, allowSelection, this.mapView) } _iid.hoverStartedForRowInSection = function(row, section) { var item = this.itemForRowInSection(row, section) this.mapView.previewLayers.addLayer(item.previewOutline) } _iid.hoverEndedForRowInSection = function(row, section) { this.mapView.previewLayers.clearLayers() } _iid.selectedCellForRowInSection = function(row, section) { var controller = this.controller var item = this.itemForRowInSection(row, section) this.mapView.previewLayers.removeLayer(item.previewOutline) if (item.selected) { item.selected = false controller.mapView.visibleLayers.removeLayer(item.mapLayer) controller.selectedItems.remove(controller.selectedItems.indexOf(item)) controller.tableViews.reloadData() } else { if (item.willDisableGeolocation && !controller.disabledGeolocation) { var dialogText = $(sprintf("<div><p class='dialog-text'>Due to security restrictions in Safari, displaying \"%s\" will disable the abilitiy to show your current location. You may also select this item for download without displaying it.</p></div>", item.LayerDisplayName)) var disableElement = $("<div class='dialog-option'>Display and Disable Current Location</div>") var selectElement = $("<div class='dialog-option'>Select for Download Only</div>") var cancelElement = $("<div class='dialog-option'>Cancel Selection</div>") dialogText.prepend("<img src='/media/img/disable-location.png' class='disable-location-logo'>") disableElement.click(function() { controller.disabledGeolocation = true controller.mapView.locateButton.remove() item.selected = true controller.selectedItems.push(item) controller.tableViews.reloadData() controller.mapView.visibleLayers.addLayer(item.mapLayer) dialogText.dialog("close") }) selectElement.click(function() { item.selected = true controller.selectedItems.push(item) controller.tableViews.reloadData() dialogText.dialog("close") }) cancelElement.click(function() { $(dialogText).dialog("close") }) dialogText.append(disableElement).append(selectElement).append(cancelElement) $(dialogText).dialog({ dialogClass: "geolocation-dialog", modal: true, title: "Disable Showing Current Location?" }) } else { item.selected = true controller.mapView.visibleLayers.addLayer(item.mapLayer) controller.selectedItems.push(item) controller.tableViews.reloadData() } } } _iid.headerForSection = function(section) { if (this.controller.loadingItems) { return new SectionHeader("Loading Items In Map Bounds", null, section) } if (this.controller.noResultsFound) { return new SectionHeader("No Items Found", null, section) } var name = this.collectionKeyForSection(section) var itemNumber = this.collectionTotalForSection(section) var itemWord = itemNumber > 1 ? "items" : "item" var title = sprintf("%s (%d %s)", name, itemNumber, itemWord) return new CollapsingSectionHeader(title, section, this, "internal-items-tableview") } _iid.footerForSection = function(section) { return null } _iid.sectionSortable = function(section) { return false } _iid.orderingForSection = function(section) { return 1 } _iid.orderChangedForSection = function(section) { } _iid.collapseStateForSection = function(section) { if (this.numberOfSections() == 1) { return false } var key = this.collectionKeyForSection(section) var state = this.collapseStates[key] if (state == undefined) { state = true this.collapseStates[key] = state } return state } _iid.collapseStateChangedForSection = function(section, state) { var key = this.collectionKeyForSection(section) this.collapseStates[key] = state } _iid.paginatingCellSetPageForSection = function(page, section) { var key = this.collectionKeyForSection(section) this.sectionCurrentPages[key] = page this.controller.loadDataForMapBounds(key, section) } function CategoryChangeTableViewDelegate(options, controller) { this.options = options this.controller = controller this.selectedIndex = 0 } _cctvd = CategoryChangeTableViewDelegate.prototype _cctvd.numberOfSections = function() { if (this.controller.timeSliderBar && this.controller.timeSliderBar.visible) { return 0 } else { return 1 } } _cctvd.numberOfRowsInSection = function(section) { return 1 } _cctvd.cellForRowInSection = function(row, section) { return new CategoryChangeCell(this.options, this.selectedIndex, this.controller, this) } _cctvd.hoverStartedForRowInSection = function(row, section) { } _cctvd.hoverEndedForRowInSection = function(row, section) { } _cctvd.selectedCellForRowInSection = function(row, section) { } _cctvd.headerForSection = function(section) { return null } _cctvd.footerForSection = function(section) { return null } _cctvd.sectionSortable = function(section) { return false } _cctvd.orderingForSection = function(section) { return 1 } _cctvd.orderChangedForSection = function(section) { } function CategoryChangeCell(options, selectedIndex, delegate, tableViewDelegate) { this.options = options this.selectedIndex = selectedIndex this.delegate = delegate this.tableViewDelegate = this } Object.defineProperty(CategoryChangeCell.prototype, "element", { get: function() { var cellElement = $("<div class='tableview-row no-highlight category-cell'></div>") for (var i = 0; i < this.options.length; ++i) { var option = this.options[i] var optionElement = $(sprintf("<span data-category-index='%d' class='category-option'>%s</span>", i, option)) if (i == this.selectedIndex) { optionElement.addClass("selected") } var cell = this optionElement.click(function() { $(".category-option").removeClass("selected") $(this).addClass("selected") var index = Number($(this).attr("data-category-index")) cell.tableViewDelegate.selectedIndex = index cell.delegate.selectedCategoryForIndex(index) }) $(cellElement).append(optionElement) } return cellElement } }) function EmptyTableViewDelegate() { } _etvd = EmptyTableViewDelegate.prototype _etvd.numberOfSections = function() { return 0 } _etvd.numberOfRowsInSection = function(section) { return 0 } _etvd.cellForRowInSection = function(row, section) { return new TextCell("") } _etvd.hoverStartedForRowInSection = function(row, section) { } _etvd.hoverEndedForRowInSection = function(row, section) { } _etvd.selectedCellForRowInSection = function(row, section) { } _etvd.headerForSection = function(section) { return null } _etvd.footerForSection = function(section) { return null } _etvd.sectionSortable = function(section) { return false } _etvd.orderingForSection = function(section) { return 1 } _etvd.orderChangedForSection = function(section) { } //Search "delegate" methods OGPController.prototype.searchRequested = function() { var map = this.mapView.map var controller = this this.searchView.disableSearch() var locationText = this.searchOptions[SO_LOCATION_TEXT] if (locationText) { this.selectedGazetteerPolygon = null var searchLocation = locationText.replace(/\s/g, "+") var osmSearchURL = sprintf("%s/search?q=%s&format=json", this.nominatimURL, searchLocation) var promise = new Promise(function(resolve, reject) { $.ajax(osmSearchURL).done(function(data) { resolve(data) }) }) promise.then(function(data) { if (data.length == 0) { alert(sprintf('Location "%s" not found.', locationText)) } else if (data.length == 1) { controller.setLocation(data[0]) } else { controller.showLocationSelection(data) } }) } else { this.loadDataForMapBounds() } } OGPController.prototype.setLocation = function(osmData) { var bbox = osmData["boundingbox"] var minY = bbox[0] var maxY = bbox[1] var minX = bbox[2] var maxX = bbox[3] var bounds = L.latLngBounds([minY, minX], [maxY, maxX]) if (this.searchOptions[SO_LIMIT_TO_LOCATION]) { this.searchData[OSM_ID] = osmData[OSM_ID] this.searchData[OSM_DISPLAY_NAME] = osmData[OSM_DISPLAY_NAME] this.searchData["bounds"] = bounds.toBBoxString() } if (this.searchOptions[SO_SHOW_POLYGON]) { this.loadOSMPolygon(osmData[OSM_DISPLAY_NAME]) } if (false) { } else { var map = this.mapView.map var oldMapBounds = map.getBounds() map.fitBounds(bounds, { maxZoom: 15 }) var newMapBounds = map.getBounds() if (newMapBounds.equals(oldMapBounds)) { this.loadDataForMapBounds() } } } OGPController.prototype.showLocationSelection = function(osmResults) { var controller = this var dialogElement = $(sprintf("<div><h3><i>%d Locations Found</i></h3></div>", osmResults.length)) var areaResults = osmResults.filter(function(osmResult) { var bbox = osmResult[OSM_BBOX] return bbox[0] != bbox[1] }) areaResults.sort(function(a,b) { return a[OSM_DISPLAY_NAME] > b[OSM_DISPLAY_NAME] ? 1 : -1 }) var pointResults = osmResults.filter(function(osmResult) { var bbox = osmResult[OSM_BBOX] return bbox[0] == bbox[1] }) pointResults.sort(function(a,b) { return a[OSM_DISPLAY_NAME] > b[OSM_DISPLAY_NAME] ? 1 : -1 }) var areaChoices = areaResults.map(function(osmResult) { var choice = $(sprintf("<div class='location-choice'>%s</div>", osmResult[OSM_DISPLAY_NAME])) $(choice).on("click", function() { controller.setLocation(osmResult) $(dialogElement).dialog("close") }) return choice }) var pointChoices = pointResults.map(function(osmResult) { var choice = $(sprintf("<div class='location-choice'>%s</div>", osmResult[OSM_DISPLAY_NAME])) $(choice).on("click", function() { controller.setLocation(osmResult) $(dialogElement).dialog("close") }) return choice }) if (areaChoices.length > 0) { dialogElement.append("<h3><img style='height: 18px' src='/media/img/location-area.png'>Areas</h3>") dialogElement.append(areaChoices) } if (pointChoices.length > 0) { dialogElement.append("<h3><img style='height: 18px' src='/media/img/location-point.png'>Single Locations</h3>") dialogElement.append(pointChoices) } var locationDialog = $(dialogElement).dialog({ dialogClass: "ui-dialog-location-dialog", title: "Choose a Location", buttons: [{ text: "Close", click: function() { $(this).dialog("close") //reset controller.loadDataForMapBounds() } }] }) } //MapView "delegate" methods OGPController.prototype.mapViewMoveEnded = function() { this.setSearchViewPlaceholder() this.loadDataForMapBounds() var locationSearchField = $("#search-field-location") if (locationSearchField.val()) { locationSearchField.animate({ "background-color": "#CCE5FF", "color": "#CCE5FF" }, 100, "swing", function() { locationSearchField.val(locationSearchField.attr("placeholder")) }).animate( { "background-color": "#FFFFFF", "color": "#888888" }, 100, "swing", function() { locationSearchField.val("") locationSearchField.css("color", "black") }) } var locationText = this.searchOptions[SO_LOCATION_TEXT] this.previousSearchOptions = {} this.previousSearchOptions[SO_LOCATION_TEXT] = locationText this.searchOptions[SO_LOCATION_TEXT] = null } if (location.search.indexOf("alert_point=true") > -1) { OGPController.prototype.mapViewClicked = function(latlng) { alert(sprintf("Lat, Lon: %f, %f", latlng.lat, latlng.lng)) } } /* OGPController.prototype.mapViewMouseMove = function(latlng) { } */ //DownloadFooterDelegate functions OGPController.prototype.downloadRequested = function(emailAddress, wfsFormat) { var downloadItems = [] for (var i = 0; i < this.selectedItems.length; ++i) { var item = this.selectedItems[i] downloadItems.push(item.LayerId) } var url = sprintf("%s/download", this.proxyURL) var postData = {"email": emailAddress, "wfsFormat": wfsFormat} if (downloadItems.length > 0) { postData["layers"] = downloadItems.join() } $.ajax(url, {"method": "POST", "data": postData, "beforeSend": function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", Cookies.get("csrftoken")) }}).done(function(data) { alert(data.response) }).fail(function(request) { var errors = JSON.parse(request.responseText)["errors"] alert(sprintf("Unable to request download. [%s]", errors.join(", "))) }) } OGPController.prototype.clearLayers = function() { for (var i = 0; i < this.selectedItems.length; ++i) { this.selectedItems[i].selected = false } this.mapView.visibleLayers.clearLayers() this.selectedItems.replaceValues([]) this.tableViews.reloadData() } //LocationDelegate OGPController.prototype.locationFound = function(latlng, accuracy) { var mapView = this.mapView var lat = latlng.lat var lng = latlng.lng mapView.map.removeLayer(mapView.userLocationLayer) mapView.userLocation = latlng mapView.userLocationMarker.setLatLng(latlng) mapView.userLocationMarker.bindPopup(sprintf("%.4f%s, %.4f%s", Math.abs(lat), lat > 0 ? "N" : "S", Math.abs(lng), lng > 0 ? "E" : "W")) mapView.userLocationAccuracyArea.setRadius(accuracy) mapView.userLocationAccuracyArea.setLatLng(latlng) mapView.map.addLayer(mapView.userLocationLayer) mapView.locateButton.options.spinner.stop() mapView.map.getZoom() > 15 ? mapView.map.setView(latlng, mapView.map.getZoom()) : mapView.map.setView(latlng, 15) } OGPController.prototype.locationError = function(error) { } //GazetteerMenuDelegate OGPController.prototype.gazetteerPolygonSelected = function(polygonID, type, name) { var controller = this var map = this.mapView.map var id = sprintf("%s:%s", type, polygonID) this.selectedGazetteerPolygon = {"id": polygonID, "type": type, "name": name} this.gazetteerLayers.clearLayers() this.enteredLocationLayers.clearLayers() this.searchOptions[SO_LOCATION_TEXT] = null $("#search-field-location").val("") this.searchData = {} var polygonObject = id == "state:02" || id == "county:02016" ? AntimeridianAdjustedGeoJSON : ClickPassingGeoJSON if (this.searchOptions[SO_SHOW_POLYGON]) { this.loadGazetteerPolygon(polygonID, type) } else { $.ajax(sprintf("/gazetteer/bbox?id=%s", id)).done(function(data) { var l = new polygonObject(data) controller.selectedGazetteerPolygon["bounds"] = l.getBounds().toBBoxString() map.fitBounds(l.getBounds()) }) } } OGPController.prototype.gazetteerPolygonUnselected = function() { this.gazetteerLayers.clearLayers() this.previousGazetteerPolygon = this.selectedGazetteerPolygon this.selectedGazetteerPolygon = null this.gazetteerMenu.tableView.reloadData() this.loadDataForMapBounds() } //TimeSliderDelegate OGPController.prototype.configureTimeSlider = function(e) { var controller = this var latlng = e.latlng controller.mapView.timeSliderButton.hideTooltip() controller.timeSliderPoint = latlng controller.timeSliderEnabled = true $("#mapview").removeClass("time-slider-selecting-point") var coord = sprintf("%f,%f", latlng.lng, latlng.lat) var url = sprintf("/ogp/items_at_coord?coord=%f,%f&fields=%s", latlng.lng, latlng.lat, this.solrFieldString) var itemsAtCoordPromise = new Promise(function(resolve, reject) { $.ajax(url).done(function(data) { resolve(data) }) }) itemsAtCoordPromise.then(function(result) { var items = result.response.map(function(item) { var foundItem = controller.selectedItems.find(function(i) { return i.LayerId == item.LayerId }) return foundItem || new BoundedItem(item, item.collection) }) controller.timeSliderItems = items controller.mapView.visibleLayers.clearLayers() controller.timeSliderBar = new TimeSliderBar(controller, controller.mapView) controller.mapView.map.addControl(controller.timeSliderBar.leafletControl) controller.internalItemsTableView.delegate = new TimeSliderTableViewDelegate(controller.mapView, controller.timeSliderItems, controller.timeSliderBar, controller, controller) controller.tableViews.reloadData() }) } OGPController.prototype.enableTimeSlider = function() { var controller = this $("#mapview").addClass("time-slider-selecting-point") this.mapView.map.once("click", this.configureTimeSlider, this) } OGPController.prototype.disableTimeSlider = function() { this.mapView.map.off("click", this.configureTimeSlider, this) $("#mapview").removeClass("time-slider-selecting-point") this.mapView.visibleLayers.clearLayers() this.timeSliderPoint = null this.timeSliderEnabled = false this.timeSliderItems = [] for (var i = 0; i < this.selectedItems.length; ++i) { var layer = this.selectedItems[i].mapLayer layer.setOpacity(1) this.mapView.visibleLayers.addLayer(layer) } $(this.selectedItems).each(function() { this.mapLayer.bringToFront() }) if (this.timeSliderBar && this.timeSliderBar.visible) { this.mapView.map.removeControl(this.timeSliderBar.leafletControl) //will set visible to false this.internalItemsTableView.delegate = this.internalItemsDelegate this.tableViews.reloadData() } } OGPController.prototype.numberOfTimeSliderItems = function() { return this.timeSliderItems ? this.timeSliderItems.length : 0 } OGPController.prototype.itemForTimeSliderPosition = function(position) { return this.timeSliderItems[position] } OGPController.prototype.setTimeSliderPosition = function(position){ var item = this.itemForTimeSliderPosition(position) var layer = item.mapLayer this.mapView.visibleLayers.clearLayers() this.mapView.visibleLayers.addLayer(layer) // this.visibleLayers.eachLayer(function(l) { l.setOpacity(0) }) // if (!this.visibleLayers.hasLayer(layer)) { // this.visibleLayers.addLayer(layer) // } // layer.bringToFront() // layer.setOpacity(1) } OGPController.prototype.yearsForTimeSlider = function() { var years = this.timeSliderItems.map(function(item) { return Number(item.ContentDate.substring(0,4)) }) return years } //CategoryChangeDelegate OGPController.prototype.selectedCategoryForIndex = function(index) { if (index == this.categoryIndex) { return } this.categoryIndex = index this.categoryChangeDelegate.selectedIndex = index this.loadDataForMapBounds() $(".category-option").removeClass("selected") $(sprintf(".category-option[data-category-index='%d']", index)).addClass("selected") } //END OF DELEGATE SECTION //TimeSliderTableViewDelegate function TimeSliderTableViewDelegate(mapView, items, timeSliderBar, timeSliderDelegate, controller) { this.mapView = mapView this.items = items this.timeSliderBar = timeSliderBar this.timeSliderDelegate = timeSliderDelegate this.controller = controller } _tstvd = TimeSliderTableViewDelegate.prototype _tstvd.numberOfSections = function() { return 1 } _tstvd.numberOfRowsInSection = function(section) { return this.items.length } _tstvd.cellForRowInSection = function(row, section) { var item = this.items[row] var selected = this.timeSliderBar.currentPosition == row var cell = new TimeSliderTableViewCell(row, section, item, this, this.timeSliderBar, selected) return cell } _tstvd.hoverStartedForRowInSection = function(row, section) { var item = this.items[row] this.mapView.previewLayers.addLayer(item.previewOutline) } _tstvd.hoverEndedForRowInSection = function(row, section) { var item = this.items[row] this.mapView.previewLayers.clearLayers() } _tstvd.selectedCellForRowInSection = function(row, section) { var item = this.items[row] if (item.reloadSection) { item.reloadSection = false if (item.selected) { this.controller.selectedItems.push(item) this.controller.selectedItemsTableView.reloadSection(0) } else { var index = this.controller.selectedItems.indexOf(item) this.controller.selectedItems.remove(index) this.controller.selectedItemsTableView.reloadSection(0) } } else { this.timeSliderBar.currentPosition = row } } _tstvd.headerForSection = function(section) { var years = this.timeSliderDelegate.yearsForTimeSlider() var firstYear = years[0] var lastYear = years[years.length-1] return new SectionHeader(sprintf("Time Slider Items (%s to %s)", firstYear, lastYear), null, 1) } _tstvd.footerForSection = function(section) { return null } _tstvd.sectionSortable = function(section) { return false } _tstvd.orderingForSection = function(section) { return 1 } function MapView(map_id, map_options, delegate) { map_options["attributionControl"] = false map_options["worldCopyJump"] = true map_options["maxZoom"] = 18 this.delegate = delegate this.map = new L.Map(map_id, map_options) this.previewLayers = new L.LayerGroup() this.visibleLayers = new L.LayerGroup() this.map.addLayer(this.previewLayers) this.map.addLayer(this.visibleLayers) if (navigator.geolocation) { this.locateButton = new LocateButton({"mapView": this}) this.map.addControl(this.locateButton) this.userLocation = null this.userLocationLayer = L.layerGroup() this.userLocationAccuracyArea = L.circle() this.userLocationAccuracyArea.setStyle({ stroke: false }) this.userLocationMarker = L.circleMarker(null, { color: "#FFFFFF", fillColor: "#03f", opacity: 1, weight: 3, fillOpacity: 1, radius: 7 }) this.userLocationLayer.addLayer(this.userLocationAccuracyArea) this.userLocationLayer.addLayer(this.userLocationMarker) } if (L.Browser.retina) { this.base_layer = L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}@2x.png', { subdomains: ['a','b','c','d'] }) } else { this.base_layer = L.tileLayer('https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png', { subdomains: ['a','b','c','d'] }) } if (location.search.indexOf("base=false") == -1) { this.map.addLayer(this.base_layer) } var attribution = new L.Control.Attribution({ position: "topright" }) attribution.addAttribution('&copy; UNH, &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>') this.map.addControl(attribution) if (delegate.mapViewClicked) { this.map.on("click", function(e) { delegate.mapViewClicked(e.latlng) }) } if (delegate.mapViewMoveEnded) { this.map.on("moveend", function() { delegate.mapViewMoveEnded() }) } if (delegate.locationFound) { this.map.on("locationfound", function(e) { var latlng = L.latLng(e.latitude, e.longitude) delegate.locationFound(latlng, e.accuracy) }) } var locateButton = this.locateButton this.map.on("locationerror", function(e) { locateButton.enabled = false $(locateButton.element).removeClass("enabled") locateButton.options.spinner.stop() if (e.code == 2) { //user allowed geolocation, but service is disabled alert("Unable to get your location.") } else if (e.code == 1) { //user denied geolocation alert("Please enable location services if you would like to display your location.") this.removeControl(locateButton.leafletControl) } else { delegate.locationError(e) } }) } MapView.prototype.removeUserLocation = function() { this.userLocation = null this.map.removeLayer(this.userLocationLayer) } var ShowNHButton = L.Control.extend({ options: { bounds: L.latLngBounds([42.6970417, -72.5571232], [45.3057789, -70.5613592]), mapView: null, position: "topleft" }, initialize: function(options) { options = L.Util.setOptions(this, options) return options }, onAdd: function(map) { var buttonElement = this._createButtonElement() L.DomEvent.disableClickPropagation(buttonElement) return buttonElement }, _createButtonElement: function() { var element = $("<div class='leaflet-button' id='show-nh-button' title='Show NH'><img src='/media/img/nh-button.png'></div>")[0] var button = this $(element).click(function() { button.options.mapView.map.fitBounds(button.options.bounds) }) return element } }) var LocateButton = L.Control.extend({ options: { enabled: false, mapView: null, position: "topleft", spinner: new Spinner({scale: 0.5}) }, initialize: function(options) { options = L.Util.setOptions(this, options) return options }, onAdd: function(map) { var buttonElement = this._createButtonElement() L.DomEvent.disableClickPropagation(buttonElement) return buttonElement }, _createButtonElement: function() { var element = $("<div class='leaflet-button' id='locate-button' title='Current Location'><img src='/media/img/locate-button.png'></div>")[0] var button = this $(element).click(function() { if (!button.options.enabled) { button.enableButton() } else { button.disableButton() } }) this.buttonElement = element return $(element)[0] }, disableButton: function() { this.options.enabled = false $(this.buttonElement).removeClass("enabled") this.options.mapView.removeUserLocation() }, enableButton: function() { this.options.enabled = true $(this.buttonElement).addClass("enabled") this.options.spinner.spin(this.buttonElement) this.options.mapView.map.locate() } }) function Tooltip(bodyText, direction) { this.bodyElement = $(sprintf("<div class='tooltip-body'>%s</div>", bodyText.replace(/ /g,"&nbsp;"))) this.direction = "left" //would use direction (top, right, bottom, left) this._element = null } Object.defineProperty(Tooltip.prototype, "element", { get: function() { if (!this._element) { this._element = $(sprintf("<div class='tooltip'><div class='%s-arrow'></div></div>", this.direction)) this._element.append($(this.bodyElement)) } return this._element } }) var TimeSliderButton = L.Control.extend({ options: { delegate: null, enabled: false, position: "topleft", tooltip: new Tooltip("Click a point on the map to start") }, initialize: function(options) { options = L.Util.setOptions(this, options) return options }, onAdd: function(map) { var buttonElement = this._createButtonElement() //using L.DomEvent.disableClickPropagation() causes the first click after //map movement to be ignored by leaflet return buttonElement }, _createButtonElement: function() { var element = $("<div class='leaflet-button' id='show-time-slider-button' title='Start Time Slider'><img src='/media/img/time-slider-button-disabled.png'></div>")[0] var button = this $(element).on("dblclick", function(e) { e.stopPropagation() }) $(element).on("click", function(e) { e.stopPropagation() // see comment in onAdd if (!button.options.enabled) { button.options.enabled = true $(this).addClass("enabled") $(this).children("img").attr("src", "/media/img/time-slider-button-enabled.png") button.options.delegate.enableTimeSlider() button.showTooltip(this) } else { button.options.enabled = false $(this).removeClass("enabled") $(this).children("img").attr("src", "/media/img/time-slider-button-disabled.png") button.options.delegate.disableTimeSlider() button.hideTooltip(this) } }) return element }, hideTooltip: function(element) { $(this.options.tooltip.element).remove() }, showTooltip: function(element) { $(element).append(this.options.tooltip.element) } }) function TimeSliderBar(delegate, mapView) { this.delegate = delegate this.mapView = mapView this.barElement = $("<div id='time-slider-bar'></div>")[0] this.prevButton = $("<span class='time-slider-button' id='time-slider-button-prev'>Prev</span>")[0] this.textElement = $("<span id='time-slider-bar-text'></span>")[0] this.nextButton = $("<span class='time-slider-button' id='time-slider-button-next'>Next</span>")[0] this._leafletControl = null this.visible = null this.timelineElement = $("<div class='time-slider-timeline'></div>")[0] this.currentPosition = 0 var bar = this $(this.prevButton).click(function() { if (bar.currentPosition > 0) { bar.currentPosition -= 1 } }) $(this.nextButton).click(function() { if (bar.currentPosition < (bar.delegate.numberOfTimeSliderItems() - 1)) { bar.currentPosition += 1 } }) $(this.barElement).append(this.timelineElement) $(this.barElement).append(this.prevButton) $(this.barElement).append(this.textElement) $(this.barElement).append(this.nextButton) } Object.defineProperty(TimeSliderBar.prototype, "timelineElement", { get: function() { return timelineElement }, set: function(element) { var timelineChartElement = $("<span class='time-slider-timeline-chart'></span>") var timelineFirstYearElement = $("<span class='time-slider-timeline-first-year time-slider-button'>First</span>") var timelineLastYearElement = $("<span class='time-slider-timeline-last-year time-slider-button'>Last</span>") var years = this.delegate.yearsForTimeSlider() var firstYear = years[0] var lastYear = years[years.length-1] $(timelineFirstYearElement).text(firstYear) $(timelineLastYearElement).text(lastYear) var timelineChartWidth = 380 var yearSpan = lastYear - firstYear var yearWidth = timelineChartWidth/(yearSpan+1) var lastYear = null for (var i = 0; i < years.length; ++i) { if (years[i] == lastYear) { continue } var yearDifference = years[i] - years[0] var leftDistance = yearDifference*yearWidth + 50 var yearElement = $("<span></span>") yearElement.css({ "display": "inline-block", "height": "20px", "width": (yearWidth - 1) + "px", "background-color": i == 0 ? "#253A71" : "#AAAAAA", "position": "absolute", "left": leftDistance+"px" }) yearElement.attr("title", years[i]) yearElement.attr("data-year", years[i]) var bar = this yearElement.click(function() { var year = Number($(this).attr("data-year")) var position = years.indexOf(year) bar.currentPosition = position }) $(timelineChartElement).append(yearElement) lastYear = years[i] } var bar = this $(timelineFirstYearElement).click(function() { bar.currentPosition = 0 }) $(timelineLastYearElement).click(function() { bar.currentPosition = bar.delegate.numberOfTimeSliderItems()-1 }) $(element).append(timelineFirstYearElement).append(timelineChartElement).append(timelineLastYearElement) timelineElement = element } }) Object.defineProperty(TimeSliderBar.prototype, "currentPosition", { get: function() { return this._currentPosition }, set: function(newValue) { if (this._currentPosition == newValue) { return } this._currentPosition = newValue currentPosition = newValue var numberOfItems = this.delegate.numberOfTimeSliderItems() //booleans var firstPosition = (newValue == 0) var lastPosition = ((numberOfItems - 1) == newValue) var noItems = (numberOfItems == 0) $(this.prevButton).removeClass("disabled") $(this.nextButton).removeClass("disabled") $(".time-slider-cell").removeClass("selected") $(sprintf(".time-slider-cell[data-position=%s]", currentPosition)).addClass("selected") $(sprintf(".time-slider-cell[data-position=%s] input[type=radio]", currentPosition)).prop("checked", true) if (firstPosition) { $(this.prevButton).addClass("disabled") } if (lastPosition || noItems) { $(this.nextButton).addClass("disabled") } $("#time-slider-bar span[data-year]").css("background-color", "#AAAAAA") $(sprintf("#time-slider-bar span[data-year=%s]", this.delegate.yearsForTimeSlider()[currentPosition])).each(function() { $(this).css("background-color", "#253A71") }) var text = null if (numberOfItems > 0) { var item = this.delegate.itemForTimeSliderPosition(newValue) var layerDisplayName = item.LayerDisplayName var year = item.ContentDate.substring(0,4) text = sprintf("%s - \"%s\"", year, layerDisplayName) this.delegate.setTimeSliderPosition(newValue) } else { text = "No items at point" } numberOfItems > 0 ? this.delegate.itemForTimeSliderPosition(newValue).LayerDisplayName : "No items at selected point" $(this.textElement).text(text) } }) Object.defineProperty(TimeSliderBar.prototype, "leafletControl", { get: function() { var barElement = this.barElement var bar = this var control = L.Control.extend({ options: { position: "bottomleft" }, onAdd: function(map) { L.DomEvent.disableClickPropagation(barElement) bar.visible = true return barElement }, onRemove: function(map) { bar.visible = false } }) if (!this._leafletControl) { this._leafletControl = new control() } return this._leafletControl } }) function TableView(tableViewID, tableViewDelegate) { this.tableViewID = tableViewID this.delegate = tableViewDelegate } TableView.prototype.reloadData = function() { var elementID = sprintf("#%s", this.tableViewID) $(elementID).empty() var numSections = this.delegate.numberOfSections() for (var i = 0; i < numSections; i++) { var sectionID = sprintf("%s-section-%d", this.tableViewID, i) var sectionElement = sprintf("<div class='tableview-section' id='%s'></div>", sectionID) $(sprintf("#%s", this.tableViewID)).append(sectionElement) var delegate = this.delegate if (this.delegate.sectionSortable(i)) { var sortHandle = $(sprintf("#%s", sectionID)).sortable({ axis: "y", handle: '.cell-sort-handle', items: 'div:not(.section-header, .section-footer)', start: function(e, ui) { $(ui.item[0]).addClass("sorting") }, stop: function(e, ui) { var section = parseInt($(ui.item[0]).attr("data-section")) delegate.orderChangedForSection(section) } }) } this.reloadSection(i) } } TableView.prototype.reloadSection = function(section) { var delegate = this.delegate var sectionID = sprintf("#%s-section-%d", this.tableViewID, section) var numRows = delegate.numberOfRowsInSection(section) $(sectionID).empty() if (numRows > 0) { var header = delegate.headerForSection(section) if (header) { $(sectionID).append(header.element) } var range = Array.range(0, numRows) range = delegate.orderingForSection(section) == 1 ? range : range.reverse() $(range).each(function() { var row = this.valueOf() var cell = delegate.cellForRowInSection(row, section) var cellElement = cell.element $(sectionID).append(cellElement) if (cell.onAdd) { cell.onAdd() } }) var footer = delegate.footerForSection(section) if (footer) { $(sectionID).append(footer.element) } } } TableView.prototype.removeRowInSection = function(row, section) { this.reloadSection(section) } function TableViewCollection(tableViews) { this.tableViews = tableViews } TableViewCollection.prototype.reloadData = function() { for (var i = 0; i < this.tableViews.length; ++i) { this.tableViews[i].reloadData() } } function SearchView(view_id, field_id_base, fields, delegate, submitButton, resetButton) { this.view_id = view_id this.element_id = sprintf("#%s",view_id) this.field_id_base = field_id_base this.delegate = delegate this.submitButton = submitButton || $("#search-button-submit") this.resetButton = resetButton || $("#search-button-reset") this.enabled = true for (var i = 0; i < fields.length; ++i) { this[sprintf("%s_field_id", fields[i])] = sprintf("#%s-%s", field_id_base, fields[i]) } $(this.element_id).keypress(function(e) { if (e.which == ENTER_KEY_CODE) { delegate.searchRequested() } }) $(this.location_field_id).bind("input", function() { delegate.searchOptions[SO_LOCATION_TEXT] = $(this).val().trim() }) $(this.keyword_field_id).bind("input", function() { delegate.searchOptions[SO_KEYWORD_TEXT] = $(this).val().trim() }) $(this.startyear_field_id).bind("input", function() { delegate.searchOptions[SO_START_YEAR] = $(this).val().trim() }) $(this.endyear_field_id).bind("input", function() { delegate.searchOptions[SO_END_YEAR] = $(this).val().trim() }) $(this.originator_field_id).bind("input", function() { delegate.searchOptions[SO_ORIGINATOR_TEXT] = $(this).val().trim() }) $(this.datatype_field_id).bind("change", function() { delegate.searchOptions[SO_DATATYPE_TEXT] = $(this).val() }) $(this.showpolygon_field_id).bind("click", function() { var checked = $(this).prop("checked") delegate.searchOptions[SO_SHOW_POLYGON] = checked delegate.searchOptions[SO_LIMIT_TO_LOCATION] = checked $("#gazetteer-showpolygon").prop("checked", checked) if (!checked) { delegate.gazetteerLayers.clearLayers() delegate.enteredLocationLayers.clearLayers() if (delegate.selectedGazetteerPolygon) { delegate.previousGazetteerPolygon = delegate.selectedGazetteerPolygon delegate.selectedGazetteerPolygon = null delegate.loadDataForMapBounds() } if (delegate.searchData[OSM_ID]) { delegate.searchData = {} delegate.loadDataForMapBounds() } } else if (checked && delegate.previousSearchOptions && delegate.previousSearchOptions[SO_LOCATION_TEXT]) { delegate.searchOptions[SO_LOCATION_TEXT] = delegate.previousSearchOptions[SO_LOCATION_TEXT] delegate.searchRequested() } else if (checked && delegate.previousGazetteerPolygon) { var p = delegate.previousGazetteerPolygon delegate.gazetteerPolygonSelected(p.id, p.type, p.name) } }) $(this.submitButton).on("click", function(e) { delegate.searchRequested() }) var searchView = this $(this.resetButton).on("click", function() { searchView.resetSearch() }) } Object.defineProperty(SearchView.prototype, "placeholderLocation", { set: function(newValue) { $(this.location_field_id).attr("placeholder", sprintf("Enter a location (Currently: %s)", newValue)) } }) Object.defineProperty(SearchView.prototype, "placeholderText", { get: function() { return $(this.location_field_id).attr("placeholder") }, set: function(newValue) { $(this.location_field_id).attr("placeholder", newValue) } }) SearchView.prototype.resetSearch = function() { var delegate = this.delegate delegate.searchOptions = {} $(this.location_field_id).val("") $(this.keyword_field_id).val("") $(this.startyear_field_id).val("") $(this.endyear_field_id).val("") $(this.originator_field_id).val("") $(this.datatype_field_id).val("") $(this.showpolygon_field_id).prop("checked", false) delegate.gazetteerLayers.clearLayers() delegate.enteredLocationLayers.clearLayers() if (delegate.selectedGazetteerPolygon) { delegate.previousGazetteerPolygon = null delegate.selectedGazetteerPolygon = null } if (delegate.searchData[OSM_ID]) { delegate.searchData = {} } delegate.loadDataForMapBounds() } SearchView.prototype.disableSearch = function() { $(this.submitButton).addClass("disabled") $(this.submitButton).text("Searching") $(this.submitButton).off("click") this.enabled = false } SearchView.prototype.enableSearch = function() { var delegate = this.delegate $(this.submitButton).removeClass("disabled") $(this.submitButton).text("Search") if (!this.enabled) { $(this.submitButton).on("click", function() { delegate.searchRequested() }) } this.enabled = true } function BoundedItem(dictionary, collection) { if (dictionary.Location && dictionary.Location.indexOf("{") != 0) { dictionary.Location = sprintf("{%s}", dictionary.Location) } if (dictionary.Location) { dictionary.Location = JSON.parse(dictionary.Location); } else { dictionary.Location = { "wms": ["/geoserver/wms"] } } for (var k in dictionary) { this[k] = dictionary[k] } this.collection = collection this.bounds = L.latLngBounds([this.MinY, this.MinX], [this.MaxY, this.MaxX]) this.previewOutline = L.rectangle(this.bounds) this.selected = false this._highResLayer = false var item = this if (this.isVectorType) { this.mapLayer = new DeferredGeoJSON(this.wfsURL) this.mapLayer.options = new LeafletOptions(this.mapLayer.options) } else if (this.DataType == "Book") { var circleText = sprintf("%s\n%s", this.ContentDate.split("-")[0], this.LayerDisplayName.split(" - ")[1].replace("Section", "§")) var fontSize = 12 var marker = new L.Marker.SVGMarker.BookMarker(this.bounds.getCenter(), {"iconOptions": { "circleText": circleText, "fontSize": fontSize }}) marker.bindPopup(sprintf("<div>%s</div><a href='/media/pdf/%s.pdf' target='_blank'>View PDF</a>", this.LayerDisplayName, this.Name)) var group = new L.LayerGroup() group.options = new LeafletOptions(group.options) group.addLayer(marker) group.addLayer(new L.Rectangle(this.bounds)) group.options.opacity = 1 this.mapLayer = group } else { this.mapLayer = L.tileLayer.wms(this.wmsURL, { layers: this.Name, format: "image/png", transparent: true }) } } Object.defineProperty(BoundedItem.prototype, "highResLayer", { get: function() { return this._highResLayer }, set: function(highRes) { this._highResLayer = highRes if (highRes) { this.mapLayer.options.tileSize = 128 this.mapLayer._map.setMaxZoom(17) this.mapLayer.options.maxZoom = 17 this.mapLayer.options.zoomOffset = 1 } else { this.mapLayer.options.tileSize = 256 this.mapLayer._map.setMaxZoom(18) this.mapLayer.options.maxZoom = 18 this.mapLayer.options.zoomOffset = 0 } this.mapLayer._update() } }) Object.defineProperty(BoundedItem.prototype, "isVectorType", { get: function() { return ["Point", "Polygon", "Line"].includes(this.DataType) } }) Object.defineProperty(BoundedItem.prototype, "wfsURL", { get: function() { if (this.Location && this.Location["wfs"] && this.WorkspaceName && this.Name) { var url = this.Location["wfs"].replace("http://","") return sprintf("/external_wfs/%s?request=GetFeature&typeName=%s:%s&outputFormat=application/json&srsName=EPSG:4326", url, this.WorkspaceName, this.Name) } else { return null } } }) Object.defineProperty(BoundedItem.prototype, "wmsURL", { get: function() { var url = this.Location && (typeof this.Location.wms) == "object" ? this.Location.wms[0] : null return url } }) Object.defineProperty(BoundedItem.prototype, "secureWMS", { get: function() { return this.wmsURL.startsWith("https://") } }) Object.defineProperty(BoundedItem.prototype, "willDisableGeolocation", { get: function() { return L.Browser.safari && !this.isVectorType && !this.secureWMS } }) Object.defineProperty(BoundedItem.prototype, "thumbnailURL", { get: function() { var url = this.Location && (typeof this.Location.wms) == "object" ? this.Location.wms[0] : null if (!url.startsWith("https://")) { url = sprintf("/external_reflect/%s", url.replace(/^http:\/\//, "")) } return url } }) Object.defineProperty(BoundedItem.prototype, "contentYear", { get: function() { return this.ContentDate.substring(0,4) } }) function BoundedItemCell(item, row, section, delegate, infoButtonDelegate, allowSelection, mapView) { this.item = item this.selected = item.selected this.row = row this.section = section this.delegate = delegate this.infoButtonDelegate = infoButtonDelegate this.allowSelection = allowSelection this.mapView = mapView this.opacityValue = 100 } BoundedItemCell.prototype.enableHiResLayer = function() { var item = this.item item.mapLayer.remove() var options = { layers: item.Name, format: "image/png", transparent: true, detectRetina: true } item.mapLayer = L.tileLayer.wms(item.wmsURL, options) item.mapLayer.options.originalTileSize = item.mapLayer.options.tileSize this.mapView.visibleLayers.addLayer(item.mapLayer) } Object.defineProperty(BoundedItemCell.prototype, "element", { get: function() { var item = this.item var collectionName = item.collection var map = this.mapView.map var selectedClass = this.selected ? " selected" : "" var cell = $(sprintf("<div class='bounded-item-cell tableview-row%s' data-row='%d' data-section='%d' data-layer-id='%s'></div>", selectedClass, this.row, this.section, item.LayerId)) if (item.DataType == "Book" || item.isVectorType) { $(cell).addClass("unsortable") } if (this.section > 1) { $(cell).attr("data-collection", collectionName) } var selectedField = $("<input type='checkbox' class='cell-field selected-field'>") selectedField.attr("checked", this.selected) var delegate = this.delegate var infoButtonDelegate = this.infoButtonDelegate var row = this.row var section = this.section if (this.allowSelection) { $(selectedField).click(function(e) { e.preventDefault() delegate.selectedCellForRowInSection(row, section) }) } else { $(selectedField).attr("disabled", "disabled") if (!this.selected) { $(selectedField).css("visibility", "hidden") } } var layerDisplayName = this.item.LayerDisplayName layerDisplayName = sprintf("%s (%s)", layerDisplayName, this.item.contentYear) var institution = this.item.Institution var layerDisplayNameField = $(sprintf("<span class='layerdisplayname-field'>%s</span>", layerDisplayName)) var institutionField = $(sprintf("<img class='institution-field' src='/media/img/logo_%s.png' title='%s' alt='%s Logo'>", institution.toLowerCase(), institution, institution)) var infoButton = new InfoButton(item, delegate.proxyURL, delegate.mapView) cell.append(selectedField) cell.append(layerDisplayNameField) cell.append(institutionField) cell.append(infoButton.element) if (L.Browser.safari && !item.isVectorType && !item.secureWMS) { var insecureItemField = $("<img class='insecure-item-field' src='/media/img/insecure-item.png' title='Selecting this item will disable geolocation' alt='Insecure Item'>") cell.append(insecureItemField) } if (this.selected) { var boundedItemCell = this var sortHandle = $("<span class='image-control cell-sort-handle' title='Click and drag to order layer'></span>") var opacityField = $("<span class='opacity-field'><span class='opacity-text'>Opacity: </span></span>") if (item.isVectorType || item.DataType == "Book") { $(sortHandle).attr("title", "Books and vector layers will not change their map layering.") } var opacityControl = new OpacityControl(this.item, this) opacityField.append(opacityControl.element) var centerButton = new CenterButton(item, this.mapView.map) if (delegate.sectionSortable(section)) { cell.append(sortHandle) } cell.append(opacityField) if (!item.isVectorType && item.DataType != "Book") { var switchResButton = new SwitchResButton(this.item, this.mapView) cell.append(switchResButton.element) } cell.append(centerButton.element) if (item.isVectorType) { var statusField = $("<span class='status-field'></span>") if (item._bytesLoaded) { var bytes = item._bytesLoaded var sizeText = bytes > 1000000 ? sprintf("%.1fMB", bytes / 1000000) : sprintf("%dKB", bytes / 1000) $(statusField).text(sizeText) } cell.append(statusField) } if (item.isVectorType || item.DataType == "Book") { var colorField = $("<span class='color-field'>Color: </span>") var colorControlContainer = $("<span class='color-control-container'></span>") var colorControl = $("<span class='color-control'></span>") colorControlContainer.append(colorControl) colorField.append(colorControlContainer) cell.append(colorField) if (item.color) { var color = item.color var transparentColor = sprintf("rgba(%s,%s,%s,0.4)",color[0],color[1],color[2]) var solidColor = sprintf("rgb(%s,%s,%s)",color[0],color[1],color[2]) colorControl.css("background-color", transparentColor) colorControl.css("border", sprintf("1px solid %s", solidColor)) } colorControl.click(function() { var colorPicker = new ColorPicker({ "selectedColor": function(color) { var transparentColor = sprintf("rgba(%s,%s,%s,0.4)",color[0],color[1],color[2]) var solidColor = sprintf("rgb(%s,%s,%s)",color[0],color[1],color[2]) item.color = color var colorControls = $(sprintf(".bounded-item-cell[data-layer-id=\"%s\"] .color-control", item.LayerId)) colorControls.css("background-color", transparentColor) colorControls.css("border", sprintf("1px solid %s", solidColor)) item.mapLayer.setStyle({ "color": solidColor }, item.LayerDisplayName) } }, item.LayerDisplayName) colorPicker.open() }) } } $(cell).hover( function() { delegate.hoverStartedForRowInSection(row, section) }, function() { delegate.hoverEndedForRowInSection(row, section) } ) return cell } }) function ElementCell(element, cellClass) { this.element = $(element) this.cellClass = cellClass } function TextCell(textElement, cellClass) { this.text = textElement this.cellClass = cellClass } Object.defineProperty(TextCell.prototype, "element", { get: function() { var cellClass = this.cellClass || "tableview-row" var cell = $(sprintf("<div class='%s no-highlight text-cell'></div>", cellClass)) cell.append(this.text) return cell } }) function NoResultsCell() { this.text = "No items were found within the map's bounds using the entered search parameters." } NoResultsCell.prototype = TextCell.prototype function EmptyCollectionCell() { this.text = "This collection does not have any unselected item within the map's bounds." } EmptyCollectionCell.prototype = TextCell.prototype function NoSelectedItemsCell() { this.text = "No items selected." } NoSelectedItemsCell.prototype = TextCell.prototype function LoadingCell() { this.loadingIndicatorElement = $("<div></div>") } Object.defineProperty(LoadingCell.prototype, "element", { get: function() { var cell = $("<div class='tableview-row no-highlight loading-cell'></div>") cell.append(this.loadingIndicatorElement) return cell } }) Object.defineProperty(LoadingCell.prototype, "onAdd", { get: function() { this.loadingIndicatorElement.spin() } }) function PaginatingCell(page, total, section, delegate) { this.page = page this.total = total this.section = section this.delegate = delegate } Object.defineProperty(PaginatingCell.prototype, "element", { get: function() { var cellElement = $("<div class='tableview-row text-cell paginating-cell no-highlight'></div>") var prevButton = $("<a class='text-control prev-button'>Prev</a>") var nextButton = $("<a class='text-control next-button'>Next</a>") var cellText = $(sprintf("<span>Page %d of %d</span>", this.page, this.total)) var cell = this $(prevButton).click(function() { cell.delegate.paginatingCellSetPageForSection(cell.page - 1, cell.section) }) $(nextButton).click(function() { cell.delegate.paginatingCellSetPageForSection(cell.page + 1, cell.section) }) $(prevButton).css("visibility", this.page == 1 ? "hidden" : "visible") $(nextButton).css("visibility", this.page == this.total ? "hidden" : "visible") $(cellElement).append(prevButton, cellText, nextButton) return cellElement } }) function TimeSliderTableViewCell(row, section, item, tableViewDelegate, timeSliderBar, selected) { this.item = item this.position = row this.section = section this.tableViewDelegate = tableViewDelegate this.timeSliderBar = timeSliderBar this.selected = selected } Object.defineProperty(TimeSliderTableViewCell.prototype, "element", { get: function() { var cell = this var element = $(sprintf("<div class='time-slider-cell tableview-row%s' data-position='%s' data-layer-id='%s'></div>", this.selected ? " selected" : "", this.position, this.item.LayerId)) var checkbox = $(sprintf("<input type='checkbox' %s>", this.item.selected ? "checked" : "")) $(checkbox).click(function(e) { e.stopPropagation() cell.item.reloadSection = true cell.item.selected = $(this).prop("checked") cell.tableViewDelegate.selectedCellForRowInSection(cell.position, cell.section) }) element.append(checkbox) element.append($(sprintf("<span class='year-field'>%s</span>", this.item.contentYear))) element.append($(sprintf("<span class='title-field'>%s</span>", this.item.LayerDisplayName))) var centerButton = new CenterButton(this.item, this.timeSliderBar.mapView.map) element.append(centerButton.element) var switchResButton = new SwitchResButton(this.item, this.timeSliderBar.mapView) element.append(switchResButton.element) var proxyURL = this.timeSliderBar.delegate.proxyURL var infoButton = new InfoButton(this.item, proxyURL, this.timeSliderBar.mapView) element.append(infoButton.element) //conver to object var opacityField = $("<span class='opacity-field'><span class='opacity-text'>Opacity: </span></span>") var opacityControl = new OpacityControl(this.item, this) opacityField.append(opacityControl.element) element.append(opacityField) var cell = this element.click(function() { cell.tableViewDelegate.selectedCellForRowInSection(cell.position, cell.section) }) var delegate = this.tableViewDelegate $(element).hover( function() { delegate.hoverStartedForRowInSection(cell.position, cell.section) }, function() { delegate.hoverEndedForRowInSection(cell.position, cell.section) } ) return element } }) function SectionHeader(mainText, subText, section, extraClasses) { this.mainTextElement = $("<span class='section-header-main-text'></span>").append(mainText) this.subTextElement = $(sprintf("<span class='section-header-sub-text'>%s</span>", subText || "")) this.section = section this.extraClasses = extraClasses || "" } Object.defineProperty(SectionHeader.prototype, "html", { get: function() { return sprintf("<div class='section-header %s'><span class='section-header-main-text'>%s</span><span class='section-header-sub-text'>%s</span></div>", this.extraClasses, this.mainText, this.subText) } }) Object.defineProperty(SectionHeader.prototype, "element", { get: function() { var headerElement = $(sprintf("<div class='section-header %s' data-section='%d'></div>", this.extraClasses, this.section)) headerElement.append(this.mainTextElement) headerElement.append(this.subTextElement) return headerElement } }) function CollapsingSectionHeader(mainText, section, delegate, tableViewID) { SectionHeader.call(this, mainText, null, section, "rounded-for-show-button") var collapsed = delegate.collapseStateForSection(section) var buttonText = null if (collapsed) { var sectionID = sprintf("#%s-section-%d", tableViewID, section) $(sprintf("#%s-section-%d", tableViewID, section)).addClass("hidden") buttonText = "Show" } else { buttonText = "Hide" } this.subTextElement = $(sprintf("<span class='section-header-sub-text'><span class='text-control show-button'>%s</span></span>", buttonText)) this.delegate = delegate $(this.subTextElement).click(function() { var tableViewSection = $(sprintf("#%s-section-%d", tableViewID, section)) if (tableViewSection.hasClass("hidden")) { tableViewSection.removeClass("hidden") $(this).children(".show-button").text("Hide") delegate.collapseStateChangedForSection(section, false) } else { tableViewSection.addClass("hidden") $(this).children(".show-button").text("Show") delegate.collapseStateChangedForSection(section, true) } }) } CollapsingSectionHeader.prototype = SectionHeader.prototype function SectionFooter(mainText) { this.mainText = mainText || "" } Object.defineProperty(SectionFooter.prototype, "html", { get: function() { return sprintf("<div class='section-footer'><span class='section-footer-main-text'>%s</span></div>", this.mainText) } }) Object.defineProperty(SectionFooter.prototype, "element", { get: function() { return $(this.html)[0] } }) function DownloadFooter(delegate, urlDelegate) { this.delegate = delegate this.urlDelegate = urlDelegate || delegate } Object.defineProperty(DownloadFooter.prototype, "element", { get: function() { var element = $(new SectionFooter().html) var downloadButtonElement = $("<a class='download-button text-control'>Download</a>") var delegate = this.delegate var urlDelegate = this.urlDelegate var emailInputElement = $("<input type='text' placeholder='Enter your email address' style='width: 380px'>") var dialogIntro = $("<p>All downloaded files include metadata files in FGDC format.</p>") var formats = { "json": "GeoJSON", "gml": "GML", "kml": "KML", "shapefile": "Shape file" } var formatInputElement = $("<select></select>") for (var value in formats) { formatInputElement.append(sprintf("<option value='%s'>%s</option", value, formats[value])) } var downloadDialogElement = $("<div>A link to a zip file containing your selected items will be sent to the following address:<div>") var hasExternalItems = false for (var i = 0; i < delegate.selectedItems.length; ++i) { var item = delegate.selectedItems[i] if (!item.LayerId.startsWith("UNH")) { hasExternalItems = true break } } if (hasExternalItems) { var formatElement = $("<div style='margin-bottom: 1em'>Select a format for vector data: </div>").append(formatInputElement) downloadDialogElement.prepend(formatElement).prepend(dialogIntro) } else { downloadDialogElement.prepend(dialogIntro) } downloadDialogElement.append(emailInputElement) var downloadDialog = $(downloadDialogElement).dialog({ autoOpen: false, title: "Enter email address", buttons: [{ text: "Request Download", click: function() { var emailAddress = $(emailInputElement).val() var wfsFormat = $(formatInputElement).val() delegate.downloadRequested(emailAddress, wfsFormat) $(this).dialog("close") } }, { text: "Close", click: function() { $(this).dialog("close") } }] }) $(downloadButtonElement).click(function() { $(downloadDialog).dialog("open") }) $(element).append(downloadButtonElement) var linkButtonElement = $("<a class='link-button text-control'>Share</a>") $(linkButtonElement).click(function() { var linkDialogElement = $(sprintf("<div><div><b>Link for selected layers</b></div><textarea readonly>%s</textarea></div>", urlDelegate.urlWithLayers)) $(linkDialogElement).dialog({ dialogClass: "link-dialog", title: "Share Selected Items", buttons: [{ text: "Close", click: function() { $(this).dialog("close") } }], open: function() { $(this).children("textarea").select() } }) }) $(element).append(linkButtonElement) var exportButtonElement = $("<a class='export-button text-control'>WFS Export</a>") var hasVectorLayers = false for (var i = 0; i < delegate.selectedItems.length; ++i) { var item = delegate.selectedItems[i] if (item.isVectorType) { hasVectorLayers = true break } } if (hasVectorLayers) { $(exportButtonElement).click(function() { var exportDialogElement = $("<div></div>") for (var i = 0; i < delegate.selectedItems.length; ++i) { var item = delegate.selectedItems[i] if (item.isVectorType) { exportDialogElement.append(sprintf("<div><b>WFS Link for <i>%s</i></b><textarea>%s</textarea></div>", item.LayerDisplayName, item.wfsURL.replace("/external_wfs/", "http://"))) } } $(exportDialogElement).dialog({ dialogClass: "link-dialog", title: "WFS Export", buttons: [{ "text": "Close", "click": function() { $(this).dialog("close") } }] }) }) } else { $(exportButtonElement).addClass("disabled") } $(element).append(exportButtonElement) var clearButtonElement = $("<a class='clear-button text-control'>Clear</a>") $(clearButtonElement).click(function() { delegate.clearLayers() }) $(element).append(clearButtonElement) return element } }) function SwitchResButton(item, mapView) { this.item = item this.mapView = mapView } Object.defineProperty(SwitchResButton.prototype, "element", { get: function() { var item = this.item var mapView = this.mapView var switchResButton = $(sprintf("<span data-layer='%s' class='switch-res-button' title='Switch Image Resolution'></span>", item.Name)) var text = null if (item.highResLayer) { $(switchResButton).addClass("high") } else { $(switchResButton).addClass("low") } $(switchResButton).click(function(e) { if (!item.mapLayer._map) { return } item.highResLayer = !item.highResLayer //property that handles actual switching if (item.highResLayer) { $(sprintf(".switch-res-button[data-layer='%s']", item.Name)).removeClass("low").addClass("high") } else { $(sprintf(".switch-res-button[data-layer='%s']", item.Name)).removeClass("high").addClass("low") } }) return switchResButton } }) function CenterButton(item, map) { this.item = item this.map = map } Object.defineProperty(CenterButton.prototype, "element", { get: function() { var centerButton = $("<span title='Center map on item' class='center-button text-control'>Center</span>") var map = this.map var item = this.item $(centerButton).click(function(e) { e.stopPropagation() map.fitBounds([[item.MinY, item.MinX], [item.MaxY, item.MaxX]]) }) return centerButton } }) function InfoButton(item, proxyURL, mapView) { this.item = item this.proxyURL = proxyURL this.mapView = mapView } Object.defineProperty(InfoButton.prototype, "element", { get: function() { var delegate = this.delegate var item = this.item var itemURL = sprintf("%s/layer?id=%s", this.proxyURL, item.LayerId) var abstractURL = sprintf("%s/abstract?id=%s", this.proxyURL, item.LayerId) var metadataURL = sprintf("%s/metadata?id=%s", this.proxyURL, item.LayerId) var element = $(sprintf("<a class='text-control info-button dialog-button' title='Click for more info'>i</a>", itemURL)) var dialogSetup = function(element, title) { var settings = { title: title, buttons: [{ text: "Close", click: function() { $(this).dialog("close") } }], dialogClass: "info-dialog", open: function() { $(this).children(".preview-image-container").spin().addClass("loading") } } var dialog = $(element).dialog(settings) } var infoButton = this $(element).click(function(e) { e.stopPropagation() var dialogText = $("<div class='dialog-text'></div>") .append(sprintf("<div><b>Content Year</b> %s</div>", item.contentYear)) .append(sprintf("<div><b>Data Type</b> %s</div>", item.DataType)) .append(sprintf("<div style='width: 190px'><b>Originator</b> %s</div>", item.Originator)) .append("<br/>") .append(sprintf("<div><a href='%s' target='_blank'>View Main Record</a></div>", itemURL)) .append(sprintf("<div><a href='%s' target='_blank'>Download Abstract</a></div>", abstractURL)) .append(sprintf("<div><a href='%s' target='_blank'>Download Metadata</a></div>", metadataURL)) var dialogElement = $("<div></div>").append(dialogText) if (item.selected && ["Point", "Line", "Polygon"].indexOf(item.DataType) != -1) { var viewJSONLink = $(sprintf("<div><a href='%s' target='_blank'>View Source Data</a></div>", item.wfsURL)) dialogElement.append(viewJSONLink) } var imageElement = $(sprintf("<img class='preview-image' src='%s/reflect?layers=%s'>", item.thumbnailURL, item.Name)) var nw = L.latLng(item.MaxY, item.MinX) var ne = L.latLng(item.MaxY, item.MaxX) var se = L.latLng(item.MinY, item.MaxX) nw = infoButton.mapView.map.project(nw) ne = infoButton.mapView.map.project(ne) se = infoButton.mapView.map.project(se) if (nw.distanceTo(ne) > ne.distanceTo(se)) { $(imageElement).addClass("wide") } else { $(imageElement).addClass("tall") } var imageElementContainer = $("<div class='preview-image-container'></div>") imageElementContainer.append(imageElement) dialogElement.prepend(imageElementContainer) $(imageElement).on("load", function() { $(this).parent().spin(false).removeClass("loading") }) dialogSetup(dialogElement, item.LayerDisplayName) }) return element } }) function OpacityControl(item, cell) { this.item = item this.cell = cell } Object.defineProperty(OpacityControl.prototype, "element", { get: function() { var item = this.item var cell = this.cell var opacityControl = null if (/(Trident)|(MSIE)/.test(navigator.userAgent)) { opacityControl = $("<input type='text' style='width: 2em'>") } else { opacityControl = $("<input type='range' class='opacity-control'>") } opacityControl.val(item.mapLayer.options.opacity*100) opacityControl.bind("input", function() { var opacity = parseInt($(this).val()) var opacityControlSelector = sprintf(".tableview-row[data-layer-id='%s'] .opacity-control", item.LayerId) $(opacityControlSelector).val(opacity) if (opacity > -1) { opacity = opacity > 100 ? 100 : opacity < 0 ? 0 : opacity $(this).val(opacity) cell.opacityValue = opacity opacity /= 100 item.mapLayer.setOpacity(opacity) } else { $(this).val("") } }) return opacityControl } }) function GazetteerMenu(gazetteerButtonID, gazetteerBaseURL, gazetteerDelegate, searchViewDelegate) { this.buttonID = gazetteerButtonID this.url = gazetteerBaseURL this.delegate = gazetteerDelegate this.searchViewDelegate = searchViewDelegate || this.delegate this.tableView = new TableView("gazetteer-tableview", this) this.menu = $("<div id='gazetteer-tableview' style='overflow: scroll'></div>") this.currentEntries = null this.currentSelection = null this.previousSelections = [] this.entries = { "states": {}, "counties": {}, "municipalities": {} } this.areaTypeForEntryType = { "states": "state", "counties": "county", "municipalities": "municipality" } this.nextTypeForEntryType = { "states": "counties", "counties": "municipalities", "municipalities": null } this.previousTypeForEntryType = { "states": null, "counties": "states", "municipalities": "counties" } //create dialog var tableView = this.tableView $(this.menu).dialog({ autoOpen: false, buttons: [{ text: "Close", click: function() { $(this).dialog("close") } }], maxHeight: 600, open: function() { $(this).css("overflow-x", "hidden") $(this).css("overflow-y", "scroll") tableView.reloadSection(0) }, resizeable: false, title: "Gazetteer" }) //load initial data this.currentSelection = {"name": "US", "id": "us", "type": "states"} this.loadEntriesForTypeAndID("states", "us") //show menu on click var gazetteer = this $(this.jqueryID).click(function() { $(gazetteer.menu).dialog("open") }) } Object.defineProperty(GazetteerMenu.prototype, "jqueryID", { get: function() { return "#" + this.buttonID } }) var gmp = GazetteerMenu.prototype gmp.loadEntriesForTypeAndID = function(type, id) { if (this.entries[type][id]) { this.currentEntries = this.entries[type][id] this.tableView.reloadData() } else { var url = sprintf("%s/%s?id=%s", this.url, type, id) var gazetteer = this $.ajax(url, { success: function(data) { gazetteer.entries[type][id] = data.response gazetteer.currentEntries = gazetteer.entries[type][id] gazetteer.tableView.reloadData() } }) } } gmp.nextEntryTypeSelectedForRowInSection = function(row, section) { var entry = this.currentEntries[row] this.previousSelections.push(this.currentSelection) this.currentSelection = {"name": entry.name, "id": entry.id, "type": this.nextTypeForEntryType[this.currentSelection.type]} this.loadEntriesForTypeAndID(this.currentSelection.type, this.currentSelection.id) } gmp.previousEntryTypeSelected = function() { this.currentSelection = this.previousSelections.pop() this.loadEntriesForTypeAndID(this.currentSelection.type, this.currentSelection.id) } //TableView delegate methods for gazetteer gmp.numberOfSections = function() { return 2 } gmp.numberOfRowsInSection = function(section) { if (section == 0) { return 1 } return this.currentEntries.length || 1 } gmp.cellForRowInSection = function(row, section) { if (section == 0) { var gazetteer = this var element = $("<span style='display: inline-block; text-align: center; width: 100%'></span>") var label = $("<label>Show and limit to location outline</label>") var checkbox = $("<input id='gazetteer-showpolygon' type='checkbox'>") var checked = this.searchViewDelegate.searchOptions[SO_SHOW_POLYGON] checkbox.prop("checked", checked) $(checkbox).click(function() { var state = gazetteer.searchViewDelegate.searchOptions[SO_SHOW_POLYGON] gazetteer.searchViewDelegate.searchOptions[SO_SHOW_POLYGON] = !state gazetteer.searchViewDelegate.searchOptions[SO_LIMIT_TO_LOCATION] = !state //TODO //remove explicit search field id $("#search-field-showpolygon").prop("checked", !state) if (state) { gazetteer.delegate.gazetteerPolygonUnselected() } else if (!state && gazetteer.delegate.previousGazetteerPolygon){ var p = gazetteer.delegate.previousGazetteerPolygon gazetteer.delegate.gazetteerPolygonSelected(p.id, p.type, p.name) } }) element.append(label.prepend(checkbox)) return new ElementCell(element) } if (this.currentEntries == 0 && row == 0) { return new TextCell(sprintf("No %s available.", this.currentSelection.type), "gazetteer-row") } var entry = this.currentEntries[row] return new GazetteerEntryCell(entry, row, section, this) } gmp.hoverStartedForRowInSection = function(row, section) { } gmp.hoverEndedForRowInSection = function(row, section) { } gmp.selectedCellForRowInSection = function(row, section) { if (section == 0) { var checked = this.searchDelegate } var entry = this.currentEntries[row] var areaType = this.areaTypeForEntryType[this.currentSelection.type] this.delegate.gazetteerPolygonSelected(entry.id, areaType, sprintf("%s, %s", entry.name, this.currentSelection.name)) } gmp.headerForSection = function(section) { if (section == 1) { return null } var previousSelection = this.previousSelections.length ? this.previousSelections[this.previousSelections.length-1] : null var mainText = sprintf("%s", this.currentSelection.name) var subText = previousSelection ? sprintf("< %s", previousSelection.name) : null var header = new SectionHeader(mainText, subText, section) if (previousSelection) { var gazetteer = this header.subTextElement.click(function() { gazetteer.previousEntryTypeSelected() }) } return header } gmp.footerForSection = function(section) { return null } gmp.sectionSortable = function(section) { return false } gmp.orderingForSection = function(section) { return 1 } gmp.orderChangedForSection = function(section) { } //end of gazetteer TableView delegate methods function GazetteerEntryCell(entry, row, section, delegate) { this.entry = entry this.delegate = delegate this.row = row this.section = section } Object.defineProperty(GazetteerEntryCell.prototype, "element", { get: function() { var entryCell = this var cell = $(sprintf("<label class='gazetteer-row' data-row='%d' data-section='%d' data-id='%s'></label>", this.row, this.section, this.entry.id)) var entryLabel = $(sprintf("<span class='entry-name'>%s</span>", this.entry.name)) var entryLabelSelect = $("<span class='entry-select'>Select </span>") entryLabel.prepend(entryLabelSelect) cell.append(entryLabel) entryLabel.click(function(e) { entryCell.delegate.selectedCellForRowInSection(entryCell.row, entryCell.section) }) var nextEntryType = this.delegate.nextTypeForEntryType[this.delegate.currentSelection.type] if (nextEntryType) { var nextButton = $("<span class='text-control borderless next-type-button'></span>") if (this.entry.next_entries) { var typeText = null if (this.entry.name == "Louisiana" && this.entry.id == "22") { typeText = "Parishes" } else if (this.entry.name == "Alaska" && this.entry.id == "02") { typeText = "Burroughs and CAs" } else if (nextEntryType == "municipalities") { typeText = this.entry.next_entries == 1 ? "Subdivision" : "Subdivisions" } else { typeText = this.entry.next_entries == 1 ? this.delegate.areaTypeForEntryType[nextEntryType].capitalize() : nextEntryType.capitalize() } var buttonText = sprintf("%s %s >", this.entry.next_entries, typeText) nextButton.text(buttonText) var viewText = $("<span class='entry-view'>View </span>") nextButton.prepend(viewText) nextButton.click(function(e) { e.preventDefault() entryCell.delegate.nextEntryTypeSelectedForRowInSection(entryCell.row, entryCell.section) }) var orText = "<span class='or-text'>or</span>" cell.append(orText) } else { var buttonText = sprintf("No %s available.", nextEntryType) nextButton.text(buttonText) nextButton.addClass("disabled") cell.addClass("no-next-type") } cell.append(nextButton) } else { cell.addClass("no-next-type") } return cell } }) function ColorPicker(delegate, itemName) { this.delegate = delegate this.dialogElement = null this.color = null this.itemName = itemName var colorPicker = this var createChoice = function(r,g,b) { var baseColor = sprintf("%d,%d,%d,1", r,g,b) var fillColor = sprintf("rgba(%d,%d,%d,0.4)", r, g, b) var borderColor = sprintf("5px solid rgba(%d,%d,%d,1.0)", r, g, b) var colorChoice = $(sprintf("<span class='color-choice' data-color='%s'></span>", baseColor)) colorChoice.css("background-color", fillColor) colorChoice.css("border", borderColor) $(colorChoice).click(function() { color = $(this).attr("data-color").split(",") delegate.selectedColor(color) }) return colorChoice } var colorChoices = $("<div class='color-choices'></div>") var colorRows = [ [[255,0,0],[0,255,0],[0,102,255],[255,255,0],[0,255,255],[255,0,255], [255,255,255]], [[128,0,0],[0,128,0],[0,0,128],[128,128,0],[0,128,128],[128,0,128], [0,0,0]] ] for (var r = 0; r < colorRows.length; ++r) { var colorRow = $("<div class='color-choice-row'></div>") for (var i = 0; i < colorRows[r].length; ++i) { var color = colorRows[r][i] var colorChoice = createChoice(color[0], color[1], color[2]) colorRow.append(colorChoice) } colorChoices.append(colorRow) } var title = this.itemName ? sprintf("Color for \"%s\"", this.itemName) : "Color" this.dialogElement = colorChoices this.dialogElement.dialog({ autoOpen: false, buttons: [{ text: "Close", click: function() { $(this).dialog("close") } }], dialogClass: "ui-dialog-color-picker", title: title }) } ColorPicker.prototype.open = function() { this.dialogElement.dialog("open") } //CUSTOM LAYERS var ClickPassingGeoJSON = L.GeoJSON.extend({ options: { pointToLayer: function(feature, latlng) { return L.marker.svgMarker(latlng) } }, initialize: function(geoJSON, options) { options = L.Util.setOptions(this, options) L.GeoJSON.prototype.initialize.call(this, geoJSON, options) mapViewDelegate = options.mapViewDelegate if (mapViewDelegate) { if (mapViewDelegate.mapViewClicked) { this.on("click", function(e) { mapViewDelegate.mapViewClicked(e.latlng) }) } this.on("dblclick", function(e) { var zoomLevel = mapViewDelegate.mapView.map.getZoom() }) } } }) //the use of the layer implies a crossing over the meridian var AntimeridianAdjustedGeoJSON = ClickPassingGeoJSON.extend({ initialize: function(geoJSON, options) { options = options || {} if (!options.coordsToLatLng) { options.coordsToLatLng = function(lnglat) { var lat = lnglat[1] var lng = lnglat[0] //convert to lat < -180 form e.g. 179 to -181 if (lng > 0) { lng = -360 + lng } return [lat,lng] } } ClickPassingGeoJSON.prototype.initialize.call(this, geoJSON, options) } }) L.GeoJSON.include({ addDataFromURL: function(url, loadStartFunction, loadEndFunction, progressFunction, timeoutFunction) { var layer = this if (loadStartFunction) { loadStartFunction() } var request = new XMLHttpRequest() request.open("GET", url, true) if (progressFunction) { request.onprogress = progressFunction } if (timeoutFunction) { request.ontimeout = timeoutFunction } request.onreadystatechange = function() { if (request.readyState == XHR_DONE && request.status == HTTP_OK) { try { var data = JSON.parse(request.responseText) layer.addData(data) } catch (exception){ alert("Unable to load this item.") } } else if (request.readyState == XHR_DONE && request.status != HTTP_OK) { alert("Unable to load this item.") } if (loadEndFunction) { loadEndFunction() } } request.send() } }) L.Rectangle.include({ setOpacity: function(opacity) { this.setStyle({ fillOpacity: L.Rectangle.prototype.options.fillOpacity * opacity, opacity: L.Rectangle.prototype.options.opacity * opacity }) } }) var DeferredGeoJSON = L.GeoJSON.extend({ options: { "markerTextProperty": null, "onLoadEnd": null, "onLoadStart": null, "opacity": 1, "progressFunction": null, "timeoutFunction": null, "url": null }, initialize: function(url, options) { options = L.Util.setOptions(this, options) options.url = url options.onEachFeature = function(feature, layer) { var properties = feature.properties if (properties) { var popupText = $("<div></div>") for (var k in properties) { if (k == "bbox") { continue } var v = properties[k] v = sprintf("%s", v).replace(/,/g, "<br>") popupText.append($(sprintf("<div>%s: %s</div>", k,v))) } layer.bindPopup(popupText[0], { maxHeight: 400 }) } } var layer = this options.pointToLayer = function(feature, latlng) { var textProperty = layer.options.markerTextProperty var text = textProperty && feature.properties[textProperty] ? feature.properties[textProperty] : null return L.marker.svgMarker(latlng, { "circleText": text }) } L.GeoJSON.prototype.initialize.call(this,null,options) this._loadStartFunction = null this._loadEndFunction = null }, onAdd: function(map) { if (this.options.url) { var layer = this this.addDataFromURL(this.options.url, function() { if (layer.options.onLoadStart) { layer.options.onLoadStart() } }, function() { if (layer.options.onLoadEnd) { layer.options.onLoadEnd() } L.GeoJSON.prototype.onAdd.call(layer, map) }, layer.options.progressFunction ) } else { L.GeoJSON.prototype.onAdd.call(this, map) } }, onLoadEnd: function(loadEndFunction) { this.options.onLoadEnd = loadEndFunction }, onLoadStart: function(loadStartFunction) { this.options.onLoadStart = loadStartFunction }, setOpacity: function(opacity) { this.options.opacity = opacity this.setStyle({ fillOpacity: DeferredGeoJSON.prototype.options.fillOpacity * opacity, opacity: DeferredGeoJSON.prototype.options.opacity * opacity }) } }) L.DivIcon.SVGIcon = L.DivIcon.extend({ options: { "circleText": "", "className": "svg-icon", "circleAnchor": null, //defaults to "circleColor": null, //defaults to color "circleOpacity": null, // defaults to opacity "circleFillColor": "rgb(255,255,255)", "circleFillOpacity": null, //default to opacity "circleRatio": 0.5, "circleWeight": null, //defaults to weight "color": "rgb(0,102,255)", "fillColor": null, // defaults to color "fillOpacity": 0.4, "fontColor": "rgb(0, 0, 0)", "fontOpacity": "1", "fontSize": null, // defaults to iconSize.x/4 "iconAnchor": null, //defaults to [iconSize.x/2, iconSize.y] (point tip) "iconSize": L.point(32,48), "opacity": 1, "popupAnchor": null, "weight": 2 }, initialize: function(options) { options = L.Util.setOptions(this, options) //iconSize needs to be converted to a Point object if it is not passed as one options.iconSize = L.point(options.iconSize) //in addition to setting option dependant defaults, Point-based options are converted to Point objects if (!options.circleAnchor) { options.circleAnchor = L.point(Number(options.iconSize.x)/2, Number(options.iconSize.x)/2) } else { options.circleAnchor = L.point(options.circleAnchor) } if (!options.circleColor) { options.circleColor = options.color } if (!options.circleFillOpacity) { options.circleFillOpacity = options.opacity } if (!options.circleOpacity) { options.circleOpacity = options.opacity } if (!options.circleWeight) { options.circleWeight = options.weight } if (!options.fillColor) { options.fillColor = options.color } if (!options.fontSize) { options.fontSize = Number(options.iconSize.x/4) } if (!options.iconAnchor) { options.iconAnchor = L.point(Number(options.iconSize.x)/2, Number(options.iconSize.y)) } else { options.iconAnchor = L.point(options.iconAnchor) } if (!options.popupAnchor) { options.popupAnchor = L.point(0, (-0.75)*(options.iconSize.y)) } else { options.popupAnchor = L.point(options.iconAnchor) } var path = this._createPath() var circle = this._createCircle() options.html = this._createSVG() }, _createCircle: function() { var cx = Number(this.options.circleAnchor.x) var cy = Number(this.options.circleAnchor.y) var radius = this.options.iconSize.x/2 * Number(this.options.circleRatio) var fill = this.options.circleFillColor var fillOpacity = this.options.circleFillOpacity var stroke = this.options.circleColor var strokeOpacity = this.options.circleOpacity var strokeWidth = this.options.circleWeight var className = this.options.className + "-circle" var circle = '<circle class="' + className + '" cx="' + cx + '" cy="' + cy + '" r="' + radius + '" fill="' + fill + '" fill-opacity="'+ fillOpacity + '" stroke="' + stroke + '" stroke-opacity=' + strokeOpacity + '" stroke-width="' + strokeWidth + '"/>' return circle }, _createPathDescription: function() { var height = Number(this.options.iconSize.y) var width = Number(this.options.iconSize.x) var weight = Number(this.options.weight) var margin = weight / 2 var startPoint = "M " + margin + " " + (width/2) + " " var leftLine = "L " + (width/2) + " " + (height - weight) + " " var rightLine = "L " + (width - margin) + " " + (width/2) + " " var arc = "A " + (width/4) + " " + (width/4) + " 0 0 0 " + margin + " " + (width/2) + " Z" var d = startPoint + leftLine + rightLine + arc return d }, _createPath: function() { var pathDescription = this._createPathDescription() var strokeWidth = this.options.weight var stroke = this.options.color var strokeOpacity = this.options.Opacity var fill = this.options.fillColor var fillOpacity = this.options.fillOpacity var className = this.options.className + "-path" var path = '<path class="' + className + '" d="' + pathDescription + '" stroke-width="' + strokeWidth + '" stroke="' + stroke + '" stroke-opacity="' + strokeOpacity + '" fill="' + fill + '" fill-opacity="' + fillOpacity + '"/>' return path }, _createSVG: function() { var path = this._createPath() var circle = this._createCircle() var text = this._createText() var className = this.options.className + "-svg" var style = "width:" + this.options.iconSize.x + "; height:" + this.options.iconSize.y + ";" var svg = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="' + className + '" style="' + style + '">' + path + circle + text + '</svg>' return svg }, _createText: function() { var fontSize = this.options.fontSize + "px" var lineHeight = Number(this.options.fontSize) var textColor = this.options.fontColor.replace("rgb(", "rgba(").replace(")", "," + this.options.fontOpacity + ")") var circleText = this.options.circleText var x = Number(this.options.iconSize.x) / 2 var y = x + (lineHeight * 0.35) //35% was found experimentally var text = '<text text-anchor="middle" x="' + x + '" y="' + y + '" style="font-size: ' + fontSize + '" fill="' + textColor + '">' + circleText + '</text>' return text } }) L.divIcon.svgIcon = function(options) { return new L.DivIcon.SVGIcon(options) } L.Marker.SVGMarker = L.Marker.extend({ options: { "iconFactory": L.divIcon.svgIcon, "iconOptions": {} }, initialize: function(latlng, options) { options = L.Util.setOptions(this, options) options.icon = options.iconFactory(options.iconOptions) this._latlng = latlng }, onAdd: function(map) { L.Marker.prototype.onAdd.call(this, map) }, setStyle: function(style) { if (this._icon) { var svg = this._icon.children[0] var iconBody = this._icon.children[0].children[0] var iconCircle = this._icon.children[0].children[1] if (style.color && !style.iconOptions) { var stroke = style.color.replace("rgb","rgba").replace(")", ","+this.options.icon.options.opacity+")") var fill = style.color.replace("rgb","rgba").replace(")", ","+this.options.icon.options.fillOpacity+")") iconBody.setAttribute("stroke", stroke) iconBody.setAttribute("fill", fill) iconCircle.setAttribute("stroke", stroke) this.options.icon.fillColor = fill this.options.icon.color = stroke this.options.icon.circleColor = stroke } if (style.opacity) { this.setOpacity(style.opacity) } if (style.iconOptions) { if (style.color) { style.iconOptions.color = style.color } iconOptions = L.Util.setOptions(this.options.icon, style.iconOptions) this.setIcon(this.options.iconFactory(iconOptions)) } } } }) L.marker.svgMarker = function(latlng, options) { return new L.Marker.SVGMarker(latlng, options) } L.DivIcon.SVGIcon.BookIcon = L.DivIcon.SVGIcon.extend({ options: { "circleWeight": 1, "iconSize": L.point(48,48) }, _createCircle: function() { return this._createInnerBook() }, _createInnerBook: function() { var pathDescription = this._createInnerBookPathDescription() var strokeWidth = this.options.circleWeight var stroke = this.options.circleColor.replace("rgb(", "rgba(").replace(")", "," + this.options.circleOpacity + ")") var fill = this.options.circleFillColor.replace("rgb(", "rgba(").replace(")", "," + this.options.circleFillOpacity + ")") var className = this.options.className + "-path" var path = '<path class="' + className + '" d="' + pathDescription + '" stroke-width="' + strokeWidth + '" stroke="' + stroke + '" fill="' + fill + '"/>' return path }, _createInnerBookPathDescription: function() { var tHeight = Number(this.options.iconSize.y) var tWidth = Number(this.options.iconSize.x) var weight = Number(this.options.circleWeight) var margin = weight / 2 var height = tHeight * (3/4) var width = tWidth * (3/4) var startPoint = sprintf("M %f %f", tWidth/8, height/12 + margin) var leftSide = sprintf("L %f %f", tWidth/8, height + tHeight/8 - margin) var bottomLeft = sprintf("A %f %f 0 0 1 %f %f", width, height/4, tWidth/2, tHeight - margin) var bottomRight = sprintf("A %f %f 0 0 1 %f %f", width, height/4, width + tWidth/8, height + tHeight/8 - margin) var rightSide = sprintf("L %f %f", width + tWidth / 8, height/12 + margin) var topRight = sprintf("A %f %f 0 0 0 %f %f", width/2, height/2, tWidth/2, height/6) var topLeft = sprintf("A %f %f 0 0 0 %f %f", width/2, height/2, tWidth/8, height/12 + margin) var end = "Z" var d = startPoint + leftSide + bottomLeft + bottomRight + rightSide + topRight + topLeft + end return d }, _createPathDescription: function() { var height = Number(this.options.iconSize.y) var width = Number(this.options.iconSize.x) var weight = Number(this.options.weight) var margin = weight / 2 var startPoint = sprintf("M %f %f ", margin, margin) var leftSide = sprintf("L %f %f ", margin, (5/6) * height) var bottomLeft = sprintf("L %f %f ", width/2, height - margin) var bottomRight = sprintf("L %f %f ", width - margin, (5/6) * height) var rightSide = sprintf("L %f %f ", width - margin, margin) var topRight = sprintf("L %f %f ", width / 2, height / 6) var topLeft = sprintf("L %f %f ", margin, margin) var end = "Z" var d = startPoint + leftSide + bottomLeft + bottomRight + rightSide + topRight + topLeft + end return d }, _createText: function() { var fontSize = this.options.fontSize + "px" var lineHeight = Number(this.options.fontSize) var textColor = this.options.fontColor.replace("rgb(", "rgba(").replace(")", "," + this.options.fontOpacity + ")") var circleText = this.options.circleText var textParts = circleText.split("\n") var x = Number(this.options.iconSize.x) / 2 var text = "" if (textParts.length == 1) { var y = x + (lineHeight * 0.35) //35% was found experimentally text = '<text text-anchor="middle" x="' + x + '" y="' + y + '" style="font-size: ' + fontSize + '" fill="' + textColor + '">' + circleText + '</text>' } else { var y = x/4 + lineHeight text = '<text text-anchor="middle" x="' + x + '" y="' + y + '" style="font-size: ' + fontSize + '" fill="' + textColor + '">' + textParts[0] + '</text>' y = x/2 + 2 * lineHeight text += '<text text-anchor="middle" x="' + x + '" y="' + y + '" style="font-size: ' + fontSize + '" fill="' + textColor + '">' + textParts[1] + '</text>' } return text } }) L.divIcon.svgIcon.bookIcon = function(options) { return new L.DivIcon.SVGIcon.BookIcon(options) } L.Marker.SVGMarker.BookMarker = L.Marker.SVGMarker.extend({ options: { "iconFactory": L.divIcon.svgIcon.bookIcon }, bringToFront: function() { } }) L.marker.svgMarker.bookMarker = function(options) { return new L.Marker.SVGMarker.BookMarker(options) } L.LayerGroup.include({ bringToFront: function() { this.eachLayer(function(layer) { layer.bringToFront() }) }, setOpacity: function(opacity) { this.options.opacity = opacity this.eachLayer(function(layer) { layer.setOpacity(opacity) }) }, setStyle: function(style) { this.eachLayer(function(layer) { layer.setStyle(style) }) } }) //Bug(?) in Leaflet reset opacity on vector layers to 1 with regular dictionaries function LeafletOptions(options) { for (var k in options) { this[k] = options[k] } } <file_sep>from geoserver.server_models import add_to_geoserver, get_coverage_store from ogp.models import BoundedItem, ItemCollection from utilities.conversion import fgdc_to_ogp_csv, image_path_with_fgdc_to_world_file from utilities.misc import ogp_timestamp_for_now from PIL import Image from urllib2 import Request, urlopen import json import requests import os import csv from gazetteer.models import Municipality #from place.settings import GEOSERVER, SOLR_REPO from django.conf import settings GEOSERVER = settings.GEOSERVER SOLR_REPO = settings.SOLR_REPO #relative image paths are assumed to be relative to the geoserver shared directory def import_map(image_path, srs, units): if not image_path.startswith("/"): image_path = "%s/%s" % (GEOSERVER['DATA_PATH'], image_path) (image_path_base, image_ext) = os.path.splitext(image_path) world_file_ext = "%s%sw" % (image_ext[1], image_ext[-1]) world_file_path = "%s.%s" % (image_path_base, world_file_ext) fgdc_file_path = "%s.xml" % (image_path_base) image_name = os.path.split(image_path)[1].replace(image_ext, "") world_file = open(world_file_path, "w") image_path_with_fgdc_to_world_file(image_path, world_file, srs, units) world_file.close() if get_coverage_store(name=image_name): saved = True else: (saved, response, coverage) = add_to_geoserver(image_name, image_path, workspace="ogp", srs=srs, units=units) if not saved: return (False, response) response = add_to_solr(image_path) saved = response.status_code == 200 if saved: directory_path = os.path.split(image_path)[0] itemName = image_name solrData = json.loads(query_solr("q=Name:%s&wt=json" % (itemName)).read())["response"]["docs"][0] del solrData["_version_"] del solrData["PlaceKeywordsSynonyms"] del solrData["OriginatorSort"] solrData["srs"] = srs if len(BoundedItem.objects.filter(Name=itemName)) == 0: b = BoundedItem(**solrData) b.directory_path = directory_path if "hurd" in directory_path: b.collection = ItemCollection.objects.get(full_name__contains="Hurd") b.save() else: b = BoundedItem.objects.get(Name=itemName) b.update_from_dictionary(solrData) b.directory_path = directory_path b.save() return (True, None) else: return (False, "Could not add to Solr") def add_to_solr(image_file_path): image_file_base = os.path.splitext(image_file_path)[0] csv_file_path = image_file_base + ".csv" fgdc_file_path = image_file_base + ".xml" (h,r) = fgdc_to_ogp_csv(fgdc_file_path, True) csv_file = open(csv_file_path, "w") csv_file.writelines([h,r]) csv_file.close() url = "%s/update/csv?commit=true&stream.file=%s&stream.contentType=text/csv;charset=utf-8&overwrite=true" % (SOLR_REPO['URL'], csv_file_path) response = requests.get(url=url) os.remove(csv_file_path) return response def query_solr(query_string): solr_url = "http://place.sr.unh.edu:8080/solr/select?%s" % (query_string) request = Request(solr_url) response = urlopen(request) return response <file_sep>from django.http import HttpResponse, Http404 from django.shortcuts import render from django.template.loader import render_to_string from fcrepo.objects import FCObject, SemanticValue from utilities.conversion import UnicodeWriter import datetime import json import os import re import requests import subprocess import sys from django.conf import settings CREATE_SUCCESS = 201 CREATE_FAILED_EXISTS = 409 CREATE_FAILED_TOMBSTONE = 410 PROPERTY_DELETE_SUCCESS = 204 UPDATE_SUCCESS = 204 def import_template_to_fcrepo(url, template, template_data = {}): r = requests.put(url) if (r.status_code == CREATE_FAILED_TOMBSTONE): return r r = requests.patch(url, data=render_to_string(template, template_data)) if (r.status_code != UPDATE_SUCCESS): return r return None def boundeditem_to_fcobject(item, update=False): properties = { "Abstract": "dcterms:abstract", "Access": "dcterms:accessRights", "ContentDate": "dcterms:created", "DataType": "dcterms:medium", "LayerDisplayName": "dcterms:title", "LayerId": "dcterms:identifier", "Location": "dcterms:references", "Originator": "dc:creator", "PlaceKeywords": "dcterms:spatial", "Publisher": "dc:publisher", "ThemeKeywords": "dcterms:subject", } fco = None if update: fco = FCObject(url=item.fedora_url, use_objects=True) else: fco = FCObject() fco.namespaces = { 'dc': 'http://purl.org/dc/elements/1.1/', 'dcterms': 'http://purl.org/dc/terms/', } for (k,v) in properties.items(): if item.__dict__[k] != '""': if v == "dcterms:spatial" or v == "dcterms:subject": fco[v] = item.__dict__[k].replace('"', "'").split(", ") else: fco[v] = item.__dict__[k].replace('"', "'") fco["dcterms:created"] = datetime.datetime.strptime(fco["dcterms:created"]._value[0].replace("Z", ".0Z"), "%Y-%m-%dT%H:%M:%S.%fZ") #MaxX to MinY as bbox string fco["dcterms:bounds"] = "%f,%f,%f,%f" % (item.MinX, item.MinY, item.MaxX, item.MaxY) fco._url = item.fedora_url fco._item = item return fco def import_collection_to_fcrepo(collection, import_items = False): t_start_response = requests.post("%s/fcr:tx" % (settings.FCREPO_BASE_URL)) t_id = t_start_response.headers["location"] collection_url = "%s/place/%s" % (t_id, collection.fedora_name) error = import_template_to_fcrepo(collection_url, "rdf/direct-container.rdf") if error: rollback(t_id) return error values = { "dc:title": collection.full_name } namespaces = { "dc": "http://purl.org/dc/elements/1.1/" } error = import_template_to_fcrepo(collection_url, "rdf/update.rdf", { "namespaces": { "dc": "http://purl.org/dc/elements/1.1/" }, "values": { "dc:title": SemanticValue(collection.full_name.replace('"', "'"), object=None, property="title", namespace="dc", initial=True) } }) if error: rollback(t_id) return error commit_response = requests.post("%s/fcr:tx/fcr:commit" % (t_id)) if (commit_response.status_code != UPDATE_SUCCESS): rollback(t_id) return commit_response if import_items: items = collection.item_set.all() errors = [] for item in items: error = import_item_to_fcrepo(item) if error: errors.append(error) if errors: return errors return None def import_item_to_fcrepo(item): #import to fedora repo fco = boundeditem_to_fcobject(item) error = fco.save() if error: return error #save FGDC metadata headers = { "Content-Disposition": "form-data", "filename": "%s-fgdc.xml" % (item.LayerId), "Content-Type": "text/xml" } url = "%s/FGDC" % (item.fedora_url) response = requests.put(url, data=item.FgdcText, headers=headers) if response.status_code != CREATE_SUCCESS and response.status_code != UPDATE_SUCCESS: return response return None def commit(t_id): response = requests.post("%s/fcr:tx/fcr:commit" % (t_id)) return response def rollback(t_id): response = requests.post("%s/fcr:tx/fcr:rollback" % (t_id)) return response <file_sep>import codecs, csv, os, StringIO, cStringIO from BeautifulSoup import BeautifulStoneSoup from django.contrib.gis.geos import Polygon from PIL import Image from pyproj import Proj, transform from utilities.misc import name_from_filepath, ogp_timestamp_for_now, ogp_timestamp_for_year def points_to_polygon(minX, maxX, minY, maxY): coords = ((minX, minY),(minX, maxY),(maxX, maxY),(maxX, minY),(minX,minY)) return Polygon(coords) def latlng_to_srs(lat, lng, srs, units='m'): srs = unicode(srs) if not srs.startswith("EPSG:"): srs = "EPSG:%s" % (srs) p = Proj(init=srs) (x,y) = p(lng, lat) m_to_ft_alpha = 3937.0 / 1200.0 if units == "ft": x = x * m_to_ft_alpha y = y * m_to_ft_alpha return (x,y) def srs_to_latlng(x,y,srs,units='m'): if not unicode(srs).startswith("EPSG:"): srs = "EPSG:%s" % (srs) ft_to_m_alpha = 1200.0 / 3937.0 #official survey foot to meter conversion if units == 'ft': x *= ft_to_m_alpha y *= ft_to_m_alpha p1 = Proj(init=srs) p2 = Proj(init="EPSG:4326") #WGS84 srs aka standard Lat./Long. projection (lng, lat) = transform(p1, p2, x, y) return (lat, lng) def meter_to_survey_foot(distance): m_to_ft_alpha = 3937.0 / 1200.0 return distance * m_to_ft_alpha def survey_foot_to_meter(distance): ft_to_m_alpha = 1200.0 / 3937.0 return distance * ft_to_m_alpha def fgdc_to_ogp_csv(fgdc_path, return_header=False): with open(fgdc_path) as f: xml = BeautifulStoneSoup(f) csv_fields = {} csv_fields['DataType'] = xml.find("direct").text csv_fields['MinX'] = float(xml.find("westbc").text) csv_fields['MaxX'] = float(xml.find("eastbc").text) csv_fields['MinY'] = float(xml.find("southbc").text) csv_fields['MaxY'] = float(xml.find("northbc").text) csv_fields['CenterX'] = (csv_fields['MinX'] + csv_fields['MaxX'])/2 csv_fields['CenterY'] = (csv_fields['MinY'] + csv_fields['MaxY'])/2 csv_fields['HalfWidth'] = csv_fields['MaxX'] - csv_fields['CenterX'] csv_fields['HalfHeight'] = csv_fields['MaxY'] - csv_fields['CenterY'] csv_fields['Area'] = 4 * csv_fields['HalfWidth'] * csv_fields['HalfHeight'] csv_fields['Institution'] = "UNH" csv_fields['WorkspaceName'] = "ogp" csv_fields['Name'] = name_from_filepath(fgdc_path) csv_fields['LayerId'] = "%s.%s" % (csv_fields['Institution'], csv_fields['Name']) csv_fields['timestamp'] = ogp_timestamp_for_now() csv_fields['Availability'] = "Online" csv_fields['GeoReferenced'] = "TRUE" themes = xml.findAll("themekey") csv_fields['ThemeKeywords'] = '"' if len(themes) > 0: csv_fields['ThemeKeywords'] += '%s' % (themes.pop().text) for t in themes: csv_fields['ThemeKeywords'] += ', %s' % (t.text) csv_fields['ThemeKeywords'] += '"' places = xml.findAll("placekey") csv_fields['PlaceKeywords'] = '"' if len(places) > 0: csv_fields['PlaceKeywords'] += '%s' % (places.pop().text) for p in places: csv_fields['PlaceKeywords'] += ', %s' % (p.text) csv_fields['PlaceKeywords'] += '"' #pubdate is correct according to the FGDC spec, but OGP expects the date to be in the same format as TimeStamp csv_fields['ContentDate'] = content_date_for_map(xml.find("timeperd").find("caldate").text) csv_fields['Originator'] = xml.findAll("origin")[-1].text csv_fields['LayerDisplayName'] = xml.find("title").text.replace("Historic Digital Raster Graphic - ", "") csv_fields['Publisher'] = xml.find("publish").text csv_fields['Access'] = "Public" csv_fields['Abstract'] = xml.find("abstract").text csv_fields['Location'] = '{"wms": ["https://place.sr.unh.edu:8080/geoserver/wms"]}' csv_fields['FgdcText'] = unicode(xml) fields = sorted(csv_fields.keys()) data = [] stringIO = cStringIO.StringIO() writer = UnicodeWriter(stringIO) for field in fields: v = csv_fields[field] if type(csv_fields[field]) == float: v = str(v) data.append(v) writer.writerow(data) csv_row = stringIO.getvalue() stringIO.close() if return_header: stringIO = StringIO.StringIO() writer = csv.writer(stringIO) writer.writerow(fields) header_row = stringIO.getvalue() stringIO.close() return (header_row, csv_row) else: return csv_row def image_path_with_fgdc_to_world_file(image_path, world_file, srs, units="m"): image = Image.open(image_path) (width, height) = image.size xml_path = "%s.xml" % (os.path.splitext(image_path)[0]) with open(xml_path, "r") as f: xml = BeautifulStoneSoup(f) north_bound = float(xml.find("northbc").text) west_bound = float(xml.find("westbc").text) south_bound = float(xml.find("southbc").text) east_bound = float(xml.find("eastbc").text) srs = "%s" % (srs) if not srs.startswith("EPSG:"): srs = "EPSG:%s" % (srs) (west_bound, north_bound) = latlng_to_srs(north_bound, west_bound, srs, units) (east_bound, south_bound) = latlng_to_srs(south_bound, east_bound, srs, units) x_pixel_width = (east_bound - west_bound) / width y_pixel_width = (south_bound - north_bound) / height for l in [x_pixel_width, 0, 0, y_pixel_width, west_bound, north_bound]: world_file.write("%s\n" % l) return world_file def content_date_for_map(date): if (type(date) == unicode or type(date) == str) and len(date) == 4: return ogp_timestamp_for_year(date) else: return ogp_timestamp_for_now() class UnicodeWriter: """ A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding. """ def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds): # Redirect output to a queue self.queue = cStringIO.StringIO() self.writer = csv.writer(self.queue, dialect=dialect, **kwds) self.stream = f self.encoder = codecs.getincrementalencoder(encoding)() def writerow(self, row): self.writer.writerow([s.encode("utf-8") for s in row]) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() data = data.decode("utf-8") # ... and reencode it into the target encoding data = self.encoder.encode(data) # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) def writerows(self, rows): for row in rows: self.writerow(row) <file_sep>groupItems = function(items, minimumSimilarity, splitRegexp) { minimumSimilarity = minimumSimilarity || 1 splitRegexp = splitRegexp || new RegExp("[ ,_]+", "g") if (items.length == 0) { return {} } if (items.length == 1) { var itemName = items[0].LayerDisplayName var groups = {} groups[itemName] = items return groups } if (items.length == 2) { var parts = splitNamesIntoParts(items, splitRegexp) var similarity = partsSimilarity(parts[0], parts[1]) var groups = {} if (similarity >= minimumSimilarity) { var key = keyForGroup(items, splitRegexp) groups[key] = items return groups } else { groups[items[0].LayerDisplayName] = [items[0]] groups[items[1].LayerDisplayName] = [items[1]] } return groups } else { var groups = {} var parts = splitNamesIntoParts(items, splitRegexp) var currentGroup = [] var similarity = null var previousSimilarity = null for (var i = 0; i < items.length; ++i) { var item = items[i] if (previousSimilarity == null && currentGroup.length == 0) { //new group currentGroup.push(item) continue } similarity = partsSimilarity(parts[i], parts[i-1]) if (currentGroup.length == 1 && similarity < minimumSimilarity || (similarity != previousSimilarity && currentGroup.length > 1)) { //should start new group previousSimilarity = null var key = keyForGroup(currentGroup, splitRegexp) groups[key] = currentGroup currentGroup = [] --i } else { //add to current group currentGroup.push(item) previousSimilarity = similarity } } groups[keyForGroup(currentGroup, splitRegexp)] = currentGroup //get key for last group and add return groups } } keyForGroup = function(keyGroup, splitRegexp) { if (keyGroup.length == 0) { return null } if (keyGroup.length == 1) { return keyGroup[0].LayerDisplayName } else { var splitString = splitRegexp.source var parts = splitNamesIntoParts([keyGroup[0], keyGroup[1]], splitRegexp) var key = keyGroup[0].LayerDisplayName if (parts[0].length == parts[1].length) { for (var i = 0; i < parts[0].length; ++i) { if (parts[0][i] != parts[1][i]) { key = key.replace(parts[0][i], "&middot;&middot;&middot;") } } } else { var similarity = partsSimilarity(parts[0], parts[1]) var similarParts = parts[0].splice(0,similarity) var regexpString = "" for (var i = 0; i < (similarParts.length - 1); ++i) { regexpString = sprintf("%s%s%s", regexpString, similarParts[i], splitString) } regexpString = sprintf("%s%s", regexpString, similarParts[similarParts.length-1]) key = keyGroup[0].LayerDisplayName.match(regexpString) } key = sprintf("%s (%d items)", key, keyGroup.length) return key } } splitNamesIntoParts = function(items, splitRegexp) { var parts = [] for (var i = 0; i < items.length; ++i) { var item = items[i] parts.push(item.LayerDisplayName.replace(splitRegexp, " ").split(" ")) } return parts } partsSimilarity = function(parts1, parts2) { var length = parts1.length > parts2.length ? parts2.length : parts1.length for (var i = 0; i < length; ++i) { if (parts1[i] != parts2[i]) { break } } return i } stringSimilarity = partsSimilarity <file_sep>from django.contrib.gis.db.models import Union from django.contrib.gis.geos import WKTReader from django.core.management.base import BaseCommand, CommandError from gazetteer.models import State, Municipality, ShapeFileData, GeneratedGeometry from gazetteer.views import shape_to_geos import os import shapefile from django.conf import settings class Command(BaseCommand): help = 'Add municipalities to the gazetteer' def add_arguments(self, parser): parser.add_argument("task", type=str) parser.add_argument("shapefile_path", type=str) parser.add_argument("--record", type=int, default=0) parser.add_argument("--srs", type=int) parser.add_argument("--units", type=str) parser.add_argument("--state", type=str) parser.add_argument("--name_field", type=str) parser.add_argument("--county_field", type=str) parser.add_argument("--id_field", type=str) parser.add_argument("--keep_loaded_shapefile", type=bool, default=False) parser.add_argument("--keep_loaded_municipalities", type=bool, default=False) parser.add_argument("--template_directory", type=str, default=settings.TEMPLATE_DIRS[0]) def handle(self, *args, **options): task = options["task"] shapefile_path = options["shapefile_path"] r = options["record"] if not task in ("fields", "load"): raise CommandError("task must be 'fields' or 'load'") if not shapefile_path: raise CommandError("A shapefile path must be provided") if task == "fields": self.show_record(shapefile_path, r) if task == "load": self.load_shapefile(shapefile_path, options) def show_record(self, shapefile_path, r): self.stdout.write("Listing shapefile fields along with a record sample") self.stdout.write("") sf = shapefile.Reader(shapefile_path) fields = [f[0] for f in sf.fields[1:]] max_length = 0 for f in fields: if len(f) > max_length: max_length = len(f) format_string = "%" + str(max_length) + "s:" record = dict(zip(fields, sf.records()[r])) for k in record: self.stdout.write(format_string % (k), ending="") self.stdout.write(unicode(record[k])) def load_shapefile(self, shapefile_path, options): srs = options["srs"] state = options["state"] name_key = options["name_field"] county_key = options["county_field"] id_key = options["id_field"] units = options["units"] if not state: raise CommandError("A 2 character state code e.g. AK, is required.") if State.objects.count() == 0: raise CommandError("Initial data must be loaded first. Use 'manage.py gaz create --state=initial'") if not name_key: raise CommandError("The field name storing the municipality's name must be provided.") if not county_key: raise CommandError("The field name storing the FIPS code for the muncipality's county must be provided. Shapefiles that do not provide this field are currently not supported.") if not id_key: raise CommandError("The field name storing the ID to use for municipalities must be provided.") if srs == 4326 and not units: units = "m" sf = shapefile.Reader(shapefile_path) fields = [f[0] for f in sf.fields[1:]] n = len(sf.records()) self.stdout.write("Loading %d shapes" % (n)) state_fips = State.objects.get(abbreviation=state).state_fips for i in range(0,n): g = shape_to_geos(sf.shapes()[i], srs, unit=units) r = [str(l) for l in sf.records()[i]] r = dict(zip(fields, r)) if r[name_key].strip() == '': continue if len(r[county_key]) <= 3: county_fips = "%3d" % (int(r[county_key])) else: county_fips = str(r[county_key])[-3:] sfd = ShapeFileData(geometry=g, record=r, state=state, name=r[name_key].decode("utf-8"), state_fips=state_fips, county_fips=county_fips) sfd.save() self.stdout.write("%d/%d" % (i+1, n)) if not options["keep_loaded_municipalities"]: self.stdout.write("Deleting current municipalities") Municipality.objects.filter(state_fips=state_fips).delete() GeneratedGeometry.objects.filter(gazetteer_id__startswith="municipality:%s" % (state_fips)).delete() self.stdout.write("Creating %d municipalities" % (ShapeFileData.objects.filter(state=state).distinct("name").count())) for sfd in ShapeFileData.objects.filter(state=state).distinct("name"): geometry = ShapeFileData.objects.filter(name=sfd.name, state_fips=state_fips, county_fips=sfd.county_fips).aggregate(Union("geometry"))["geometry__union"] d = { "county_fips": sfd.county_fips, "geometry": geometry, "place_id": sfd.record[id_key], "name": sfd.name, "state_fips": state_fips } m = Municipality(**d) m.save() gg = GeneratedGeometry(geometry=geometry, gazetteer_id="municipality:%s%s-%s" % (state_fips, sfd.county_fips, sfd.record[id_key])) gg.save() template_dir = options["template_directory"] municipality_template_dir = "%s/polygons/municipality/%s/%s" % (template_dir, state_fips, sfd.county_fips) if not (os.path.exists(municipality_template_dir)): os.makedirs(municipality_template_dir, mode=0755) with open("%s/%s.json" % (municipality_template_dir, sfd.record[id_key]), "w") as f: f.write(geometry.geojson) if not options["keep_loaded_shapefile"]: ShapeFileData.objects.filter(state_fips=state_fips).delete() <file_sep>from django.core.management.base import BaseCommand, CommandError import crontab #from place.settings import BASE_DIR from django.conf import settings BASE_DIR = settings.BASE_DIR class Command(BaseCommand): help = 'Start or stop the cron jobs associated with processing download requests and updating the database from external Solr repositories.' def add_arguments(self, parser): parser.add_argument("command", type=str) parser.add_argument("task", type=str) def handle(self, *args, **options): command = options["command"] task = options["task"] if not command in ("start", "stop"): raise CommandError("command must be either 'start' or 'stop'") if not task in ("downloads", "update", "all"): raise CommandError("task must be either 'downloads', 'update', or 'all' for both.") if task == "downloads": self.toggle_downloads(command) self.toggle_delete(command) elif task == "update": self.toggle_update(command) elif task == "all": self.toggle_downloads(command) self.toggle_delete(command) self.toggle_update(command) def toggle_downloads(self, command): cron = crontab.CronTab(user=False, tabfile="/etc/crontab") jobs = list(cron.find_command("%s/cron/process_download_requests.py" % (BASE_DIR))) job = None if len(jobs) == 0: job = cron.new("%s/cron/process_download_requests.py" % (BASE_DIR), user="apache") job.minute.every(5) else: job = jobs[0] job.enable(command == "start") cron.write() self.stdout.write("%s background download request processing" % ("Enabled" if command == "start" else "Disabled")) def toggle_delete(self, command): cron = crontab.CronTab(user=False, tabfile="/etc/crontab") jobs = list(cron.find_command("%s/cron/delete_old_downloads.py" % (BASE_DIR))) job = None if len(jobs) == 0: job = cron.new("%s/cron/delete_old_downloads.py" % (BASE_DIR), user="apache") job.minute.on(0) job.hour.on(0) else: job = jobs[0] job.enable(command == "start") cron.write() self.stdout.write("%s background download deletion" % ("Enabled" if command == "start" else "Disabled")) def toggle_update(self, command): cron = crontab.CronTab(user=False, tabfile="/etc/crontab") jobs = list(cron.find_command("%s/cron/update_db_from_solr.py" % (BASE_DIR))) job = None if len(jobs) == 0: job = cron.new("%s/cron/update_db_from_solr.py" % (BASE_DIR), user="apache") job.minute.on(0) job.hour.on(0) job.dow.on(0) else: job = jobs[0] job.enable(command == "start") cron.write() self.stdout.write("%s background database update" % ("Enabled" if command == "start" else "Disabled")) <file_sep>from django.contrib.gis.geos import WKTReader, Polygon, MultiPolygon, GEOSException from django.db import connections from django.db.models import Q from django.http import HttpResponse from django.shortcuts import render from gazetteer.models import GeneratedGeometry, Municipality, GNIS, ShapeFileData, State, County from nominatim.models import CountryName, USState, USStateCounty from ogp.views import bad_request, completed_request from utilities.conversion import srs_to_latlng def bbox_polygon(request): gazetteer_id = request.GET.get("id") if not gazetteer_id: return bad_request(["MISSING: id"]) with connections["default"].cursor() as cursor: cursor.execute("SELECT ST_AsGeoJSON(Box2d(gazetteer_generatedgeometry_test.geometry)) from gazetteer_generatedgeometry_test where gazetteer_id=%s", [gazetteer_id]) geojson = cursor.fetchone()[0] return HttpResponse(geojson, content_type="application/json") def gazetteer_countries(request): language_code = request.GET.get("language", "en") countries = [{"name": c.name_for_language(language_code), "id": c.country_code} for c in CountryName.objects.all()] countries.sort(key=lambda c: c["name"]) return completed_request(countries) def country_polygon(request): country = request.GET.get("id") if not country: return bad_request(["MISSING: id"]) country = country.lower() return render(request, "polygons/country/%s.json" % (country), content_type="application/json") def gazetteer_states(request): states = [{"name": s.name, "id": s.state_fips, "next_entries": s.counties.count()} for s in State.objects.all().order_by("name")] return completed_request(states) def state_polygon(request): state_fips = request.GET.get("id") if not state_fips: return bad_request(["MISSING: id"]) return render(request, "polygons/state/%s.json" % (state_fips), content_type="application/json") def counties_for_state(request): state_fips = request.GET.get("id") if not state_fips: return bad_request(["MISSING: id"]) counties = [{"name": c.name, "id": c.identifier, "next_entries": c.municipalities.count()} for c in County.objects.filter(state_fips=state_fips).order_by("name")] return completed_request(counties) def county_polygon(request): fips = request.GET.get("id") if not fips: return bad_request(["MISSING: id"]) state_fips = fips[:2] county_fips = fips[2:] return render(request, "polygons/county/%s/%s.json" % (state_fips, county_fips), content_type="application/json") def municipalities_for_county(request): fips = request.GET.get("id") if not fips: return bad_request(["MISSING: id"]) municipalities = [{ "name": m.name, "id": "%s%s-%s" % (m.state_fips, m.county_fips, m.identifier), "next_entries": 0, } for m in Municipality.objects.filter(state_fips = fips[:2], county_fips = fips[2:]).order_by("name")] return completed_request(municipalities) def municipality_polygon(request): m_id = request.GET.get("id") if not m_id: return bad_request(["MISSING: id"]) (fips, identifier) = m_id.split("-") return render(request, "polygons/municipality/%s/%s/%s.json" % (fips[:2], fips[2:], identifier), content_type="application/json") def shape_to_geos(shape, srs, unit="m"): args = [] for point_index in range(0, len(shape.points)): if point_index in shape.parts: args.append([]) point = shape.points[point_index] point = srs_to_latlng(point[0], point[1], srs, unit) args[-1].append([point[1], point[0]]) polygon = Polygon(*args) try: polygon.union(polygon) #this will fail if the polygon is actual a MultiPolygon except GEOSException as e: polygon = MultiPolygon([Polygon(p) for p in polygon]) return polygon def load_shapefile(sf, srs, state, state_fips, name_key, unit="m", title_case=False, county_key=None): fields = [f[0] for f in sf.fields[1:]] n = len(sf.records()) for i in range(0,n): g = shape_to_geos(sf.shapes()[i], srs, unit=unit) if title_case: r = [str(l).title() for l in sf.records()[i]] else: r = [str(l) for l in sf.records()[i]] r = dict(zip(fields, r)) county_fips = "%03d" % (int(r[county_key])) if county_key else None sfd = ShapeFileData(geometry=g, record=r, state=state, name=r[name_key], state_fips=state_fips, county_fips=county_fips) sfd.save() print "%d/%d" % (i+1, n) def add_gnis(file_name): print file_name with open(file_name) as f: lines = [l.strip().split("|") for l in f.readlines()] lines = lines[1:] attributes = ['feature_id', 'feature_name', 'feature_class', 'state_alpha', 'state_numeric', 'county_name', 'county_numeric', 'primary_latitude_dms', 'primary_longitude_dms', 'primary_latitude_dec', 'primary_longitude_dec', 'source_latitude_dms', 'source_longitude_dms', 'source_latitude_dec', 'source_longitude_dec', 'elevation_meters', 'elevation_feet', 'map_name', 'date_created', 'date_modified'] num_attributes = len(attributes) number_of_lines = len(lines) current_line_number = 0 skipped = 0 print "Loading %d" % (number_of_lines) for line in lines: current_line_number += 1 if current_line_number % 1000 == 0: print "%d/%d" % (current_line_number + 1, number_of_lines) if GNIS.objects.filter(feature_id=line[0]).exists(): skipped += 1 continue record = dict(zip(attributes, line)) record['feature_id'] = int(record['feature_id']) record['primary_latitude_dec'] = float(record['primary_latitude_dec']) record['primary_longitude_dec'] = float(record['primary_longitude_dec']) record['source_latitude_dec'] = float(record['source_latitude_dec']) if record['source_latitude_dec'] != '' else None record['source_longitude_dec'] = float(record['source_longitude_dec']) if record['source_longitude_dec'] != '' else None record['elevation_meters'] = float(record['elevation_meters']) if record['elevation_meters'] else None record['elevation_feet'] = float(record['elevation_feet']) if record['elevation_feet'] else None g = GNIS(**record) g.save() return skipped <file_sep>L.LatLngBounds.prototype.union = function(bounds) { var east = this.getEast() > bounds.getEast() ? this.getEast() : bounds.getEast() var west = this.getWest() < bounds.getWest() ? this.getWest() : bounds.getWest() var north = this.getNorth() > bounds.getNorth() ? this.getNorth() : bounds.getNorth() var south = this.getSouth() < bounds.getSouth() ? this.getSouth() : bounds.getSouth() return L.latLngBounds([south, west],[north,east]) } <file_sep>#!/usr/bin/python import os import settings os.system("python %s/manage.py downloads process" % (settings.BASE_DIR)) <file_sep>from django.contrib.gis.db.models import Union from django.contrib.gis.geos import Polygon, Point, WKBReader from django.core.management.base import BaseCommand, CommandError from django.db import connections from nominatim.models import USState, USStateCounty from gazetteer.models import GeneratedGeometry, GNIS, FIPS55, Municipality, ShapeFileData, State, County from gazetteer.views import shape_to_geos from glob import glob from lockfile import LockFile from zipfile import ZipFile import datetime import errno import os import requests import shapefile import shutil import sys import urllib #from place.settings import BASE_DIR from django.conf import settings BASE_DIR = settings.BASE_DIR BOLD_START = '\033[1m' BOLD_END = '\033[0m' class Command(BaseCommand): help = 'Create or update the gazetteer' def add_arguments(self, parser): parser.add_argument("task", type=str) parser.add_argument("--state", type=str) parser.add_argument("--county", type=str) parser.add_argument("--template_directory", type=str, default=settings.TEMPLATE_DIRS[0]) def handle(self, *args, **options): task = options["task"] state = options["state"] county = options["county"] template_dir = options["template_directory"] if not task in ("create", "list", "load_fips", "load_gnis"): raise CommandError("task must be 'create', 'list', 'load_fips' or 'load_gnis'") if task == "create": if not state: raise CommandError("A state is required. Use '--state=initial' to create the initial gazetteer data, or '--state=all' to load all gazetteer data.") if state == "initial": self.load_initial_data(template_dir) elif state == "all": if State.objects.all().count() == 0: self.load_initial_data(template_dir) for s in State.objects.all().order_by("state_fips"): self.stdout.write(s.name) self.load_tiger_shapefile(s.state_fips, template_dir) else: self.load_tiger_shapefile(state, template_dir) if task == "list": if state == "all": for state in State.objects.distinct("name").order_by("name"): self.stdout.write(state.name) for county in County.objects.filter(state_fips = state.state_fips).distinct("name").order_by("name"): self.stdout.write(u" %s" % (county)) for m in Municipality.objects.filter(state_fips=state.state_fips, county_fips=county.county_fips).order_by("name"): self.stdout.write(u" %s" % (m)) elif not state and not county: states = State.objects.all().distinct("state_fips").order_by("state_fips").values_list("state_fips", "name", "abbreviation") self.stdout.write("Listing all states with FIPS code and abbreviation.") for state in states: self.stdout.write("%s/%s - %s" % (state[0], state[2], state[1])) elif state and not county: state = self.state_to_fips(state) self.stdout.write("Listing all counties in %s%s%s with FIPS codes" % (BOLD_START, State.objects.get(state_fips=state).name, BOLD_END)) for county in County.objects.filter(state_fips=state).order_by("county_fips"): self.stdout.write("%s - %s" % (county.county_fips, county)) elif state and county: state = self.state_to_fips(state) county = self.county_to_fips(state, county) self.stdout.write("Listing all municipalities and county subdivisions in %s%s, %s%s" % (BOLD_START, County.objects.get(county_fips=county, state_fips=state), State.objects.get(state_fips=state), BOLD_END)) for m in Municipality.objects.filter(state_fips=state, county_fips=county).order_by("name"): self.stdout.write("%s" % (m)) return if task == "load_gnis": if not state: raise CommandError("A 2 character state code is required") self.load_gnis(state) if task == "load_fips": if not state: raise CommandError("A 2 character state code is required or enter \"all\" for the entire US") self.load_fips(state) def load_fips(self, state): url = None if len(state) == 2: state_fips = self.state_to_fips(state) url = "https://www2.census.gov/geo/docs/reference/codes/files/st%s_%s_places.txt" % (state_fips, state.lower()) elif state == "all": url = "https://www2.census.gov/geo/docs/reference/codes/files/national_places.txt" else: raise CommandError("A 2 character state code is required or enter \"all\" for the entire US") response = requests.get(url) lines = [l.strip().split("|") for l in response.text.split("\n")] if state == "all": lines = lines[1:] last_state = None for fips_values in lines: fips_keys = ["state", "state_fips", "place_fips", "place_name", "place_type", "status", "county"] d = dict(zip(fips_keys, fips_values)) if not "place_fips" in d: continue if d["state"] != last_state: last_state = d["state"] self.stdout.write("Loading codes for %s" % last_state) qs = FIPS55.objects.filter(state=d["state"], place_fips=d["place_fips"]) if qs.exists(): continue fips = FIPS55(**d) fips.save() return def municipalities_in_county(self, state, county): state = self.state_to_fips(state) county = self.county_to_fips(state, county) return Municipality.objects.filter(state_fips=state, county_fips=county).order_by("name") def state_to_fips(self, state): if len(state) == 2 and state.isdigit(): qs = State.objects.filter(state_fips=state) if not qs.exists(): raise CommandError("\"%s\" is not a valid state FIPS code. Use \"gazetteer list\" to get a list of state codes." % (state)) return state elif len(state) == 2: #not 2 digit code qs = State.objects.filter(abbreviation=state) if not qs.exists(): raise CommandError("\"%s\" is not a valid 2 character abbreviation. Use \"gazetteer list\" to get a list of state codes." % (state)) return qs.first().state_fips elif len(state) > 2: qs = State.objects.filter(name=state) if not qs.exists(): raise CommandError("\"%s\" is not a valid state name. Use \"gazetteer list\" to get a list of state codes." % (state)) return qs.first().state_fips else: raise CommandError("State must be either the full state name, the 2 character abbreviation or the 2 digit FIPS code. Use \"gazetteer list\" to get a list of state codes.") def county_to_fips(self, state, county): state = self.state_to_fips(state) if len(county) == 3 and county.isdigit(): qs = County.objects.filter(state_fips = state, county_fips=county) if not qs.exists(): raise CommandError("\"%s\" is not a valid county FIPS code. Use \"gazetteer list --state=%s\" to get a list of county codes." % (county, state)) return county else: qs = County.objects.filter(state_fips = state, name = county) if not qs.exists(): raise CommandError("\"%s\" is not a valid county name. Use \"gazetteer list --state=%s\" to get a list of county codes." % (county, state)) return qs.first().county_fips def load_tiger_shapefile(self, state, template_dir): state = self.state_to_fips(state) url = "https://www2.census.gov/geo/tiger/TIGER2016/COUSUB/tl_2016_%s_cousub.zip" % (state) tmp_dir = "/tmp/tiger-%s" % (state) tmp_file = "%s/tl_2016_%s_cousub.zip" % (tmp_dir, state) #create directory if needed try: os.makedirs(tmp_dir) except OSError, e: if e.errno != errno.EEXIST: raise e #retrieve file urllib.urlretrieve(url, tmp_file) #extract zipfile = ZipFile(tmp_file) zipfile.extractall(path=tmp_dir) zipfile.close() #process sf = shapefile.Reader(tmp_file.replace("zip", "shp")) fields = [f[0] for f in sf.fields[1:]] n = len(sf.records()) for i in range(0,n): r = dict(zip(fields, sf.records()[i])) if Municipality.objects.filter(state_fips=r["STATEFP"], county_fips=r["COUNTYFP"], name=r["NAME"]).exists(): continue s = shape_to_geos(sf.shapes()[i], 4326) d = { "county_fips": r["COUNTYFP"], "geometry": s, "place_id": unicode(r["GEOID"]), "name": r["NAME"].decode("utf-8"), "state_fips": r["STATEFP"], } m = Municipality(**d) m.save() gg = GeneratedGeometry(geometry=s, gazetteer_id="municipality:%s%s-%s" % (r["STATEFP"], r["COUNTYFP"], r["GEOID"])) gg.save() municipality_template_dir = "%s/polygons/municipality/%s/%s" % (template_dir, r["STATEFP"], r["COUNTYFP"]) if not (os.path.exists(municipality_template_dir)): os.makedirs(municipality_template_dir, mode=0755) with open("%s/%s.json" % (municipality_template_dir, r["GEOID"]), "w") as f: f.write(s.geojson) self.stdout.write("%d/%d - %s" % (i+1, n, r["NAME"].decode("utf-8"))) #delete file for f in glob("%s/tl_2016_%s_cousub.*" % (tmp_dir, state)): os.remove(f) try: os.rmdir(tmp_dir) except e: pass return def load_initial_data(self, template_dir): self.load_initial_states(template_dir) self.load_initial_counties(template_dir) def load_initial_states(self, template_dir): state_directory = "%s/polygons/state" % (template_dir) #creates states if not os.path.exists(state_directory): os.makedirs(state_directory, mode=0755) state_url = "https://www2.census.gov/geo/tiger/TIGER2016/STATE/tl_2016_us_state.zip" tmp_dir = "/tmp/tiger-state" tmp_file = "%s/tl_2016_us_state.zip" % (tmp_dir) try: os.makedirs(tmp_dir) except OSError, e: if e.errno != errno.EEXIST: raise e urllib.urlretrieve(state_url, tmp_file) zipfile = ZipFile(tmp_file) zipfile.extractall(path=tmp_dir) zipfile.close() sf = shapefile.Reader(tmp_file.replace("zip", "shp")) fields = [f[0] for f in sf.fields[1:]] n = len(sf.records()) self.stdout.write("Loading %d states and territories" % (n)) for i in range(0,n): r = dict(zip(fields, sf.records()[i])) if State.objects.filter(state_fips=r["STATEFP"]).exists(): continue s = shape_to_geos(sf.shapes()[i], 4326) d = { "name": r["NAME"].decode("utf-8"), "geometry": s, "state_fips": r["STATEFP"], "abbreviation": r["STUSPS"], } state = State(**d) state.save() gg = GeneratedGeometry(geometry=s, gazetteer_id="state:%s" % (r["STATEFP"])) gg.save() with open("%s/%s.json" % (state_directory, r["STATEFP"]), "w") as f: f.write(s.geojson) self.stdout.write("%d/%d - %s" % (i+1, n, r["NAME"].decode("utf-8"))) for f in glob("%s/tl_2016_us_state.*" % (tmp_dir)): os.remove(f) try: os.rmdir(tmp_dir) except e: pass return def load_initial_counties(self, template_dir): county_directory = "%s/polygons/county" % (template_dir) if not os.path.exists(county_directory): os.makedirs(county_directory, mode=0755) county_url = "https://www2.census.gov/geo/tiger/TIGER2016/COUNTY/tl_2016_us_county.zip" tmp_dir = "/tmp/tiger-county" tmp_file = "%s/tl_2016_us_county.zip" % (tmp_dir) try: os.makedirs(tmp_dir) except OSError, e: if e.errno != errno.EEXIST: raise e urllib.urlretrieve(county_url, tmp_file) zipfile = ZipFile(tmp_file) zipfile.extractall(path=tmp_dir) zipfile.close() sf = shapefile.Reader(tmp_file.replace("zip", "shp")) fields = [f[0] for f in sf.fields[1:]] n = len(sf.records()) self.stdout.write("Loading %d counties" % (n)) for i in range(0,n): if (i+1) % 100 == 0: self.stdout.write("%d/%d" % (i+1, n)) r = dict(zip(fields, sf.records()[i])) if County.objects.filter(state_fips=r["STATEFP"], county_fips=r["COUNTYFP"]).exists(): continue s = shape_to_geos(sf.shapes()[i], 4326) d = { "name": r["NAME"].decode("utf-8"), "geometry": s, "state_fips": r["STATEFP"], "county_fips": r["COUNTYFP"], } county = County(**d) county.save() gg = GeneratedGeometry(geometry=s, gazetteer_id="county:%s%s" % (r["STATEFP"], r["COUNTYFP"])) gg.save() county_template_directory = "%s/%d" % (county_directory, r["STATEFP"]) if not (os.path.exists(county_template_directory)): os.makedirs(county_template_directory, mode=0755) with open("%s/%s.json" % (county_template_directory, r["COUNTYFP"]), w) as f: f.write(s.geojson) for f in glob("%s/tl_2016_us_county.*" % (tmp_dir)): os.remove(f) try: os.rmdir(tmp_dir) except e: pass return def load_gnis(self, state): if not State.objects.filter(abbreviation=state).exists(): raise CommandError("'%s' is not a valid state" % (state)) url = 'https://geonames.usgs.gov/docs/stategaz/%s_Features_20171001.zip' % (state) tmp_file = '/tmp/%s_Features_20171001.zip' % (state) urllib.urlretrieve(url, tmp_file) zipfile = ZipFile(tmp_file) zipfile.extractall(path="/tmp") zipfile.close() with open(tmp_file.replace("zip", "txt")) as f: lines = [l.strip().split("|") for l in f.readlines()] lines = lines[1:] attributes = ['feature_id', 'feature_name', 'feature_class', 'state_alpha', 'state_numeric', 'county_name', 'county_numeric', 'primary_latitude_dms', 'primary_longitude_dms', 'primary_latitude_dec', 'primary_longitude_dec', 'source_latitude_dms', 'source_longitude_dms', 'source_latitude_dec', 'source_longitude_dec', 'elevation_meters', 'elevation_feet', 'map_name', 'date_created', 'date_modified'] num_attributes = len(attributes) number_of_lines = len(lines) current_line_number = 0 skipped = 0 self.stdout.write("Loading %d for %s" % (number_of_lines, state)) for line in lines: current_line_number += 1 if current_line_number % 1000 == 0: print "%d/%d" % (current_line_number, number_of_lines) if GNIS.objects.filter(feature_id=line[0]).exists(): skipped += 1 continue record = dict(zip(attributes, line)) record['feature_id'] = int(record['feature_id']) record['primary_latitude_dec'] = float(record['primary_latitude_dec']) record['primary_longitude_dec'] = float(record['primary_longitude_dec']) record['source_latitude_dec'] = float(record['source_latitude_dec']) if record['source_latitude_dec'] != '' else None record['source_longitude_dec'] = float(record['source_longitude_dec']) if record['source_longitude_dec'] != '' else None record['elevation_meters'] = float(record['elevation_meters']) if record['elevation_meters'] else None record['elevation_feet'] = float(record['elevation_feet']) if record['elevation_feet'] else None g = GNIS(**record) g.save() os.remove(tmp_file) os.remove(tmp_file.replace("zip", "txt")) if skipped > 0: self.stdout.write("%d already loaded" % (skipped)) <file_sep>import requests from django.template.loader import render_to_string from utilities.conversion import * from utilities.misc import is_string from PIL import Image from django.conf import settings GEOSERVER = settings.GEOSERVER def get_workspace(json={}, name=None): if not 'name' in json and not name: return None elif 'name' in json: name = json['name'] url = "%s/workspaces/%s" % (GEOSERVER['REST_URL'], name) headers = { "Accept" : "text/json" } response = requests.get(url, auth = (GEOSERVER['USER'], GEOSERVER['PASSWORD']), headers = headers) if response.status_code == 404: return None return Workspace(json=response.json()) def get_coverage_store(json={}, workspace="ogp", name=None): if 'name' in json and 'workspace' in json: name = json['name'] workspace = json['workspace']['name'] elif not workspace or not name: return None if is_string(workspace): workspace = Workspace(name=workspace) url = "%s/coveragestores/%s" % (workspace.url_with_name(), name) auth = (GEOSERVER['USER'], GEOSERVER['PASSWORD']) headers = {"Accept": "application/json"} response = requests.get(url=url, auth=auth, headers=headers) if response.status_code == 404: return None return CoverageStore(json=response.json()) def get_coverage(coverage_store=None, name=None): if not name and not coverage_store: return None if is_string(coverage_store): coverage_store = get_coverage_store(name=coverage_store) url = "%s/coverages/%s" % (coverage_store.url_with_name(), name) auth = (GEOSERVER['USER'], GEOSERVER['PASSWORD']) headers = {"Accept": "application/json"} response = requests.get(url=url, auth=auth, headers=headers) return Coverage(json=response.json(), coverage_store=coverage_store) #assumes map plus worldfile is already on the server #relative paths are relative to the geoserver data directory def add_to_geoserver(name, filepath, workspace="ogp", srs="EPSG:3445", units="ft"): if not filepath.startswith("file:"): filepath = "file:" + filepath if not unicode(srs).startswith("EPSG:"): srs = "EPSG:%s" % (srs) coverage_store = CoverageStore(name=name, workspace=workspace, url=filepath) (saved, response) = coverage_store.save() if saved: coverage = Coverage(name=coverage_store.name, coverage_store=coverage_store, srs=srs, units = units) (saved, response) = coverage.save() return (saved, response, coverage) else: return (saved, response, None) class GeoServerObject(object): name = None _server_name = None _modified = False _new = False get_functions = { 'workspace': get_workspace, 'coverageStore': get_coverage_store, } def __init__(self, *args, **kwargs): if 'json' in kwargs: json = kwargs['json'] main_key = json.keys()[0] #the top level of the dictionary has a lone key with the same name as the object type attribute_json = json[main_key] attributes = dir(self) if 'name' in attribute_json: self._server_name = attribute_json['name'] for k in attribute_json: if k in attributes and not k in self.get_functions: self.__setattr__(k, attribute_json[k]) elif k in attributes and k in self.get_functions: geo_server_object = self.get_functions[k](json=attribute_json[k]) self.__setattr__(k, geo_server_object) else: self._new = True def __setattr__(self, name, value): if not name.startswith("_") and not self._new and name in self.__dict__: self._modified = True super(GeoServerObject, self).__setattr__(name, value) def base_url(self): return GEOSERVER['REST_URL'] def url_with_name(self): return "%s/%s" % (self.base_url(), self.name if self._new else self._server_name) def save(self, *args, **kwargs): if 'headers' in kwargs and 'data' in kwargs: headers = kwargs['headers'] data = kwargs['data'] auth = (GEOSERVER['USER'], GEOSERVER['PASSWORD']) response = None status_okay = None if self._new: url = self.base_url() response = requests.post(url=url, auth=auth, headers=headers, data=unicode(data)) if response.status_code == 201: status_okay = True else: url = self.url_with_name() response = requests.put(url=url, auth=auth, headers=headers, data=unicode(data)) if response.status_code == 200: status_okay = True if status_okay: self._new = False self._modified = False self._server_name = self.name return (True, response) else: return (False, response) else: return (False, None) def delete(self, *args, **kwargs): if not self._new: url = self.url_with_name() response = requests.delete(url=url, auth=(GEOSERVER['USER'], GEOSERVER['PASSWORD'])) if response.status_code == 200: self._new = True self._modified = False return (True, response) else: return (False, response) else: return (False, None) class Workspace(GeoServerObject): def __init__(self, *args, **kwargs): #if json is given, ignore all other keywords. 'name' is the only attribute exposed by the REST api, and it can't be modified #for other types, this check would not be included and super__init__ would be called directly. Other keywords would overwrite what is in the json if 'json' in kwargs: super(Workspace, self).__init__(*args, **kwargs) return self._new = True if 'name' in kwargs: self.name = kwargs['name'] def base_url(self): return "%s/workspaces" % (GEOSERVER['REST_URL']) def save(self, *args, **kwargs): if not self._new: return (False, None) #only new Workspaces can be saved headers = {'Content-Type': 'application/json'} data = { 'workspace': { 'name': self.name } } return super(Workspace, self).save(headers=headers, data=data) class CoverageStore(GeoServerObject): url = None type = "WorldImage" enabled = True workspace = None def __init__(self, *args, **kwargs): super(CoverageStore, self).__init__(*args, **kwargs) attributes = ['name', 'url', 'type', 'enabled', 'workspace'] for k in kwargs: if k == 'workspace' and is_string(kwargs[k]): self.workspace = get_workspace({'name':kwargs[k]}) elif k in attributes: self.__setattr__(k, kwargs[k]) def save(self, *args, **kwargs): if self._new or self._modified: attributes_to_save = ['name', 'type', 'url', 'enabled'] xml = "<coverageStore>" for a in attributes_to_save: xml += "<%s>%s</%s>" % (a, self.__getattribute__(a), a) xml += "</coverageStore>" headers = {'Content-Type': "text/xml"} return super(CoverageStore, self).save(headers=headers, data=xml) else: return (False, None) def base_url(self): if type(self.workspace) == Workspace: return "%s/workspaces/%s/coveragestores" % (GEOSERVER['REST_URL'], self.workspace.name) class Coverage(GeoServerObject): name = None srs = None coverage_store = None height = None width = None units = None def __init__(self, *args, **kwargs): super(Coverage,self).__init__(*args, **kwargs) parameters = ['name', 'srs', 'coverage_store', 'units'] for k in kwargs: if k == 'coverage_store' and is_string(kwargs[k]) and 'workspace' in kwargs: workspace = kwargs['workspace'] self.coverage_store = get_coverage_store(workspace = workspace if is_string(workspace) else workspace.name, name = kwargs['coverage_store']) elif k in parameters: self.__setattr__(k, kwargs[k]) if self.coverage_store: world_file = open(self.world_file_path()) image_file_path = self.image_file_path() (self.width, self.height) = Image.open(image_file_path).size def world_file_path(self): if self.coverage_store: path = self.image_file_path() ext = path.split(".")[-1] path = path.replace(ext, "%s%sw" % (ext[0], ext[2])) return path def image_file_path(self): if self.coverage_store: path = self.coverage_store.url.replace("file:","") if path.startswith("/"): return path else: return "%s%s" % (GEOSERVER['DATA_PATH'], self.coverage_store.url.replace("file:","")) def base_url(self): if type(self.coverage_store) == CoverageStore: return "%s/coverages" % (self.coverage_store.url_with_name()) def save(self): if self._new or self._modified: data = self.xml() headers = {'Content-Type': "text/xml"} return super(Coverage, self).save(headers=headers, data=data) else: return (False, None) def delete(self): if not self._new: url = "%s/layers/%s" % (GEOSERVER['REST_URL'], self.name) response = requests.delete(url=url, auth=(GEOSERVER['USER'], GEOSERVER['PASSWORD'])) if response.status_code == 200: return super(Coverage,self).delete() else: return (False, response) else: return (False, None) def xml(self): if type(self.coverage_store) == CoverageStore: world_file = open(self.world_file_path()) lines = world_file.readlines() world_file.close() x_pixel_width = float(lines[0]) y_pixel_width = float(lines[3]) min_x = float(lines[4]) max_y = float(lines[5]) width, height = Image.open(self.image_file_path()).size max_x = min_x + width*x_pixel_width min_y = max_y + height*y_pixel_width (min_lat, min_lng) = srs_to_latlng(min_x, min_y, srs=self.srs, units=self.units) (max_lat, max_lng) = srs_to_latlng(max_x, max_y, srs=self.srs, units=self.units) data = { 'min_x': min_x, 'max_x': max_x, 'min_y': min_y, 'max_y': max_y, 'x_width': x_pixel_width, 'y_width': y_pixel_width, 'min_lat': min_lat, 'max_lat': max_lat, 'min_lng': min_lng, 'max_lng': max_lng, 'height': height, 'width': width, 'coverage_store_name': self.coverage_store.name, 'name': self.name, 'srs': self.srs, } return render_to_string("coverage.xml", data) <file_sep>from django.conf.urls import include, url from django.contrib import admin from django.http import HttpResponse, HttpResponseRedirect from . import views as ogpviews ogp_urlpatterns = [ url(r'^abstract$', ogpviews.abstract_for_layer), url(r'^download$', ogpviews.download_items), url(r'^find$', ogpviews.find_items), url(r'^import$', ogpviews.import_item), url(r'^items$', ogpviews.items_for_layers), url(r'^layer$', ogpviews.link_for_layer), url(r'^map$', ogpviews.map), url(r'^metadata$', ogpviews.metadata_for_layer), url(r'^minimal_import', ogpviews.minimal_ogp_import), url(r'^originators', ogpviews.originators), url(r'^bbox', ogpviews.bbox_for_layers), url(r'items_at_coord', ogpviews.items_at_coord), url(r'import_pdf', ogpviews.import_pdf), ] urlpatterns = [ url(r'ogp/', include(ogp_urlpatterns)), url(r'^gazetteer/', include('gazetteer.urls')), url(r'^$', ogpviews.map), url(r'^external_wfs/(.*)/wfs$', ogpviews.external_wfs_request), url(r'^external_reflect/(.*)/wms/reflect$', ogpviews.external_reflect_request), url(r'^external_solr$', ogpviews.external_solr_request), url(r'^geoserver/', ogpviews.geoserver_request), url(r'^nominatim/', ogpviews.nominatim_request), url(r'^opengeoportal$', lambda r: HttpResponseRedirect("/opengeoportal/")), url(r'^opengeoportal/', ogpviews.ogp_request), url(r'^solr/', ogpviews.solr_request), url(r'^(?P<page>.+)$', 'ogp.views.display_page'), ] <file_sep>from django.contrib.gis.db import models from django.template.loader import render_to_string import datetime import re import requests from django.conf import settings CREATE_SUCCESS = 201 CREATE_FAILED_EXISTS = 409 CREATE_FAILED_TOMBSTONE = 410 PROPERTY_DELETE_SUCCESS = 204 UPDATE_SUCCESS = 204 def import_template_to_fcrepo(url, template, template_data = {}): r = requests.put(url) if (r.status_code == CREATE_FAILED_TOMBSTONE): return r r = requests.patch(url, data=render_to_string(template, template_data)) if (r.status_code != UPDATE_SUCCESS): return r return None def rollback(t_id): response = requests.post("%s/fcr:tx/fcr:rollback" % (t_id)) return response class FCObject(object): _new = None _rdf = None _url = None _use_objects = None _changed_properties = [] _item = None properties = {} types = {} namespaces = {} @classmethod def string_to_object(self, string): if re.match('".*"\^\^<.*>', string): string = re.sub('^"|"$', "", string) string = re.sub('"\^\^', "^^", string) (v, t) = string.split("^^") t = re.sub("^<.*#|>$", "", t) if t == "boolean": return True if t.lower() == "true" else False elif t == "dateTime": return datetime.datetime.strptime(v, "%Y-%m-%dT%H:%M:%S.%fZ") elif t == "string": return v else: return v elif re.match("^<.*>$", string): url = re.sub("^<|>$", "", string) return FCObject(url=url, use_objects = True) elif re.match(".*:.*", string): return string else: return None def save(self): values = {} namespaces = {} for k in self._changed_properties: values[k] = self[k] ns = k.split(":")[0] if not ns in namespaces: namespaces[ns] = self.namespaces[ns] t_id = requests.post("%s/fcr:tx" % (settings.FCREPO_BASE_URL)).headers["location"] save_url = self._url.replace(settings.FCREPO_BASE_URL, t_id) template_data = { "namespaces": namespaces, "values": values } if self._new: error = import_template_to_fcrepo(save_url, "rdf/object.rdf") if error: return error error = import_template_to_fcrepo(save_url, "rdf/update.rdf", template_data) if error: return error commit_response = requests.post("%s/fcr:tx/fcr:commit" % (t_id)) if commit_response.status_code != UPDATE_SUCCESS: return commit_response self._new = False self.__load_rdf__() return None @property def rdf_update_text(self): values = {} namespaces = {} for k in self._changed_properties: values[k] = self[k] ns = k.split(":")[0] if not ns in namespaces: namespaces[ns] = self.namespaces[ns] template_data = { "namespaces": namespaces, "values": values } text = render_to_string("rdf/update.rdf", template_data) return text def __init__(self, *args, **kwargs): if "url" in kwargs: self._new = False url = kwargs["url"] use_objects = True load_rdf = kwargs.get("load_rdf") == True if url.startswith("/"): url = "%s%s" % (settings.FCREPO_BASE_URL, url) self._url = url self._use_objects = use_objects if load_rdf: self.__load_rdf__() else: self._new = True def __contains__(self, key): if not ":" in key: return False (ns, k) = key.split(":", 1) if not ns in self.properties: return False if not k in self.properties[ns]: return False return True def __getitem__(self, key): if not ":" in key: if not key in self.properties: raise KeyError("Invalid Namespace: %s" % (key)) else: return self.properties[key] (ns, k) = key.split(":", 1) if not ns in self.properties: raise KeyError("Invalid Namespace: %s" % (ns)) if not k in self.properties[ns]: raise KeyError("Invalid Property: %s" % (k)) return self.properties[ns][k] def __setitem__(self, key, value): if not ":" in key: raise KeyError("Invalid Format: %s" % (key)) (ns, k) = key.split(":", 1) if not ns in self.properties: self.properties[ns] = {} original_value = self.properties[ns][k]._original_value if k in self.properties[ns] else [] if type(value) != list: value = [value] self.properties[ns][k] = SemanticValue(*value, object=self, namespace=ns, property=k, original_value = original_value) def __getattribute__(self, name): if name in ["properties", "types", "namespaces"] and not self._new and not self._rdf: self.__load_rdf__() return object.__getattribute__(self, name) @property def rdf(self): if not self._new and not self._rdf: self.__load_rdf__() return self._rdf def __load_rdf__(self): self._changed_properties = [] self._rdf = requests.get(self._url).text lines = [x.strip() for x in self._rdf.split("\n")] properties = {} types = {} namespaces = {} for line in lines: line = re.sub("^<.*?>| ;$| .$", "", line).strip() if line == (""): continue if line.startswith("@prefix"): l = re.sub("^@prefix| .$|<|>", "", line) (ns, v) = (x.strip() for x in l.split(": ")) namespaces[ns] = v continue if line.startswith("a "): ts = re.sub("a ", "", line).split(" , ") for t in ts: (ns, v) = t.split(":") if not ns in types: types[ns] = [] types[ns].append(v) elif line.startswith("rdf:type"): line = re.sub("^rdf:type *", "", line) (ns, v) = line.split(":") if not ns in types: types[ns] = [] types[ns].append(v) else: (p,value) = line.split(" ",1) (namespace, key) = p.split(":") value = value.strip() if not namespace in properties: properties[namespace] = {} if key in properties[namespace]: if self._use_objects: properties[namespace][key].append(self.string_to_object(value), initial=True) else: properties[namespace][key].append(value, initial=True) else: kwargs = { "initial": True, "object": self, "namespace": namespace, "property": key } if self._use_objects: properties[namespace][key] = SemanticValue(self.string_to_object(value), **kwargs) else: properties[namespace][key] = SemanticValue(value, **kwargs) self.lines = lines self.types = types self.namespaces = namespaces self.properties = properties def __unicode__(self): return u"<%s>" % (self._url) def __str__(self): return u"<%s>" % (self._url) def __repr__(self): return u"<%s: %s>" % (self.__class__.__name__, self._url) class SemanticValue(object): _namespace = None _original_value = [] _property = None _value = [] _object = None def __init__(self, *args, **kwargs): self._object = kwargs.get("object") self._namespace = kwargs["namespace"] self._property = kwargs["property"] original_value = kwargs.get("original_value", []) initial = kwargs.get("initial") == True self._value = [x for x in args] if initial: self._original_value = [x for x in args] if not initial: self._original_value = original_value self.set_changed_property() def __getitem__(self, index): return self._value[index] def set_changed_property(self): key = "%s:%s" % (self._namespace, self._property) if not key in self._object._changed_properties: self._object._changed_properties.append(key) def append(self, *args, **kwargs): if len(args) == 0: raise ValueError("Must supply at least 1 value.") for value in args: self._value.append(value) initial = kwargs.get("initial") == True if not initial: self.set_changed_property() else: self._original_value = [x for x in self._value] def remove(self, value): try: self._value.remove(value) self.set_changed_property() except: raise ValueError("Semantic value does not contain %s" % (value)) def replace(self, *args): self._value = [x for x in args] self.set_changed_property() @property def rdf_value(self): if self._value and len(self._value) > 0: value = self._value[0] if type(value) == datetime.datetime: value_format = '"%s.0Z"^^<http://www.w3.org/2001/XMLSchema#dateTime>' return " , ".join([value_format % (x.isoformat()) for x in self._value]) elif type(value) == bool: value_format = '"%s"^^<http://www.w3.org/2001/XMLSchema#boolean>' return " , ".join([value_format % ("true" if x == True else "false") for x in self._value]) else: value_format = '%s' if re.match("^<.*?>$", unicode(self._value[0])) else '"%s"' return " , ".join([value_format % (unicode(x)) for x in self._value]) else: return None @property def rdf_original_value(self): if self._original_value and len(self._original_value) > 0: value = self._original_value[0] if type(value) == datetime.datetime: value_format = '"%s.0Z"^^<http://www.w3.org/2001/XMLSchema#dateTime>' return " , ".join([value_format % (x.isoformat()) for x in self._original_value]) elif type(value) == bool: value_format = '"%s"^^<http://www.w3.org/2001/XMLSchema#boolean>' return " , ".join([value_format % ("true" if x == True else "false") for x in self._value]) else: value_format = '%s' if re.match("^<.*?>$", unicode(self._original_value[0])) else '"%s"' return " , ".join([value_format % (unicode(x)) for x in self._original_value]) else: return None def __unicode__(self): return unicode(self._value) def __str__(self): return str(self._value) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, repr(self._value)) <file_sep>from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^external_wfs/(.*)/wfs$', 'ogp.views.external_wfs_request'), url(r'^external_reflect/(.*)/wms/reflect$', 'ogp.views.external_reflect_request'), url(r'^external_solr$', 'ogp.views.external_solr_request'), url(r'^geoserver/', 'ogp.views.geoserver_request'), url(r'^nominatim/', 'ogp.views.nominatim_request'), url(r'^opengeoportal$', lambda r: HttpResponseRedirect("/opengeoportal/")), url(r'^opengeoportal/', 'ogp.views.ogp_request'), url(r'^solr/', 'ogp.views.solr_request'), ) <file_sep>#use this file in place of the one generated by django when creating a project. Place it in the proper directory and do not leave it here. from django.conf.urls import include, url from django.contrib import admin from django.http import HttpResponse, HttpResponseRedirect from ogp import views as ogpviews admin.autodiscover() urlpatterns = [ url(r'^robots\.txt$', lambda r: HttpResponse("User-agent: *\nDisallow: /", mimetype="text/plain")), url(r'^admin/', include(admin.site.urls)), url(r'', include('ogp.urls')), ] <file_sep>To use the PLACE project, create a new Django project and place all these files in the created directory. Replace the generated urls.py file with the one provided and add the settings in the additional_settings.py file to the project's settings.py. The last 3 settings in additional_settings.py are appended to the existing setting. Please note that in order for the Current Location function to work, the website must be served over HTTPS. UNH's PLACE instance is located at [https://place.sr.unh.edu](http://place.sr.unh.edu). Additional information is available at [http://docs.place.sr.unh.edu](http://docs.place.sr.unh.edu) <file_sep>import datetime import time import os from PIL import Image def is_string(value): return type(value) == str or type(value) == unicode def name_from_filepath(filepath): return os.path.splitext(os.path.split(filepath)[1])[0] def ogp_timestamp_for_now(): return datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%dT%H:%M:%SZ') def ogp_timestamp_for_year(year): return "%s-01-01T01:01:01Z" % (year) <file_sep>from django.contrib.gis.db import models from django.contrib.gis.geos import Polygon from django.contrib.postgres.fields import ArrayField, HStoreField from django.db import connection from django.db.models.signals import pre_save, post_save from django.dispatch import receiver from email.mime.text import MIMEText from urllib import urlretrieve from utilities.misc import is_string import json import os import smtplib import zipfile from django.conf import settings class Item(models.Model): Abstract = models.TextField() Access = models.TextField() Area = models.FloatField() Availability = models.TextField(default="online") CenterX = models.FloatField() CenterY = models.FloatField() ContentDate = models.TextField() DataType = models.TextField() FgdcText = models.TextField() GeoReferenced = models.BooleanField() HalfHeight = models.FloatField() HalfWidth = models.FloatField() Institution = models.TextField() LayerDisplayName = models.TextField() LayerId = models.TextField() Location = models.TextField() MaxX = models.FloatField() MinX = models.FloatField() MaxY = models.FloatField() MinY = models.FloatField() Name = models.TextField(unique=True) Originator = models.TextField() PlaceKeywords = models.TextField() Publisher = models.TextField() ThemeKeywords = models.TextField() WorkspaceName = models.TextField() timestamp = models.TextField() collection = models.ForeignKey("ItemCollection", blank=True, null=True) directory_path = models.TextField() def __unicode__(self): return self.Name def date_object(self): ogp_time_format = '%Y-%m-%dT%H:%M:%SZ' @property def fedora_url(self): return "%s/place/%s/%s" % (settings.FCREPO_BASE_URL, self.collection.fedora_name, self.LayerId) class BoundedItem(Item): bounds = models.PolygonField() srs = models.IntegerField(default=4326) objects = models.GeoManager() def json_from_db(self, fields): if type(fields) != list and type(fields) != tuple: if is_string(fields): fields = fields.split(",") else: return None s = "SELECT row_to_json(t) from (SELECT" for f in fields: s = "%s \"%s\"," % (s, f) s = "%s from ogp_item WHERE \"LayerId\" = %%s) t;" % (s[:-1]) cursor = connection.cursor() cursor.execute(s, [self.LayerId]) return cursor.fetchone()[0] def as_dictionary(self, fields, include_collection = False): if type(fields) != list and type(fields) != tuple: if is_string(fields): fields = fields.split(",") else: return None d = {} for field in fields: if hasattr(self, field): d[field] = self.__getattribute__(field) if (include_collection): d["collection"] = self.collection.name return d def update_from_dictionary(self, dictionary): for k in dictionary.keys(): if hasattr(self, k): self.__setattr__(k, dictionary[k]) @classmethod def from_json(object_type, dictionary): b = None if "Name" in dictionary and BoundedItem.objects.filter(Name=dictionary["Name"]).count() > 0: b = BoundedItem.objects.get(Name=dictionary["Name"]) else: b = BoundedItem() for k in dictionary.keys(): if hasattr(b, k): b.__setattr__(k, dictionary[k]) return b @receiver(pre_save, sender=BoundedItem) def add_bounds_to_item(sender, **kwargs): i = kwargs['instance'] minX = i.MinX maxX = i.MaxX minY = i.MinY maxY = i.MaxY i.bounds = Polygon(((minX, minY), (minX, maxY), (maxX, maxY), (maxX, minY), (minX, minY))) class ItemCollection(models.Model): full_name = models.TextField() short_name = models.TextField() metadata_available = models.BooleanField(default=False) external = models.BooleanField(blank=True, default=False) enabled = models.BooleanField(blank=True, default=False) @property def name(self): return self.short_name or self.full_name @property def fedora_name(self): return self.short_name.replace(" ", "_").lower() @property def fedora_url(self): return "%s/place/%s" % (settings.FCREPO_BASE_URL, self.fedora_name) def __unicode__(self): return self.name @receiver(pre_save, sender=ItemCollection) def add_short_name(sender, **kwargs): i = kwargs['instance'] if i.short_name == '': i.short_name = i.full_name class DownloadRequest(models.Model): email_address = models.EmailField() items = models.ManyToManyField(BoundedItem, blank=True) #stored as array of string JSON, only used once so that's okay in this case, change if upgraded to Postgres 9.4+ #FIXME: remove, no longer used external_items = ArrayField(models.TextField(), null=True, blank=True) date = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=False) image_width = models.IntegerField(default=2000) wfs_format = models.TextField(null=True, blank=True) def create_zip_file_and_notify(self, **kwargs): i = self if not i.active: return zip_file_path = "/media/zip/place_data_for_%s_%d.zip" % (i.email_address, i.id) zip_file = zipfile.ZipFile("%s/%s" % (settings.BASE_DIR, zip_file_path), "w") for item in i.items.all(): location = "{%s}" if not item.Location[0] == '{' else item.Location location = json.loads(location) if item.DataType == "Book": pdf_file_path = "%s/media/pdf/%s.pdf" % (settings.BASE_DIR, item.Name) zip_file.write(pdf_file_path, "place_data/%s.pdf" % (item.LayerId)) zip_file.writestr("place_data/%s.xml" % (item.LayerId), item.FgdcText.encode('utf-8')) elif "wfs" in location: wfs_path = location["wfs"][0] data_file_path = "%s/temp/%s_%d.json" % (settings.BASE_DIR, item.LayerId, i.id) data_url = "http://%s/external_wfs/%s?request=GetFeature&typeName=%s:%s&outputFormat=%s&srsName=EPSG:4326" % (settings.ALLOWED_HOSTS[0], wfs_path.replace("http://",""),item.WorkspaceName,item.Name, i.wfs_format) urlretrieve(data_url, data_file_path) extension = None if i.wfs_format == "shape-zip": extension = "zip" elif i.wfs_format == "GML2" or i.wfs_format == "GML3": extension = "gml" elif i.wfs_format == "KML": extension = "kml" else: extension = "json" zip_file.write(data_file_path, "place_data/%s.%s" % (item.LayerId, extension)) os.remove(data_file_path) zip_file.writestr("place_data/%s.xml" % (item.LayerId), item.FgdcText.encode('utf-8')) elif "wms" in location: wms_path = location["wms"][0] image_file_path = "%s/temp/%s_%d.tiff" % (settings.BASE_DIR, item.Name, i.id) image_url = "%s/reflect?format=image/geotiff&transparent=true&width=%d&layers=%s" % (wms_path, i.image_width, item.Name) urlretrieve(image_url, image_file_path) zip_file.write(image_file_path, "place_data/%s.tif" % (item.LayerId)) os.remove(image_file_path) zip_file.writestr("place_data/%s.xml" % (item.LayerId), item.FgdcText.encode('utf-8')) zip_file.close() # send mail with zip link mail_server = smtplib.SMTP('cisunix.unh.edu') message = MIMEText("Your download request is located at http://%s%s. It will be deleted after 24 hours." % (settings.ALLOWED_HOSTS[0], zip_file_path)) message["Subject"] = "PLACE Data ready for download" message["To"] = i.email_address message["From"] = "<EMAIL>" mail_server.sendmail(message["From"], [i.email_address], message.as_string()) i.active = False i.save() class Category(models.Model): name = models.TextField() keyword = models.TextField() # items = models.ManyToManyField(BoundedItem, blank=True) def __unicode__(self): return "%s (%s)" % (self.name, self.keyword) @property def items(self): return BoundedItem.objects.filter(ThemeKeywords__icontains=self.keyword) <file_sep>from django.contrib.gis.geos import WKTReader, Polygon from django.db import connections from django.db.models import Q from django.http import HttpResponse from django.shortcuts import render from gazetteer.models import GeneratedGeometry, Municipality, GNIS from nominatim.models import CountryName, USState, USStateCounty from ogp.views import bad_request, completed_request from utilities.conversion import srs_to_latlng import shapefile # Create your views here. def bbox_polygon(request): gazetteer_id = request.GET.get("id") if not gazetteer_id: return bad_request(["MISSING: id"]) with connections["default"].cursor() as cursor: cursor.execute("SELECT ST_AsGeoJSON(Box2d(gazetteer_generatedgeometry.geometry)) from gazetteer_generatedgeometry where gazetteer_id=%s", [gazetteer_id]) geojson = cursor.fetchone()[0] return HttpResponse(geojson, content_type="application/json") def gazetteer_countries(request): language_code = request.GET.get("language", "en") countries = [{"name": c.name_for_language(language_code), "id": c.country_code} for c in CountryName.objects.all()] countries.sort(key=lambda c: c["name"]) return completed_request(countries) def country_polygon(request): country = request.GET.get("id") if not country: return bad_request(["MISSING: id"]) country = country.lower() return render(request, "polygons/country/%s.json" % (country), content_type="application/json") def gazetteer_states(request): states = [{"name": s.state, "id": s.state_fips, "next_entries": s.counties.count()} for s in USState.objects.all().distinct("state").order_by("state")] return completed_request(states) def state_polygon(request): state_fips = request.GET.get("id") if not state_fips: return bad_request(["MISSING: id"]) return render(request, "polygons/state/%s.json" % (state_fips), content_type="application/json") def counties_for_state(request): state_fips = request.GET.get("id") if not state_fips: return bad_request(["MISSING: id"]) counties = [{"name": c.county, "id": c.fips, "next_entries": c.municipalities.count()} for c in USStateCounty.objects.filter(state_fips=state_fips).order_by("county").distinct("county")] return completed_request(counties) def county_polygon(request): fips = request.GET.get("id") if not fips: return bad_request(["MISSING: id"]) state_fips = fips[:2] county_fips = fips[2:] return render(request, "polygons/county/%s/%s.json" % (state_fips, county_fips), content_type="application/json") def municipalities_for_county(request): fips = request.GET.get("id") if not fips: return bad_request(["MISSING: id"]) municipalities = [{ "name": m.name, "id": "%s%s-%s" % (m.state_fips, m.county_fips, m.identifier), "next_entries": 0, } for m in Municipality.objects.filter(state_fips = fips[:2], county_fips = fips[2:]).order_by("name")] return completed_request(municipalities) def municipality_polygon(request): m_id = request.GET.get("id") if not m_id: return bad_request(["MISSING: id"]) (fips, identifier) = m_id.split("-") return render(request, "polygons/municipality/%s/%s/%s.json" % (fips[:2], fips[2:], identifier), content_type="application/json") def add_gnis(file_name): print file_name with open(file_name) as f: lines = [l.strip().split("|") for l in f.readlines()] attributes = lines[0] lines = lines[1:] num_attributes = len(attributes) number_of_lines = len(lines) current_line_number = 0 skipped = 0 print "%d/%d" % (current_line_number, number_of_lines) for line in lines: current_line_number += 1 if current_line_number % 1000 == 0: print "%d/%d" % (current_line_number, number_of_lines) if GNIS.objects.filter(feature_id=line[0]).count(): skipped += 1 continue g = GNIS() for i in range(0,num_attributes): v = line[i] or None g.__dict__[attributes[i]] = v g.save() return skipped #for testing def municipalities_in_county(fips): county = USStateCounty.objects.filter(fips=fips)[0].county gnis = GNIS.objects.filter(feature_class="Civil", state_numeric=fips[:2], county_numeric=fips[2:]).exclude(feature_name__startswith="State of").exclude(feature_name=county) ewkt = None results = [] rows = None with connections["nominatim"].cursor() as c: c.execute("select ST_AsEWKT(ST_Union(us_statecounty.the_geom)) from us_statecounty where fips=%s", [fips]) ewkt = c.fetchone()[0] c.execute("select placex.name->'name', placex.place_id, placex.indexed_date, ST_Area(placex.geometry) from placex where class='boundary' and type='administrative' and ST_Intersects(placex.geometry, %s) and ST_Area(ST_Difference(placex.geometry, %s)) < 0.5 * ST_Area(placex.geometry) and ST_Area(placex.geometry) < 0.99*ST_Area(%s) order by placex.name->'name', ST_Area(placex.geometry) desc", [ewkt,ewkt,ewkt]) rows = c.fetchall() last_place_name = None for row in rows: name = row[0] gnis_name = " of %s" % (name) if name == last_place_name: print "Duplicate (%s): %s" % (name, row) continue if ("'" in name): name_count = gnis.filter(feature_name__endswith=gnis_name).count() if name_count > 1: print "Too many (%s): %s" % (name, row) continue elif name_count == 0: without_apos_count = gnis.filter(feature_name__endswith=gnis_name.replace("'", "")).count() if without_apos_count == 0: print "Can't find (%s): %s" % (gnis_name.replace("'",""), row) continue elif without_apos_count == 1: gnis_name = name.replace("'","") else: #with_apos_count > 1 print "Too many (%s) %d: %s" % (gnis_name.replace("'", ""), without_apos_count, row) count = gnis.filter(feature_name__endswith=gnis_name).count() if count == 0: print "Can't find (%s): %s" % (gnis_name, row) elif count == 1: results.append(row) else: # count > 1 print "Too many (%s) %d: %s" % (gnis_name, count, row) last_place_name = name return results def add_vermont(): vt_names = [] vt_dict = {} with open("/tmp/vt_names") as f: vt_names = [l.strip() for l in f.readlines()] for name in vt_names: vt_name = name gnis_name = None municipality_name = None if " - " in name: (vt_name, gnis_name, municipality_name) = name.split(" - ") if gnis_name: gnis = GNIS.objects.get(feature_class="Civil", state_alpha="VT", feature_name=gnis_name) else: gnis = GNIS.objects.filter(feature_class="Civil", state_alpha="VT", feature_name__endswith="of %s" % (vt_name)).exclude(feature_name__startswith="Village of")[0] vt_dict[vt_name] = { "vt_name": vt_name, "gnis_name": gnis_name or vt_name, "municipality_name": municipality_name or vt_name, "gnis": gnis } wktr = WKTReader() sf = shapefile.Reader("/tmp/Boundary_BNDHASH_region_towns.shp") for i in range(0,255): shape = sf.shape(i) record = sf.record(i) wkt = "POLYGON ((" for p in shape.points: p = srs_to_latlng(p[0],p[1],2852) wkt += "%f %f," % (p[1], p[0]) wkt = wkt[:-1] wkt += "))" try: polygon = wktr.read(wkt) except: p = srs_to_latlng(shape.points[0][0], shape.points[0][1], 2852) wkt = wkt[:-2] wkt += ",%f %f))" % (p[1], p[0]) polygon = wktr.read(wkt) dict_entry = vt_dict[record[6]] gnis = dict_entry["gnis"] m = Municipality() m.name = dict_entry["municipality_name"] m.geometry = polygon m.state_fips = gnis.state_numeric m.county_fips = gnis.county_numeric m.gnis = gnis.feature_id m.save() print "Saved %s" % (m) def add_maine_data(): sf = shapefile.Reader("/net/home/cv/iatkin/me/metwp24p.shp") wktr = WKTReader() for me_index in range(0,8422): m = MaineData() m.name = sf.record(me_index)[0] m.county = sf.record(me_index)[4] m.data_type = sf.record(me_index)[12] args = [] shape = sf.shape(me_index) for point_index in range(0, len(shape.points)): if point_index in shape.parts: args.append([]) point = shape.points[point_index] point = srs_to_latlng(point[0], point[1], 26919) args[-1].append([point[1], point[0]]) try: polygon = Polygon(*args) except: print me_index continue m.geometry = polygon m.save() if me_index % 1000 == 0: print "%04d/8422" % (me_index) def import_maine_data(): base_query = Q(feature_class="Civil") & Q(state_alpha="ME") maine_municipalities = MaineData.objects.filter(skip=False).distinct("name").order_by("name") for municipality in maine_municipalities: name = municipality.name name_query = None township_query = Q(feature_name=name.replace("Twp", "Township")) | Q(feature_name="Township of %s" % (name.replace(" Twp",""))) plantation_query = Q(feature_name=name.replace("Plt", "Plantation")) | Q(feature_name="Plantation of %s" % (name.replace(" Plt",""))) if " Twp" in name: name_query = Q(feature_name=name.replace("Twp", "Township")) | Q(feature_name="Township of %s" % (name.replace(" Twp",""))) elif name.endswith(" Plt"): name_query = Q(feature_name=name.replace("Plt", "Plantation")) | Q(feature_name="Plantation of %s" % (name.replace(" Plt",""))) else: name_query = Q(feature_name=name) | Q(feature_name ="Town of %s" % (name)) | Q(feature_name ="City of %s" % (name)) gnis = GNIS.objects.filter(base_query, name_query) if gnis.count() == 0: gnis = GNIS.objects.filter(state_alpha="ME", feature_class="Island", feature_name=name) if gnis.count() > 0: gnis = gnis[0] else: gnis = None args = {"name": None, "geometry": None, "state_fips": None, "county_fips": None, "gnis": None} if gnis: args["name"] = name args["state_fips"] = gnis.state_numeric args["county_fips"] = gnis.county_numeric args["gnis"] = gnis.feature_id else: args["name"] = name args["state_fips"] = "23" try: args["county_fips"] = "%03d" % (int(municipality.county)) except: print municipality continue with connections["default"].cursor() as c: c.execute("select ST_AsEWKT(ST_Collect(geometry)) from gazetteer_mainedata where name = %s", [name]) args["geometry"] = c.fetchone()[0] m = Municipality(**args) m.save() def shape_to_geos(shape, srs, units="m"): args = [] for point_index in range(0, len(shape.points)): if point_index in shape.parts: args.append([]) point = shape.points[point_index] point = srs_to_latlng(point[0], point[1], srs, units) args[-1].append([point[1], point[0]]) polygon = Polygon(*args) return polygon <file_sep>// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys (CC-BY-SA 2.5) if (!Object.keys) { Object.keys = (function() { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'), dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ], dontEnumsLength = dontEnums.length; return function(obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); } //Replaces objects keys in place Object.replace = function(dictionary, newKVs) { for (var k in dictionary) { delete dictionary[k] } for (var newK in newKVs) { dictionary[newK] = newKVs[newK] } } //returns a copy of the string with the first letter capitalized String.prototype.capitalize = function() { var firstLetter = this[0].toUpperCase() var restOfString = this.substring(1) return firstLetter + restOfString } //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith if (!String.prototype.endsWith) { String.prototype.endsWith = function(searchString, position) { var subjectString = this.toString(); if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) { position = subjectString.length; } position -= searchString.length; var lastIndex = subjectString.indexOf(searchString, position); return lastIndex !== -1 && lastIndex === position; }; } //returns pixels per point if (!window.devicePixelRatio) { if (window.screen.deviceXDPI && window.screen.logicalXDPI) { window.devicePixelRatio = window.screen.deviceXDPI / window.screen.logicalXDPI } else { window.devicePixelRatio = 1 } } <file_sep>from django.core.management.base import BaseCommand, CommandError from glob import glob from lockfile import LockFile from ogp.models import DownloadRequest import datetime import os #from place.settings import BASE_DIR from django.conf import settings BASE_DIR = settings.BASE_DIR class Command(BaseCommand): help = 'Process current download requests' def add_arguments(self, parser): parser.add_argument("task", type=str) def handle(self, *args, **options): task = options["task"] if not task in ("count", "delete", "process"): raise CommandError("task must be either 'count', 'delete' or 'process'") if task == "count": count = DownloadRequest.objects.filter(active=True).count() self.stdout.write("%d requests pending" % (count)) if task == "delete": lock_file_path = "/tmp/place.downloads.delete" lock = LockFile(lock_file_path) if lock.is_locked(): return lock.acquire() files = glob("%s/media/zip/*.zip" % BASE_DIR) for file_name in files: date = datetime.datetime.fromtimestamp(os.path.getctime(file_name)) days = (datetime.datetime.now() - date).days if days > 0: os.remove(file_name) lock.release() if task == "process": lock_file_path = "/tmp/place.downloads.process" lock = LockFile(lock_file_path) if lock.is_locked(): return lock.acquire() count = DownloadRequest.objects.filter(active=True).count() for dr in DownloadRequest.objects.filter(active=True): dr.create_zip_file_and_notify() lock.release() if count > 0: self.stdout.write("%d requests processed" % (count)) <file_sep>from django.core.management.base import BaseCommand, CommandError from ogp.models import BoundedItem, ItemCollection import requests #from place.settings import EXT_SOLR_REPOS from django.conf import settings EXT_SOLR_REPOS = settings.EXT_SOLR_REPOS class Command(BaseCommand): help = 'Update the database using the dictionary EXT_SOLR_REPOS from the settings file.' def add_arguments(self, parser): parser.add_argument("task", type=str) parser.add_argument("--repo", type=str) def handle(self, *args, **options): task = options["task"] repo = options["repo"] if not task in ("full", "incremental"): raise CommandError("task must be either 'full' or 'incremental'") if repo: repos = {repo: EXT_SOLR_REPOS[repo]} else: repos = EXT_SOLR_REPOS for k in repos: url = "http://%s/solr/select" % (repos[k]["url"]) institutions = repos[k]["institutions"] if len(institutions) > 0: institutions_string = "Institution:(%s" % (institutions[0]) fields = "Abstract,Access,Area,CenterX,CenterY,ContentDate,DataType,FgdcText,GeoReferenced,HalfHeight,HalfWidth,Institution,LayerDisplayName,LayerId,Location,MaxX,MinX,MaxY,MinY,Name,Originator,PlaceKeywords,Publisher,ThemeKeywords,WorkspaceName,timestamp" for i in range(1,len(institutions)): institution = institutions[i] institutions_string += "+OR+%s" % (institution) institutions_string += ")" url += "?q=Access:Public" if "datatypes" in repos[k]: url += "+AND+DataType:(%s)" % ("+OR+").join(repos[k]["datatypes"]) else: url += "+AND+DataType:(Raster+OR+Scanned+Map+OR+Paper+Map+OR+Point+OR+Line+OR+Polygon)" url += "+AND+%s" % (institutions_string) if task == "full": self.stdout.write("PLACE External Solr Full Update") elif task == "incremental": self.stdout.write("PLACE External Solr Incremental Update") url += "+AND+timestamp:[NOW/DAY-7DAYS+TO+NOW]" num_found = requests.get("%s&rows=0&wt=json" % (url)).json()["response"]["numFound"] if num_found > 0: self.stdout.write("Loading %d items" % (num_found)) url += "&fl=%s&rows=%d&wt=json" % (fields, num_found) new_items = requests.get(url).json()["response"]["docs"] for new_item in new_items: b = BoundedItem.from_json(new_item) if not b.collection: b.collection = ItemCollection.objects.get(short_name = new_item["Institution"]) try: b.save() except: self.stdout.write("Invalid: %s" % (b.LayerDisplayName)) if task == "incremental": self.stdout.write(b.LayerDisplayName) if task == "full": self.stdout.write("%d items added" % (num_found)) else: self.stdout.write("%s: No new items found." % (k)) <file_sep>from django.contrib import admin from ogp.models import BoundedItem, Category, DownloadRequest, ItemCollection # Register your models here. admin.site.register(BoundedItem) admin.site.register(Category) admin.site.register(ItemCollection) admin.site.register(DownloadRequest) <file_sep>// depends on jQuery for creating shallow copies of javascript objects - $.extend({}, object). Also for various utility functions like $.grep() // Author: <NAME>, XEETech.com // License Note; // Implied public domain // http://freshplayer.blogspot.com/2014/04/intersection-of-two-2d-polygons-in.html?showComment=1441533790958#c3501058308871877758 /** Returns a new polygon (array of points) which represents an intersection of the two polygons that were passed as arguments. If intersection of two polygons results in multiple polygons, function only returns one of them. Supports concave polygons but does not support complex polygons (http://upload.wikimedia.org/wikipedia/commons/3/34/Complex_polygon.png). This implementation is similar to the one described by Margalit & Knott: "An algorithm for computing the union, intersection or difference of two polygons" (http://gvu.gatech.edu/people/official/jarek/graphics/papers/04PolygonBooleansMargalit.pdf) Its complexity is O(n^2). 4*n1*n2, to be more precise, where n1 is number of points in the first polygon, and n2 number of points in second polygon. With a few tweaks, the algorithm could be optimized, but with the same general idea in place, it is impossible to get rid of n^2 complexity. */ function intersectionPolygons(polygon1, polygon2) { polygon1 = clockwisePolygon(polygon1); polygon2 = clockwisePolygon(polygon2); var polygon1ExpandedDict = {}; var polygon2ExpandedDict = {}; for (var i = 0; i < polygon1.length; i++) { var polygon1Line = [polygon1[i], polygon1[(i + 1) % polygon1.length]]; polygon1ExpandedDict[i] = [cloneObject(polygon1[i])]; for (var j = 0; j < polygon2.length; j++) { if (i == 0) polygon2ExpandedDict[j] = [cloneObject(polygon2[j])]; var polygon2Line = [polygon2[j], polygon2[(j + 1) % polygon2.length]]; var intersectionResult = intersectionLines(polygon1Line, polygon2Line); if (intersectionResult.onLine1 && intersectionResult.onLine2) { if (pointsEqual(intersectionResult, polygon1[i])) { polygon1ExpandedDict[i][0].isCrossPoint = true; polygon1ExpandedDict[i][0].isOriginalPoint = true; polygon1ExpandedDict[i][0].crossingLine = polygon2Line; } else if (pointsEqual(intersectionResult, polygon1[(i + 1) % polygon1.length])) { } else { var newPolygon1Point = cloneObject(intersectionResult); newPolygon1Point.isCrossPoint = true; newPolygon1Point.crossingLine = polygon2Line; newPolygon1Point.distanceFromPreviousPoint = pointsDistance(polygon1[i], newPolygon1Point); var lastIndex = polygon1ExpandedDict[i].length - 1; while (polygon1ExpandedDict[i][lastIndex].distanceFromPreviousPoint && polygon1ExpandedDict[i][lastIndex].distanceFromPreviousPoint > newPolygon1Point.distanceFromPreviousPoint) { lastIndex--; // maybe current polygon1Line will be intersected in many places, // when intersection points are added to polygon1Expanded, they need to be properly sorted } if (!pointsEqual(polygon1ExpandedDict[i][lastIndex], newPolygon1Point) && !pointsEqual(polygon1ExpandedDict[i][lastIndex + 1], newPolygon1Point)) { polygon1ExpandedDict[i].splice(lastIndex + 1, 0, newPolygon1Point); } } if (pointsEqual(intersectionResult, polygon2[j])) { polygon2ExpandedDict[j][0].isCrossPoint = true; polygon2ExpandedDict[j][0].isOriginalPoint = true; polygon2ExpandedDict[j][0].crossingLine = polygon1Line; } else if (pointsEqual(intersectionResult, polygon2[(j + 1) % polygon2.length])) { } else { var newPolygon2Point = cloneObject(intersectionResult); newPolygon2Point.isCrossPoint = true; newPolygon2Point.crossingLine = polygon1Line; newPolygon2Point.distanceFromPreviousPoint = pointsDistance(polygon2[j], newPolygon2Point); lastIndex = polygon2ExpandedDict[j].length - 1; while (polygon2ExpandedDict[j][lastIndex].distanceFromPreviousPoint && polygon2ExpandedDict[j][lastIndex].distanceFromPreviousPoint > newPolygon2Point.distanceFromPreviousPoint) { lastIndex--; } if (!pointsEqual(polygon2ExpandedDict[j][lastIndex], newPolygon2Point) && !pointsEqual(polygon2ExpandedDict[j][lastIndex+1], newPolygon2Point)) { polygon2ExpandedDict[j].splice(lastIndex + 1, 0, newPolygon2Point); } } } } } var polygon1Expanded = []; for (i = 0; i < polygon1.length; i++) { for (j = 0; j < polygon1ExpandedDict[i].length; j++) { var polygon1ExpandedPoint = polygon1ExpandedDict[i][j]; polygon1Expanded.push(polygon1ExpandedPoint); } } var polygon2Expanded = []; var startingPoint = null; var currentPolygon = null; var otherPolygon = null; var currentIndex = null; var currentPoint = null; var polygon2ExpandedIndex = null; var index = 0; for (i = 0; i < polygon2.length; i++) { for (j = 0; j < polygon2ExpandedDict[i].length; j++) { var polygon2ExpandedPoint = polygon2ExpandedDict[i][j]; polygon2Expanded.push(polygon2ExpandedPoint); if (startingPoint == null && polygon2ExpandedPoint.isCrossPoint) { startingPoint = polygon2ExpandedPoint; polygon2ExpandedIndex = index; } index++; } } if (startingPoint == null) { // either polygons are separated, or one contains another <==> polygons' lines never intersect one another var isPolygon2WithinPolygon1 = isPointInsidePolygon(polygon2[0], polygon1); if (isPolygon2WithinPolygon1) { startingPoint = polygon2Expanded[0]; currentPolygon = polygon2Expanded; otherPolygon = polygon1Expanded; currentIndex = 0; } else { var isPolygon1WithinPolygon2 = isPointInsidePolygon(polygon1[0], polygon2); if (isPolygon1WithinPolygon2) { startingPoint = polygon1Expanded[0]; currentPolygon = polygon1Expanded; otherPolygon = polygon2Expanded; currentIndex = 0; } else { // these two polygons are completely separated return []; } } } else { currentPolygon = polygon2Expanded; otherPolygon = polygon1Expanded; currentIndex = polygon2ExpandedIndex; } var intersectingPolygon = [startingPoint]; var switchPolygons = false; if (startingPoint.isCrossPoint) { var pointJustAfterStartingPoint = justAfterPointOfACrossPoint(currentIndex, currentPolygon); if (isPointInsidePolygon(pointJustAfterStartingPoint, otherPolygon)) { switchPolygons = false; } else { switchPolygons = true; } } else { switchPolygons = false; } if (switchPolygons) { var temp = currentPolygon; currentPolygon = otherPolygon; otherPolygon = temp; currentIndex = indexElementMatchingFunction(currentPolygon, function (point) { return pointsEqual(startingPoint, point); }); } currentPoint = currentPolygon[(currentIndex + 1) % currentPolygon.length];; currentIndex = (currentIndex + 1) % currentPolygon.length; while (!pointsEqual(currentPoint, startingPoint)) { intersectingPolygon.push(currentPoint); if (currentPoint.isCrossPoint) { if (currentPoint.crossingLine && currentPoint.isOriginalPoint) { var pointJustBeforeCurrent = justBeforePointOfACrossPoint(currentIndex, currentPolygon); var pointJustAfterCurrent = justAfterPointOfACrossPoint(currentIndex, currentPolygon); var isBeforeLeft = isPointLeftOfLine(pointJustBeforeCurrent, currentPoint.crossingLine); var isAfterLeft = isPointLeftOfLine(pointJustAfterCurrent, currentPoint.crossingLine); if (isBeforeLeft == isAfterLeft) { // do not switch to different polygon } else { var temp = currentPolygon; currentPolygon = otherPolygon; otherPolygon = temp; } } else { var temp = currentPolygon; currentPolygon = otherPolygon; otherPolygon = temp; } currentIndex = indexElementMatchingFunction(currentPolygon, function(point) { return pointsEqual(currentPoint, point); }); } currentIndex = (currentIndex + 1) % currentPolygon.length; currentPoint = currentPolygon[currentIndex]; } return intersectingPolygon; } function justBeforePointOfACrossPoint(pointIndex, polygon) { var point = polygon[pointIndex]; var previousIndex = (polygon.length + pointIndex - 1) % polygon.length; var previousPoint = polygon[previousIndex]; var pointJustBeforeCurrent = { x: (point.x + previousPoint.x) / 2, y: (point.y + previousPoint.y) / 2 }; return pointJustBeforeCurrent; } function justAfterPointOfACrossPoint(pointIndex, polygon) { var point = polygon[pointIndex]; var nextIndex = (pointIndex + 1) % polygon.length; var nextPoint = polygon[nextIndex]; var pointJustAfterCurrent = { x: (point.x + nextPoint.x) / 2, y: (point.y + nextPoint.y) / 2 }; return pointJustAfterCurrent; } /** If the polygon that is passed as argument is clockwise, that polygon is returned. If it is counter-clockwise, a polygon with same points but in reversed order is returned. Complexity O(n) */ function clockwisePolygon(polygon) { var sum = 0; var filterDuplicates = []; var reversedPolygon = []; for (var i = 0; i < polygon.length; i++) { var currentPoint = polygon[i]; var nextPoint = polygon[(i + 1) % polygon.length]; if (!pointsEqual(currentPoint, nextPoint)) { filterDuplicates.push(currentPoint); reversedPolygon.splice(0, 0, currentPoint); } sum += (nextPoint.x - currentPoint.x) * (nextPoint.y + currentPoint.y); } if (sum > 0) { // polygon is clockwise return polygon; } else { // polygon is counter-clockwise return reversedPolygon; } } /** Works for any polygon, not just convex polygons. @param bordersCountAsOutside - if point is exactly on the polygon's border, this parameter determines whether the point will be classified as 'inside' or 'outside' */ function isPointInsidePolygon(point, polygon, onBorderCountsAsOutside) { // point is any javascript object that contains both x & y numeric parameters // polygon is array of points, properly sorted to form a polygon var pointVerticalLine = [point, { x: point.x, y: point.y + 1 }]; var higherIntersectionsCount = 0; var lowerIntersectionCount = 0; for (var i = 0; i < polygon.length; i++) { var polygonLine = [polygon[i], polygon[(i+1) % polygon.length]]; var result = intersectionLines(pointVerticalLine, polygonLine); if (result.onLine2) { if (pointsEqual(point, result)) { return !onBorderCountsAsOutside; } if (result.y > point.y) { higherIntersectionsCount++; } else { lowerIntersectionCount++; } } } if (higherIntersectionsCount % 2 != 0 && lowerIntersectionCount % 2 != 0) { return true; } else { return false; } } function intersectionLines(line1, line2, excludeStartingPoints, includeEndingPoints) { return checkLineIntersection(line1[0].x, line1[0].y, line1[1].x, line1[1].y, line2[0].x, line2[0].y, line2[1].x, line2[1].y, excludeStartingPoints, includeEndingPoints); } /** Credits to: http://jsfiddle.net/justin_c_rounds/Gd2S2/light/ example: returns { x : 12, y : 16, onLine1 : false, onLine2 : true } */ function checkLineIntersection(line1StartX, line1StartY, line1EndX, line1EndY, line2StartX, line2StartY, line2EndX, line2EndY, excludeStartingPoints, includeEndingPoints) { // if the lines intersect, the result contains the x and y of the intersection (treating the lines as infinite) and booleans for whether line segment 1 or line segment 2 contain the point var denominator, a, b, numerator1, numerator2, result = { x: null, y: null, onLine1: false, onLine2: false }; denominator = ((line2EndY - line2StartY) * (line1EndX - line1StartX)) - ((line2EndX - line2StartX) * (line1EndY - line1StartY)); if (denominator == 0) { return result; } a = line1StartY - line2StartY; b = line1StartX - line2StartX; numerator1 = ((line2EndX - line2StartX) * a) - ((line2EndY - line2StartY) * b); numerator2 = ((line1EndX - line1StartX) * a) - ((line1EndY - line1StartY) * b); a = numerator1 / denominator; b = numerator2 / denominator; // if we cast these lines infinitely in both directions, they intersect here: result.x = line1StartX + (a * (line1EndX - line1StartX)); result.y = line1StartY + (a * (line1EndY - line1StartY)); /* // it is worth noting that this should be the same as: x = line2StartX + (b * (line2EndX - line2StartX)); y = line2StartX + (b * (line2EndY - line2StartY)); */ // if line1 is a segment and line2 is infinite, they intersect if: if (!excludeStartingPoints && numbersEqual(a,0)) { result.onLine1 = true; } if (includeEndingPoints && numbersEqual(a, 1)) { result.onLine1 = true; } if (firstGreaterThanSecond(a,0) && firstLessThanSecond(a,1)) { result.onLine1 = true; } // if line2 is a segment and line1 is infinite, they intersect if: if (!excludeStartingPoints && numbersEqual(b, 0)) { result.onLine2 = true; } if (includeEndingPoints && numbersEqual(b, 1)) { result.onLine2 = true; } if (firstGreaterThanSecond(b, 0) && firstLessThanSecond(b, 1)) { result.onLine2 = true; } // if line1 and line2 are segments, they intersect if both of the above are true return result; }; function isPointLeftOfLine(point, line) { var linePoint1 = line[0]; var linePoint2 = line[1]; return ((linePoint2.x - linePoint1.x)*(point.y - linePoint1.y) - (linePoint2.y - linePoint1.y)*(point.x - linePoint1.x)) > 0; } function pointsEqual(point1, point2) { if (!point1) return false; if (!point2) return false; // return point1.x == point2.x && point1.y == point2.y; return numbersEqual(pointsDistance(point1, point2), 0); } function numbersEqual(num1, num2) { return Math.abs(num2 - num1) < 1e-14; } function firstGreaterThanSecond(a,b) { return !numbersEqual(a, b) && a > b; } function firstLessThanSecond(a, b) { return !numbersEqual(a, b) && a < b; } function pointsDistance(point1, point2) { return Math.pow(Math.pow(point2.x - point1.x, 2) + Math.pow(point2.y - point1.y, 2), 0.5); } function cloneObject(object) { return $.extend({}, object); } function filterFirstMatchingElement(array, fn) { var element = $.grep(array, fn)[0]; return element; } function indexElementMatchingFunction(array, fn) { var element = filterFirstMatchingElement(array, fn); return array.indexOf(element); } <file_sep>from django.contrib.gis.db import models from django.contrib.gis.geos import WKTReader from django.contrib.postgres.fields import HStoreField from django.db import connections from gazetteer.models import Municipality import subprocess class USState(models.Model): gid = models.IntegerField(primary_key=True) area = models.FloatField(null=True) perimeter = models.FloatField(null=True) statesp020 = models.IntegerField(null=True) state = models.CharField(null=True, max_length=20) state_fips = models.TextField(null=True, max_length=2) order_adm = models.IntegerField(null=True) month_adm = models.TextField(null=True) day_adm = models.IntegerField(null=True) year_adm = models.IntegerField(null=True) geometry = models.MultiPolygonField(db_column='the_geom', null=True) objects = models.GeoManager() #better to use pre-generated files because Alaska takes an inordinate amount of time to generate #it's basically the same as every other state combined @staticmethod def geojson_for_state(state): with connections["nominatim"].cursor() as cursor: cursor.execute("SELECT ST_AsGeoJSON(ST_Union(us_state.the_geom)) FROM us_state WHERE state=%s", [state]) geojson = cursor.fetchone()[0] return geojson @property def counties(self): return USStateCounty.objects.filter(state_fips=self.state_fips).distinct("fips") def __unicode__(self): return self.state class Meta: db_table = 'us_state' managed = False class USStateCounty(models.Model): gid = models.IntegerField(primary_key=True) area = models.FloatField(null=True) perimeter = models.FloatField(null=True) countyp020 = models.IntegerField(null=True) state = models.CharField(max_length=2, null=True) county = models.CharField(max_length=50, null=True) fips = models.CharField(max_length=5, null=True) state_fips = models.CharField(max_length=2, null=True) square_mil = models.FloatField(null=True) geometry = models.MultiPolygonField(db_column='the_geom', null=True) objects = models.GeoManager() @staticmethod def geojson_for_county(fips): with connections["nominatim"].cursor() as cursor: cursor.execute("SELECT ST_AsGeoJSON(ST_Union(us_statecounty.the_geom)) from us_statecounty where fips=%s", [fips]) geojson = cursor.fetchone()[0] return geojson @property def municipalities(self): return Municipality.objects.filter(state_fips=self.state_fips, county_fips=self.county_fips) @property def county_fips(self): return self.fips[2:] @property def state_name(self): return USState.objects.filter(state_fips=self.state_fips).first().state def __unicode__(self): if self.county: return "%s, %s" % (self.county, self.state) else: return "Unknown County" class Meta: db_table = 'us_statecounty' managed = False class CountryName(models.Model): country_code = models.CharField(primary_key=True, max_length=2) name = HStoreField() @property def english_name(self): return self.name_for_language("en") def name_for_language(self, language_code): with connections["nominatim"].cursor() as cursor: cursor.execute("SELECT hstore(name)->ARRAY[%s, 'name', %s, 'official_name'] FROM country_name WHERE country_code=%s", ["name:%s" % (language_code), "official_name:%s" % (language_code), self.country_code]) (name_lc, name, official_lc, official) = cursor.fetchone()[0] return name_lc or name or official_lc or official def __unicode__(self): return self.english_name class Meta: db_table = "country_name" managed = False class CountryOSMGrid(models.Model): country_code = models.CharField(max_length=2) geometry = models.GeometryField() area = models.FloatField(primary_key=True) objects = models.GeoManager() def __unicode__(self): return self.country_code class Meta: db_table = "country_osm_grid" managed = False class PlaceBase(models.Model): osm_type = models.CharField(max_length = 1) osm_id = models.IntegerField(primary_key=True) place_class = models.TextField(db_column="class") place_type = models.TextField(db_column="type") name = HStoreField(null=True) admin_level = models.IntegerField(null=True) housenumber = models.TextField(null=True) street = models.TextField(null=True) addr_place = models.TextField(null=True) isin = models.TextField(null=True) postcode = models.TextField(null=True) country_code = models.CharField(max_length=2, null=True) extratags = HStoreField(null=True) geometry = models.GeometryField() @property def english_name(self): return self.name_for_language("en") def name_for_language(self, language_code): if "name" in self.name: with connections["nominatim"].cursor() as cursor: cursor.execute("SELECT hstore(name)->ARRAY[%s, 'name'] FROM place WHERE osm_id=%s", ["name:%s" % (language_code), self.osm_id]) (name_lc, name) = cursor.fetchone()[0] return name_lc or name elif self.name: return self.name else: return None @property def geojson_with_name(self): gj = self.geometry.geojson gj = gj.replace("{", '{"properties": { "name": "%s" },' % (self.english_name), 1) return gj def __unicode__(self): if self.name: name = self.english_name or self.name.split(", ")[0] return "%s (%s)" % (self.place_type, name) else: return "No name" class Meta: abstract = True class Place(PlaceBase): #all fields are in PlaceBase objects = models.GeoManager() class Meta: db_table = "place" managed = False class Placex(PlaceBase): #from PlaceBase # osm_type = models.CharField(max_length = 1) # osm_id = models.IntegerField(primary_key=True) # place_class = models.TextField(db_column="class") # place_type = models.TextField(db_column="type") # name = HStoreField(null=True) # admin_level = models.IntegerField(null=True) # housenumber = models.TextField(null=True) # street = models.TextField(null=True) # addr_place = models.TextField(null=True) # isin = models.TextField(null=True) # postcode = models.TextField(null=True) # country_code = models.CharField(max_length=2, null=True) # extratags = HStoreField(null=True) # geometry = models.GeometryField() calculated_country_code = models.CharField(max_length=2, null=True) centroid = models.GeometryField(null=True) geometry_sector = models.IntegerField(null=True) importance = models.FloatField(null=True) indexed_date = models.DateTimeField(null=True) indexed_status = models.IntegerField(null=True) linked_place_id = models.IntegerField(null=True) parent_place_id = models.IntegerField(null=True) partition = models.IntegerField(null=True) place_id = models.IntegerField(unique=True) rank_address = models.IntegerField(null=True) rank_search = models.IntegerField(null=True) wikipedia = models.TextField(null=True) objects = models.GeoManager() class Meta: db_table = "placex" managed = False class LocationArea(models.Model): partition = models.IntegerField(null=True) # place_id = models.IntegerField(primary_key=True) country_code = models.CharField(max_length=2, null=True) keywords = models.TextField(null=True) rank_search = models.IntegerField() rank_address = models.IntegerField() isguess = models.NullBooleanField(null=True) centroid = models.PointField(null=True) geometry = models.GeometryField(null=True) place = models.ForeignKey(Placex, to_field="place_id") objects = models.GeoManager() class Meta: db_table = "location_area" managed = False def __unicode__(self): return self.place.__unicode__() #not super useful because bounds are estimates and coverage possibly imcomplete class CountryNaturalEarthData(models.Model): country_code = models.CharField(max_length=2) geometry = models.GeometryField(primary_key = True) objects = models.GeoManager() class Meta: db_table = "country_naturalearthdata" managed = False <file_sep>from django.conf.urls import include, url from . import views as gazetteerviews urlpatterns = [ url(r'^bbox', gazetteerviews.bbox_polygon), url(r'^countries', gazetteerviews.gazetteer_countries), url(r'^country', gazetteerviews.country_polygon), url(r'^states', gazetteerviews.gazetteer_states), url(r'^state', gazetteerviews.state_polygon), url(r'^counties', gazetteerviews.counties_for_state), url(r'^county', gazetteerviews.county_polygon), url(r'^municipalities', gazetteerviews.municipalities_for_county), url(r'^municipality', gazetteerviews.municipality_polygon), ] <file_sep>from nominatim import * def polygon_for_type_and_id(polygon_type, polygon_id): if (polygon_type == "country"): pass elif (polygon_type == "state"): pass elif (polygon_type == "county"): pass return None <file_sep>class NominatimRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'nominatim': return 'nominatim' else: return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'nominatim' and obj2._meta.app_label == 'nominatim': return True elif obj1._meta.app_label != 'nominatim' and obj2._meta.app_label != 'nominatim': return True else: return False def allow_migrate(self, db, model): if db == 'nominatim': return False else: return True def allow_syncdb(self, db, model): if db == 'nominatim': return False else: return True
1eb378dd4885005dd3c49cfdacb46995505efb9c
[ "JavaScript", "Python", "Markdown" ]
32
Python
iatkin/place
20ac87674fbfefec18619fb00b0a23511b88054e
3918e7faa60d1667161f2dc86bbf51008228be6e
refs/heads/master
<file_sep>#include "calculation.h" #include "parameters.h" /* void DampingField(complex<double> *A, size_t n_x, size_t Ntotal, double rnb = 8., double degree = 4.) { size_t i_glob; double betta; for (size_t i_loc = 0; i_loc < n_x; ++i_loc) { i_glob = i_loc + rank*n_x; for (size_t j = 0; j < Ntotal; ++j) { betta = exp(-pow((sqrt(sqr(i_glob - Ntotal/2) + sqr(j - Ntotal/2)) - Ntotal/2)/rnb, degree)); A[i_loc*Ntotal + j] *= exp(-betta); } } } void DampingSpectrum(complex<double> *A, size_t n_x, size_t Ntotal, double rnb = 16., double degree = 2.) { size_t i_glob; double betta; for (size_t i_loc = 0; i_loc < n_x; ++i_loc) { i_glob = i_loc + rank*n_x; for (size_t j = 0; j < Ntotal; ++j) { betta = exp(-pow((sqr(i_glob - Ntotal/2) + sqr(j - Ntotal/2))/sqr(rnb), degree)); A[i_loc*Ntotal + j] *= exp(-betta); } } } */ void Linear(std::complex<double> *A, size_t n_x, size_t Ntotal, size_t N_t, double z_step) { size_t i_glob, idx, idx1; const std::complex<double> tmp1 = 2.*sqr(M_PI)*z_step*_COMPLEX_I; std::complex<double> tmp; fftw_complex *A_fftw = reinterpret_cast<fftw_complex*>(A); fftwnd_mpi(plan_f, 1, A_fftw, NULL, FFTW_TRANSPOSED_ORDER); A = reinterpret_cast<std::complex<double>*>(A_fftw); if (rank < size/2) // even number of processes only! for (size_t i_loc = 0; i_loc < n_x; ++i_loc) { i_glob = i_loc + rank*n_x; idx1 = i_loc*Ntotal*N_t; for (size_t j = 0; j < Ntotal/2; ++j) { idx = idx1 + j*N_t; tmp = exp((double)(sqr(i_glob) + sqr(j))*tmp1); for (size_t k = 0; k < N_t; ++k) A[idx + k] *= tmp*exp(sp_coeff[k]*z_step); } for (size_t j = Ntotal/2; j < Ntotal; ++j) { idx = idx1 + j*N_t; tmp = exp((double)(sqr(i_glob) + sqr(j - Ntotal))*tmp1); for (size_t k = 0; k < N_t; ++k) A[idx + k] *= tmp*exp(sp_coeff[k]*z_step); } } else for (size_t i_loc = 0; i_loc < n_x; ++i_loc) { i_glob = i_loc + rank*n_x - Ntotal; idx1 = i_loc*Ntotal*N_t; for (size_t j = 0; j < Ntotal/2; ++j) { idx = idx1 + j*N_t; tmp = exp((double)(sqr(i_glob) + sqr(j))*tmp1); for (size_t k = 0; k < N_t; ++k) A[idx + k] *= tmp*exp(sp_coeff[k]*z_step); } for (size_t j = Ntotal/2; j < Ntotal; ++j) { idx = idx1 + j*N_t; tmp = exp((double)(sqr(i_glob) + sqr(j - Ntotal))*tmp1); for (size_t k = 0; k < N_t; ++k) A[idx + k] *= tmp*exp(sp_coeff[k]*z_step); } } // DampingSpectrum(A, n_x, Ntotal); A_fftw = reinterpret_cast<fftw_complex*>(A); fftwnd_mpi(plan_b, 1, A_fftw, NULL, FFTW_TRANSPOSED_ORDER); A = reinterpret_cast<std::complex<double>*>(A_fftw); double buf = 1./sqr(Ntotal)/N_t; for (size_t idx = 0; idx < n_x*Ntotal*N_t; ++idx) A[idx] *= buf; } <file_sep>#include "dispersion.h" #include "parameters.h" const double c_light = 299792458*1e2; // speed of light in vacuum, cm/s double n_refract_air(double f) // Cauchy formula, coefficients taken from Akhmanov, Nikitin. Fizicheskaya optika. M. "Nauka", 2004. { double AA = 2.73*1e-4; double BB = 7.52*1e-11; return 1. + AA*(1. + BB*sqr(f/c_light)); } /* double n_refract_air(double f) { double f0 = c_light/lambda; double k0 = 2.*M_PI/lambda*1.000276208; double k1 = 1./c_light*2.*M_PI*1.000282623; double k2 = 2.72659e-31*sqr(2.*M_PI); double k3 = 2.8724303e-44; return c_light/2./M_PI/f*(k0 + k1*(f - f0) + k2/2.*sqr(f - f0) + k3/6.*pow(f - f0, 3)); } */ /* double n_refract_air(double f) // based on formula in Peck, Reeder. Dispersion of Air. JOSA, v.62, 8, 1972. // http://www.opticsinfobase.org/view_article.cfm?gotourl=http%3A%2F%2Fwww%2Eopticsinfobase%2Eorg%2FDirectPDFAccess%2F0883FD76%2DCBB5%2D5776%2D85B864A52FA014F8%5F54743%2Epdf%3Fda%3D1%26id%3D54743%26seq%3D0%26mobile%3Dno&org=Moscow%20State%20University%20Scientific%20Lib { double c_l = c_light*1e4; // c_light must be expressed in um/s return 1. + 1e-8*(8060.51 + 2480990/(132.274 - sqr(f/c_l)) + 17455.7/(39.32957 - sqr(f/c_l))); } */ double k_number(double f) { return 2.*M_PI*f/c_light*n_refract_air(f); } void CreateDispersionCoeff(std::complex<double> *coeff, int N_t, double ldiff, double ldisp) // ldiff, ldisp in cm { double freq[N_t]; double f0 = c_light/lambda; double k0 = 2.*M_PI/lambda*1.00027620775000003483512500679; double k1 = 1./c_light*2.*M_PI*1.00028262324999994703489392123; // complex<double> tmp = -_COMPLEX_I*ldiff/ldisp*sqr(M_PI)*2.; // for (k = 0; k < N_t/2; k++) freq[k] = k; // for (k = N_t/2; k < N_t; k++) freq[k] = k - N_t; // for (k = 0; k < N_t; k++) coeff[k] = tmp*sqr(freq[k]); std::complex<double> tmp = -_COMPLEX_I/2./k0*ldiff; for (size_t k = 0; k < N_t/2; ++k) freq[k] = k/grid_size_t*1e15; for (size_t k = N_t/2; k < N_t; ++k) freq[k] = (k - N_t)/grid_size_t*1e15; for (size_t k = 0; k < N_t; ++k) coeff[k] = tmp*(sqr(k_number(freq[k] + f0)) - sqr(k0 + k1*freq[k])); }<file_sep>#include "ionization.h" #include <cmath> #include <fstream> IonizationData::IonizationData(const char * filename) { std::fstream f(filename); if (!f) { printf("Can't open ionization data file %s!\n", filename); exit(1); } f >> imin_log >> imax_log >> i_step; imin_log -= 4.0; // convert W/m^2 -> W/cm^2 (4 orders) imax_log -= 4.0; // convert W/m^2 -> W/cm^2 (4 orders) size_t data_size = (int)((imax_log - imin_log) / i_step) + 1; data.reserve(data_size); double tmp; for (int i = 0; i < data_size; ++i) { f >> tmp; data.push_back(std::pow(10.0, tmp - 15.0)); // convert s^-1 to fs^-1 (15 orders) } } double IonizationData::getRate(double intensity) const { int idx = (int)((log10(intensity) - imin_log) / i_step + 0.5); if (idx < 0) idx = 0; if (idx >= data.size()) idx = data.size() - 1; return data[idx]; } <file_sep>#ifndef OUTPUT_H_INCLUDED #define OUTPUT_H_INCLUDED #include <complex> #include <cstddef> void OutRealBinary(const double *source, size_t len, const char *file_name); void OutRealText(const double *source, size_t len, const char *file_name); void OutRealParallel(const double *source, size_t len, const char *file_name); void OutComplexBinary(const std::complex<double> *source, size_t len, const char *file_name); void OutComplexText(const std::complex<double> *source, size_t len, const char *file_name); void OutComplexParallel(const std::complex<double> *source, size_t len, const char *file_name); void InComplexParallel(std::complex<double> *source, size_t len, const char *file_name); #endif // OUTPUT_H_INCLUDED<file_sep>MPI_CC = mpicxx LD = mpicxx CCFLAGS = -std=c++11 -c -Wall LDFLAGS = -lfftw_mpi -lfftw TARGET = fil.e OBJECTS = $(patsubst %.cpp, %.o, $(wildcard *.cpp)) SHELL := /bin/bash all: $(TARGET) $(TARGET): $(OBJECTS) . /usr/share/Modules/init/bash; \ module load openmpi/1.8.4-icc; \ module load intel/15.0.090; \ $(LD) -o $@ $^ $(LDFLAGS) -I/home/users/dergachev/local/include -L/home/users/dergachev/local/lib %.o: %.cpp . /usr/share/Modules/init/bash; \ module load openmpi/1.8.4-icc; \ module load intel/15.0.090; \ $(MPI_CC) $(CCFLAGS) $^ -o $@ -I/home/users/dergachev/local/include clean: rm $(TARGET) $(OBJECTS)<file_sep>#ifndef INITIALIZATION_H_INCLUDED #define INITIALIZATION_H_INCLUDED #include <complex> #include <cstddef> void InitField(std::complex<double> *Arr, size_t n_x, size_t Ntotal, size_t N_t, double gs, double rad, double gs_t, double rad_t); void Allocate(); #endif // INITIALIZATION_H_INCLUDED<file_sep>#ifndef IONIZATION_H_INCLUDED #define IONIZATION_H_INCLUDED #include <vector> class IonizationData { public: IonizationData(const char * filename); double getRate(double intensity) const; // intensity must be in W/cm^2 private: std::vector<double> data; double imin_log; // log10(I_min) double imax_log; // log10(I_max) double i_step; }; #endif // IONIZATION_H_INCLUDED<file_sep>#ifndef FINALIZATION_H_INCLUDED #define FINALIZATION_H_INCLUDED void Finalize(); #endif // FINALIZATION_H_INCLUDED<file_sep>#ifndef PROPAGATION_H_INCLUDED #define PROPAGATION_H_INCLUDED void Propagate(); #endif // PROPAGATION_H_INCLUDED<file_sep>#ifndef DISPERSION_H_INCLUDED #define DISPERSION_H_INCLUDED #include <complex> void CreateDispersionCoeff(std::complex<double> *coeff, int N_t, double ldiff, double ldisp); #endif // DISPERSION_H_INCLUDED<file_sep>#include "dispersion.h" #include "parameters.h" #include "initialization.h" void CheckParametres() {/* int err_code = -1; if (size % 2 != 0) { p_log = fopen(log_name, "a+t"); fprintf(p_log, "001: Odd number of processes!\n"); fclose(p_log); MPI_Abort(MPI_COMM_WORLD, err_code); } if (NN % size != 0) { p_log = fopen(log_name, "a+t"); fprintf(p_log, "002: Sizes of grid and communicator don't match!\n"); fclose(p_log); MPI_Abort(MPI_COMM_WORLD, err_code); }*/ } void InitField(std::complex<double> *Arr, size_t n_x, size_t Ntotal, size_t N_t, double gs, double rad, double gs_t, double rad_t) { const size_t len = N_t*Ntotal; size_t idx, idx1; double tmp; if (N_t == 1) for (size_t i = 0; i < n_x; ++i) { idx1 = i*len; for (size_t j = 0; j < Ntotal; ++j) { idx = idx1 + j*N_t; tmp = exp(-0.5*sqr(gs/rad/Ntotal)*(sqr(i + rank*n_x - (Ntotal - 1.)/2.) + sqr(j - (Ntotal - 1.)/2.))); for (size_t k = 0; k < N_t; ++k) Arr[idx + k] = tmp; } } else for (size_t i = 0; i < n_x; ++i) { idx1 = i*len; for (size_t j = 0; j < Ntotal; ++j) { idx = idx1 + j*N_t; tmp = exp(-0.5*sqr(gs/rad/Ntotal)*(sqr(i + rank*n_x - (Ntotal - 1.)/2.) + sqr(j - (Ntotal - 1.)/2.))); for (size_t k = 0; k < N_t; ++k) Arr[idx + k] = tmp*exp(-0.5*sqr(gs_t/rad_t)*sqr(-0.5 + (double)k/(double)(N_t - 1))); } } } void Allocate() { CheckParametres(); EEE = new std::complex<double>[local_nx*NN*NN_t]; sp_coeff = new std::complex<double>[NN_t]; fluence = new double[local_nx*NN]; CreateDispersionCoeff(sp_coeff, NN_t, ldiff, ldisp); plan_f = fftw3d_mpi_create_plan(MPI_COMM_WORLD, NN, NN, NN_t, FFTW_FORWARD, FFTW_ESTIMATE); plan_b = fftw3d_mpi_create_plan(MPI_COMM_WORLD, NN, NN, NN_t, FFTW_BACKWARD, FFTW_ESTIMATE); MPI_Barrier(MPI_COMM_WORLD); }<file_sep>#ifndef PARAMETERS_H_INCLUDED #define PARAMETERS_H_INCLUDED #include <cstddef> #include <string> #include <mpi.h> #include <fftw_mpi.h> #include "misc.h" extern std::string dir_name; // series directory const size_t NN = 1024; // whole number of points, square grid extern size_t local_nx; // number of rows for a process const double rad = 0.1; // beam radius, cm const double grid_size = 1.; // size of grid, cm extern double min_dxdy; // cross-section step of the grid, ~5 um const size_t NN_t = 1024; // number of time lays const double rad_t = 500; // pulse half-duration in fs; "1/e-time radius" for intensity const double grid_size_t = 5000; // size of grid in time dimension extern double min_dt; // time step of the grid, ~1 fs const long int schmax = 100; // anyway, somewhere we must stop... const int save_frequency = 1; // number of steps between savings extern double dz; // initial step const double lambda = 0.8e-4; // wavelength, cm extern double ldiff, ldisp; // diffraction length, cm const double k2 = 2.72659401330929268349444781979e-31*sqr(2*M_PI); // d2k/df2 for f = f0, cannot be calculated from n(f) due to round-off error extern std::complex<double> *EEE; // EEE - E-field of pulse part extern std::complex<double> *sp_coeff; // coefficients for dispersion, not to recalculate them extern double *fluence; // fluence - integral of intensity over time in cross-section extern int rank, size; // rank of process and size of communicator extern fftwnd_mpi_plan plan_f, plan_b; // Fourier plans #endif // PARAMETERS_H_INCLUDED<file_sep>#ifndef CALCULATION_H_INCLUDED #define CALCULATION_H_INCLUDED #include <complex> #include <cstddef> void Linear(std::complex<double> *A, size_t n_x, size_t Ntotal, size_t N_t, double z_step); #endif // CALCULATION_H_INCLUDED<file_sep>#include "output.h" #include <cstdio> #include <mpi.h> void OutRealBinary(const double *source, size_t len, const char *file_name) { FILE *p_f = fopen(file_name, "wb"); if (!p_f) return; fwrite(source, sizeof(*source), len, p_f); fclose(p_f); } void OutRealText(const double *source, size_t len, const char *file_name) { FILE *p_f = fopen(file_name, "wt"); if (!p_f) return; for (size_t k = 0; k < len; ++k) fprintf(p_f, "%f\n", source[k]); fclose(p_f); } void OutRealParallel(const double *source, size_t len, const char *file_name) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_File p_f; MPI_Status st; MPI_File_open(MPI_COMM_WORLD, file_name, MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &p_f); MPI_File_set_view(p_f, rank*len*sizeof(*source), MPI_DOUBLE, MPI_DOUBLE, "native", MPI_INFO_NULL); MPI_File_write_all(p_f, source, len, MPI_DOUBLE, &st); MPI_File_close(&p_f); } void OutComplexBinary(const std::complex<double> *source, size_t len, const char *file_name) { FILE *p_f = fopen(file_name, "wb"); if (!p_f) return; fwrite(source, sizeof(*source), 2*len, p_f); fclose(p_f); } void OutComplexText(const std::complex<double> *source, size_t len, const char *file_name) { FILE *p_f = fopen(file_name, "wt"); if (!p_f) return; for (size_t k = 0; k < len; ++k) fprintf(p_f, "%f\n%f\n", source[k].real(), source[k].imag()); fclose(p_f); } void OutComplexParallel(const std::complex<double> *source, size_t len, const char *file_name) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_File p_f; MPI_Status st; MPI_File_open(MPI_COMM_WORLD, file_name, MPI_MODE_CREATE | MPI_MODE_WRONLY, MPI_INFO_NULL, &p_f); MPI_File_set_view(p_f, rank*len*sizeof(*source), MPI_DOUBLE_COMPLEX, MPI_DOUBLE_COMPLEX, "native", MPI_INFO_NULL); MPI_File_write_all(p_f, source, len, MPI_DOUBLE_COMPLEX, &st); MPI_File_close(&p_f); } void InComplexParallel(std::complex<double> *source, size_t len, const char *file_name) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_File p_f; MPI_Status st; MPI_File_open(MPI_COMM_WORLD, file_name, MPI_MODE_RDONLY, MPI_INFO_NULL, &p_f); MPI_File_set_view(p_f, rank*len*sizeof(*source), MPI_DOUBLE_COMPLEX, MPI_DOUBLE_COMPLEX, "native", MPI_INFO_NULL); MPI_File_read_all(p_f, source, len, MPI_DOUBLE_COMPLEX, &st); MPI_File_close(&p_f); }<file_sep>#include "propagation.h" #include "initialization.h" #include "parameters.h" #include "calculation.h" #include <sstream> #include <fstream> #include <iomanip> static double cur_z; static double max_phase, global_max_phase, max_I, global_max_I, max_F, global_max_F; static long int sch; void Tact() { ++sch; cur_z += dz; for (size_t i = 0; i < local_nx*NN; ++i) fluence[i] = 0.; max_F = 0.; max_I = 0.; max_phase = 0.; Linear(EEE, local_nx, NN, NN_t, dz); for (size_t i = 0; i < local_nx; ++i) { size_t idx11 = i*NN, idx21 = i*NN*NN_t; for (size_t j = 0; j < NN; ++j) { size_t idx12 = idx11 + j, idx22 = idx21 + j*NN_t; for (size_t k = 0; k < NN_t; ++k) fluence[idx12] += norm(EEE[idx22 + k]); if (fluence[idx12] > max_F) max_F = fluence[idx12]; } } } std::complex<double> direct(double z, double t) { double z_disp = sqr(rad_t*1e-15)/k2*sqr(2.*M_PI); double z_diff = sqr(rad)*2.*M_PI/lambda; return exp(-sqr(grid_size/2./NN/rad))*1./sqrt(1. + _COMPLEX_I*z*ldiff/z_disp)*1./(1. - _COMPLEX_I*z*ldiff/z_diff)*exp(-0.5*sqr(t*grid_size_t/rad_t)/(1. + _COMPLEX_I*z*ldiff/z_disp)); } void Save() { if (rank == size/2) { std::ostringstream ss; ss << dir_name << "/Field/intensity" << std::setw(6) << std::setfill('0') << sch << ".bin"; std::ofstream f(ss.str()); for (size_t k = 0; k < NN_t; ++k) { std::complex<double> field_e = EEE[NN*NN_t/2 + k], dir = direct(cur_z, (double)k/(NN_t - 1.) - 1./2.); f << k << ' ' << cur_z << ' ' << std::real(field_e) << ' ' << std::imag(field_e) << ' ' << std::norm(field_e) << ' ' << std::arg(field_e) << ' ' << std::real(dir) << ' ' << std::imag(dir) << ' ' << std::norm(dir) << ' ' << std::arg(dir) << '\n'; } } /* complex<double> *buf; buf = new complex<double>[NN*local_nx]; for (int k = 0; k < NN_t; k++) { for (int i = 0; i < local_nx; i++) for (int j = 0; j < NN; j++) buf[i*NN + j] = EEE[(i*NN + j)*NN_t + k]; sprintf(file_name, "%s/log/pole%.3ld%.3d.bin", dir_name, sch, k); OutComplexParallel(buf, local_nx*NN, file_name); } delete[] buf;*/ // sprintf(file_name, "%s/Fluence/fluence%.6ld.bin", dir_name, sch); // OutRealParallel(fluence, local_nx*NN, file_name); } void Propagate() { InitField(EEE, local_nx, NN, NN_t, grid_size, rad, grid_size_t, rad_t); MPI_Barrier(MPI_COMM_WORLD); std::string log_name(dir_name + "log.txt"); if (rank == 0) { std::ofstream log(log_name, std::ios_base::app); log << "iteration cur_z z_step phase intensity fluence\n"; } sch = 0; cur_z = 0.; Save(); while (sch < schmax) { Tact(); // MPI_Allreduce(&max_I, &global_max_I, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD); MPI_Allreduce(&max_F, &global_max_F, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD); // MPI_Allreduce(&max_phase, &global_max_phase, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD); if (sch % save_frequency == 0) Save(); if (rank == 0) { std::ofstream log(log_name, std::ios_base::app); log << sch << " " << cur_z*ldiff << " " << dz*ldiff << " " << global_max_phase << " " << global_max_I << " " << global_max_F << "\n"; } // if ((global_max_phase > PHASE_THRESHOLD_HIGH) || (global_max_phase < PHASE_THRESHOLD_LOW)) dz *= PHASE_THRESHOLD_LOW/global_max_phase; } }<file_sep>#!/bin/bash SCRATCH_PATH=$(echo $(pwd) | sed 's/Programs/_scratch/g') rm -rf "$SCRATCH_PATH" mkdir -p "$SCRATCH_PATH" cp -R *.{e,tf} run "$SCRATCH_PATH" 2>>/dev/null cd "$SCRATCH_PATH" <file_sep>#include <cstdlib> #include <fstream> #include "misc.h" #include "parameters.h" #include "initialization.h" #include "propagation.h" #include "finalization.h" void GetParam(int argc, char **argv) { if (argc < 2) std::exit(1); // not enough arguments dir_name = std::string(argv[1]); local_nx = NN / size; min_dxdy = grid_size / NN; min_dt = grid_size_t / NN_t; ldisp = sqr(grid_size_t*1e-15) / k2 * sqr(2.*M_PI); ldiff = 2. * M_PI / lambda * sqr(grid_size); dz = 0.05*sqr(rad/grid_size);// * ldisp / ldiff * sqr(rad_t / grid_size_t);// } void OutParam() { std::string str(dir_name + "/param.txt"); std::ofstream f(str); if (!f) { std::cout << "Can't open file " << str << "!\n"; exit(1); } f << "NN = " << NN << "\n"; f << "rad = " << rad << " cm\n"; f << "grid_size = " << grid_size << " cm\n"; f << "min_dxdy = " << min_dxdy * 10000 <<" um\n\n"; f << "NN_t = " << NN_t << "\n"; f << "rad_t = " << rad_t << " fs\n"; f << "grid_size_t = " << grid_size_t << " fs\n"; f << "min_dt = " << min_dt << " fs\n\n"; f << "lambda = " << lambda*1e4 << " um\n"; f << "diffraction length (grid) = " << ldiff << " cm\n"; f << "diffraction length (beam) = " << ldiff * sqr(rad / grid_size) << " cm\n"; f << "dispersion length (grid) = " << ldisp << " cm\n"; f << "dispersion length (pulse) = " << ldisp * sqr(rad_t / grid_size_t) << " cm\n\n"; f << "number of processes = " << size << "\n"; } int main(int argc, char **argv) { MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); GetParam(argc, argv); if (rank == 0) OutParam(); MPI_Barrier(MPI_COMM_WORLD); Allocate(); Propagate(); Finalize(); MPI_Finalize(); }<file_sep>#include "parameters.h" std::string dir_name; size_t local_nx; double min_dxdy; double min_dt; double dz; double ldiff, ldisp; std::complex<double> *EEE; std::complex<double> *sp_coeff; double *fluence; int rank, size; fftwnd_mpi_plan plan_f, plan_b; <file_sep>#include "parameters.h" void Finalize() { delete[] EEE; delete[] sp_coeff; delete[] fluence; fftwnd_mpi_destroy_plan(plan_f); fftwnd_mpi_destroy_plan(plan_b); }<file_sep>#!/bin/bash module load openmpi/1.8.4-icc module load intel/15.0.090 RESULTS_DIR="Results" mkdir "$RESULTS_DIR" mkdir "$RESULTS_DIR/Fluence" mkdir "$RESULTS_DIR/Plasma" mkdir "$RESULTS_DIR/Field" sbatch -n 64 -p test -t 15 ompi ./fil.e "$RESULTS_DIR" <file_sep>#ifndef MISC_H_INCLUDED #define MISC_H_INCLUDED #include <complex> template <typename T> inline T sqr(T x) { return x*x; } const std::complex<double> _COMPLEX_I(0.0, 1.0); #endif // MISC_H_INCLUDED
c56e41b573b5479e7fbca4511ef9dfbbe75c07aa
[ "C", "Makefile", "C++", "Shell" ]
21
C++
kitozawr/Filament_3DT
66683b13772c59b064de7058595c81a011d6557c
1e2a21c7fee9a1404341988cbe31fc8e2fdb3269
refs/heads/master
<repo_name>hhagay/DemoProject<file_sep>/src/main/java/Example2.java import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class Example2 { static WebDriver driver; public static void main(String[] args) { String projectPath = System.getProperty("user.dir"); System.setProperty("webdriver.chrome.driver", projectPath+"/browsers/chromedriver.exe"); driver = new ChromeDriver(); driver.get("http://www.wikipedia.org"); // driver.manage().window().fullscreen(); WebElement searchBox = driver.findElement(By.id("searchInput")); searchBox.clear(); searchBox.sendKeys("Selenium"); searchBox.clear(); WebElement searchBoxByName = driver.findElement(By.name("search")); searchBoxByName.clear(); searchBoxByName.sendKeys("Webdriver"); WebElement clickSearchButton = driver.findElement(By.className("pure-button-primary-progressive")); clickSearchButton.click(); WebElement resultPageTile = driver.findElement(By.id("firstHeading")); String headingText = resultPageTile.getText(); if(headingText.equals("Selenium (software)")) System.out.println("Pass"); else System.out.println("Fail"); } } <file_sep>/test-output/old/Default Suite/DemoProject.properties [SuiteResult context=DemoProject]<file_sep>/src/main/java/pages/BasePage.java package pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; public class BasePage { public boolean insertText(WebElement element, String textToInsert) { element.sendKeys(textToInsert); String textAfter = element.getText(); if(textAfter.isEmpty()) textAfter = element.getAttribute("value"); return textToInsert.equals(textAfter); } public void mouseHover(WebDriver driver, WebElement element) { Actions actions = new Actions(driver); actions.moveToElement(element).perform(); } } <file_sep>/src/main/java/Example3.java import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.Assert; import org.testng.annotations.*; public class Example3 { WebDriver driver; String projectPath; @BeforeSuite public void beforeSuite(){ System.out.println("before suite"); } @BeforeClass public void envSetup(){ projectPath = System.getProperty("user.dir"); System.setProperty("webdriver.chrome.driver", projectPath+"/browsers/chromedriver.exe"); } @BeforeMethod public void testSetup(){ driver = new ChromeDriver(); } @Test public void gmailNavigation(){ driver.get("https://www.gmail.com"); String currentUrl = driver.getCurrentUrl(); Assert.assertTrue(currentUrl.contains("google"), "Expected gmail but found "+currentUrl); WebElement userTextBox = driver.findElement(By.id("identifierId")); Assert.assertNotNull(userTextBox, "User text box is not found"); } @Test public void myTest2(){ System.out.println("Test # 2"); Assert.assertTrue(false, "method failed"); } @AfterMethod public void tearDown(){ driver.quit(); } }
cf6bcccd9247c4b8406067dd9ffbb3af63927c7d
[ "Java", "INI" ]
4
Java
hhagay/DemoProject
ce5d92dffdf320dd5d685f450d8a0114e230b18c
ebab80903ae316f8eebadc45cdf906a5ed50dc71
refs/heads/master
<file_sep>var height = 500, width = 800, data = []; //Margins on bottom and left are larger to provide room for axes. var margin = {top: Math.round(0.05 * height), right: Math.round(0.05 * width), bottom: Math.round(0.1 * height), left: Math.round(0.1 * width)}; var innerHeight = height - margin.top - margin.bottom; var innerWidth = width - margin.left - margin.right; //Add SVG element to body. var svg = d3.select('body').append('svg') .attr('height', height) .attr('width', width); //Provide a visible frame around the SVG element. //In the code below the rect elements forming the bars are members of class 'bar'; in this way they are distinguished from the rect forming the frame. svg.append('rect') .attr('height', height) .attr('width', width) .style('fill', 'none') .style('stroke', 'gray') .style('stroke-width', '1px'); //Generate an SVG grouping element shifted with respect to the left and top margins. var inner = svg.append('g') .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')'); function update_data(action) { if (action == 'push') { data.push(Math.random()); } else if (action == 'unshift') { data.unshift(Math.random()); } else if (action == 'pop') { data.pop(); } else if (action == 'shift') { data.shift(); } else if (action == 'slideLeft') { update_data('push'); update_data('shift'); } else if (action == 'slideRight') { update_data('unshift'); update_data('pop'); } } function randomize(lolim) { //Select a random number of bars between lolim and 32. Beyond 32 bars, the chart becomes too crowded for good readability. //In the present function we avoid generating fewer than 2 bars (unless lolim is explicitly set below 2) as the user might view the absence of bars, or even just 1 bar, as a bug if produced by randomize(). //On the other hand, if the user is manually removing bars through actions that call update_data() then it is natural for 1 and then 0 bars to eventually be reached. In that context I conjecture the user is unlikely to view 1 or 0 bars as a bug. if (lolim == undefined) lolim = 2; var nb = Math.round(lolim + Math.random() * (32 - lolim)); data = Array(nb); //Select bar heights in the range [0, 1). for (var ii = 0; ii < nb; ++ii) data[ii] = Math.random(); } d3.select('#push').on('click', function() { update_data('push'); update_chart(data); }); d3.select('#pop').on('click', function() { update_data('pop'); update_chart(data); }); d3.select('#unshift').on('click', function() { update_data('unshift'); update_chart(data); }); d3.select('#shift').on('click', function() { update_data('shift'); update_chart(data); }); d3.select('#randomize').on('click', function() { randomize(); update_chart(data); }); d3.select('#slideLeft').on('click', function() { update_data('slideLeft'); update_chart(data); }); d3.select('#slideRight').on('click', function() { update_data('slideRight'); update_chart(data); }); //Generate scales. Domains are set in the update_chart function. xScale = d3.scaleBand().range([0, innerWidth]).padding(0.1); //For the y-axis to display properly the range must go from high to low. yScale = d3.scaleLinear().range([innerHeight, 0]); function update_chart(data) { //Set scale domains. The bars are numbered beginning with 1. xScale.domain(d3.range(data.length + 1).slice(1)); yScale.domain([0, d3.max(data)]); //Generate axes. //First remove any prior axes. svg.selectAll('.axis').remove(); svg.append('g').attr('class', 'axis') .attr('transform', 'translate(' + margin.left + ',' + (margin.top + innerHeight) + ')') //NOTE: If a call to ticks(<n>) is included below it has no effect. //This makes sense as scaleBand is designed to accomodate categorical data. .call(d3.axisBottom(xScale).tickSizeOuter(0)); svg.append('g').attr('class', 'axis') .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')') .call(d3.axisLeft(yScale).tickSizeOuter(0)); //Add, remove, update bars as appropriate. var bars = inner.selectAll('.bar').data(data); bars.enter().append('rect') .attr('class', 'bar') .style('fill', 'rgba(0, 128, 128, 0.75)') .style('opacity', 0.5) .merge(bars) .attr('x', function(d, i) { return xScale(i + 1); }) .attr('y', function(d, i) { return yScale(d); }) .attr('width', xScale.bandwidth()) .attr('height', function(d, i) { return innerHeight - yScale(d); }); bars.exit().remove(); } //Begin by generating a chart. randomize(5); update_chart(data); <file_sep>#Dynamic bar chart User can * Add a bar on left * Add a bar on right * Remove a bar from left * Remove a bar from right * Slide the bars left * Slide the bars right * Randomly generate a set of bars Implemented with d3.v4. View output <a href='https://quantbo.github.io/dynamic_bar_chart/' target='_blank'>here</a>.
a3793e2cf6a5b9fdf6becf474f32dfe0ad50509a
[ "JavaScript", "Markdown" ]
2
JavaScript
quantbo/dynamic_bar_chart
5da04ac4fcdbeaf3e720c6b43b9200f78ae90ecb
8dbe10c14fa358711a4c2379f7e3545e7d49effe
refs/heads/master
<repo_name>krisity/Student-Information-System<file_sep>/StudentInfoSystem/src/java/util/package-info.java /** * This package is for initiating database connection to MySQL. * */ package util;<file_sep>/StudentInfoSystem/src/java/controller/ListAllStudents.java package controller; import dao.UserDao; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet class that is used to get all the students from the database. * * @author User */ public class ListAllStudents extends HttpServlet { // Declare a static string variable that will hold the path to the // listStudent.jsp private static final String LIST_STUDENT = "/listStudent.jsp"; // Declare a UserDao variable from the UserDao class. private final UserDao dao; /** * Constructor for the servlet that only declares a new UserDao variable. */ public ListAllStudents(){ // Create a new instance of UserDao class. dao = new UserDao(); } /** * Get method that handles the "list all students" request. * * @param request HttpServletRequest * @param response HttpServletResponse * @throws ServletException * @throws IOException */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Declare a string variable that will initially be an empty character. String forward = ""; // Get the "action" parameter from the request and store it as a // string variable to use it later on. String action = request.getParameter("action"); // Check whether the string "action" is actually "listStudent" if (action.equalsIgnoreCase("listStudent")){ // Set the forward string to be equal to the LIST_STUDENT forward = LIST_STUDENT; // Set the attribute for the request by getting all the students. // The name of the attribute is "students". request.setAttribute("students", dao.getAllStudents()); } // Get the request dispatcher RequestDispatcher view = request.getRequestDispatcher(forward); // Forward the request dispatcher view.forward(request, response); } /** * Override of the post method that handles the listStudent action. * * @param request * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the request dispatcher RequestDispatcher view = request.getRequestDispatcher(LIST_STUDENT); // Get all students and set the attribute of the request request.setAttribute("students", dao.getAllStudents()); // Forward the request back. view.forward(request, response); } } <file_sep>/StudentInfoSystem/src/java/model/RegisterUser.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; /** * Class that is used when registering a student - contains information about the * student general information such as name, faculty number etc. * @author User */ public class RegisterUser { // The variables which appear on the student registration page. private String facultyNumber, name, surname, pIdNumber, phone, faculty,specialty, degree, email; // Getter for the faculty number. public String getFacultyNumber() { return facultyNumber; } // Setter for the faculty number. public void setFacultyNumber(String facultyNumber) { this.facultyNumber = facultyNumber; } // Getter for the name. public String getName() { return name; } // Setter for the name. public void setName(String name) { this.name = name; } // Getter for the surname. public String getSurname() { return surname; } // Setter for the surname. public void setSurname(String surname) { this.surname = surname; } // Getter for the personal ID number. public String getpIdNumber() { return pIdNumber; } // Setter for the personal ID number. public void setpIdNumber(String pIdNumber) { this.pIdNumber = pIdNumber; } // Getter for the phone. public String getPhone() { return phone; } // Setter for the phone. public void setPhone(String phone) { this.phone = phone; } // Getter for the faculty. public String getFaculty() { return faculty; } // Setter for the faculty. public void setFaculty(String faculty) { this.faculty = faculty; } // Getter for the specialty. public String getSpecialty() { return specialty; } // Setter for the specialty. public void setSpecialty(String specialty) { this.specialty = specialty; } // Getter for the degree. public String getDegree() { return degree; } // Setter for the degree. public void setDegree(String degree) { this.degree = degree; } // Getter for the email. public String getEmail() { return email; } // Setter for the email. public void setEmail(String email) { this.email = email; } } <file_sep>/StudentInfoSystem/src/java/controller/UpdateStudent.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controller; import dao.UserDao; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import model.Faculty; import model.RegisterUser; /** * Servlet class that is used when an administrator is updating the information for a specific student. * @author User */ public class UpdateStudent extends HttpServlet { // Declare a string variable that will hold the path to updateStudent.jsp page. private static final String EDIT = "/updateStudent.jsp"; // Declare a UserDao variable. private final UserDao dao; // Default constructor for the UpdateStudent servlet. public UpdateStudent(){ // Initialize the UserDao variable. dao = new UserDao(); } /** * Override of the get method. * * @param request * @param response * @throws ServletException * @throws IOException */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Declare an empty string that will be used for quick forwarding through the jsp pages. String forward=""; // Declare a string that will hold the action parameter. String action = request.getParameter("action"); // Check if the action is "edit" i.e. if the user has clicked on "Update", not on "Delete". if (action.equalsIgnoreCase("edit")){ // Change the empty forward string to be the path to the updateStudent.jsp page. forward = EDIT; // Get the facultyNumber parameter and store it in a string variable. String facultyNumber = request.getParameter("facultyNumber"); // Load the info for the currently selected user by his/hers facultyNumber. RegisterUser user = dao.searchStudent(facultyNumber); // Set an attribute "user" holding info for the selected student. This attribute // is sent back to the client-side (i.e. the updateStudent.jsp). request.setAttribute("user", user); // Get the faculty of the selected user and store it in a string. String studentFaculty = user.getFaculty(); // Get all other faculties from the db and store them in a list. // The list holds REFERENCES to all faculties except for the faculty // of the currently selected student. List<Faculty> allFaculties = dao.listFaculty(studentFaculty); // Declare a new ArrayList to hold the actual codes for all faculties. List<String> facultyArrayList = new ArrayList<>(); // Loop through the allFaculties list and for each item from the list: allFaculties.forEach((faculty) -> { // get the faculty name and add it to the facultyArrayList list. // After this is done the facultyArrayList is populated with the // codes for all faculties except for the faculty in which the // selected student is in. facultyArrayList.add(faculty.getFaculty()); }); // Set an attribute "faculty" which holds the codes for all faculties // except for the faculty in which the selected student is in. request.setAttribute("faculty", facultyArrayList); // Get the specialty of the selected student and store it in a string variable. String specialty = user.getSpecialty(); // Get all other specialties from the db and store them in a list. // The list holds REFERENCES to all specialties except for the specialty // of the currently selected student. List<Faculty> allSpecialties = dao.listSpecialty(specialty); // Declare a new ArrayList to hold the actual codes for all specialties. List<String> specialtiesArrayList = new ArrayList<>(); // Loop through the allSpecialties list and for each item from the list: allSpecialties.forEach((specialty1) -> { // get the specialty name and add it to the specialtiesArrayList list. // After this is done the specialtiesArrayList is populated with the // codes for all specialties except for the specialty in which the // selected student is in. specialtiesArrayList.add(specialty1.getSpecialty()); }); // Set an attribute "specialty" which holds the codes for all specialties // except for the specialty in which the selected student is in. request.setAttribute("specialty", specialtiesArrayList); // Get the degree of the student and store it in a string. String degree = user.getDegree(); // Check if the degree of the selected student is Master. if(degree.equals("Master")){ // Declare a string that will hold "Bachelor". String bac = "Bachelor"; // Set an attribute "degree" that holds the string bac. request.setAttribute("degree", bac); // Check if the degree of the selected student is Bachelor. }else if(degree.equals("Bachelor")){ // Declare a string that will hold "Master". String mas = "Master"; // Set an attribute "degree" that holds the string mas. request.setAttribute("degree", mas); } } // Check if the action is delete i.e. if the user has clicked on delete. else if (action.equalsIgnoreCase("delete")){ // Get the student facultyNumber parameter and store it in a string. String studentId = request.getParameter("facultyNumber"); // Call to the deleteStudent method. dao.deleteStudent(studentId); // Change the empty forward string to be the path to the listStudent.jsp page. forward = "/listStudent.jsp"; // Declare a string that will hold the success message that a student has been deleted. String deletemsg = "Success! Student with faculty number: " + studentId + " has been deleted! " ; // Set attribute "deletemsg" to pass it back to the listStudent.jsp. request.setAttribute("deletemsg", deletemsg); // Set attribute "students" that will hold all info for all students to // pass it back to the listStudent.jsp. request.setAttribute("students", dao.getAllStudents()); } // Get the RequestDispatcher. RequestDispatcher view = request.getRequestDispatcher(forward); // Forward the RequestDispatcher to the correct jsp page. view.forward(request, response); } /** * Override of the post method. * * @param request * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Declare a RegisterUser variable. RegisterUser student = new RegisterUser(); // Get all parameters from the updateStudent.jsp page and set them as parameters // for the RegisterUser variable. student.setName(request.getParameter("txtname")); student.setSurname(request.getParameter("txtsurname")); student.setpIdNumber(request.getParameter("txtpIdNumber")); student.setPhone(request.getParameter("txtphone")); student.setFaculty(request.getParameter("txtfaculty")); student.setSpecialty(request.getParameter("txtspecialty")); student.setDegree(request.getParameter("txtdegree")); student.setEmail(request.getParameter("txtemail")); // Get the faculty number of the student from the updateStudent.jsp pag // and store it in a string variable. String facultyNumber = request.getParameter("txtfacultyNumber"); // Set the faculty number as parameter // for the RegisterUser variable. student.setFacultyNumber(facultyNumber); // Call to the updateStudent method. dao.updateStudent(student); // Declare a string that will hold the success message that the student has been updated. String msg = "Success! Student with faculty number: " + facultyNumber + " has been updated! " ; // Get the getRequestDispatcher. RequestDispatcher view = request.getRequestDispatcher("/listStudent.jsp"); // Set attribute "students" that will hold all students from the db. request.setAttribute("students", dao.getAllStudents()); // Set attribute "successMsg". request.setAttribute("successMsg", msg); // Forward the request to the correct jsp page. view.forward(request, response); } } <file_sep>/StudentInfoSystem/src/java/model/Faculty.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; /** * Class that is used to show the relation of faculty and specialty of a student. * @author User */ public class Faculty { // Declare 2 strings - 1 for faculty and 1 for specialty. String faculty, specialty; // Getter for the faculty. public String getFaculty() { return faculty; } // Setter for the faculty. public void setFaculty(String faculty) { this.faculty = faculty; } // Getter for the specialty. public String getSpecialty() { return specialty; } // Setter for the specialty. public void setSpecialty(String specialty) { this.specialty = specialty; } } <file_sep>/StudentInfoSystem/src/java/model/Discipline.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package model; /** * Class that is used to show the relation of specialty and disciplines of a student. * * @author User */ public class Discipline { // Declare 2 string variables - one for specialty and one for discipline. private String specialty, discipline; // Getter for the specialty. public String getSpecialty() { return specialty; } // Setter for the specialty. public void setSpecialty(String specialty) { this.specialty = specialty; } // Getter for the discipline. public String getDiscipline() { return discipline; } // Setter for the discipline. public void setDiscipline(String discipline) { this.discipline = discipline; } } <file_sep>/StudentInfoSystem/src/java/controller/LoginServlet.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controller; import dao.UserDao; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import model.RegisterUser; import model.User; /** * Servlet class that is used to verify the login of a user into the system. * * @author User */ public class LoginServlet extends HttpServlet { // Default empty constructor. public LoginServlet() { } /** * Override of the post method. * * @param request * @param response * @throws ServletException * @throws IOException */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the txtUsername parameter from the index.jsp and store it // as a string username. String username = request.getParameter("txtUsername"); // Get the txtPassword parameter from the index.jsp and store it // as a string username. String password = request.getParameter("txtPassword"); // Declare an instance of the User class. User user = new User(); // Set the username of the above declared user. The username is the // text entered by the person inside the username textfield. user.setUsername(username); // Set the password of the above declared user. The password is the // text entered by the person inside the password textfield. user.setPassword(password); // Declare an instance of the USerDao class. UserDao loginDao = new UserDao(); // Try to authenticate the user. try{ // Call the authenticateUser method in order to validate the user credentials // The method returns a string with the role of the user. String userValidate = loginDao.authenticateUser(user); // Check if the role of the user is "admin" if (userValidate.equals("admin_role")) { // Get the request session and store it in a httpsession variable. HttpSession session = request.getSession(); // Set the session attribute with the username. session.setAttribute("Admin", username); // Set the request attribute with the username. request.setAttribute("username", username); // Get the request dispatcher and forward it to AdminPage.jsp request.getRequestDispatcher("AdminPage.jsp").forward(request, response); // Check if the role of the user is student_role. } else if (userValidate.equals("student_role")) { // Get the request session and store it in a httpsession variable. HttpSession session = request.getSession(); // Set the session attribute with the username. session.setAttribute("Student", username); // Set the request attribute with the username. request.setAttribute("username", username); // Search for a student by a username and set the attribute. request.setAttribute("student", loginDao.searchStudent(username)); // Declare an instance of the RegisterUser class. RegisterUser student = new RegisterUser(); // Set the faculty number of the student instance declared above // by getting the facultyNumber parameter. student.setFacultyNumber(request.getParameter("facultyNumber")); // Set the name of the student instance declared above by getting // the name request parameter. student.setName(request.getParameter("name")); // Set the request parameter and forward it to StudentPAge.jsp. request.getRequestDispatcher("StudentPage.jsp").forward(request, response); } // If the role of the user is neither student nor admin. else { //System.out.println("Error message = "+userValidate); // Set request attribute for the error message request.setAttribute("errMessage", userValidate); // Get the request dispatcher and forward the request to index.jsp request.getRequestDispatcher("index.jsp").forward(request, response); } // Catch a possible exception and handle it. }catch(IOException | ServletException e1){ } } }<file_sep>/README.md # Student-Information-System Super simple student information system done with Java. There is no implementation of any security-related features or so. | Name | Description | | --- | --- | | Project Name | Student Information System | | Abstract | Student information system, designed to register and maintain student information data. The system can also be used to enter and edit grades.| | Technologies | Netbeans 8.2; GlassFish Server 4.1,JSP,Servlet | | Architecture | MVC | | Programming Language | Java 8 | | Database | MySql 5.7.12 | | Web front-end framework | Bootstrap v4.0.0-beta.2 | The project uses JSP technology There are different modules that include: - **Sign in module**; - **Administration panel where admin users can**: - regsiter students; - edit student info; - create and edit student grades; - delete a student; - **Student panel where students can**: - check their personal information; - check their faculty and specialty data; - check their grades; | STUDENT | ADMIN | | --- | --- | | ![](Screenshots/17.png) | ![](Screenshots/18.png) | | SCREENSHOT | DESCRIPTION | | --- | --- | | ![](Screenshots/1.png) | Admin panel | | ![](Screenshots/2.png) | Register new student form | | ![](Screenshots/3.png) | Register new student form - filled | | ![](Screenshots/4.png) | Success message after registering new student | | ![](Screenshots/5.png) | Update student table - list with all registered students | | ![](Screenshots/6.png) | Update student info - filled form | | ![](Screenshots/9.png) | Student grades | | ![](Screenshots/10.png) | Student grades - updating specific student grades| | ![](Screenshots/12.png) | Login screen - invalid credentials error | | ![](Screenshots/13.png) | Welcome page | | ![](Screenshots/14.png) | Student profile page | | ![](Screenshots/15.png) | Student grades page |
b08a6171c07d11578316d09c3f0afd1a1088a3dc
[ "Markdown", "Java" ]
8
Java
krisity/Student-Information-System
8a75e8a14f1cd5fa0358a0c124c7c3d64aa96271
27f2a34baa1dc29f915a43b2c7161ed84a0fdb97
refs/heads/master
<repo_name>felix-scholz/bricker<file_sep>/src/brickerGLGUI/GameTeile.java /** * */ package brickerGLGUI; /** * Das sind die einzelnen GameTeile * @author felix * @version 0.1 */ public enum GameTeile { GAME, MULTIPLAYER, GAMEMENU, HAUPTMENU, EINSTELLUNGEN, BRICKERBUILDER, INTRO; } <file_sep>/README.md # Bricker Das ist mein Java-Beleg. Im Modul Einführung in die Programmierung. <file_sep>/src/lwjgl/Texture.java /** * Wie siet die Textur aus muss hier rein oder erben von einer externen Libary * @author <NAME> <<EMAIL>> * @version 0.1 * * #1 Create <NAME> am 25.04.2016 * + importiert von https://github.com/SilverTiger/lwjgl3-tutorial/blob/master/src/silvertiger/tutorial/lwjgl/graphic/Texture.java * + etwas Angepasst * */ package lwjgl; import java.nio.ByteBuffer; import java.nio.IntBuffer; import org.lwjgl.BufferUtils; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL13.GL_CLAMP_TO_BORDER; import static org.lwjgl.stb.STBImage.*; public class Texture { private final int id; //Stores the handle of the texture. private final int width; //Width of the texture. private final int height; //Height of the texture. /** * Erstellt eine Textur mit hoehe, breite und Bild * * @param width Breite der Textur * @param height Höhe der Textur * @param data Bilddaten im RGBA format */ public Texture(int width, int height, ByteBuffer data) { id = glGenTextures(); this.width = width; this.height = height; glBindTexture(GL_TEXTURE_2D, id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); } /** * Binds the texture. */ public void bind() { glBindTexture(GL_TEXTURE_2D, id); } /** * Delete the texture. */ public void delete() { glDeleteTextures(id); } /** * Gets the texture width. * * @return Texture width */ public int getWidth() { return width; } /** * Gets the texture height. * * @return Texture height */ public int getHeight() { return height; } /** * Load texture from file. * * @param path File path of the texture * @return Texture from specified file */ public static Texture loadTexture(String path) { /* Prepare image buffers */ IntBuffer w = BufferUtils.createIntBuffer(1); IntBuffer h = BufferUtils.createIntBuffer(1); IntBuffer comp = BufferUtils.createIntBuffer(1); /* Load image */ stbi_set_flip_vertically_on_load(1); ByteBuffer image = stbi_load(path, w, h, comp, 4); if (image == null) { throw new RuntimeException("Failed to load a texture file!" + System.lineSeparator() + stbi_failure_reason()); } /* Get width and height of image */ int width = w.get(); int height = h.get(); return new Texture(width, height, image); } } <file_sep>/src/brickerGLStrg/BrickerStrgMaus.java /** * Die Hauptsteuerungsklasse, hier wird die Steuerung gemacht. * @author <NAME> <<EMAIL>> * @version 0.1 * */ package brickerGLStrg; import org.lwjgl.glfw.GLFWMouseButtonCallback; import brickerGLGUI.BrickerGUI; import brickerGLGUI.GameTeile; import org.lwjgl.glfw.GLFW; public class BrickerStrgMaus extends GLFWMouseButtonCallback { private BrickerGUI gui; public BrickerStrgMaus(BrickerGUI gui){ this.gui = gui; } @Override public void invoke(long window, int key, int action, int mods) { switch(gui.getTeil()) { case INTRO: System.out.println(key); if(key == GLFW.GLFW_MOUSE_BUTTON_LEFT && action == GLFW.GLFW_RELEASE) gui.setTeil(GameTeile.HAUPTMENU); break; case HAUPTMENU: if(key == GLFW.GLFW_MOUSE_BUTTON_LEFT && action == GLFW.GLFW_RELEASE){ if(gui.getB()[0].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) gui.setTeil(GameTeile.GAMEMENU); if(gui.getB()[1].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) gui.setTeil(GameTeile.MULTIPLAYER); if(gui.getB()[2].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) gui.setTeil(GameTeile.BRICKERBUILDER); if(gui.getB()[3].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) gui.setTeil(GameTeile.EINSTELLUNGEN); if(gui.getB()[4].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) gui.setlaeuft(false); } break; case EINSTELLUNGEN: if(key == GLFW.GLFW_MOUSE_BUTTON_LEFT && action == GLFW.GLFW_RELEASE){ if(gui.getB()[5].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) System.out.println(gui.getB()[5].toString()); if(gui.getB()[6].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) System.out.println(gui.getB()[6].toString()); if(gui.getB()[7].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) System.out.println(gui.getB()[7].toString()); if(gui.getB()[8].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) System.out.println(gui.getB()[8].toString()); if(gui.getB()[9].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) gui.setTeil(GameTeile.HAUPTMENU); } break; case GAME: if(key == GLFW.GLFW_MOUSE_BUTTON_LEFT && action == GLFW.GLFW_RELEASE){ if(gui.getB()[10].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) System.out.println(gui.getB()[10].toString()); if(gui.getB()[11].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) System.out.println(gui.getB()[11].toString()); if(gui.getB()[12].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) gui.setTeil(GameTeile.HAUPTMENU); if(gui.getB()[13].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) gui.setlaeuft(false); } break; case GAMEMENU: if(key == GLFW.GLFW_MOUSE_BUTTON_LEFT && action == GLFW.GLFW_RELEASE){ if(gui.getB()[14].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) gui.setTeil(GameTeile.GAME); if(gui.getB()[15].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) System.out.println(gui.getB()[15].toString()); if(gui.getB()[16].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) System.out.println(gui.getB()[16].toString()); } break; case MULTIPLAYER: if(key == GLFW.GLFW_MOUSE_BUTTON_LEFT && action == GLFW.GLFW_RELEASE){ if(gui.getB()[17].isTrin(gui.getMZP().getXInt(),gui.getMZP().getYInt())) gui.setTeil(GameTeile.HAUPTMENU); } break; case BRICKERBUILDER: break; default: break; } } }<file_sep>/src/math/Vektor3D.java /** * Hier von kann alles Erben was eine Position im Bild hat. Also die Mutteklasse von vielen Klassen. * @author <NAME> <<EMAIL>> * @version 0.1 * */ package math; public class Vektor3D { private double x; private double y; private double z; /** * Default-Konstruktor */ public Vektor3D() { this.x = 0.0; this.y = 0.0; this.z = 0.0; } /** * Konstruktor */ public Vektor3D(double x, double y, double z){ this.x = x; this.y = y; this.z = z; } /** * neuen x-Wert setzten * @param x */ public void setX(double x){ this.x = x; } /** * neuen y-Wert setzen * @param y */ public void setY(double y){ this.y = y; } /** * neuen z-Wert setzen * @param z */ public void setZ(double z){ this.z = z; } /** * gibt den x-Wert aus * @return */ public double getX(){ return x; } /** * gibt den y-Wert aus * @return */ public double getY(){ return y; } /** * gibt den z-Wert aus * @return */ public double getZ(){ return z; } /** * gibt ein Array mit x- und y-Wert aus ([x, y, z]). * @return */ public double[] getXYZ(){ double[] werte = new double[3]; werte[0] = x; werte[1] = y; werte[2] = z; return werte; } /** * Zum Vektoren hinzuaddieren * @param b zweiter Vektor * @return */ public Vektor3D addieren(Vektor3D a){ return new Vektor3D(this.x + a.x, this.y + a.y, this.z + a.z); } /** * Zum Addieren von zwei Vektoren * @param a erster Vektor * @param b zweiter Vektor * @return */ public static Vektor3D addieren(Vektor3D a, Vektor3D b){ return new Vektor3D(a.x + b.x, a.y + b.y, a.z + b.z); } /** * Eine Zahl zum Multiplizieren zum Vektor * @param i - double Zahl * @return */ public Vektor3D multiSkal(double i){ return new Vektor3D(this.x * i, this.x * i, this.z * i); } /** * Zum Multiplizieren von einem Vektor mit einer Zahl * @param a - Vektor * @param i - double Zahl * @return */ public static Vektor3D multiSkal(Vektor3D a, double i){ return new Vektor3D(a.x * i, a.x * i, a.z * i); } /** * Zum Vektor einen Vektor Skalar hinzu multipliziern * @param a * @return ein double Wert */ public double skalProdukt(Vektor3D a){ return (a.x * this.x) + (a.y * this.y) + (a.z * this.z); } /** * Zwei Vektoren Skalar Multipliziern * @param a * @param b * @return ein double Wert */ public static double skalProdukt(Vektor3D a, Vektor3D b){ return (a.x * b.x) + (a.y * b.y) + (a.z * b.z); } /** * Das Kreuzprodukt von diesem und dem Vektor a * @param a * @param b * @return */ public Vektor3D kreuzPodukt(Vektor3D a){ return new Vektor3D((a.y * this.z) - (a.z * this.y) , (a.z * this.x) - (a.x * this.z) , (a.x * this.y) - (a.y * this.x)); } /** * Das Kreuzprodukt von zwei Vektoren * @param a * @param b * @return */ public static Vektor3D kreuzPodukt(Vektor3D a, Vektor3D b){ return new Vektor3D((a.y * b.z) - (a.z * b.y) , (a.z * b.x) - (a.x * b.z) , (a.x * b.y) - (a.y * b.x)); } /** * Das Spatprodukt von drei Vektoren. Hierbei kommet ein Volumen heraus. * @param a - Kreuzprodukt mit b * @param b - Kreuzprodukt mit a * @param c - Multipliziert mit dem Kreuzprodukt aus a und b * @return einen double Wert */ public static double spatProdukt(Vektor3D a, Vektor3D b, Vektor3D c){ return skalProdukt(kreuzPodukt(a , b) , c); } /** * Hiermit kann man einen Einheitsvektor binden, der hat den Betrag "1". * @return */ public Vektor3D einheitsVektor(){ return new Vektor3D(this.x / betragVektor() , this.y / betragVektor() , this.z / betragVektor()); } /** * Hiermit kann man einen Einheitsvektor binden, der hat den Betrag "1". * @param a der Vektor * @return */ public static Vektor3D einheitsVektor(Vektor3D a){ return new Vektor3D(a.x / betragVektor(a) , a.y / betragVektor(a) , a.z / betragVektor(a)); } /** * Den Betrag des Vektors bekommt man hierher raus. * @param a * @return */ public double betragVektor(){ return Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2) + Math.pow(this.z, 2)); } /** * Den Betrag des Vektors bekommt man hierher raus. * @param a * @return */ public static double betragVektor(Vektor3D a){ return Math.sqrt(Math.pow(a.x, 2) + Math.pow(a.y, 2) + Math.pow(a.z, 2)); } /** * Hier kann man sich den Vektor ausgeben lassen in folgender Form (x-Wert, y-Wert, z-Wert). */ public String toString(){ return "(" + x + ", " + y + ", " + z + ")"; } } <file_sep>/src/brickerGL/Objekt.java /** * Hier von kann alles Erben was eine Position im Bild hat. Also die Mutteklasse von vielen Klassen. * @author <NAME> <<EMAIL>> * @version 0.1 * */ package brickerGL; import math.Vektor3D; public abstract class Objekt{ private Vektor3D pos; /** * Der Konstuktor, der die Werte einzeln übergibt. * @param x * @param y * @param z */ public Objekt(double x, double y, double z) { pos = new Vektor3D(x, y, z); } /** * Der Konstuktor, der gleich einen Vektor3D übergibt. * @param v */ public Objekt(Vektor3D v) { pos = v; } /** * Hohlen des Vektor. * @return pos - der Vektor */ public Vektor3D getPos() { return pos; } /** * Setzen eines neuen Vektor v. * @param v - Der Vektor den man setzt */ public void setpos(Vektor3D v) { pos = v; } /** * Das Objekt als String ausgeben * @return Den Sting des Objekts */ public String toString(){ return "Objekt["+pos.getX()+", "+pos.getY()+", "+pos.getZ()+"]"; } } <file_sep>/src/brickerGLGUI/Rend.java /** * Renderfunktion * @author <NAME> <<EMAIL>> * @version 0.1 * */ package brickerGLGUI; import org.lwjgl.opengl.GL11; import lwjgl.Texture; import math.Vektor3D; public class Rend { /** * Hier wird der Hindergrund als Quad mit Textur erstellt. * @param breite * @param hoehe * @param tex */ public static void erstelleHintergrund(float breite, float hoehe, float tiefe, Texture tex) { tex.bind(); GL11.glColor3f(1, 1, 1); GL11.glBegin(GL11.GL_QUADS); GL11.glTexCoord2f(0, 1);GL11.glVertex3f(0, 0, tiefe); GL11.glTexCoord2f(1, 1);GL11.glVertex3f(breite, 0, tiefe); GL11.glTexCoord2f(1, 0);GL11.glVertex3f(breite, hoehe, tiefe); GL11.glTexCoord2f(0, 0);GL11.glVertex3f(0, hoehe, tiefe); GL11.glEnd(); } /** * Hier werden die Menubars gezeichnet/erstellt mit Textur * @param pos * @param breite * @param hoehe * @param tex */ public static void erstelleMenubar(Vektor3D pos, float breite, float hoehe, Texture tex) { tex.bind(); GL11.glColor3f(1, 1, 1); GL11.glBegin(GL11.GL_QUADS); GL11.glTexCoord2f(0, 1);GL11.glVertex3f((float) pos.getX(), (float) pos.getY(), (float) pos.getZ()); GL11.glTexCoord2f(1, 1);GL11.glVertex3f((float) pos.getX() + breite, (float) pos.getY(), (float) pos.getZ()); GL11.glTexCoord2f(1, 0);GL11.glVertex3f((float) pos.getX() + breite, (float) pos.getY() + hoehe, (float) pos.getZ()); GL11.glTexCoord2f(0, 0);GL11.glVertex3f((float) pos.getX(), (float) pos.getY() + hoehe, (float) pos.getZ()); GL11.glEnd(); } /** * Null Ecke */ public static void nullEcke() { GL11.glColor3f(0, 0, 0); GL11.glBegin(GL11.GL_TRIANGLES); GL11.glVertex3f(10f, 10f, 0.9f); GL11.glVertex3f(20f, 10f, 0.9f); GL11.glVertex3f(10f, 20f, 0.9f); GL11.glEnd(); } } <file_sep>/src/brickerGL/BrickList.java /** * Hier sind die Listen, die die Brick auf dem Spielfeld bzw im Brickerbuilder beinhalten, also wichtige Klasse. * @author <NAME> <<EMAIL>> * @version 0.1 * */ package brickerGL; import java.util.ArrayList; import java.util.List; public class BrickList { private List<Brick> bbbricklist; //hier kommen die Bicks aus den Brickerbuilder rein = 0 private List<Brick> gamebricklist; //hier die abgeschossen werden sollen = 1 public BrickList(){ bbbricklist = new ArrayList<Brick>(); gamebricklist = new ArrayList<Brick>(); } /** * Gibt eine der Listen aus und Variable i sagt welche. 0 = bbbricklist, 1 = gamebricklist * @param i - Welche Liste * @return List<Brick> */ public List<Brick> getBrickList(int i){ if(i == 0) return bbbricklist; if(i == 1) return gamebricklist; else throw new IllegalArgumentException(); } /** * Setzt eine der Listen und Variable i sagt welche. 0 = bbbricklist, 1 = gamebricklist * @param i - Welche Liste * @param List<Brick> */ public void setBrickList(List<Brick> list, int i){ if(i == 0) bbbricklist = list; if(i == 1) gamebricklist = list; } /** * Gibt einen Brick aus einer List und Variable i sagt welche. 0 = bbbricklist, 1 = gamebricklist * @param b - der Brick der ausgegeben werden soll * @param i - welche List * @return einen Brick */ public Brick getBrick(Brick b, int i){ if(i == 0) return bbbricklist.get(bbbricklist.indexOf(b)); if(i == 1) return gamebricklist.get(gamebricklist.indexOf(b)); else throw new IllegalArgumentException(); } /** * Fügt einen Brick an eine der Listen an und Variable i sagt welche. 0 = bbbricklist, 1 = gamebricklist * @param b - der Brick welcher angefügt werden soll * @param rb - RenderBrick das ein neuer erstellt werden kann * @param i - welche List */ public void addBrick(Brick b, int i){ if(i == 0){ bbbricklist.add(b); } if(i == 1){ //mal schauen was noch kommt } } /** * Macht einer der Bricklisten leer und Variable i sagt welche. 0 = bbbricklist, 1 = gamebricklist * @param i - welche List */ public void clearBricklist(int i){ if(i == 0) bbbricklist.clear(); if(i == 1) gamebricklist.clear(); } /** * Hier kannst du nen Brick aus einer der Listen löschen und Variable i sagt welche. 0 = bbbricklist, 1 = gamebricklist * @param b - der zu löschende Brick * @param i - welche Liste */ public void delBrick(Brick b, int i){ if(i == 0) bbbricklist.remove(b); if(i == 1) gamebricklist.remove(b); } /** * Hier kannst du nen Brick aus einer der Listen löschen und Variable i sagt welche. 0 = bbbricklist, 1 = gamebricklist * @param b - der zu löschende Brick * @param i - welche Liste * @return der gelöschte Brick */ public Brick delBrickmReturn(Brick b, int i){ if(i == 0){ Brick hilf = b; bbbricklist.remove(b); return hilf; } else if(i == 1){ Brick hilf = b; gamebricklist.remove(b); return hilf; } else throw new IllegalArgumentException(); } /** * Hier gibt es alle Brick in einer Liste aus und Variable i sagt welche. 0 = bbbricklist, 1 = gamebricklist * @param i - welche Liste * @return Liste der Bricks als String */ public String allwrite(int i){ String s = "[ "; if(i == 0){ for(Brick b : bbbricklist){ s = "-->" + b.toString(); } return s; } else if(i == 1){ for(Brick b : gamebricklist){ s = "-->" + b.toString(); } return s; } else throw new IllegalArgumentException(); } /** * Hier wird gefragt ob die Bricks noch gezeichnet werden sollen und Variable i sagt welche aus welcher Liste. 0 = bbbricklist, 1 = gamebricklist * @param i - welche Liste */ public void sollGez(int i){ if(i == 0){ for(Brick b : bbbricklist){ if(b.getAktiv()) b.draw(b.getTexture()); } } else if(i == 1){ for(Brick b : gamebricklist){ if(b.getAktiv()) b.draw(b.getTexture()); } } else throw new IllegalArgumentException(); } /** * Hier wird eine Brick aus der Liste gelösche und eine neuer an die Maus angehangen um ihn an eine neue Position zu verschieben und Variable i sagt aus welcher Liste. 0 = bbbricklist, 1 = gamebricklist * @param i - welche Liste * @return Den neuen Brick */ public Brick verschiebeBrick(int i, int mausx, int mausy){ Brick brick = null; if(i == 0){ for(Brick b : bbbricklist){ if((mausx >= b.getPos().getX()) && (mausx <= b.getPos().getX() + b.getBreite()) && (mausy >= b.getPos().getY()) && (mausy <= b.getPos().getY() + b.getHoehe())){ brick = new Brick_Normal(b.getPos(), b.getBreite(), b.getHoehe(), b.getTexture()); } } return brick; } else if(i == 1){ for(Brick b : gamebricklist){ if((mausx >= b.getPos().getX()) && (mausx <= b.getPos().getX() + b.getBreite()) && (mausy >= b.getPos().getY()) && (mausy <= b.getPos().getY() + b.getHoehe())){ brick = new Brick_Normal(b.getPos(), b.getBreite(), b.getHoehe(), b.getTexture()); } } return brick; } else throw new IllegalArgumentException(); } /** * Zeichnet eine ganze Brickliste aus. Man muss nur sagen welche Liste. * @param i - Welche Liste. */ public void draw(int i){ List<Brick> l; if(i == 0) l = bbbricklist; else if(i == 1) l = gamebricklist; else throw new IllegalArgumentException(); if(!(l.isEmpty())){ for(Brick o : l){ o.draw(o.getTexture()); } } } }
5e02dc1ae81282fdc93fe5a59e21fa8b98db93fc
[ "Markdown", "Java" ]
8
Java
felix-scholz/bricker
4dfd6c38727e469a8e55e0512e9841ed755f8f8e
d8d85d7adfcb0e8de4019d8bf35bfe97ae5f5360
refs/heads/main
<file_sep>/* Crie um banco de dados para um serviço de RH de uma empresa, onde o sistema trabalhará com as informações dos funcionaries desta empresa. Crie uma tabela de funcionaries e utilizando a habilidade de abstração e determine 5 atributos relevantes dos funcionaries para se trabalhar com o serviço deste RH. Popule esta tabela com até 5 dados; Faça um select que retorne os funcionaries com o salário maior do que 2000. Faça um select que retorne os funcionaries com o salário menor do que 2000. Ao término atualize um dado desta tabela através de uma query de atualização. salve as querys para cada uma dos requisitos o exercício em um arquivo .SQL ou texto e coloque no seu GitHuB pessoal e compartilhe esta atividade.*/ create database db_recursosHumanos; use db_recursosHumanos; create table tb_funcionaries( id bigint auto_increment, nome varchar(255), idade int, sexo varchar(255), funcao varchar(255), salario decimal(8,3), primary key(id) ); insert into tb_funcionaries(nome, idade, sexo, funcao, salario) values ("<NAME>", 25, "Masculino", "Desenvolvedor Java Fullstrack Jr.", 5.000); insert into tb_funcionaries(nome, idade, sexo, funcao, salario) values ("<NAME>", 49, "Masculino", "Animador de platéia", 1.500); insert into tb_funcionaries(nome, idade, sexo, funcao, salario) values ("<NAME>", 28, "Feminino", "CEO", 90.000); insert into tb_funcionaries(nome, idade, sexo, funcao, salario) values ("<NAME>", 23, "Masculino", "Desenvolvedor Backend", 7.000); insert into tb_funcionaries(nome, idade, sexo, funcao, salario) values ("<NAME>", 75, "Masculino", "Lindo", 30.000); select * from tb_funcionaries where salario > 2.000; select * from tb_funcionaries where salario < 2.000; update tb_funcionaries set salario = 10.000 where id = 1; <file_sep>/* Crie um banco de dados para um e commerce, onde o sistema trabalhará com as informações dos produtos deste ecommerce. Crie uma tabela produtos e utilizando a habilidade de abstração e determine 5 atributos relevantes dos produtos para se trabalhar com o serviço deste ecommerce. Popule esta tabela com até 8 dados; Faça um select que retorne os produtos com o valor maior do que 500. Faça um select que retorne os produtos com o valor menor do que 500. Ao término atualize um dado desta tabela através de uma query de atualização. salve as querys para cada uma dos requisitos o exercício em um arquivo .SQL ou texto e coloque no seu GitHuB pessoal e compartilhe esta atividade.*/ create database db_ecommerce; use db_ecommerce; create table tb_produtos( id bigint auto_increment, produto varchar(255), fabricante varchar(255), quantidade int, preco decimal(8,2), categoria varchar(255), primary key(id) ); insert into tb_produtos(produto, fabricante, quantidade, preco, categoria) values ("Máscara respirador PPF2 GVS Aero 2", "GVS", 50, 5.90, "Máscaras de Segurança"); insert into tb_produtos(produto, fabricante, quantidade, preco, categoria) values ("Toca Discos At-lp60x", "Audio-technica", 1, 1848.99, "Toca-discos"); insert into tb_produtos(produto, fabricante, quantidade, preco, categoria) values ("Batedeira Stand Mixer Proline", "KitchenAid", 10, 4099.00, "Batedeiras"); insert into tb_produtos(produto, fabricante, quantidade, preco, categoria) values ("Hub USB-C", "Ugreen", 2, 429.00, "Informática"); insert into tb_produtos(produto, fabricante, quantidade, preco, categoria) values ("Webcam Logitech C920s", "Logitech", 200, 464.90, "Informática"); insert into tb_produtos(produto, fabricante, quantidade, preco, categoria) values ("Chaleira elétrica térmica", "Xiaomi", 3000, 259.00, "Eletrodomésticos"); insert into tb_produtos(produto, fabricante, quantidade, preco, categoria) values ("Console Playstation 4 Slim", "Sony", 5000, 2549.00, "Games"); insert into tb_produtos(produto, fabricante, quantidade, preco, categoria) values ("Xbox Series S", "Microsoft", 6000, 2870.00, "Games"); select * from tb_produtos where preco > 500; select * from tb_produtos where preco < 500; update tb_produtos set preco = 3099.00 where id = 4; <file_sep># exerciciosMYSQL Repositório com exercícios de MySQL realizandos durante o bootcamp da Generation Brasil
d7fff0a14812a1bd918614d2f2545c262831bcab
[ "Markdown", "SQL" ]
3
SQL
ihmorais/mysql-exercicios
f7379969e44ca520377e56cb7b93a77223c888ca
40da8df03dda585e0b699502739469678aff0d2a
refs/heads/master
<repo_name>ChristAren/SunsetHills<file_sep>/js/custom.js document.getElementById("SunsetA").addEventListener("click", SunsetHi); function SunsetHi(){ let nums=[1,4,2,7,4]; let currentMax = nums[0]; let seeCount = 1; let textOutput = `Building 1 with height of ${nums[0]} can see the sun <br />`; let outputArea = document.getElementById("see"); //I need to go through the array and check if each number is more than currentMax //But since I know the first building always sees the sun I can start my loop //at the second position for(let loop = 1; loop < nums.length; loop++){ if(nums[loop] > currentMax){ currentMax = nums[loop]; seeCount++; textOutput += `Building ${loop + 1} with height of ${nums[loop]} can see the sun <br />` } } outputArea.innerHTML = textOutput; // for(let maxNum=1; maxNum < loop.length; maxNum++){ // let bigger = false; // for(let loop= 0 ; loop < maxNum; loop++); // if (nums[loop] >= nums[maxNum]){ // bigger= true; // break; // } else { // continue; // } // } // bigger ? results.push("cant-see") || results.push("See"): // document.getElementById("See").innerText = results; }
47ba7a681910ca5fcbf30a40c25298d1b7d00144
[ "JavaScript" ]
1
JavaScript
ChristAren/SunsetHills
864a0d7c13e023bfdcfc326d68ea63e7367a3158
6f45a38bd01449250d6d6e4686e3c6b9f73c0d93
refs/heads/master
<repo_name>joalvarado2/pag-prueba<file_sep>/scripts/index.js var botton = document.getElementById("btn") var photo = document.getElementById("photo") var brand = document.getElementById("brand") const push = () =>{ var menu = document.getElementById("opcion-menu") if(menu.classList.contains("ocul-menu")){ menu.classList.remove("ocul-menu") menu.classList.add("most-menu") } else{ menu.classList.remove("most-menu") menu.classList.add("ocul-menu") } } botton.addEventListener("click", push) const change = (e) =>{ e.preventDefault() document.getElementById("foto1").src="./images/1.jpg" document.getElementById("foto2").src="./images/2.jpg" document.getElementById("foto3").src="./images/3.jpg" document.getElementById("foto4").src="./images/4.jpg" document.getElementById("foto5").src="./images/6.jpg" document.getElementById("foto6").src="./images/7.jpg" document.getElementById("foto7").src="./images/8.jpg" document.getElementById("foto8").src="./images/9.jpg" document.getElementById("foto9").src="./images/10.jpg" } brand.addEventListener("click", change) const cambiar = (e) =>{ e.preventDefault() document.getElementById("foto1").src="./images/11.jpg" document.getElementById("foto2").src="./images/12.jpg" document.getElementById("foto3").src="./images/13.jpg" document.getElementById("foto4").src="./images/14.jpg" document.getElementById("foto5").src="./images/15.jpg" document.getElementById("foto6").src="./images/16.jpg" document.getElementById("foto7").src="./images/17.jpg" document.getElementById("foto8").src="./images/18.jpg" document.getElementById("foto9").src="./images/19.jpg" } photo.addEventListener("click", cambiar)
10a503f24508cb1870a6fd4118ba5ff63f4ddbc9
[ "JavaScript" ]
1
JavaScript
joalvarado2/pag-prueba
bd872b634fc704fca1ab31a4e60cd644f31f9eb4
99647c3dace39436cc0f7580cc180d012c4e5084
refs/heads/master
<file_sep># --------- # This source file is part of the Dependency Extractor python open source package. # Copyright (c) 2021, <NAME>. # # Licensed under the MIT License. # --------- # Standard library. import os from os import name, path from typing import Set # Third party dependencies. from colorama import Fore # Local package dependencies. from .languages import supported_languages class SourceFile: def __init__(self, path): """ Retrieve any path and analyse all source file content for library dependencies. Parameters ---------- - `path : str` A string containing the full system path for the source file. - `language : ProgrammingLanguage` A ProgrammingLanguage object which indicates the programming language of this source file. """ if os.path.isfile(path): self.path: str = path else: raise TypeError self.name, self.extension = os.path.splitext(path) known = False for specific_language in supported_languages: if self.extension in specific_language.extensions: self.language = specific_language known = True if not known: raise NotImplementedError def dependencies(self, verbose: bool = False, strict: bool = False) -> Set: """ Read the source file and extract imported package names using regular expressions. """ # 0. Initialize empty set of discovered dependencies. found = set() # 1. When file is written in a supported language. # 1.1. When file isn't too large. # ----- # NOTE: Most source files for most use cases are not # expected to exceed 5MB in size (editable). try: # 1.1.1. Open file for reading. file = open(self.path, "r") if verbose: print("[dextractor]", end=" ") print(Fore.CYAN + "INFORMATION:", end=" ") print(f"Reading {os.path.basename(file.name)}") # 1.1.2. Match regex and obtain named capture group. if self.language.supports_grouped_dependencies: containerQuery = self.language.expressions["dependencies"]["container"] grouped = containerQuery.findall(file.read()) if grouped: query = self.language.expressions["dependencies"]["internal"] matches = query.findall(grouped[0]) else: query = self.language.expressions["dependencies"]["regular"] matches = query.findall(file.read()) if "matches" in locals(): found.update(matches) if not found and verbose: print("[dextractor]", end=" ") print(Fore.CYAN + "INFORMATION:", end=" ") print("This file doesn't include any dependencies.") # 1.1.3. Close file for memory optimisation. file.close() except IOError: print("[dextractor]", end=" ") print(Fore.RED + "ERROR:", end=" ") print(f"There was an IO error when trying to access the file '{name}'.") return found<file_sep># Testing This directory is populated at will when cloning the repository. It is recommended to clone a complex open source repository in this directory and run the tests. # How to To run unit tests using `unittest` on package modules: 1. Clone a repository into the `data` folder. 1. From this project's root, run: `python -m unittest tests/test-analyse.py` 1. The testing script will return all imports found in the source code of your chosen repository. <file_sep># --------- # This source file is part of the Dependency Extractor python open source package. # Copyright (c) 2021, <NAME>. # # Licensed under the MIT License. # --------- # # Define supported languages with their corresponding compiled import regex. # ----- # NOTE: Strict suffix queries exclude local and relative imports. # NOTE: These expressions were formulated with the help of https://regex101.com. import re from typing import List class ProgrammingLanguage: def __init__(self, name, extensions, expressions, supports_grouped_dependencies): self.name: str = name self.extensions: List[str] = extensions self.expressions = expressions self.supports_grouped_dependencies = supports_grouped_dependencies supported_languages = [ ProgrammingLanguage( "C++", extensions=[".cpp", ".hpp"], expressions={ "dependencies": { "regular": re.compile( r"#include [<\"](?P<dependency>[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':\"\\|,.<>\/?]+)[\">]" ), "strict": re.compile( r"#include [<\"](?P<dependency>[^.][a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':\"\\|,.<>\/?]+[^.hpp][^.h])[\">]" ), } }, supports_grouped_dependencies = False ), ProgrammingLanguage( "C", extensions=[".c", ".h"], expressions={ "dependencies": { "regular": re.compile( r"#include [<\"](?P<dependency>[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':\"\\|,.<>\/?]+)[\">]" ), "strict": re.compile( r"#include [<\"](?P<dependency>[^.][a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};':\"\\|,.<>\/?]+[^.hpp][^.h])[\">]" ), } }, supports_grouped_dependencies = False ), # TODO: #1 Needs improvement (it only reads last dependency in list + strict mode.) ProgrammingLanguage( "Go", extensions=[".go"], expressions={ "dependencies": { "container": re.compile( r"import[\s]+\((?P<list>[a-zA-Z0-9!@#$%^&*_+\-\[\]{};':\"\s\\.\/?]+)\)" ), "internal": re.compile( r"[\s]+\"(?P<dependency>.*)\"" ) } }, supports_grouped_dependencies = True ), ProgrammingLanguage( "Java", extensions=[".java"], expressions={ "dependencies": { "regular": re.compile( r"import (?P<dependency>[a-zA-Z0-9!@#$%^&*_+\-\[\]{};':\"\\.\/?]+);" ) } }, supports_grouped_dependencies = False ), ProgrammingLanguage( "Python", extensions=[".py", ".pyi"], expressions={ "dependencies": { "regular": re.compile( r"^(?:[ ]|)+(?:import|from) (?P<dependency>[^_][a-zA-Z0-9!@#$%^&*()_+\-\[\]{}.;':\"\\\/?]+)" ), "strict": re.compile( r"^(?:[ ]|)+(?:import|from) (?P<dependency>[^_.][a-zA-Z0-9!@#$%^&*()_+\-\[\]{};':\"\\\/?]+)" ), } }, supports_grouped_dependencies = False ), ProgrammingLanguage( "JavaScript", extensions=[".json"], expressions={ "dependencies": { "container": re.compile( r"\"dependencies\":[ |]{(?P<list>[a-zA-Z0-9!@#$%^&*_+\-\[,\];':\"\s\\.\/?]+)" ), "internal": re.compile( r"[\s]+\"(?P<dependency>.*)\":" ) } }, supports_grouped_dependencies = True ), ]<file_sep># --------- # This testing file is part of the Dependency Extractor python package. # Copyright (c) 2021, <NAME>. # # Licensed under the MIT License. # --------- import unittest import os from pprint import pprint from dextractor import analyse if os.getcwd().endswith("dependency-extractor") == False: raise Exception( """ -------------------- ERROR -------------------- Please launch the script from the root directory of the dextractor package. ----------------------------------------------- """ ) class LanguageTest(unittest.TestCase): dir_path = os.path.dirname(os.path.realpath(__file__)) def test_data_analysis(self): """ Test using the data directory. """ results = analyse(os.getcwd() + "/tests/data",5000000,True,True) if not results: print("\nNo results were returned.") else: pprint(results, compact=True) if __name__ == "__main__": unittest.main()<file_sep># --------- # This source file is part of the Dependency Extractor python open source package. # Copyright (c) 2021, <NAME>. # # Licensed under the MIT License. # --------- # # Define a list of known configuration files, file extensions and names to be ignored. configuration_files = [ "Dockerfile", "Makefile", "docker-compose.yml", "serverless.yaml", "serverless.yml" ] ignored_files = [ ".gitignore", ".DS_Store", "README", "LICENSE", "MAINTAINERS", "BUGS", "CONTRIBUTING", "CONTRIBUTORS", "AUTHORS", "PATENTS", ] ignored_extensions = [ ".png", ".ico", ".jpg", ".svg", ".tiff", ".yml", ".yaml", ".rst", ".json", ".xml", ".html", ".har", ".properties", ".plist", ".all", ".txt", ".doc", ".xls", ".ppt", ".docx", ".xlsx", ".pptx", ".csv", ".jmx", ".cmd", ".sh", ".mod", ".sum", ".tpl", ".npy", ".npz", ".ini", ".inc", ]<file_sep># --------- # This source file is part of the Dependency Extractor python open source package. # Copyright (c) 2021, <NAME>. # # Licensed under the MIT License. # --------- # Standard library. import os from posixpath import lexists from typing import Set, List # Third party dependencies. import colorama from colorama import Fore # Local dependencies. from .src.parser import SourceFile from .src.exclusions import configuration_files, ignored_files, ignored_extensions def analyse( any_path: str, max_file_size=5000000, strict=False, verbose=False, ) -> Set: """ Retrieve any path and analyse for configuration files and source file library dependencies. Parameters ---------- - `any_path : str` A string containing a valid system path which is accessible from this script. - `max_file_size : int` A integer indicating the byte limit of source files to be read. This is useful for directories were irrelevant large data sets are also included. - `strict : bool` A flag which excludes internal and relative packages. - `verbose : bool` Enables verbose output for each scanned file. """ # 0. Setup # - 0.1. Directory coverage counter. coverage_counter = 0 ignored_counter = 0 # - 0.2 Initialise colorama. colorama.init(autoreset=True) # 0. Initialise empty dependencies array. dependencies = set() configurations = set() results = {} # 1. Process given path. if os.path.isdir(any_path): total_file_count = 0 # 1.1. When the given path points to a directory, # recursively check the directory tree for all files. for root, _, files in os.walk(any_path): # 1.1.1. Traverse all available files. for file in files: try: # 1.1.2. Check for supported language and size. if os.stat(os.path.join(root, file)).st_size < max_file_size: if ( os.path.splitext(file)[0] + os.path.splitext(file)[1] in configuration_files ): configurations.update( {os.path.splitext(file)[0] + os.path.splitext(file)[1]} ) if ( (os.path.splitext(file)[0] not in ignored_files) and ( os.path.splitext(file)[0] + os.path.splitext(file)[1] not in configuration_files ) and (os.path.splitext(file)[1] not in ignored_extensions) or ( os.path.splitext(file)[0] + os.path.splitext(file)[1] == "package.json" ) ): # 1.1.3. Extract dependencies. source_file = SourceFile(os.path.join(root, file)) dependencies.update( source_file.dependencies(verbose, strict) ) coverage_counter += 1 else: ignored_counter += 1 raise TypeError else: raise MemoryError except TypeError: if verbose: print("[dextractor]", end=" ") print(Fore.YELLOW + "NOTICE:", end=" ") print(f"The file '{file}' does not contain source code.") except NotImplementedError: if verbose: print("[dextractor]", end=" ") print(Fore.YELLOW + "NOTICE:", end=" ") print(f"The file '{file}' is not yet supported by this module.") except MemoryError: if verbose: print("[dextractor]", end=" ") print(Fore.YELLOW + "NOTICE:", end=" ") print(f"The file '{file}' is too large and will be ignored.") except IOError: print("[dextractor]", end=" ") print(Fore.RED + "ERROR:", end=" ") print(f"The file '{file}' could not be accessed.") # 1.1.4 Update total file count. total_file_count += len(files) # 1.1.5. Extract statistics. if verbose and len(files) > 0 and coverage_counter > 0: print("[dextractor]", end=" ") print(Fore.GREEN + "SUCCESS:") print( f""" - - - - - - - | Files detected under {round(max_file_size/1000000,1)}MB: {total_file_count} | Files scanned: {coverage_counter} | Non-source files ignored: {ignored_counter} | Unsupported files: {total_file_count-coverage_counter-ignored_counter} | Source file coverage: {round(coverage_counter/(total_file_count-ignored_counter),3)*100}% | Dependencies found: {len(dependencies)} - - - - - - - """ ) elif os.path.isfile(any_path): # 1.2. When the given path points to a single file. # ----- # NOTE: Exception descriptions are different when # running the script for a single file. filename, extension = os.path.splitext(any_path) try: source_file = SourceFile(any_path) dependencies.update(source_file.dependencies(verbose, strict)) # 1.1.2. Check for supported language and size. if os.stat(any_path).st_size < max_file_size: if (os.path.splitext(source_file)[0] not in ignored_files) and ( os.path.splitext(source_file)[1] not in ignored_extensions ): # 1.1.3. Extract dependencies. source_file = SourceFile(any_path) dependencies.update(source_file.dependencies(verbose, strict)) coverage_counter += 1 else: ignored_counter += 1 raise TypeError else: raise MemoryError except TypeError: if verbose: print("[dextractor]", end=" ") print(Fore.RED + "ERROR:", end=" ") print( f"The file '{os.path.basename(filename)}{extension}' is not a source file." ) except NotImplementedError: if verbose: print("[dextractor]", end=" ") print(Fore.YELLOW + "NOTICE:", end=" ") print( f"The file '{os.path.basename(filename)}{extension}' is not yet supported by this module." ) except MemoryError: if verbose: print("[dextractor]", end=" ") print(Fore.RED + "ERROR:", end=" ") print( f"The file '{os.path.basename(filename)}{extension}' is too large." ) except IOError: if verbose: print("[dextractor]", end=" ") print(Fore.RED + "ERROR:", end=" ") print( f"The file '{os.path.basename(filename)}{extension}' could not be accessed." ) else: raise Exception( "This is not a file or a directory. It might be a special file (e.g. socket, FIFO, device file), which is unsupported by this package. " ) results["configurations"] = list(configurations) results["dependencies"] = list(dependencies) return results<file_sep># Dependency Extractor A Python library which extracts library dependencies from source files written in most mainstream programming languages. ** :warning: Warning: This library is not meant for production use, as extended testing has not been carried out yet.** ## Getting started Follow the steps below to get started with `dextractor`. ### Installation This package can be installed easily via `pip`. Run the commands below: ```bash # Clone or download the .zip from the Releases tab. git clone https://www.github.com/alexandrosraikos/dependency-extractor # Navigate to the folder. cd dependency-extractor # Install locally pip install . ``` ### Usage It is meant to be imported and called via a single module, which returns a `Dictionary` of dependencies given a single file or a directory. ```python from dextractor import analyse # Use all default parameters. result = analyse("path/to/file/or/directory") # Define a different maximum file size (in bytes). result = analyse("path/to/file/or/directory", max_file_size=2000000) # <- 2MB # Ignore local and relative dependencies. result = analyse("path/to/file/or/directory", strict=True) # Enable verbose output. NOTE: Do not enable on parallel analyses. result = analyse("path/to/file/or/directory", verbose=True) # # Then you can access the following keys: # -- dependencies = result["dependencies"] configurations = result["configurations"] ``` ## Unit testing Please consult the README in the `tests` folder. ## Supported languages All languages which are supported are still in alpha. Regular expressions which detect imports in source files must be polished and updated with the nuances of each programming language. Currently the supported languages are: 1. C/C++ 1. Go 1. Python (_duh!_) 1. Java 1. JavaScript
12e0751e42b1be57b3838b439beefe89adf63304
[ "Markdown", "Python" ]
7
Python
dacresearchgroup/c137-morphemic-dependency-extractor
dbf8d4651d6708cd70b4920f8b02da1ee8409817
537c01fe44d090fc19917c535df6991fdd266153
refs/heads/master
<repo_name>Rannys/todoredux<file_sep>/src/container/todo.js import React, { Component } from 'react' import { connect } from 'react-redux' import { AddBtn } from '../actions/todoAction' import uuid from 'react-uuid' import { Delete, Complete, Edit } from '../actions/todoAction' import { Card, Button } from 'react-bootstrap' class Todos extends Component { constructor(props) { super(props) this.state = { text: '', edit: false } } handleChange = e => { this.setState({ text: e.target.value }) } // setUpdate = e =>{ // this.setState({ // newText:e.target.value // }) // } saveTodo = todo => { this.setState({ ...todo, edit: true }) } addOrEdit = () => { if (this.state.edit) { this.props.editNewTodo(this.state) this.setState({ text: '', edit: false }) } else { this.props.addNewTodo({ text: this.state.text, id: uuid(), complete: false }) this.setState({ text: '', edit: false }) } } render() { return ( <div > <div className='d-flex justify-content-center header '> <input type='text' className='form-control' onChange={this.handleChange} value={this.state.text} /> <Button variant='primary' className='btn btn-default' onClick={this.addOrEdit}>{this.state.edit ? 'Edit' : 'ADD'}</Button> </div> <div className='d-flex flex-column added'> {this.props.allTodos.map(el => <div> <h4 className={el.complete ? 'todoDone' : 'todoNotDone'}>{el.text}</h4> <Button variant='primary' onClick={() => this.props.newTodoCompleted(el.id)}>{el.complete ? 'undo' : 'complete'}</Button> <Button variant='primary' onClick={() => this.props.deleteNewTodo(el.id)}>delete</Button> <Button variant='primary' onClick={() => this.saveTodo(el)}>Edit</Button> </div>)} </div> </div > ) } } const mapStateToProps = state => { return { allTodos: state.todo } } const mapDispatchToprops = dispatch => { return { addNewTodo: todo => dispatch(AddBtn(todo)), deleteNewTodo: id => dispatch(Delete(id)), newTodoCompleted: done => dispatch(Complete(done)), editNewTodo: edited => dispatch(Edit(edited)) } } export default connect(mapStateToProps, mapDispatchToprops)(Todos)<file_sep>/src/actions/type.js export const ADD_TODO = 'ADD_TODO' export const DELETE_BTN ='DELETE_BTN' export const COMPLETE_BTN ='COMPLETE_BTN' export const EDIT_BTN='EDIT_BTN'<file_sep>/src/reducers/todoReducers.js import { ADD_TODO, DELETE_BTN,COMPLETE_BTN , EDIT_BTN } from "../actions/type" let initState = [] const TodoReducer = (state = initState, action) => { switch (action.type) { case ADD_TODO: return state.concat(action.payload); break; case DELETE_BTN: return state.filter(el => action.payload !== el.id) break; case COMPLETE_BTN: return state.map(el => el.id === action.payload ? {...el, complete : !el.complete}: el) break; case EDIT_BTN: return state.map(el=> el.id === action.payload.id ? action.payload : el) default: return state } } export default TodoReducer
7c13c66fb7349ec8a7daeb6e096208b1d96ee93a
[ "JavaScript" ]
3
JavaScript
Rannys/todoredux
1330e23cf5f88828cb5e62fb6e99ef74f61f9fb4
aaf77d05bee924ccb70afc28d962b4037c15c94c
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel.Core; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI; using Windows.UI.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace UFanWriter { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true; ApplicationViewTitleBar titleBar = ApplicationView.GetForCurrentView().TitleBar; titleBar.ButtonBackgroundColor = Colors.Transparent; titleBar.ButtonInactiveBackgroundColor = Colors.Transparent; Window.Current.SetTitleBar(DraggableTitlebar); } // Open sidebar private void SidebarBtn_Click(object sender, RoutedEventArgs e) { SV_Sidebar.IsPaneOpen = !SV_Sidebar.IsPaneOpen; } // Settings flyout closing private void Flyout_Closing(FlyoutBase sender, FlyoutBaseClosingEventArgs args) { PaperColourBtn.Foreground = new SolidColorBrush(PaperColorPicker.Color); } // Handle menu buttons private void Sidebar_ItemClick(object sender, ItemClickEventArgs e) { var dbg = e.ClickedItem as Grid; MainTextBlock.PlaceholderText += dbg.Name + Environment.NewLine; } // Color picker changing color private void PaperColorPicker_ColorChanged(ColorPicker sender, ColorChangedEventArgs args) { PaperColourBtn.Foreground= new SolidColorBrush(PaperColorPicker.Color); ToolbarGrid.Background = new SolidColorBrush(PaperColorPicker.Color); MainTextBlock.Background = new SolidColorBrush(PaperColorPicker.Color); } } }
81fafdc7fc36e0f62eebdce5320de4039f74b3d3
[ "C#" ]
1
C#
Atulin/UFanWriter
0b96048fe98b203ed21729eef8423a8cecb813f5
ffdc9b88e1b34391acc6e6dfa1935409f6985b8f
refs/heads/master
<file_sep># -*- coding:utf-8 -*- from flask_wtf import FlaskForm from wtforms import StringField, SubmitField from wtforms.validators import Length, DataRequired, URL from flask_pagedown.fields import PageDownField from flask_wtf.file import FileField, FileAllowed from app import avatars class EditProfileForm(FlaskForm): name = StringField(u'<NAME>', validators=[DataRequired(message=u"Please fill out!"), Length(1, 64, message=u"1 to 64 characters")]) major = StringField(u'Major', validators=[Length(0, 128, message=u"0 to 128 characters")]) headline = StringField(u'Intro', validators=[Length(0, 32, message=u"32 characters")]) about_me = PageDownField(u"Introduction") submit = SubmitField(u"Save Changes") class AvatarEditForm(FlaskForm): avatar_url = StringField('', validators=[Length(1, 100, message=u"100 characters"), URL(message=u"Correct URL")]) submit = SubmitField(u"Save") class AvatarUploadForm(FlaskForm): avatar = FileField('', validators=[FileAllowed(avatars, message=u"Only pictures allowed")]) <file_sep>import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_login import LoginManager from flask_bootstrap import Bootstrap from flask_pagedown import PageDown from flask_uploads import UploadSet, IMAGES, configure_uploads app = Flask(__name__) app.config.from_object('config') db = SQLAlchemy(app) lm = LoginManager(app) bootstrap = Bootstrap(app) pagedown = PageDown(app) avatars = UploadSet('avatars', IMAGES) configure_uploads(app, avatars) from app.main import main, auth, user, book, comment, log from app.api import api_bp for blueprint in [main, auth, user, book, comment, log, api_bp]: app.register_blueprint(blueprint) from app import models exists_db = os.path.isfile(app.config['DATABASE']) if not exists_db: from . import db_fill from flask import render_template from werkzeug.exceptions import HTTPException @app.errorhandler(Exception) def handle_err(e): code = 500 if isinstance(e, HTTPException): code = e.code if code == 404: return render_template('404.html'), 404 elif code == 500: return render_template('500.html'), 500 #return jsonify(error=str(e)), code<file_sep>from os import environ from app import app if __name__ == '__main__': # app.run(debug=True, host='0.0.0.0') HOST = environ.get('SERVER_HOST', 'localhost') try: PORT = int(environ.get('SERVER_PORT', '5555')) except ValueError: PORT = 5555 #app.run(debug=True, host=HOST, port=PORT) app.run(host=HOST, port=PORT) # Just for the fun, python easter eggs, spam and egg # from __future__ import braces # import this; print(this.s) # import __hello__ # import antigravity # from antigravity import geohash # geohash(37.421542, -122.085589, b'2005-05-26-10458.68') # and it's Monty Python not the reptile<file_sep>aniso8601==4.1.0 bleach==3.1.0 Click==7.0 dominate==2.3.5 Flask==1.0.2 Flask-Bootstrap==3.3.7.1 Flask-Login==0.4.1 Flask-PageDown==0.2.2 Flask-RESTful==0.3.7 Flask-SQLAlchemy==2.3.2 Flask-Uploads==0.2.1 Flask-WTF==0.14.2 html5lib==1.0.1 itsdangerous==1.1.0 Jinja2==2.10 Markdown==3.0.1 MarkupSafe==1.1.0 python-dateutil==2.7.5 pytz==2018.9 six==1.12.0 SQLAlchemy==1.2.16 visitor==0.1.3 webencodings==0.5.1 Werkzeug==0.14.1 WTForms==2.2.1 IMDbPY==6.6 Pillow==5.4.1 itsdangerous==1.1.0 numpy==1.16.1 pandas==0.24.1 wsgiref==3.5 <file_sep># -*- coding:utf-8 -*- from app.models import Book from flask_pagedown.fields import PageDownField from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, IntegerField from wtforms import ValidationError from wtforms.validators import Length, DataRequired, Regexp class EditBookForm(FlaskForm): isbn = StringField(u"IMDb#", validators=[DataRequired(message=u"This item forgot to fill in!"), Regexp('[0-9]{13,13}', message=u"IMDb# must be 13 digits")]) title = StringField(u"title", validators=[DataRequired(message=u"Please fill it out!"), Length(1, 128, message=u"1 to 128 characters in length")]) #origin_title = StringField(u"Original name", validators=[Length(0, 128, message=u"0 to 128 characters in length")]) subtitle = StringField(u"Subtitle", validators=[Length(0, 128, message=u"0 to 128 characters in length")]) author = StringField(u"Stars", validators=[Length(0, 128, message=u"0 to 64 characters in length")]) #translator = StringField(u"Translater", validators=[Length(0, 64, message=u"0 to 64 characters in length")]) #publisher = StringField(u"Publisher", validators=[Length(0, 64, message=u"0 to 64 characters in length")]) image = StringField(u"Cover Address", validators=[Length(0, 128, message=u"0 to 128 characters in length")]) #pubdate = StringField(u"Publish Date", validators=[Length(0, 32, message=u"0 to 32 characters in length")]) tags = StringField(u"Tag", validators=[Length(0, 128, message=u"0 to 128 characters in length")]) #pages = IntegerField(u"Pages") #price = StringField(u"Price", validators=[Length(0, 64, message=u"0 to 32 characters in length")]) #binding = StringField(u"Binding", validators=[Length(0, 16, message=u"0 to 16 characters in length")]) #numbers = IntegerField(u"Collection", validators=[DataRequired(message=u"Please fill it out!")]) summary = PageDownField(u"Brief introduction") catalog = PageDownField(u"Catalogue") submit = SubmitField(u"Save Changes") class AddBookForm(EditBookForm): def validate_isbn(self, filed): if Book.query.filter_by(isbn=filed.data).count(): raise ValidationError(u'The same IMDb# already exists and cannot be entered. Please check carefully whether the movie is in record.') class SearchForm(FlaskForm): search = StringField(validators=[DataRequired()]) submit = SubmitField(u"Search") <file_sep># -*- coding:utf-8 -*- from flask_wtf import FlaskForm from wtforms import SubmitField, TextAreaField from wtforms.validators import Length, DataRequired class CommentForm(FlaskForm): comment = TextAreaField(u"Your reviews", validators=[DataRequired(message=u"Contents cannot be blank"), Length(1, 5120, message=u"Reviews are 5120 characters only")]) submit = SubmitField(u"Post")
4cde269c661c0099874bd01b19e5051602c38885
[ "Python", "Text" ]
6
Python
chanmadeleine/Stint
ec8e6c16cae1603a361e89d09ec92d7e9630afeb
296e25135bdb758e3f2cf1c12860fb711c26e9c1
refs/heads/master
<repo_name>wnqnguo/MyReactApp<file_sep>/src/components/Landing.jsx import React, { Component } from 'react'; import SearchBar from './SearchBar' import Weekend from './Weekend' import Header from './Header' export default class Landing extends Component { render() { return ( <div> <Header /> <SearchBar /> <Weekend /> </div> ); } } <file_sep>/src/components/SearchDropDown.jsx import React, { Component } from'react'; import ReactDOM from 'react-dom'; import DatePicker from './DatePicker' var moment = require('moment'); export default class SearchDropDown extends Component{ constructor(props){ super(props); this.state = { focusedInput: null, startDate: null, endDate: null}; this.getInitialState = this.getInitialState.bind(this); this.handleChange = this.handleChange.bind(this); this.fetchSearchResult = this.fetchSearchResult.bind(this); } getInitialState(){ return { startDate: moment() }; } fetchSearchResult(event){ this.props.fetchSearchResult(event) } componentDidMount(){ $('.datepicker').datepicker(); } handleChange(date) { this.setState({ startDate: date }); } checkBoxChange(event){ console.log("event is",event); } render(){ return( <div id="header-search-settings" className="search-dropdown"> <div className="search-dropdown panel header-menu"> <div className="row row-condensed"> <div className="col-sm-9"> <div className="row row-condensed"> <div className="col-sm-4"> <DatePicker/> </div> <div className="col-sm-4"> <DatePicker/> </div> </div> </div> <div className="col-sm-3" > <div className="form-group"> <label for="header-search-guests" className="field-label">Guests</label> <div className="select select-block"> <select id="header-search-guests" name="guests"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> </div> </div> </div> <fieldset> <div className="panel panel-default"> <div className="panel-header menu-header"> <legend>Room type</legend> </div> <div className="panel-body"> <div> <label className="menu-item"> <input name="radio" type="radio" /> <i className="icon icon-private-romom-horizontal-margin-medium"/> <span>Entire home/apt</span> </label> <label className="menu-item"> <input name="radio" type="radio" /> <i className="icon icon-private-romom-horizontal-margin-medium"/> <span>Private room</span> </label> <label className="menu-item"> <input name="radio" type="radio" onChange={this.checkBoxChange} /> <i className="icon icon-private-romom-horizontal-margin-medium"/> <span>Shared room</span> </label> </div> </div> </div> </fieldset> <div className="panel-body"> <button className="btn btn-primary btn-block" onClick={this.fetchSearchResult}> <i className ="icon icon-search"/> <span>Find a place</span> </button> </div> </div> </div> ) } }<file_sep>/src/components/GoogleMap.jsx import React, { Component } from'react'; import ReactDOM from 'react-dom'; export default class GoogleMap extends Component { componentDidMount(){ var mapOptions = { center: { lat: -34.397, lng: 150.644}, zoom: 8 }; new google.maps.Map(ReactDOM.findDOMNode(this.refs.map_canvas), mapOptions); } render() { var container={ width: '100%', height:'300px' } var mapStyle={ width: '100%', width: '100%' } return ( <div className= "map_container" style={container}> <div className ="map"ref="map_canvas" style={mapStyle} ></div> </div> ); } }<file_sep>/src/components/Header.jsx import React, { Component } from'react'; import SearchBar from './SearchBar' export default class Header extends Component{ render(){ return( <div className="header-container"> <header> <div className="container"> <div className="row"> <div className="col-lg-12"> <img className="img-responsive" src="../../style/assets/Header.jpg" alt=""/> </div> </div> </div> </header> </div> ) } }<file_sep>/src/routes.js import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/app'; import PostIndex from './components/PostIndex'; import Landing from './components/Landing'; import Listings from './components/Listings'; const Greeting = () => { return <div>Hey there!</div>; }; export default ( <Route path="/" component={App} > <IndexRoute component = {Landing} /> <Route path="great" component ={Greeting} /> <Route path='listings' component ={Listings} /> </Route> );<file_sep>/src/components/Weekend.jsx import React, { Component } from'react'; export default class Weekend extends Component{ render(){ return( <div> <section id="portfolio"> <div className="container"> <div className="row carousel-item"> <div className="col-lg-12 text-center"> <h2>Just For The Weekend</h2> </div> </div> <div className="row"> <div className="col-sm-4 portfolio-item"> <img src="../../style/assets/napa.jpg" className="img-responsive" alt=""/> </div> <div className="col-sm-4 portfolio-item"> <img src="../../style/assets/sonoma.jpg" className="img-responsive" alt=""/> </div> <div className="col-sm-4 portfolio-item"> <img src="../../style/assets/santa-cruz.jpg" className="img-responsive" alt=""/> </div> </div> <div className="row"> <div className="col-sm-12 col-lg- col-lg-offset-4 space-top-4 hide-sm"> <a href="" className="btn btn-large btn-block"> See All Destinations </a> </div> </div> </div> </section> </div> ) } }
233086777cbb38ccbf561bddd529d46e1b8925d7
[ "JavaScript" ]
6
JavaScript
wnqnguo/MyReactApp
b6a7846c37b6e1c597654989cd88b01747496b0a
d4dec60cb965ad563bbf2aea550336aff51c8b93
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Random_Matcher { class Program { static void Main(string[] args) { List<int> Players = new List<int>(); Console.WriteLine("Enter IDs of players and enter non-integral value to finish"); string EnteredPlayer = Console.ReadLine(); int enteredPlayerId = 0; while (int.TryParse(EnteredPlayer, out enteredPlayerId)) { Players.Add(enteredPlayerId); EnteredPlayer = Console.ReadLine(); } Console.WriteLine(); Console.WriteLine("Matches"); Random rnd = new Random(); int TotalMatches = (int)Math.Floor((double)Players.Count / 2); for (int i = 0; i < TotalMatches; i++) { int playerIndex = rnd.Next(Players.Count); Console.Write(Players[playerIndex].ToString() + " vs "); Players.RemoveAt(playerIndex); int opponentIndex = rnd.Next(Players.Count); Console.WriteLine(Players[opponentIndex].ToString()); Players.RemoveAt(opponentIndex); } if (Players.Count > 0) Console.WriteLine("Bye: " + Players[0]); Console.ReadKey(); } } }
8a51a91d302e6e9829fb1cd53b11e70818585068
[ "C#" ]
1
C#
ajayRaghav37/Random-Matcher
5871e07706054b241669bc15a41e35502398356d
b87c1e29aa75e75e609bce5e684fc35e84d44b0f
refs/heads/master
<repo_name>Tahsinoshin/test<file_sep>/evensum.c #include<stdio.h> int main(){ int i,j=2,n,sum=0; printf("Enter the number of even number:"); scanf("%d",&n); printf("The even numbers are:"); for(i=1;i<=n;i++){ printf("%d ",j); j=j+2; } j=2; for(i=1;i<=n;i++){ sum=sum+j; j=j+2; } printf("\nThe sum of even numbers is:%d",sum); return 0; }
1a8613eeb01e686b8245bb12edeb913221ce1162
[ "C" ]
1
C
Tahsinoshin/test
80ca844f1d9760db5ff36fe3b28baa03b5983ccf
55d852079b95599cae6fd692a2fb9ed7fde3ecb1
refs/heads/master
<file_sep>/* Using recursion return the number of leaf nodes and non leaf nodes from a single method without any global variables for a given BST */ #include <stddef.h> typedef struct Node Node; struct Node { int val; Node* left; Node* right; }; int func(Node* root)//number of leaf { if(root == NULL) return 0; if((root->left == NULL) //root is leaf && (root->right == NULL)) { printf("%d\n", root->val); return 1; } return func(root->left) + func(root->right); } int func2(Node* root)//number of non-leaf { int root_non_leaf = 0; if(root == NULL) return 0; if((root->left == NULL) // root is leaf && (root->right == NULL)) return 0; printf("%d\n", root->val); return 1 + func2(root->left) + func2(root->right); } Node nodes[11]; void init_tree() { nodes[0].val = 8; nodes[0].left = &nodes[1]; nodes[0].right = &nodes[2]; nodes[1].val = 3; nodes[1].left = &nodes[3]; nodes[1].right = &nodes[4]; nodes[2].val = 10; nodes[2].left = NULL; nodes[2].right = &nodes[6]; nodes[3].val = 1; nodes[3].left = NULL; nodes[3].right = NULL; nodes[4].val = 6; nodes[4].left = NULL; nodes[4].right = NULL; //nodes[5] nodes[6].val = 14; nodes[6].left = NULL; nodes[6].right = NULL; } int main() { int sum=0; init_tree(); //sum = func(&nodes[0]); sum = func2(&nodes[0]); printf("%d", sum); return 0; }
b3916786982e2a764e8057f3036f4e5d9093393b
[ "C" ]
1
C
laohixdxm/careercup
a731864736207ac8cc0baa0c45d83d151e0a2d64
730146d7d2b81bf9f76d973b94217a956c3ae670
refs/heads/master
<repo_name>ChenShuai1981/ssp-archive<file_sep>/ansible/genconf.py # coding=utf-8 import os import sys import yaml import jinja2 from jinja2 import Environment,PackageLoader _workdir=os.getcwd() _templatedir=os.path.join(_workdir,'templates') def getTemplateFile(): templateFiles=os.listdir(_templatedir); return templateFiles def renderFile(template,d): env = Environment(loader=PackageLoader(sys.argv[0][:-3],'templates'),undefined=jinja2.StrictUndefined) template = env.get_template(template) return template.render(**d) + '\n' def writeConf(d,c,n): if not os.path.exists(d): os.makedirs(d) fn = os.path.join(d, n) with open(fn, 'w') as f: f.write(c) os.chmod(fn, 0o755) def main(): targetEnv=sys.argv[1] if len(sys.argv)>1 else 'local' targetDir=os.path.join(_workdir,'target',targetEnv) confDir=os.path.join(_workdir,'src') confFile=confDir+'/'+targetEnv+'.yaml' with open(confFile,'r') as f: _renderVar=yaml.load(f) tf=getTemplateFile() for file in tf: writeConf(targetDir,renderFile(file,_renderVar[file]),file) if __name__ == '__main__': main() print('\ngenerated configuration files success!\n') os._exit(1) <file_sep>/build/tools/functions.sh #!/bin/bash # Modify Date: 20151123 function print_task() { local TITLE=$1 && local LINE_LENGTH=80 && local PAD=$(printf '%0.1s' "="{1..60}) local LEFT_PADDING=$((($LINE_LENGTH-${#TITLE})/2)) && local RIGHT_PADDING=$(($LINE_LENGTH-${#TITLE}-$LEFT_PADDING)) printf "\n\n\033[33m%.*s%s%.*s\033[0m\n\n" $((LEFT_PADDING)) "${PAD}" "${TITLE}" $((RIGHT_PADDING)) "${PAD}" } function cleanup_container() { local CONTAINER_NAME=$1 echo "Looking for container [ ${CONTAINER_NAME} ]" && local MESSAGE=" ===> Stop running container [ ${CONTAINER_NAME} ]" docker ps -a | grep -e "[[:space:]]${CONTAINER_NAME}[[:space:]]" && echo "${MESSAGE}" && docker rm -f "${CONTAINER_NAME}" || echo } function cleanup_image() { local IMAGE_NAME=$1 local TAG_NAME=$2 if [[ -z "${TAG_NAME}" ]]; then TAG_NAME="latest"; fi echo "Looking for image [ ${IMAGE_NAME} ]" && local MESSAGE=" ===> Remove older image [ ${IMAGE_NAME}:${TAG_NAME} ]" docker images | grep -e "${IMAGE_NAME}[[:space:]]" | grep -e "[[:space:]]${TAG_NAME}[[:space:]]" && echo "${MESSAGE}" && docker rmi -f "${IMAGE_NAME}:${TAG_NAME}" || echo } function cleanup_folder_files() { local FOLDER_PATH=$1 local MESSAGE="Remove legacy files [ ${FOLDER_PATH} ]" if [ -d "${FOLDER_PATH}" ]; then echo "${MESSAGE}" && rm -rf "${FOLDER_PATH}" || echo; fi }<file_sep>/bin/startup.sh #!/usr/bin/env bash if [ $# -ne 3 ] then echo "Usage: startup.sh <ENV> <AKKA_PORT> <HTTP_PORT>, ENV options: local, dev, qa" exit fi ENV=$1 AKKA_PORT=$2 HTTP_PORT=$3 cd `dirname $0`/../ansible #rm target/${ENV}/* echo "generating configuration files ......" python genconf.py ${ENV} cd .. echo "launching application ......" #sbt -Dlogback.configurationFile=./ansible/target/${ENV}/logback.xml "runMain com.vpon.ssp.report.dedup.Main -c ./ansible/target/${ENV}/application.conf" sbt -DPORT=${AKKA_PORT} -Dlogback.configurationFile=./ansible/target/dev/logback.xml "runMain com.vpon.ssp.report.archive.Main -c ./ansible/target/dev/application.conf -h ${HTTP_PORT}" <file_sep>/build/build.sh #!/bin/bash BUILD_NUM=$1 BUILD_TAG=$2 BUILD_FOLDER="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" PROJECT_PATH="$( cd "$( dirname "${BUILD_FOLDER}" )" && pwd )" PROJECT_NAME=`grep "val Name" ${PROJECT_PATH}/project/build.scala | awk -F\" '{print $2}'` PROJECT_VERSION=`grep "val Version" ${PROJECT_PATH}/project/build.scala | awk -F\" '{print $2}'` IMAGE_NAME="192.168.105.243:5000/vpon/${PROJECT_NAME}-${BUILD_TAG}-v${PROJECT_VERSION}" DOCKER_FILES_FOLDER="${BUILD_FOLDER}/docker_packager" DOCKER_CONTAINER_NAME="${PROJECT_NAME}-build-files-holder-${BUILD_TAG}" DOCKER_TAG_COMPILE="${PROJECT_NAME}-build-compile-${BUILD_TAG}-tmp" DOCKER_TAG_PACKAGE="${PROJECT_NAME}-build-package-${BUILD_TAG}-tmp" PACKAGE_NAME="project_source_code.tar.gz" PACKAGE_FILE="${PROJECT_NAME}-assembly.jar" PACKAGE_FILE_VERSION="${PROJECT_NAME}-assembly-${PROJECT_VERSION}.jar" echo "================================" echo " PROJECT_VERSION: [ ${PROJECT_VERSION} ]" echo " BUILD_FOLDER: [ ${BUILD_FOLDER} ]" echo " BUILD_NUM: [ ${BUILD_NUM} ]" echo " IMAGE_NAME: [ ${IMAGE_NAME} ]" echo "================================" # Load function tools . "${BUILD_FOLDER}/tools/functions.sh" function cleanup_container_and_image(){ cleanup_container "${DOCKER_CONTAINER_NAME}" cleanup_image "${DOCKER_TAG_COMPILE}" cleanup_image "${DOCKER_TAG_PACKAGE}" cleanup_image "${IMAGE_NAME}" "${BUILD_NUM}" cleanup_image "${IMAGE_NAME}" } function cleanup_temp_folder(){ cleanup_folder_files "${DOCKER_FILES_FOLDER}/tmp/" cleanup_folder_files "${PROJECT_PATH}/${PACKAGE_NAME}" } # Environment init print_task " Cleaning up build environment " cleanup_container_and_image cleanup_temp_folder cd "${PROJECT_PATH}" # Pull submodule project ./git_submod_pull.sh master # Set compression level to the fastest. -1 (or --fast) to -9 (or --best) export BZIP=--fast export GZIP=--fast # Package project to single file print_task " Packaging project resources to a single file " tar zcvf "${PACKAGE_NAME}" ./* mkdir -p "${DOCKER_FILES_FOLDER}/tmp/" mv "${PACKAGE_NAME}" "${DOCKER_FILES_FOLDER}/tmp/" # sbt packager (output fat jar) #If the <src> parameter of ADD is an archive in a recognised compression format, it will be unpacked docker build -t "${DOCKER_TAG_COMPILE}" -f "${DOCKER_FILES_FOLDER}/Dockerfile.compile" "${DOCKER_FILES_FOLDER}/" || exit $? print_task " Compiling project in docker container " time docker run --cpuset-cpus=2,3 \ --net=host \ --name="${DOCKER_CONTAINER_NAME}" \ --privileged=true \ -v /etc/localtime:/etc/localtime:ro \ -v ~/.sbt/:/root/.sbt/ \ -v ~/.ivy2/:/root/.ivy2/ \ "${DOCKER_TAG_COMPILE}" sh "/opt/package.sh" || exit $? print_task " Extracting package file from container " time docker cp "${DOCKER_CONTAINER_NAME}:/opt/target/scala/${PACKAGE_FILE_VERSION}" "${DOCKER_FILES_FOLDER}/tmp/" mv "${DOCKER_FILES_FOLDER}/tmp/${PACKAGE_FILE_VERSION}" "${DOCKER_FILES_FOLDER}/tmp/${PACKAGE_FILE}" || exit $? # Prepare conf folder cp -r "${BUILD_FOLDER}/conf" "${DOCKER_FILES_FOLDER}/tmp" # docker image packager (output docker image) print_task " Building final docker image " time docker build -t "${DOCKER_TAG_PACKAGE}" -f "${DOCKER_FILES_FOLDER}/Dockerfile.package" "${DOCKER_FILES_FOLDER}/" || exit $? # Push image to private docker registry print_task " Pushing images to private docker registry " echo "Docker image: [ ${IMAGE_NAME}:${BUILD_NUM} ]" docker tag "${DOCKER_TAG_PACKAGE}" "${IMAGE_NAME}:${BUILD_NUM}" docker tag -f "${DOCKER_TAG_PACKAGE}" "${IMAGE_NAME}:latest" docker push "${IMAGE_NAME}:${BUILD_NUM}" docker push "${IMAGE_NAME}:latest" # Remove intermediate images and containers on this host print_task " Removing intermediate data, images and containers " cleanup_container_and_image cleanup_temp_folder <file_sep>/build/Dockerfile FROM jeanblanchard/java:8 MAINTAINER chenshuai <<EMAIL>> RUN apk add --update bash RUN mkdir /app WORKDIR / VOLUME ["/conf", "/logs"] ADD *-assembly-*.jar /app/ssp-archive-assembly.jar ENTRYPOINT ["java", "-server", "-Xmx2G", "-XX:MaxPermSize=100m", "-XX:+UseConcMarkSweepGC", "-XX:+DisableExplicitGC", "-Dlogback.configurationFile=/conf/logback.xml", "-DPORT=7661", "-cp", "/app/ssp-dedup-assembly.jar", "com.vpon.ssp.report.archive.Main", "-h", "17661", "-c", "/conf/application.conf"] <file_sep>/build/run.sh #!/bin/bash SHORT=hp:c:g:t:n:j:o:v:a:e: LONG=help,conf-dir:,logs-dir:,http-port:,tag:,build-number:,jvm:,options:,version:,environment:,akka-port: PARSED=`getopt --options $SHORT --longoptions $LONG --name "$0" -- "$@"` if [[ $? != 0 ]]; then exit 2 fi eval set -- "$PARSED" while true; do case "$1" in -h|--help) NEED_HELP=y shift ;; -v|--version) VERSION="$2" shift 2 ;; -t|--tag) TAG="$2" shift 2 ;; -j|--jvm) JVM_OPT="$2" shift 2 ;; -o|--options) OPTS="$2" shift 2 ;; -n|--build-number) BUILD_NUMBER="$2" shift 2 ;; -p|--http-port) HTTP_PORT="$2" shift 2 ;; -c|--conf-dir) CONF_DIR="$2" shift 2 ;; -g|--logs-dir) LOGS_DIR="$2" shift 2 ;; -e|--environment) ENVIRONMENT="$2" shift 2 ;; -a|--akka-port) AKKA_PORT="$2" shift 2 ;; --) shift break ;; *) echo "Command line parameters parsing error!" echo "exit!" exit 3 ;; esac done function help() { echo " usage: -t, --tag required docker image tag, eg: release, dev, feature -n, --build-number required docker image build number, eg: latest, 123 -c, --conf-dir optional conf dir -g, --logs-dir required logs dir -a, --akka-port required akka port, eg: 7661 -p, --http-port required http port, eg: 17661 -j, --jvm optional JVM OPTS, eg: \"-Xmx8192m -Dfile.encoding=UTF-8\" -o, --options optional other application options, eg: \"--name ssp-reporting-service -h 10.0.1.2\", run \"sbt 'run --help'\" to get details -e, --environment required environment, eg: dev, qa -h, --help required print this help message " } if [[ ${NEED_HELP} ]]; then help exit 0 fi if [[ ! $TAG || ! $BUILD_NUMBER || ! $HTTP_PORT || ! $LOGS_DIR || ! $VERSION || ! $AKKA_PORT || ! $ENVIRONMENT ]]; then echo "" echo "Error! parameters missing!" help exit 1 fi APP_NAME="ssp-dedup-${TAG}-${VERSION}" IMAGE="192.168.105.243:5000/vpon/${APP_NAME}:${BUILD_NUMBER}" if [[ ${CONF_DIR} ]]; then CONF_MOUNT="-v ${CONF_DIR}:/conf" fi mkdir -p ${LOGS_DIR} docker ps -a | grep -e "[[:space:]]${APP_NAME}[[:space:]]" && docker rm -f ${APP_NAME} && docker rmi -f ${IMAGE} > /dev/null docker pull ${IMAGE} ENTRYPOINT="java ${JVM_OPT} -Dlogback.configurationFile=/opt/apps/conf/${ENVIRONMENT}/logback.xml -DPORT=${AKKA_PORT} -classpath /opt/apps/ssp-dedup-assembly.jar com.vpon.ssp.report.dedup.Main -h ${HTTP_PORT} -c /opt/apps/conf/${ENVIRONMENT}/application.conf ${OPTS}" docker run -itd --privileged=true --name ${APP_NAME} --net=host ${CONF_MOUNT} -v ${LOGS_DIR}:/logs ${IMAGE} ${ENTRYPOINT} echo "${APP_NAME} started! AKKA port is ${AKKA_PORT}, HTTP port is ${HTTP_PORT}, log files located in ${LOGS_DIR}" #docker attach `docker ps | grep ${APP_NAME} | awk '{print $1}'` <file_sep>/package.sh #!/bin/bash # Build project source cd /opt/ bash ./sbt -Dsbt.repository.config=repositories -Dsbt.override.build.repos=true -Dsbt.log.noformat=true clean assembly || exit $? # Create symbolic link for output folder ln -s /opt/target/scala-* /opt/target/scala <file_sep>/build/simple_run.sh #!/bin/bash BASE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" TAG=$1 ENV=$3 if [[ $2 ]]; then BUILD_NUMBER=$2; else BUILD_NUMBER="latest"; fi PROJECT_NAME=`grep "val Name" ${BASE_DIR}/../project/build.scala | awk '{print $NF}' | awk -F \" '{print $2}'` PROJECT_VERSION=`grep "val Version" ${BASE_DIR}/../project/build.scala | awk '{print $NF}' | awk -F \" '{print $2}'` VERSION="v${PROJECT_VERSION}" echo "version = ${VERSION}" APP_NAME="${PROJECT_NAME}-${TAG}-${VERSION}" ID=${APP_NAME}-${ENV} AKKA_PORT=7661 HTTP_PORT=17661 LOGS_DIR=/data/logs/${PROJECT_NAME} mkdir -p ${LOGS_DIR} echo "${APP_NAME} started! AKKA port: ${AKKA_PORT}, HTTP port: ${HTTP_PORT}, log files located in: ${LOGS_DIR}" sh ${BASE_DIR}/run.sh -g ${LOGS_DIR} -a ${AKKA_PORT} -p ${HTTP_PORT} -t ${TAG} -n ${BUILD_NUMBER} -v ${VERSION} -j "-Ddedup.cluster-group=${ID}" -e ${ENV} exit 0
202caca918cce03945b7c43c7fc40a5bca07aaca
[ "Python", "Dockerfile", "Shell" ]
8
Python
ChenShuai1981/ssp-archive
cf72fc802b47f05eb9f3b0da4a157ab3db1d383b
0877153d2c90bb0b13a3a1fbba88821ff2843ac4
refs/heads/master
<repo_name>AlexisAmand/MyFirstSite<file_sep>/archives/Site perso 2/Amand 08-2008HTML/individus/listeindividus0.htm <HTML> <HEAD> <TITLE>Liste des individus</TITLE> <LINK rel="STYLESHEET" type="text/css" HREF="../menu/css.css"> <SCRIPT LANGUAGE="Javascript" SRC="../menu/coolmenus.js"></SCRIPT> </HEAD> <BODY topmargin=0 marginheight=0 background="./../images/fond.jpg"> <SCRIPT LANGUAGE="Javascript" SRC="../menu/menu.js"></SCRIPT> <BR><BR> <BR><BR> <CENTER><DIV class="titre">Liste des individus</DIV></CENTER> <BR><BR> <CENTER><TABLE><TR><TD> <A NAME=i0></A> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche0.htm#f0">? Andréa</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche0.htm#f1">? Ginette</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche0.htm#f2">? Jeanne</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche0.htm#f3">? Léoncia</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche0.htm#f4">? Louisette</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche1.htm#f5">? Maria</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche1.htm#f6">? <NAME></A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche1.htm#f7">? Meli</A> ( ? - ? )<BR> <A NAME=i8></A> <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche1.htm#f8">ABRASSART Jeanne</A> ( ? - 1765 )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche1.htm#f9">ABRASSART <NAME></A> ( 1790 - ? )<BR> <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche2.htm#f10">ABRASSART <NAME></A> ( ? - ? )<BR> <A NAME=i11></A> <IMG SRC="../images/i.gif"> <A HREF="../fiches/fiche2.htm#f11">ALEGLAVE Estienne</A> ( ? - ? )<BR> <A NAME=i12></A> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche2.htm#f12">AMAND Achille</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche2.htm#f13">AMAND Adéle</A> ( 1845 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche2.htm#f14">AMAND Adelson</A> ( ? - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche3.htm#f15">AMAND Adelson</A> ( ? - ? )<BR> <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche3.htm#f16">AMAND Adolphe</A> ( 1833 - ? )<BR> <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche3.htm#f17">AMAND Adolphe</A> ( 1855 - 1893 )<BR> <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche3.htm#f18">AMAND Adolphe</A> ( 1877 - 1934 )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche3.htm#f19">AMAND Adolphe</A> ( 1894 - ? )<BR> <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche4.htm#f20">AMAND Adolphe</A> ( 1902 - 1971 )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche4.htm#f21">AMAND Adolphe</A> ( 1926 - 1926 )<BR> <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche4.htm#f22">AMAND Adolphe</A> ( 1929 - 2002 )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche4.htm#f23">AMAND Adolphine</A> ( 1853 - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche4.htm#f24">AMAND Adolphine</A> ( 1893 - 1893 )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche5.htm#f25">AMAND Alexandra</A> ( 1983 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche5.htm#f26">AMAND Alexis</A> ( 1718 - 1777 )<BR> <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche5.htm#f27">AMAND Alexis</A> ( 1979 - ? )<BR> <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche5.htm#f28">AMAND <NAME></A> ( 1681 - 1743 )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche5.htm#f29">AMAND Alphonse</A> ( 1946 - 1946 )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche6.htm#f30">AMAND Amelie</A> ( 1940 - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche6.htm#f31">AMAND Andrée</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche6.htm#f32">AMAND Angélique</A> ( 1793 - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche6.htm#f33">AMAND Anne Jeanne</A> ( 1764 - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche6.htm#f34">AMAND Antoinette</A> ( 1880 - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche7.htm#f35">AMAND Arthurine</A> ( 1936 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche7.htm#f36">AMAND Benoît</A> ( 1753 - 1754 )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche7.htm#f37">AMAND Bernadette</A> ( ? - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche7.htm#f38">AMAND Bernard</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche7.htm#f39">AMAND Bertha</A> ( 1934 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche8.htm#f40">AMAND Boniface</A> ( 1754 - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche8.htm#f41">AMAND Brigitte</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche8.htm#f42">AMAND Catherine</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche8.htm#f43">AMAND Catherine</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche8.htm#f44">AMAND Catherine</A> ( 1712 - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche9.htm#f45">AMAND Chantal</A> ( 1949 - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche9.htm#f46">AMAND Christelle</A> ( 1989 - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche9.htm#f47">AMAND Christine</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche9.htm#f48">AMAND Christine</A> ( ? - 2005 )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche9.htm#f49">AMAND Claudine</A> ( 1952 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche10.htm#f50">AMAND Cyrille</A> ( 1756 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche10.htm#f51">AMAND Daniel</A> ( ? - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche10.htm#f52">AMAND Désiré</A> ( 1822 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche10.htm#f53">AMAND Dimitri</A> ( ? - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche10.htm#f54">AMAND Druon</A> ( 1762 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche11.htm#f55">AMAND Druon</A> ( 1795 - 1859 )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche11.htm#f56">AMAND Edouard</A> ( 1926 - 1971 )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche11.htm#f57">AMAND Elise</A> ( 1893 - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche11.htm#f58">AMAND Elise</A> ( 1930 - 1931 )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche11.htm#f59">AMAND Elise</A> ( 1932 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche12.htm#f60">AMAND Etienne</A> ( 1723 - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche12.htm#f61">AMAND Eva</A> ( 1913 - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche12.htm#f62">AMAND Eva</A> ( 1927 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche12.htm#f63">AMAND Fabian</A> ( 1984 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche12.htm#f64">AMAND Felix</A> ( 1850 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche13.htm#f65">AMAND Fernand</A> ( 1918 - 1972 )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche13.htm#f66">AMAND Françoise</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche13.htm#f67">AMAND Geneviève</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche13.htm#f68">AMAND Geneviève</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche13.htm#f69">AMAND Georgette</A> ( ? - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche14.htm#f70">AMAND Georgette</A> ( 1943 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche14.htm#f71">AMAND Gerard</A> ( ? - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche14.htm#f72">AMAND Gérard</A> ( ? - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche14.htm#f73">AMAND Gregoire</A> ( 1771 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche14.htm#f74">AMAND Henri</A> ( 1865 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche15.htm#f75">AMAND Henri</A> ( 1890 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche15.htm#f76">AMAND Henri</A> ( 1930 - 1972 )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche15.htm#f77">AMAND <NAME></A> ( 1913 - 1998 )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche15.htm#f78">AMAND <NAME></A> ( 1956 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche15.htm#f79">AMAND Jacques</A> ( 1713 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche16.htm#f80">AMAND Jacques</A> ( 1716 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche16.htm#f81">AMAND Jacques</A> ( 1765 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche16.htm#f82">AMAND Jean</A> ( 1729 - ? )<BR> <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche16.htm#f83">AMAND Jean</A> ( 1731 - 1786 )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche16.htm#f84">AMAND Jean</A> ( 1759 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche17.htm#f85">AMAND Jean Baptiste</A> ( 1752 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche17.htm#f86">AMAND Jean Baptiste</A> ( 1800 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche17.htm#f87">AMAND Jean Claude</A> ( 1945 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche17.htm#f88">AMAND Jean Jacques</A> ( 1750 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche17.htm#f89">AMAND Jean Joseph</A> ( 1721 - ? )<BR> <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche18.htm#f90">AMAND Jean Joseph</A> ( 1768 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche18.htm#f91">AMAND Jean Luc</A> ( ? - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche18.htm#f92">AMAND Jean Michel</A> ( 1956 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche18.htm#f93">AMAND Jean Philippe</A> ( 1768 - 1789 )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche18.htm#f94">AMAND Jean Pierre</A> ( 1947 - 1968 )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche19.htm#f95">AMAND Jean<NAME></A> ( 1949 - ? )<BR> <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche19.htm#f96">AMAND Joëlle</A> ( 1951 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche19.htm#f97">AMAND José</A> ( ? - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche19.htm#f98">AMAND Joseph</A> ( 1797 - ? )<BR> <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche19.htm#f99">AMAND Joseph</A> ( 1927 - 1987 )<BR> </TD></TR></TABLE></CENTER> <BR><BR> <CENTER> <A HREF="./../individus/listeindividus0.htm#"><IMG SRC="../images/iconTop.gif" border=0></A> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <A HREF="./../individus/listeindividus1.htm"><IMG SRC="../images/iconRight.gif" border=0></A> </CENTER> <BR><BR> <DIV class="baspage" align="center"> Ces pages ont été créées par <A HREF="http://www.heredis.com" target="_blank">Heredis 10 pour Windows</A> , &copy; BSD Concept <BR><BR> <A HREF="http://www.heredis.com" target="_blank"><IMG SRC="../images/heredis.jpg" border=0></A> <A HREF="http://www.planete-genealogie.fr" target="_blank"><IMG SRC="../images/pg.jpg" border=0></A> </DIV> </BODY> </HTML> <file_sep>/genealogie/etats/listeevenements5.htm <HTML> <HEAD> <TITLE>Liste des événements</TITLE> <LINK rel="STYLESHEET" type="text/css" HREF="../menu/css.css"> <SCRIPT LANGUAGE="Javascript" SRC="../menu/coolmenus.js"></SCRIPT> </HEAD> <BODY topmargin=0 marginheight=0 background="./../images/fond.jpg"> <!-- phpmyvisites --> <a href="http://www.phpmyvisites.net/" title="phpMyVisites | Open source web analytics" onclick="window.open(this.href);return(false);"><script type="text/javascript"> <!-- var a_vars = Array(); var pagename=''; var phpmyvisitesSite = 1; var phpmyvisitesURL = "http://tabouet.hostarea.org/phpmyvisites/phpmv2/phpmyvisites.php"; //--> </script> <script language="javascript" src="http://tabouet.hostarea.org/phpmyvisites/phpmv2/phpmyvisites.js" type="text/javascript"></script> <object><noscript><p>phpMyVisites | Open source web analytics <img src="http://tabouet.hostarea.org/phpmyvisites/phpmv2/phpmyvisites.php" alt="Statistics" style="border:0" /> </p></noscript></object></a> <!-- /phpmyvisites --> <SCRIPT LANGUAGE="Javascript" SRC="../menu/menu.js"></SCRIPT> <BR><BR> <BR><BR> <CENTER><DIV class="titre">Liste des événements</DIV></CENTER> <BR><BR> <CENTER> <BR><BR> <TABLE width=95% border=1 cellspacing=0> <TR> <TD class="titretab" align="center"> Date </TD> <TD class="titretab" align="center"> Lieu <TD class="titretab" align="center"> Evénement </TD></TR> <TR valign="top"><TD> 29 septembre 1763 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche157.htm#f785"><NAME></A> ( 1760 - 1763 )<BR> </TD></TR> <TR valign="top"><TD> 18 novembre 1763 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche154.htm#f772"><NAME></A> ( 1763 - ? )<BR> </TD></TR> <TR valign="top"><TD> 16 décembre 1763 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche239.htm#f1197">VILAIN <NAME></A> ( 1763 - ? )<BR> </TD></TR> <TR valign="top"><TD> 16 décembre 1763 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche251.htm#f1257"><NAME></A> ( 1763 - ? )<BR> </TD></TR> <TR valign="top"><TD> 1764 </TD><TD> &nbsp; </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche129.htm#f646"><NAME></A> ( 1764 - ? )<BR> </TD></TR> <TR valign="top"><TD> 20 janvier 1764 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche6.htm#f33">AM<NAME></A> ( 1764 - ? )<BR> </TD></TR> <TR valign="top"><TD> 19 février 1764 </TD><TD> Quarouble 59243 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche185.htm#f927"><NAME></A> ( 1764 - ? )<BR> </TD></TR> <TR valign="top"><TD> 11 mars 1764 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche225.htm#f1125">THON <NAME></A> ( 1764 - ? )<BR> </TD></TR> <TR valign="top"><TD> 17 mars 1764 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche96.htm#f483">DELPORTE <NAME></A> ( 1764 - 1764 )<BR> </TD></TR> <TR valign="top"><TD> 30 avril 1764 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche254.htm#f1270">WILQUAIN <NAME></A> ( 1763 - 1764 )<BR> </TD></TR> <TR valign="top"><TD> 1 juin 1764 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche163.htm#f818">LEFEBVRE <NAME></A> ( 1764 - 1771 )<BR> </TD></TR> <TR valign="top"><TD> 13 juin 1764 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche200.htm#f1004">MOURY Simon</A> ( 1722 - 1764 )<BR> </TD></TR> <TR valign="top"><TD> 4 juillet 1764 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche96.htm#f483">DELPORTE Jean<NAME></A> ( 1764 - 1764 )<BR> </TD></TR> <TR valign="top"><TD> 10 août 1764 </TD><TD> Bellaing 59135 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche180.htm#f900">MARISSALE <NAME></A> ( 1764 - ? )<BR> </TD></TR> <TR valign="top"><TD> 2 octobre 1764 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche49.htm#f249">BOULAR<NAME></A> ( 1764 - 1817 )<BR> </TD></TR> <TR valign="top"><TD> 13 décembre 1764 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche99.htm#f496">DELPORTE <NAME></A> ( 1727 - 1764 )<BR> </TD></TR> <TR valign="top"><TD> 23 février 1765 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche194.htm#f974">MORE<NAME></A> ( 1765 - ? )<BR> </TD></TR> <TR valign="top"><TD> 2 avril 1765 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche254.htm#f1271">WILQUAIN <NAME></A> ( 1765 - ? )<BR> </TD></TR> <TR valign="top"><TD> 5 mai 1765 </TD><TD> &nbsp; </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche16.htm#f81">AMAND Jacques</A> ( 1765 - ? )<BR> </TD></TR> <TR valign="top"><TD> 28 mai 1765 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche195.htm#f977">MORE<NAME></A> ( 1765 - ? )<BR> </TD></TR> <TR valign="top"><TD> 31 mai 1765 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche164.htm#f824">LEFE<NAME></A> ( 1744 - 1765 )<BR> </TD></TR> <TR valign="top"><TD> 21 août 1765 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche252.htm#f1264"><NAME></A> ( 1765 - 1767 )<BR> </TD></TR> <TR valign="top"><TD> 11 octobre 1765 </TD><TD> Elouges B7370 </TD><TD> Décès de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche1.htm#f8">ABRASSART Jeanne</A> ( ? - 1765 )<BR> </TD></TR> <TR valign="top"><TD> 6 novembre 1765 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche244.htm#f1222"><NAME></A> ( 1765 - ? )<BR> </TD></TR> <TR valign="top"><TD> 11 décembre 1765 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche23.htm#f115">AMAND <NAME></A> ( 1765 - ? )<BR> </TD></TR> <TR valign="top"><TD> 1766 </TD><TD> Peruwelz B7600 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche107.htm#f538">DRION <NAME></A> ( 1766 - ? )<BR> </TD></TR> <TR valign="top"><TD> 1766 </TD><TD> &nbsp; </TD><TD> Naissance de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche166.htm#f831">LEGAT Alexandrine</A> ( 1766 - ? )<BR> </TD></TR> <TR valign="top"><TD> 18 janvier 1766 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche244.htm#f1220"><NAME></A> ( 1766 - 1767 )<BR> </TD></TR> <TR valign="top"><TD> 9 février 1766 </TD><TD> Quarouble 59243 </TD><TD> Décès de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche52.htm#f261">BRACONNIER Jean</A> ( 1683 - 1766 )<BR> </TD></TR> <TR valign="top"><TD> 14 février 1766 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche163.htm#f815">LEFEBVRE <NAME></A> ( 1766 - ? )<BR> </TD></TR> <TR valign="top"><TD> 20 mai 1766 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche98.htm#f491">DELPORTE Marie Marguerite</A> ( 1766 - ? )<BR> </TD></TR> <TR valign="top"><TD> 28 juin 1766 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche236.htm#f1180">VILAIN <NAME></A> ( 1766 - ? )<BR> </TD></TR> <TR valign="top"><TD> 16 juillet 1766 </TD><TD> &nbsp; </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche61.htm#f308">CAMBIER Jacques</A> ( 1766 - ? )<BR> </TD></TR> <TR valign="top"><TD> 22 septembre 1766 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche158.htm#f791">LAURENT Marie Ignace</A> ( 1766 - ? )<BR> </TD></TR> <TR valign="top"><TD> 7 octobre 1766 </TD><TD> Dour B7370 </TD><TD> Mariage de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche220.htm#f1100"><NAME></A> ( 1741 - 1782 )<BR> <BR>et de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche253.htm#f1269"><NAME></A> ( 1740 - 1788 )<BR> </TD></TR> <TR valign="top"><TD> 12 octobre 1766 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche192.htm#f963"><NAME></A> ( 1766 - ? )<BR> </TD></TR> <TR valign="top"><TD> 14 octobre 1766 </TD><TD> &nbsp; </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche109.htm#f548">DUBREUCQ Jean Baptiste</A> ( 1689 - 1766 )<BR> </TD></TR> <TR valign="top"><TD> 6 novembre 1766 </TD><TD> Quarouble 59243 </TD><TD> Décès de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche100.htm#f501">DEMAREZ <NAME></A> ( 1721 - 1766 )<BR> </TD></TR> <TR valign="top"><TD> 24 avril 1767 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche244.htm#f1220"><NAME></A> ( 1766 - 1767 )<BR> </TD></TR> <TR valign="top"><TD> 22 juin 1767 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche252.htm#f1264"><NAME></A> ( 1765 - 1767 )<BR> </TD></TR> <TR valign="top"><TD> 6 juillet 1767 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche220.htm#f1103"><NAME></A> ( 1767 - 1767 )<BR> </TD></TR> <TR valign="top"><TD> 25 juillet 1767 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche94.htm#f473">DELPORTE Casimir Agapite François</A> ( 1763 - 1767 )<BR> </TD></TR> <TR valign="top"><TD> 25 septembre 1767 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche220.htm#f1103"><NAME></A> ( 1767 - 1767 )<BR> </TD></TR> <TR valign="top"><TD> 23 janvier 1768 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche33.htm#f169"><NAME></A> ( 1768 - ? )<BR> </TD></TR> <TR valign="top"><TD> 9 février 1768 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche250.htm#f1254"><NAME></A> ( 1768 - ? )<BR> </TD></TR> <TR valign="top"><TD> 19 avril 1768 </TD><TD> Thulin B7350 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche18.htm#f90">AM<NAME> Joseph</A> ( 1768 - ? )<BR> </TD></TR> <TR valign="top"><TD> 16 juin 1768 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche81.htm#f407">DANHIEZ Anne</A> ( 1721 - 1768 )<BR> </TD></TR> <TR valign="top"><TD> 18 septembre 1768 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche18.htm#f93">AM<NAME></A> ( 1768 - 1789 )<BR> </TD></TR> <TR valign="top"><TD> 18 septembre 1768 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche164.htm#f820">LEFEBVRE Marie Rose</A> ( 1768 - 1772 )<BR> </TD></TR> <TR valign="top"><TD> 20 septembre 1768 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche196.htm#f981">MOREAU <NAME></A> ( 1768 - ? )<BR> </TD></TR> <TR valign="top"><TD> 4 décembre 1768 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche75.htm#f375">CAVENELLE <NAME></A> ( 1768 - ? )<BR> </TD></TR> <TR valign="top"><TD> 2 avril 1769 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche219.htm#f1099">RUELLE <NAME></A> ( 1769 - ? )<BR> </TD></TR> <TR valign="top"><TD> 3 avril 1769 </TD><TD> Thulin B7350 </TD><TD> Naissance de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche84.htm#f422">DEBIEVE Alexandrine</A> ( 1769 - ? )<BR> </TD></TR> <TR valign="top"><TD> 20 novembre 1769 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche241.htm#f1208"><NAME></A> ( 1769 - ? )<BR> </TD></TR> <TR valign="top"><TD> 1770 </TD><TD> Peruwelz B7600 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche107.htm#f537">DR<NAME></A> ( 1770 - ? )<BR> </TD></TR> <TR valign="top"><TD> 3 janvier 1770 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche196.htm#f984">MOREAU N.</A> ( 1770 - 1770 )<BR> </TD></TR> <TR valign="top"><TD> 3 janvier 1770 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche196.htm#f984">MOREAU N.</A> ( 1770 - 1770 )<BR> </TD></TR> <TR valign="top"><TD> 31 janvier 1770 </TD><TD> Elouges B7370 </TD><TD> Naissance de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche77.htm#f385"><NAME></A> ( 1770 - ? )<BR> </TD></TR> <TR valign="top"><TD> 19 février 1770 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche130.htm#f654">GLINEUR Jacques</A> ( 1703 - 1770 )<BR> </TD></TR> <TR valign="top"><TD> 10 avril 1770 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche98.htm#f490">DELPORTE <NAME></A> ( 1757 - 1770 )<BR> </TD></TR> <TR valign="top"><TD> 1 septembre 1770 </TD><TD> Fresnes sur Escaut 59970 </TD><TD> Décès de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche166.htm#f833">LEGRAND <NAME></A> ( 1733 - 1770 )<BR> </TD></TR> <TR valign="top"><TD> 22 décembre 1770 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche196.htm#f980">MOREAU Marie Marguerite</A> ( 1770 - 1773 )<BR> </TD></TR> <TR valign="top"><TD> 11 mars 1771 </TD><TD> &nbsp; </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche14.htm#f73">AMAND Gregoire</A> ( 1771 - ? )<BR> </TD></TR> <TR valign="top"><TD> 27 avril 1771 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche219.htm#f1097">RUELLE <NAME></A> ( 1771 - ? )<BR> </TD></TR> <TR valign="top"><TD> 13 mai 1771 </TD><TD> Dour B7370 </TD><TD> Mariage de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche95.htm#f477">DELPORTE Jean</A> ( 1737 - 1797 )<BR> <BR>et de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche167.htm#f836">LEJEUNE Anne Marguerite</A> ( 1749 - ? )<BR> </TD></TR> <TR valign="top"><TD> 1 juillet 1771 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche164.htm#f823">LEFEBVRE <NAME></A> ( 1771 - 1793 )<BR> </TD></TR> <TR valign="top"><TD> 1 septembre 1771 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche157.htm#f789">LAURENT Marie</A> ( 1715 - 1771 )<BR> </TD></TR> <TR valign="top"><TD> 27 septembre 1771 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche248.htm#f1241">WILQUAIN <NAME></A> ( 1771 - ? )<BR> </TD></TR> <TR valign="top"><TD> 26 octobre 1771 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche221.htm#f1108">SAUSSEZ Marie Angélique</A> ( 1771 - ? )<BR> </TD></TR> <TR valign="top"><TD> 30 décembre 1771 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche163.htm#f818">LEFEBVRE Marie Joseph</A> ( 1764 - 1771 )<BR> </TD></TR> <TR valign="top"><TD> 7 janvier 1772 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche164.htm#f820">LE<NAME></A> ( 1768 - 1772 )<BR> </TD></TR> <TR valign="top"><TD> 11 janvier 1772 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche239.htm#f1196">VILAIN <NAME></A> ( 1772 - ? )<BR> </TD></TR> <TR valign="top"><TD> 1 mars 1772 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche98.htm#f492">DELPORTE Marie Marguerite</A> ( 1772 - ? )<BR> </TD></TR> <TR valign="top"><TD> 10 mai 1772 </TD><TD> Eugies (Frameries) B7080 </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche87.htm#f435">DECAMPS Antoine</A> ( 1706 - 1772 )<BR> </TD></TR> <TR valign="top"><TD> 1 juillet 1772 </TD><TD> Dour B7370 </TD><TD> Mariage de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche99.htm#f497">DELPORTE <NAME></A> ( 1751 - 1831 )<BR> <BR>et de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche79.htm#f397"><NAME></A> ( 1748 - 1819 )<BR> </TD></TR> <TR valign="top"><TD> 10 août 1772 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche139.htm#f695">HARMEGNIES Pierre</A> ( 1772 - < 1820 )<BR> </TD></TR> <TR valign="top"><TD> 22 septembre 1772 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche138.htm#f691">HARMEGNIES François Grégoire</A> ( 1772 - ? )<BR> </TD></TR> <TR valign="top"><TD> 7 février 1773 </TD><TD> Elouges B7370 </TD><TD> Décès de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche77.htm#f387">CIPLY Jean Baptiste</A> ( 1713 - 1773 )<BR> </TD></TR> <TR valign="top"><TD> 27 février 1773 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche196.htm#f980">MOREAU Marie Marguerite</A> ( 1770 - 1773 )<BR> </TD></TR> <TR valign="top"><TD> 15 mars 1773 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche208.htm#f1044">QUEVY Patrice</A> ( 1773 - ? )<BR> </TD></TR> <TR valign="top"><TD> 2 avril 1773 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche213.htm#f1067"><NAME></A> ( 1773 - ? )<BR> </TD></TR> <TR valign="top"><TD> 14 avril 1773 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche23.htm#f116">AMAND Martin</A> ( 1735 - 1773 )<BR> </TD></TR> <TR valign="top"><TD> 2 juin 1773 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche98.htm#f493">DELPORTE <NAME></A> ( 1773 - 1809 )<BR> </TD></TR> <TR valign="top"><TD> 15 juin 1773 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche91.htm#f456">DEH<NAME></A> ( 1773 - ? )<BR> </TD></TR> <TR valign="top"><TD> 21 octobre 1773 </TD><TD> Dour B7370 </TD><TD> Décès de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche132.htm#f663">GL<NAME></A> ( 1705 - 1773 )<BR> </TD></TR> <TR valign="top"><TD> 23 novembre 1773 </TD><TD> Wiheries B7370 </TD><TD> Mariage de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche229.htm#f1148"><NAME></A> ( 1747 - 1786 )<BR> <BR>et de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche110.htm#f550"><NAME></A> ( 1747 - ? )<BR> </TD></TR> <TR valign="top"><TD> 25 novembre 1773 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche217.htm#f1087"><NAME></A> ( 1773 - ? )<BR> </TD></TR> <TR valign="top"><TD> 3 décembre 1773 </TD><TD> Fresnes sur Escaut 59970 </TD><TD> Décès de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche61.htm#f306">CAM<NAME></A> ( ? - 1773 )<BR> </TD></TR> <TR valign="top"><TD> 7 décembre 1773 </TD><TD> Thulin B7350 </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche85.htm#f428">DEB<NAME></A> ( 1732 - 1773 )<BR> </TD></TR> <TR valign="top"><TD> 11 janvier 1774 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche217.htm#f1085"><NAME></A> ( 1774 - ? )<BR> </TD></TR> <TR valign="top"><TD> 14 janvier 1774 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche100.htm#f500">DELPORTE Vindicienne Eulalie</A> ( 1774 - ? )<BR> </TD></TR> <TR valign="top"><TD> 18 janvier 1774 </TD><TD> Quarouble 59243 </TD><TD> Décès de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche198.htm#f991">MOR<NAME></A> ( 1725 - 1774 )<BR> </TD></TR> <TR valign="top"><TD> 12 mars 1774 </TD><TD> Wiheries B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche230.htm#f1153"><NAME></A> ( 1774 - 1774 )<BR> </TD></TR> <TR valign="top"><TD> 13 mars 1774 </TD><TD> Wiheries B7370 </TD><TD> Décès de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche230.htm#f1153">VALLEE <NAME></A> ( 1774 - 1774 )<BR> </TD></TR> <TR valign="top"><TD> 19 mai 1774 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche246.htm#f1231">VILAIN Romaine</A> ( 1774 - ? )<BR> </TD></TR> <TR valign="top"><TD> 27 mai 1774 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche253.htm#f1265">W<NAME></A> ( 1774 - ? )<BR> </TD></TR> <TR valign="top"><TD> 12 juin 1774 </TD><TD> Wiheries B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche228.htm#f1140">VALAIN <NAME></A> ( 1774 - ? )<BR> </TD></TR> <TR valign="top"><TD> 24 novembre 1774 </TD><TD> Elouges B7370 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche76.htm#f384">CHUPIN P<NAME></A> ( 1774 - ? )<BR> </TD></TR> <TR valign="top"><TD> 7 décembre 1774 </TD><TD> Dour B7370 </TD><TD> Naissance de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche34.htm#f171"><NAME></A> ( 1774 - ? )<BR> </TD></TR> <TR valign="top"><TD> 24 juin 1775 </TD><TD> Elouges B7370 </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche78.htm#f392"><NAME></A> ( 1724 - 1775 )<BR> </TD></TR> </TABLE> <BR><BR> <CENTER> <A HREF="./../etats/listeevenements4.htm"><IMG SRC="../images/iconLeft.gif" border=0></A> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <A HREF="./../etats/listeevenements5.htm#"><IMG SRC="../images/iconTop.gif" border=0></A> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <A HREF="./../etats/listeevenements6.htm"><IMG SRC="../images/iconRight.gif" border=0></A> </CENTER> <BR><BR> <DIV class="baspage" align="center"> Ces pages ont été créées par <A HREF="http://www.heredis.com" target="_blank">Heredis 10 pour Windows</A> , &copy; BSD Concept <BR><BR> <A HREF="http://www.heredis.com" target="_blank"><IMG SRC="../images/heredis.jpg" border=0></A> <A HREF="http://www.planete-genealogie.fr" target="_blank"><IMG SRC="../images/pg.jpg" border=0></A> </DIV> </BODY> </HTML> <file_sep>/archives/Site perso 2/Amand 08-2008HTML/menu/menu.js oM=new makeCM("oM"); oM.resizeCheck=1; oM.rows=1; oM.onlineRoot=""; oM.pxBetween=0; oM.fillImg="cm_fill.gif"; oM.fromTop=10; oM.fromLeft=155; oM.wait=300; oM.zIndex=400; oM.useBar=1; oM.barWidth="100%"; oM.barHeight="menu"; oM.barX=0; oM.barY="menu"; oM.barClass="clBar"; oM.barBorderX=0; oM.barBorderY=0; oM.level[0]=new cm_makeLevel(90,21,"clT","clTover",1,1,"clB",0,"bottom",0,0,0,0,0); oM.level[1]=new cm_makeLevel(102,22,"clS","clSover",1,1,"clB",0,"right",0,0,"menu_arrow.gif",10,10); oM.makeMenu('m1','','Accueil','../heredis/accueil.htm'); oM.makeMenu('m2','','Individus','../individus/individus.htm'); oM.makeMenu('m7','m2','Patronymes','../individus/patronymes0.htm','',200,0); oM.makeMenu('m8','m2','Liste des individus','../individus/listeindividus0.htm','',200,0); oM.makeMenu('m9','m2','Fiches individuelles','../fiches/fiche0.htm','',200,0); oM.makeMenu('m10','m2','Mon ascendance','../individus/ascendance0.htm','',200,0); oM.makeMenu('m11','m2','Liste �clair','../individus/listeeclair0.htm','',200,0); oM.makeMenu('m3','','Lieux','../lieux/lieux.htm'); oM.makeMenu('m18','m3','Liste des lieux','../lieux/lieux0.htm','',200,0); oM.makeMenu('m19','m3','Patronymes par lieux','../lieux/patroparlieux0.htm','',200,0); oM.makeMenu('m4','','Etats','../etats/etats.htm'); oM.makeMenu('m12','m4','Liste des �v�nements','../etats/listeevenements0.htm','',200,0); oM.makeMenu('m13','m4','Liste des sources','../etats/listesources0.htm','',200,0); oM.makeMenu('m14','m4','Liste des images','../etats/listemedias0.htm','',200,0); oM.makeMenu('m15','m4','Liste des actes � rechercher','../etats/actesarechercher0.htm','',200,0); oM.makeMenu('m17','m4','Statistiques','../etats/stats.htm','',200,0); oM.makeMenu('m5','','Arbre 3D','../dswmedia/arbre3D.htm'); var avail="40+((cmpage.x2-45)/5)"; oM.menuPlacement=new Array(42,avail+"-11",avail+"*2-8",avail+"*3-12",avail+"*4-7"); oM.construct(); <file_sep>/genealogie/etats/actesarechercher1.htm <HTML> <HEAD> <TITLE>Liste des actes à rechercher</TITLE> <LINK rel="STYLESHEET" type="text/css" HREF="../menu/css.css"> <SCRIPT LANGUAGE="Javascript" SRC="../menu/coolmenus.js"></SCRIPT> </HEAD> <BODY topmargin=0 marginheight=0 background="./../images/fond.jpg"> <!-- phpmyvisites --> <a href="http://www.phpmyvisites.net/" title="phpMyVisites | Open source web analytics" onclick="window.open(this.href);return(false);"><script type="text/javascript"> <!-- var a_vars = Array(); var pagename=''; var phpmyvisitesSite = 1; var phpmyvisitesURL = "http://tabouet.hostarea.org/phpmyvisites/phpmv2/phpmyvisites.php"; //--> </script> <script language="javascript" src="http://tabouet.hostarea.org/phpmyvisites/phpmv2/phpmyvisites.js" type="text/javascript"></script> <object><noscript><p>phpMyVisites | Open source web analytics <img src="http://tabouet.hostarea.org/phpmyvisites/phpmv2/phpmyvisites.php" alt="Statistics" style="border:0" /> </p></noscript></object></a> <!-- /phpmyvisites --> <SCRIPT LANGUAGE="Javascript" SRC="../menu/menu.js"></SCRIPT> <BR><BR> <BR><BR> <CENTER><DIV class="titre">Liste des actes à rechercher</DIV></CENTER> <BR><BR> <CENTER> <BR><BR> <TABLE width=95% border=1 cellspacing=0> <TR> <TD class="titretab" align="center"> Date </TD> <TD class="titretab" align="center"> Lieu <TD class="titretab" align="center"> Evénement </TD></TR> <TR><TD> 14 août 1787 </TD><TD> Fresnes sur Escaut 59970 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche63.htm#f315"><NAME></A> ( 1787 - ? )<BR> </TD></TR> <TR><TD> 22 octobre 1789 </TD><TD> Fresnes sur Escaut 59970 </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche63.htm#f319"><NAME></A> ( ~ 1705 - 1789 )<BR> </TD></TR> <TR><TD> 8 février 1791 </TD><TD> Elouges B7370 </TD><TD> Mariage de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche236.htm#f1180"><NAME></A> ( 1766 - ? )<BR> <BR>de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche77.htm#f385"><NAME></A> ( 1770 - ? )<BR> </TD></TR> <TR><TD> 27 avril 1791 </TD><TD> Thulin B7350 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche28.htm#f142"><NAME></A> ( 1791 - 1847 )<BR> </TD></TR> <TR><TD> 1792 </TD><TD> &nbsp; </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche112.htm#f562">DUEZ <NAME></A> ( 1792 - 1854 )<BR> </TD></TR> <TR><TD> 1793 </TD><TD> &nbsp; </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche50.htm#f252"><NAME></A> ( 1793 - 1848 )<BR> </TD></TR> <TR><TD> 15 juin 1793 </TD><TD> &nbsp; </TD><TD> Décès de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche232.htm#f1160">VAUTIER Albertine</A> ( ? - 1793 )<BR> </TD></TR> <TR><TD> 1 octobre 1793 </TD><TD> Fresnes sur Escaut 59970 </TD><TD> Décès de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche122.htm#f610"><NAME></A> ( 1722 - 1793 )<BR> </TD></TR> <TR><TD> 20 juillet 1795 </TD><TD> Fresnes sur Escaut 59970 </TD><TD> Naissance de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche48.htm#f242">BOUILLIEZ Françoise</A> ( 1795 - ? )<BR> </TD></TR> <TR><TD> vers 1796 </TD><TD> Fresnes sur Escaut 59970 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche179.htm#f899"><NAME></A> ( ~ 1796 - ? )<BR> </TD></TR> <TR><TD> vers 1798 </TD><TD> &nbsp; </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche67.htm#f337"><NAME></A> ( ~ 1798 - ? )<BR> </TD></TR> <TR><TD> vers 1800 </TD><TD> &nbsp; </TD><TD> Naissance de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche88.htm#f442">DEGAGE <NAME></A> ( ~ 1800 - ? )<BR> </TD></TR> <TR><TD> 7 février 1812 </TD><TD> Fresnes sur Escaut 59970 </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche63.htm#f318"><NAME></A> ( ~ 1746 - 1812 )<BR> </TD></TR> <TR><TD> 22 octobre 1814 </TD><TD> Quarouble 59243 </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche146.htm#f734"><NAME></A> ( 1750 - 1814 )<BR> </TD></TR> <TR><TD> 1816 </TD><TD> &nbsp; </TD><TD> Mariage de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche112.htm#f562"><NAME></A> ( 1792 - 1854 )<BR> <BR>de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche151.htm#f758">JOLY <NAME></A> ( 1793 - 1832 )<BR> </TD></TR> <TR><TD> 15 novembre 1820 </TD><TD> Fresnes sur Escaut 59970 </TD><TD> Mariage de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche63.htm#f315"><NAME></A> ( 1787 - ? )<BR> <BR>de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche48.htm#f242">BOUILLIEZ Françoise</A> ( 1795 - ? )<BR> </TD></TR> <TR><TD> 29 avril 1822 </TD><TD> Elouges B7370 </TD><TD> Mariage de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche28.htm#f142"><NAME></A> ( 1791 - 1847 )<BR> <BR>de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche234.htm#f1172"><NAME></A> ( 1799 - ? )<BR> </TD></TR> <TR><TD> 17 janvier 1826 </TD><TD> &nbsp; </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche48.htm#f241"><NAME></A> ( ~ 1753 - 1826 )<BR> </TD></TR> <TR><TD> 25 mai 1826 </TD><TD> Sebourg 59990 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche66.htm#f330"><NAME></A> ( 1826 - 1891 )<BR> </TD></TR> <TR><TD> 20 février 1830 </TD><TD> Fresnes sur Escaut 59970 </TD><TD> Décès de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche109.htm#f549">DUBRE<NAME></A> ( 1757 - 1830 )<BR> </TD></TR> <TR><TD> 18 août 1830 </TD><TD> Quarouble 59243 </TD><TD> Mariage de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche148.htm#f741"><NAME></A> ( 1808 - 1887 )<BR> <BR>de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche111.htm#f558">DUEE Désirée</A> ( 1810 - 1847 )<BR> </TD></TR> <TR><TD> 25 mai 1832 </TD><TD> Fresnes sur Escaut 59970 </TD><TD> Décès de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche179.htm#f898"><NAME></A> ( ~ 1757 - 1832 )<BR> </TD></TR> <TR><TD> 1 décembre 1833 </TD><TD> Sebourg 59990 </TD><TD> Naissance de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche202.htm#f1014"><NAME></A> ( 1833 - 1878 )<BR> </TD></TR> <TR><TD> 20 septembre 1834 </TD><TD> Quarouble 59243 </TD><TD> Décès de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche184.htm#f920">M<NAME></A> ( 1762 - 1834 )<BR> </TD></TR> <TR><TD> 24 décembre 1838 </TD><TD> Fresnes sur Escaut 59970 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche63.htm#f316">CANONNE Nestor</A> ( 1838 - ? )<BR> </TD></TR> <TR><TD> 1845 </TD><TD> &nbsp; </TD><TD> Décès de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche144.htm#f724">JOLY Ambroisine</A> ( 1783 - 1845 )<BR> </TD></TR> <TR><TD> 25 décembre 1847 </TD><TD> Elouges B7370 </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche28.htm#f142"><NAME></A> ( 1791 - 1847 )<BR> </TD></TR> <TR><TD> 31 décembre 1848 </TD><TD> &nbsp; </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche50.htm#f252"><NAME></A> ( 1793 - 1848 )<BR> </TD></TR> <TR><TD> 14 juillet 1851 </TD><TD> Quarouble 59243 </TD><TD> Naissance de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche112.htm#f560">DUEE Tressance Appoline</A> ( 1851 - 1882 )<BR> </TD></TR> <TR><TD> 1854 </TD><TD> &nbsp; </TD><TD> Décès de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche112.htm#f562">DUEZ <NAME></A> ( 1792 - 1854 )<BR> </TD></TR> <TR><TD> 27 novembre 1854 </TD><TD> <NAME> 59297 </TD><TD> Naissance de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche186.htm#f933">MAZY <NAME></A> ( 1854 - ? )<BR> </TD></TR> <TR><TD> 15 mars 1866 </TD><TD> Fresnes sur Escaut 59970 </TD><TD> Mariage de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche63.htm#f316">CANONNE Nestor</A> ( 1838 - ? )<BR> <BR>de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche179.htm#f896">MARECHAL Josephine</A> ( 1846 - ? )<BR> </TD></TR> <TR><TD> 19 février 1867 </TD><TD> Anzin 59410 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche63.htm#f317">CANONNE Nestor</A> ( 1867 - 1936 )<BR> </TD></TR> <TR><TD> 1871 </TD><TD> &nbsp; </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche35.htm#f177"><NAME></A> ( 1871 - 1935 )<BR> </TD></TR> <TR><TD> 27 mars 1874 </TD><TD> Quarouble 59243 </TD><TD> Naissance de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche203.htm#f1016">PELEZ Adelade</A> ( 1874 - 1955 )<BR> </TD></TR> <TR><TD> 1875 </TD><TD> <NAME> 59297 </TD><TD> Naissance de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche232.htm#f1163">VELU Martine</A> ( 1875 - 1937 )<BR> </TD></TR> <TR><TD> 21 juin 1876 </TD><TD> &nbsp; </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche135.htm#f678">GRAIN Louis</A> ( 1876 - 1956 )<BR> </TD></TR> <TR><TD> 27 août 1877 </TD><TD> Lievin 62800 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche3.htm#f18">AMAND Adolphe</A> ( 1877 - 1934 )<BR> </TD></TR> <TR><TD> 1 mars 1880 </TD><TD> Sebourg 59990 </TD><TD> Naissance de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche81.htm#f406">DANHIEZ Angele</A> ( 1880 - 1969 )<BR> </TD></TR> <TR><TD> 6 juin 1881 </TD><TD> Lievin 62800 </TD><TD> Naissance de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche153.htm#f767">JO<NAME></A> ( 1881 - ? )<BR> </TD></TR> <TR><TD> 18 février 1882 </TD><TD> Quarouble 59243 </TD><TD> Décès de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche112.htm#f560">DUEE Tressance Appoline</A> ( 1851 - 1882 )<BR> </TD></TR> <TR><TD> 24 février 1892 </TD><TD> Anzin 59410 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche122.htm#f613"><NAME></A> ( 1892 - ? )<BR> </TD></TR> <TR><TD> 9 décembre 1895 </TD><TD> Quarouble 59243 </TD><TD> Mariage de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche150.htm#f754"><NAME></A> ( 1873 - 1946 )<BR> <BR>de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche203.htm#f1016">PELEZ Adelade</A> ( 1874 - 1955 )<BR> </TD></TR> <TR><TD> 3 décembre 1901 </TD><TD> Flenu B7012 </TD><TD> Mariage de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche3.htm#f18">AMAND Adolphe</A> ( 1877 - 1934 )<BR> <BR>de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche211.htm#f1056"><NAME></A> ( 1882 - 1965 )<BR> </TD></TR> <TR><TD> 1903 </TD><TD> &nbsp; </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche151.htm#f755"><NAME></A> ( 1903 - 1981 )<BR> </TD></TR> <TR><TD> 21 décembre 1903 </TD><TD> Quarouble 59243 </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche148.htm#f744"><NAME></A> ( 1841 - 1903 )<BR> </TD></TR> <TR><TD> 23 novembre 1905 </TD><TD> Sebourg 59990 </TD><TD> Naissance de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche67.htm#f335"><NAME></A> ( 1905 - 1997 )<BR> </TD></TR> <TR><TD> 9 mai 1910 </TD><TD> Lille 59800 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche117.htm#f589">FIEVET Kleber</A> ( 1910 - 1970 )<BR> </TD></TR> <TR><TD> 13 juin 1912 </TD><TD> &nbsp; </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche36.htm#f184">ARNOULD Robert</A> ( 1912 - 1968 )<BR> </TD></TR> <TR><TD> 20 décembre 1927 </TD><TD> &nbsp; </TD><TD> Naissance de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche151.htm#f757"><NAME></A> ( 1927 - ? )<BR> </TD></TR> <TR><TD> 3 février 1929 </TD><TD> Quiévrechain 59920 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche4.htm#f22">AMAND Adolphe</A> ( 1929 - 2002 )<BR> </TD></TR> <TR><TD> 20 juillet 1934 </TD><TD> Saint-Amand 59230 </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche3.htm#f18">AMAND Adolphe</A> ( 1877 - 1934 )<BR> </TD></TR> <TR><TD> 1935 </TD><TD> &nbsp; </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche35.htm#f177"><NAME></A> ( 1871 - 1935 )<BR> </TD></TR> <TR><TD> 11 février 1936 </TD><TD> Valenciennes 59300 </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche63.htm#f317"><NAME></A> ( 1867 - 1936 )<BR> </TD></TR> <TR><TD> 17 septembre 1936 </TD><TD> Beuvrages 59192 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche116.htm#f583">FIEVET Charles</A> ( 1936 - ? )<BR> </TD></TR> <TR><TD> 12 août 1937 </TD><TD> Bétheniville 51490 </TD><TD> Décès de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche232.htm#f1163">VELU Martine</A> ( 1875 - 1937 )<BR> </TD></TR> <TR><TD> 4 septembre 1937 </TD><TD> Bétheniville 51490 </TD><TD> Naissance de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche36.htm#f181">ARNOULD Josette</A> ( 1937 - ? )<BR> </TD></TR> <TR><TD> 27 avril 1942 </TD><TD> Charleroi- Pa </TD><TD> Domicile de <IMG SRC="../images/h.gif"> <A HREF="../fiches/fiche153.htm#f767">JOSS<NAME></A> ( 1881 - ? )<BR> <BR>de <IMG SRC="../images/f.gif"> <A HREF="../fiches/fiche28.htm#f144">AMAND Rosa</A> ( 1882 - ? )<BR> </TD></TR> <TR><TD> 11 février 1950 </TD><TD> Onnaing 59264 </TD><TD> Mariage de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche4.htm#f22">AMAND Adolphe</A> ( 1929 - 2002 )<BR> <BR>de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche151.htm#f757"><NAME></A> ( 1927 - ? )<BR> </TD></TR> <TR><TD> 9 septembre 1953 </TD><TD> Onnaing 59264 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche29.htm#f147">AMAND Ser<NAME></A> ( 1953 - ? )<BR> </TD></TR> <TR><TD> 29 janvier 1955 </TD><TD> Quarouble 59243 </TD><TD> Décès de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche203.htm#f1016">PELEZ Adelade</A> ( 1874 - 1955 )<BR> </TD></TR> <TR><TD> 18 octobre 1956 </TD><TD> Bétheniville 51490 </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche135.htm#f678">GRAIN Louis</A> ( 1876 - 1956 )<BR> </TD></TR> <TR><TD> 3 mars 1957 </TD><TD> Bétheniville 51490 </TD><TD> Naissance de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche118.htm#f591">FIEVET Marie-Claire</A> ( 1957 - ? )<BR> </TD></TR> <TR><TD> 29 septembre 1968 </TD><TD> &nbsp; </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche36.htm#f184"><NAME></A> ( 1912 - 1968 )<BR> </TD></TR> <TR><TD> 17 avril 1969 </TD><TD> Vicq 59970 </TD><TD> Décès de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche81.htm#f406"><NAME></A> ( 1880 - 1969 )<BR> </TD></TR> <TR><TD> 4 septembre 1970 </TD><TD> Beuvrages 59192 </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche117.htm#f589">FIEVET Kleber</A> ( 1910 - 1970 )<BR> </TD></TR> <TR><TD> décembre 1974 </TD><TD> &nbsp; </TD><TD> Décès de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche62.htm#f314"><NAME></A> ( ? - 1974 )<BR> </TD></TR> <TR><TD> 23 décembre 1978 </TD><TD> Raismes 59590 </TD><TD> Mariage de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche29.htm#f147"><NAME></A> ( 1953 - ? )<BR> <BR>de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche118.htm#f591"><NAME></A> ( 1957 - ? )<BR> </TD></TR> <TR><TD> 3 septembre 1979 </TD><TD> Valenciennes 59300 </TD><TD> Naissance de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche5.htm#f27">AMAND Alexis</A> ( 1979 - ? )<BR> </TD></TR> <TR><TD> 1981 </TD><TD> Onnaing 59264 </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche151.htm#f755"><NAME></A> ( 1903 - 1981 )<BR> </TD></TR> <TR><TD> février 1997 </TD><TD> Valenciennes 59300 </TD><TD> Décès de <IMG SRC="../images/f_s.gif"> <A HREF="../fiches/fiche67.htm#f335"><NAME></A> ( 1905 - 1997 )<BR> </TD></TR> <TR><TD> 5 décembre 2002 </TD><TD> Quarouble 59243 </TD><TD> Décès de <IMG SRC="../images/h_s.gif"> <A HREF="../fiches/fiche4.htm#f22">AMAND Adolphe</A> ( 1929 - 2002 )<BR> </TD></TR> </TABLE> <BR><BR> <CENTER> <A HREF="./../etats/actesarechercher0.htm"><IMG SRC="../images/iconLeft.gif" border=0></A> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <A HREF="./../etats/actesarechercher1.htm#"><IMG SRC="../images/iconTop.gif" border=0></A> </CENTER> <BR><BR> <DIV class="baspage" align="center"> Ces pages ont été créées par <A HREF="http://www.heredis.com" target="_blank">Heredis 10 pour Windows</A> , &copy; BSD Concept <BR><BR> <A HREF="http://www.heredis.com" target="_blank"><IMG SRC="../images/heredis.jpg" border=0></A> <A HREF="http://www.planete-genealogie.fr" target="_blank"><IMG SRC="../images/pg.jpg" border=0></A> </DIV> </BODY> </HTML> <file_sep>/genealogie/individus/ascendance2.htm~ <HTML> <HEAD> <TITLE>Mon ascendance</TITLE> <LINK rel="STYLESHEET" type="text/css" HREF="../menu/css.css"> <SCRIPT LANGUAGE="Javascript" SRC="../menu/coolmenus.js"></SCRIPT> </HEAD> <BODY topmargin=0 marginheight=0 background="./../images/fond.jpg"> <SCRIPT LANGUAGE="Javascript" SRC="../menu/menu.js"></SCRIPT> <BR><BR> <BR><BR> <CENTER><DIV class="titre">Mon ascendance</DIV></CENTER> <BR><BR> <CENTER> <TABLE width=95%><TR><TD> <DIV class="sstitre"> Génération 6 :</DIV> <TABLE width=100% border=1 cellspacing=0> <TR><TD class="titretab" align="center"> N° </TD><TD class="titretab" align="center"> Nom / Prénoms </TD><TD class="titretab" align="center"> Naissance </TD><TD class="titretab" align="center"> Décès </TD></TR> <TR><TD> 32 </TD><TD> <A HREF="../fiches/fiche3.htm#f17">AMAND Adolphe</A> </TD><TD> 9 août 1855 à Elouges B7370 </TD><TD> 11 janvier 1893 à Quiévrechain 59920 </TD></TR> <TR><TD> 33 </TD><TD> <A HREF="../fiches/fiche54.htm#f274">BROUETTE Antoinette</A> </TD><TD> 4 novembre 1854 à Dour B7370 </TD><TD> &nbsp; </TD></TR> <TR><TD> 34 </TD><TD> <A HREF="../fiches/fiche211.htm#f1059"><NAME></A> </TD><TD> 2 mars 1848 à Obourg B7000 </TD><TD> 18 août 1899 à Flenu B7012 </TD></TR> <TR><TD> 35 </TD><TD> <A HREF="../fiches/fiche102.htm#f511">DERNONCOURT Pauline</A> </TD><TD> 17 juillet 1849 à Jemmappes B7000 </TD><TD> 30 juillet 1884 à Flenu B7012 </TD></TR> <TR><TD> 38 </TD><TD> <A HREF="../fiches/fiche53.htm#f269">BRASSEUR Joseph</A> </TD><TD> vers 1850 </TD><TD> &nbsp; </TD></TR> <TR><TD> 40 </TD><TD> <A HREF="../fiches/fiche148.htm#f744"><NAME></A> </TD><TD> 20 juillet 1841 à Quarouble 59243 </TD><TD> 21 décembre 1903 à Quarouble 59243 </TD></TR> <TR><TD> 41 </TD><TD> <A HREF="../fiches/fiche112.htm#f560">DUEE Tressance Appoline</A> </TD><TD> 14 juillet 1851 à Quarouble 59243 </TD><TD> 18 février 1882 à Quarouble 59243 </TD></TR> <TR><TD> 44 </TD><TD> <A HREF="../fiches/fiche66.htm#f330"><NAME></A> </TD><TD> 25 mai 1826 à Sebourg 59990 </TD><TD> 8 juin 1891 à Sebourg 59990 </TD></TR> <TR><TD> 45 </TD><TD> <A HREF="../fiches/fiche202.htm#f1014"><NAME></A> </TD><TD> 1 décembre 1833 à Sebourg 59990 </TD><TD> 10 novembre 1878 à Sebourg 59990 </TD></TR> <TR><TD> 47 </TD><TD> <A HREF="../fiches/fiche81.htm#f408"><NAME></A> </TD><TD> vers 1855 </TD><TD> &nbsp; </TD></TR> <TR><TD> 48 </TD><TD> <A HREF="../fiches/fiche117.htm#f585">FIEVET <NAME></A> </TD><TD> 12 octobre 1854 à Lille 59800 </TD><TD> vers 1940 </TD></TR> <TR><TD> 49 </TD><TD> <A HREF="../fiches/fiche176.htm#f881"><NAME></A> </TD><TD> 5 novembre 1863 à Lille 59800 </TD><TD> 19 mai 1894 à Lille 59800 </TD></TR> <TR><TD> 50 </TD><TD> <A HREF="../fiches/fiche93.htm#f469">DELAUX Adolphe Auguste</A> </TD><TD> 9 septembre 1854 à Lille 59800 </TD><TD> 11 janvier 1906 à Lille 59800 </TD></TR> <TR><TD> 51 </TD><TD> <A HREF="../fiches/fiche214.htm#f1070"><NAME></A> </TD><TD> 26 mars 1857 à Lille 59800 </TD><TD> &nbsp; </TD></TR> <TR><TD> 54 </TD><TD> <A HREF="../fiches/fiche63.htm#f317"><NAME></A> </TD><TD> 19 février 1867 à Anzin 59410 </TD><TD> 11 février 1936 à Valenciennes 59300 </TD></TR> <TR><TD> 55 </TD><TD> <A HREF="../fiches/fiche110.htm#f554"><NAME></A> </TD><TD> &nbsp; </TD><TD> &nbsp; </TD></TR> <TR><TD> 60 </TD><TD> <A HREF="../fiches/fiche135.htm#f677"><NAME></A> </TD><TD> &nbsp; </TD><TD> &nbsp; </TD></TR> <TR><TD> 61 </TD><TD> <A HREF="../fiches/fiche232.htm#f1162">VELU Joséphine</A> </TD><TD> &nbsp; </TD><TD> &nbsp; </TD></TR> <TR><TD> 62 </TD><TD> <A HREF="../fiches/fiche232.htm#f1161">VELU Alphonse</A> </TD><TD> &nbsp; </TD><TD> &nbsp; </TD></TR> <TR><TD> 63 </TD><TD> <A HREF="../fiches/fiche186.htm#f933">MAZY <NAME></A> </TD><TD> 27 novembre 1854 à <NAME> 59297 </TD><TD> &nbsp; </TD></TR> </TABLE> <BR><BR> </CENTER> <BR><BR> <CENTER> <A HREF="./../individus/ascendance1.htm"><IMG SRC="../images/iconLeft.gif" border=0></A> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <A HREF="./../individus/ascendance2.htm#"><IMG SRC="../images/iconTop.gif" border=0></A> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <A HREF="./../individus/ascendance3.htm"><IMG SRC="../images/iconRight.gif" border=0></A> </CENTER> <BR><BR> <DIV class="baspage" align="center"> Ces pages ont été créées par <A HREF="http://www.heredis.com" target="_blank">Heredis 10 pour Windows</A> , &copy; BSD Concept <BR><BR> <A HREF="http://www.heredis.com" target="_blank"><IMG SRC="../images/heredis.jpg" border=0></A> <A HREF="http://www.planete-genealogie.fr" target="_blank"><IMG SRC="../images/pg.jpg" border=0></A> </DIV> </BODY> </HTML> <file_sep>/archives/siteperso3/genealogie/heredis/accueil[1].htm <HTML> <HEAD> <TITLE>Ma g�n�alogie</TITLE> <LINK rel="STYLESHEET" type="text/css" HREF="../menu/css.css"> <SCRIPT LANGUAGE="Javascript" SRC="../menu/coolmenus.js"></SCRIPT> </HEAD> <BODY topmargin=0 marginheight=0 background="./../images/fond.jpg"> <SCRIPT LANGUAGE="Javascript" SRC="../menu/menu.js"></SCRIPT> <BR><BR> <BR><BR> <CENTER><DIV class="titre">Ma g�n�alogie</DIV></CENTER> <BR><BR> <br> <br> <CENTER> Ce site pr�sente d�sormais ma g�n�alogie, ... <BR><BR><BR> Cette g�n�alogie se compose de : <BR> 1283 individus, 390 familles, 298 patronymes et 79 lieux <BR><BR><BR> T�l�chargez mon Gedcom : <A HREF="gedcom_al.GED" target="_blank">mon gedcom</A> <BR><BR><BR> Elle a �t� pr�par�e et �dit�e par : <BR> <NAME> <BR> 7-41 rue blaise pascal <BR> <A HREF="mailto:<EMAIL>"><EMAIL></A> <BR> <A HREF="http://www.la-genealogie-entre-amis.com" target="_blank">http://www.la-genealogie-entre-amis.com</A> <BR> <BR><BR> Retrouvez l'ensemble des donn�es � l'aide des menus situ�s dans la barre du haut. <BR><BR> Derni�re mise � jour le 06/12/2008 <BR><BR> </CENTER> <BR><BR> <DIV class="baspage" align="center"> Ces pages ont �t� cr��es par <A HREF="http://www.heredis.com" target="_blank">Heredis 10 pour Windows</A> , &copy; BSD Concept <BR> <A HREF="http://www.heredis.com" target="_blank"><IMG SRC="../images/heredis.jpg" border=0></A> <A HREF="http://www.planete-genealogie.fr" target="_blank"><IMG SRC="../images/pg.jpg" border=0></A> </DIV> </BODY> </HTML>
52855f8ff853a7be8622dcc5eb29faa02524a1a9
[ "JavaScript", "HTML" ]
6
HTML
AlexisAmand/MyFirstSite
0a2da7c108b1b1dce5858d7191ed010fc91310fc
02c1db22e14193ea533bcdccf62682a025371034
refs/heads/master
<file_sep>#!/usr/bin/env python # coding: utf-8 # In[1]: import os import sys import time import warnings import numpy as np import pandas as pd from numpy import newaxis from keras.layers.core import Dense, Activation, Dropout from keras.layers import Convolution1D, MaxPooling1D, Flatten, Embedding from keras.layers import Conv1D, GlobalMaxPooling1D from keras.layers.recurrent import LSTM from keras.models import Sequential from datetime import datetime import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler, Normalizer np.random.seed(7) os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' warnings.filterwarnings("ignore") t_0 = '2011-09-18' t_n = '2020-03-01' # This is an hourly csv file. Read it in and resample it. eudf = pd.read_csv('/media/sf_tickdata/EURUSD-H1-2004.csv', parse_dates=True) eudf['Date'] = pd.to_datetime(eudf['Date'],yearfirst=True, format='%Y%m%d') #eudf['Date'] = pd.to_datetime(eudf['Date']) eudf['Timestamp'] = eudf['Date'].astype(str) + ' ' + eudf['Timestamp'].astype(str) eudf.index = pd.to_datetime(eudf['Timestamp']) eudf = eudf.loc[eudf.index >= pd.to_datetime(t_0)] eudf = eudf.loc[eudf.index <= pd.to_datetime(t_n)] eudf = eudf[['Timestamp', 'Close']] eudf.head() #Create a daily data frame from an hourly #eudf1 = eudf eudf1 = eudf['Close'].astype('float').resample('D').asfreq() eudf1.columns = ['Close'] print("eudf:\n", eudf1.head()) # S&P spdf = pd.read_csv('/media/sf_tickdata/USA500IDXUSD.csv', index_col='Timestamp', parse_dates=True) spdf['Date'] = pd.to_datetime(spdf['Date'],yearfirst=True, format='%Y%m%d') spdf.index = spdf['Date'] spdf = spdf.loc[spdf.index >= pd.to_datetime(t_0)] spdf = spdf.loc[spdf.index <= pd.to_datetime(t_n)] spdf.tail() #YEN dailies ujdf = pd.read_csv('/media/sf_tickdata/USDJPY-2003-daily.csv', index_col='Timestamp', parse_dates=True) ujdf['Date'] = pd.to_datetime(ujdf['Date'],yearfirst=True, format='%Y%m%d') ujdf.index = ujdf['Date'] ujdf = ujdf.loc[ujdf.index >= pd.to_datetime(t_0)] ujdf = ujdf.loc[ujdf.index <= pd.to_datetime(t_n)] #Guppie Dailies gjdf = pd.read_csv('/media/sf_tickdata/GBPJPY-2008-daily.csv', index_col='Timestamp', parse_dates=True) gjdf['Date'] = pd.to_datetime(gjdf['Date'],yearfirst=True, format='%Y%m%d') gjdf.index = gjdf['Date'] gjdf = gjdf.loc[gjdf.index >= pd.to_datetime(t_0)] gjdf = gjdf.loc[gjdf.index <= pd.to_datetime(t_n)] #Cable Dailies gudf3 = pd.read_hdf('/media/sf_tickdata/GBPUSD-2008-daily.h5') gudf3['Date'] = pd.to_datetime(gudf3['Date'],yearfirst=True, format='%Y%m%d') gudf3.index = gudf3['Date'] gudf3 = gudf3.loc[gudf3.index > pd.to_datetime(t_0)] gudf3 = gudf3.loc[gudf3.index <= pd.to_datetime(t_n)] #plt.plot(gudf3.loc[gudf3.index > pd.to_datetime(t_0)]['Close']) #plt.show() #Create a historically cross-sectional financial context #Start with S&P fulldf = spdf fulldf['S&P500'] = fulldf['Close'] fulldf = fulldf[['Date', 'S&P500']] #Add Guppie fulldf['GBPJPY'] = gjdf['Close'] #Add Yen fulldf['USDJPY'] = ujdf['Close'] #Add Euro fulldf['EURUSD'] = eudf1#['Close'] #Add Cable fulldf['GBPUSD'] = gudf3['Close'] fulldf = fulldf.iloc[50:] #plt.plot(gjdf['Close']) #plt.plot(fulldf['GBPJPY']) #plt.show() #plt.plot(ujdf['Close']) #plt.plot(fulldf['USDJPY']) #plt.show() #plt.plot(eudf1)#['Close']) #plt.plot(fulldf['EURUSD']) #plt.show() #plt.plot(gudf3['Close']) #plt.plot(fulldf['GBPUSD']) #plt.show() ''' prices = pd.read_hdf('/media/sf_tickdata/fulldf.h5') prices = prices.loc[prices.index > pd.to_datetime('2011-09-18')] plt.plot(gudf3['Close'], "g") plt.plot(gudf3.loc[gudf3.index > pd.to_datetime('2011-09-18')]['Close'], "g") ''' def retFFT(key, df): n = len(df[key]) Y = np.fft.fft(df[key]) np.put(Y, range(100, n), 0.0) ifft = np.fft.ifft(Y) ifftdf = pd.DataFrame(ifft.real, index= df.index, columns=['Fourier Series']) #plt.plot(ifftdf[5:n-5], "r-") #plt.plot(df[key], "g") return ifftdf prices = fulldf prices['GBPUSD-ifft'] = retFFT('GBPUSD', prices) prices['GBPJPY-ifft'] = retFFT('GBPJPY', prices) prices['USDJPY-ifft'] = retFFT('USDJPY', prices) print("prices:\n", prices.head()) print(prices.columns) ''' n = len(prices['GBPUSD']) Y = np.fft.fft(prices['GBPUSD']) np.put(Y, range(100, n), 0.0) ifft = np.fft.ifft(Y) ifftdf = pd.DataFrame(ifft, index= prices.index, columns=['Fourier Series']) ''' #plt.plot(gudf3.loc[gudf3.index > pd.to_datetime(t_0)]['Close']) ''' # In[20]: df = pd.read_hdf('../data/DeepLearning.h5', 'Data_GBPJPY') #df = df.loc[df.index > pd.to_datetime('2008-01-01')] df.head() # In[121]: didf = pd.read_hdf('../data/DeepLearning.h5', 'Data_Index') #df = df.loc[df.index > pd.to_datetime('2008-01-01')] didf.tail() # In[122]: dpdf = pd.read_hdf('../data/DeepLearning.h5', 'Deep_Portfolio') #df = df.loc[df.index > pd.to_datetime('2008-01-01')] dpdf.tail() # In[119]: import h5py with h5py.File("../data/DeepLearning.h5") as f: print(f.keys()) # In[6]: ''' df = prices del df['Date'] #prices[''].pct_change().fillna(0) for c in df.columns: print("column: ", c) df[c+'_ret'] = df[c].pct_change().fillna(0) def create_dataset(dataset, look_back=1, columns = ['GBPJPY']): dataX, dataY = [], [] for i in range(len(dataset.index)): if i <= look_back: continue a = None for c in columns: b = dataset.loc[dataset.index[i-look_back:i], c].as_matrix() if a is None: a = b else: a = np.append(a,b) dataX.append(a) dataY.append(dataset.loc[dataset.index[i], columns].as_matrix()) return np.array(dataX), np.array(dataY) look_back = 12 sc = StandardScaler() df.loc[:, 'GBPJPY'] = sc.fit_transform(np.array(df.loc[:, 'GBPJPY']).reshape(-1,1)) sc1 = StandardScaler() df.loc[:, 'S&P500'] = sc1.fit_transform(np.array(df.loc[:, 'S&P500']).reshape(-1,1)) sc2 = StandardScaler() df.loc[:, 'USDJPY'] = sc1.fit_transform(np.array(df.loc[:, 'USDJPY']).reshape(-1,1)) sc2 = StandardScaler() df.loc[:, 'GBPUSD'] = sc1.fit_transform(np.array(df.loc[:, 'GBPUSD']).reshape(-1,1)) df.loc[:, 'GBPJPY-ifft'] = sc.fit_transform(np.array(df.loc[:, 'GBPJPY-ifft']).reshape(-1,1)) sc1 = StandardScaler() df.loc[:, 'USDJPY-ifft'] = sc1.fit_transform(np.array(df.loc[:, 'USDJPY-ifft']).reshape(-1,1)) sc2 = StandardScaler() df.loc[:, 'GBPUSD-ifft'] = sc1.fit_transform(np.array(df.loc[:, 'GBPUSD-ifft']).reshape(-1,1)) df.head() train_df = df.loc[df.index < pd.to_datetime('2016-01-01')] #val_df = train_df.loc[train_df.index >= pd.to_datetime('2013-01-01')] #train_df = train_df.loc[train_df.index < pd.to_datetime('2013-01-01')] #test_df = df.loc[df.index >= pd.to_datetime('2016-01-01')] #train_x, train_y = create_dataset(train_df, look_back=look_back) ##val_x, val_y = create_dataset(val_df, look_back=look_back) #test_x, test_y = create_dataset(test_df, look_back=look_back) timeseries = np.asarray(df.GBPJPY) timeseries = np.atleast_2d(timeseries) if timeseries.shape[0] == 1: timeseries = timeseries.T X = np.atleast_3d(np.array([timeseries[start:start + look_back] for start in range(0, timeseries.shape[0] - look_back)])) y = timeseries[look_back:] predictors = ['GBPJPY']#, 'GBPUSD','S&P500']#, 'USDJPY'] #TRAIN_SIZE = train_x.shape[0] #EMB_SIZE = look_back model = Sequential() #model.add(Embedding(TRAIN_SIZE, 1, input_length=EMB_SIZE)) model.add(Convolution1D(input_shape = (look_back,1), nb_filter=64, filter_length=2, border_mode='valid', activation='relu', subsample_length=1)) model.add(MaxPooling1D(pool_length=2)) model.add(Convolution1D(input_shape = (look_back,1), nb_filter=64, filter_length=2, border_mode='valid', activation='relu', subsample_length=1)) model.add(MaxPooling1D(pool_length=2)) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(250)) model.add(Dropout(0.25)) model.add(Activation('relu')) model.add(Dense(1)) model.add(Activation('linear')) start = time.time() model.compile(loss="mse", optimizer="rmsprop") model.fit(X, y, epochs=1000, batch_size=80, verbose=1, shuffle=False) df['Pred'] = df.loc[df.index[0], 'GBPJPY'] for i in range(len(df.index)): if i <= look_back: continue a = None for c in predictors: b = df.loc[df.index[i-look_back:i], c].as_matrix() if a is None: a = b else: a = np.append(a,b) a = a y = model.predict(a.reshape(1,look_back*len(predictors),1)) df.loc[df.index[i], 'Pred']=y[0][0] df.to_hdf('DeepLearning.h5', 'Pred_CNN') df.loc[:, 'GBPJPY'] = sc.inverse_transform(df.loc[:, 'GBPJPY']) df.loc[:, 'Pred'] = sc.inverse_transform(df.loc[:, 'Pred']) plt.plot(df.GBPJPY,'y') plt.plot(df.Pred, 'g') plt.show()
5382f5f14be22abe7157ce893341bd6068b02c42
[ "Python" ]
1
Python
revivalfx/DeepLearningInFinance
8780402a4b0712d5d03981f5dd740fb94ef9955b
f8a43566c08d6f2d4c1bc55486da27ed9bbc4c41
refs/heads/master
<repo_name>satylogin/basics<file_sep>/README.md # basics the following is a collection of some very basic programming elements. <file_sep>/do_while_loop_2.cpp // it is a c/c++ implementation of do while loops // this function shows the general implementation of do while loop. #include <stdio.h> int main() { int i = 1; do { printf("%d\n", i); ++i; } while (i <= 20); return 0; } <file_sep>/while_loop.cpp //the following is a c/c++ implemetation of while loop // problem - to print numbers from 1 to 20 #include <stdio.h> int main() { int i = 1; // initialiasation // check while (i <= 20) { printf("%d\n", i); ++i; // update } return 0; } <file_sep>/do_while_loop_1.cpp // it is a c/c++ implementation of do while loops // this function shows that the program will execute atleast once even if the condition is false. #include <stdio.h> int main() { int i = 21; do { printf("%d\n", i); ++i; } while (i <= 20); return 0; }
899f59cce84082f9d7e26e69ed144dcca3a374fa
[ "Markdown", "C++" ]
4
Markdown
satylogin/basics
1d1b0c76ae188461d829ec2f1ff5f2df636ecf61
a44b6d8f0ee1c81edcb6bdd9108f4f1cf53da4c0
refs/heads/master
<file_sep>org.gradle.jvmargs=-Xmx4608m android.useAndroidX=true android.enableJetifier=true android.enableR8=true extra-gen-snapshot-options=--obfuscate<file_sep>import io.flutter.embedding.android.FlutterFragmentActivity class MainActivity: FlutterFragmentActivity() { override fun configureFlutterEngine(flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) }<file_sep>package com.example.chatify; import io.flutter.app.FlutterApplication; public class Application extends FlutterApplication{ }<file_sep># Chatify - Chat and Video Call App ## Table of Contents - [Introduction](#introduction) - [Features](#features) - [Installation](#installation) - [Usage](#usage) - [Customization](#customization) - [Contributing](#contributing) - [License](#license) ## Introduction Chatify is a secure chat and video call app built using Flutter. It allows users to communicate with each other in real-time through encrypted messages, ensuring privacy and confidentiality. The app also supports high-quality video calls and multimedia sharing. It leverages Google Firebase as the backend to provide seamless and reliable communication. ## Features - **Real-time Chat**: Users can exchange encrypted text messages in real-time, ensuring secure communication. - **Message Encryption**: Chatify encrypts messages using advanced encryption algorithms, providing end-to-end security and protecting user data. - **Video Calls**: Chatify supports high-quality video calls, enabling face-to-face conversations regardless of users' locations. - **Multimedia Sharing**: The app allows users to securely share photos, videos, documents, and other multimedia files, enhancing communication and collaboration. - **Contact Management**: Users can manage their contacts by adding new contacts, searching for existing ones, and organizing them into groups. - **Notification System**: Chatify provides a notification system to ensure users stay updated with new messages, missed calls, and other important events. ## Installation 1. Clone the repository: ``` git clone https://github.com/tejasbirsingh/Chatify-Video-Calling-and-Chatting.git ``` 2. Install the necessary dependencies: ``` cd Chatify-Video-Calling-and-Chatting flutter pub get ``` 3. Configure Firebase: - Create a new Firebase project on the [Firebase Console](https://console.firebase.google.com/). - Follow the instructions to add your Flutter app to the Firebase project and download the `google-services.json` file. - Replace the existing `google-services.json` file in the `android/app` directory of the project with the downloaded file. 4. Run the app: ``` flutter run ``` ## Usage 1. Launch the Chatify app on your device. 2. Sign up or log in to your account. 3. Explore the app's intuitive interface to access the following features: - Chat: Select a contact or create a new chat room to exchange encrypted text messages. - Video Call: Initiate a video call with a contact who is currently online. - Multimedia Sharing: Use the provided options to securely share photos, videos, or documents. - Contact Management: Add, search, and organize your contacts as needed. 4. Enjoy seamless and secure communication, knowing that your messages are encrypted and protected. ## Customization Chatify provides several customization options to enhance the user experience: - **Themes**: Personalize the app's appearance by choosing from a range of themes, such as light mode or dark mode. You can toggle between these themes in the app's settings. - **Background Colors**: Customize the background color of the app by selecting from a palette of colors or by providing a custom color code. This allows you to create a personalized look and feel for your Chatify experience. - **Notifications**: Configure notification settings to control how and when you receive notifications for new messages, calls, or other events. - **Privacy**: Customize privacy settings to manage who can contact you, view your online status, or access your shared content. Feel free to explore these customization options to make Chatify truly personalized and tailored to your preferences. ## Contributing Contributions are welcome! If you'd like to contribute to this project, please follow these steps: 1. Fork the repository. 2. Create a new branch for your feature or bug fix. 3. Make your changes and test them thoroughly. 4. Submit a pull request describing your changes and their benefits. ## License This project is licensed under the [MIT License](LICENSE). A new Flutter project. ## Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this is your first Flutter project: - [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab) - [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook) For help getting started with Flutter, view our [online documentation](https://flutter.dev/docs), which offers tutorials, samples, guidance on mobile development, and a full API reference. <file_sep>// const functions = require('firebase-functions'); // // Create and Deploy Your First Cloud Functions // // https://firebase.google.com/docs/functions/write-firebase-functions // // exports.helloWorld = functions.https.onRequest((request, response) => { // functions.logger.info("Hello logs!", {structuredData: true}); // response.send("Hello from Firebase!"); // }); // const admin = require('firebase-admin') // admin.initializeApp() // exports.sendNotification = functions.firestore.document("messages/{sender}/{receiver}/{notification}") // .onCreate(async (snapshot,context)=>{ // try { // const notificationsDocument=snapshot.data() // console.log(notificationsDocument) // const uid = context.params.user; // const message = notificationsDocument.message; // const userDoc = await admin.firestore().collection("messages").doc(uid).collection(notificationsDocument.receiverId).get() // const tokenFcm=userDoc.data().token; // const message={ // "notification":{ // title:"New Message", // body: message // }, // token:tokenFcm // } // return admin.messaging().send(message) // } catch (error) { // console.log(error) // } // }) const functions = require('firebase-functions') const admin = require('firebase-admin') admin.initializeApp() exports.sendNotification = functions.firestore .document('messages/{groupId1}/{groupId2}/{message}') .onCreate((snap, context) => { console.log('----------------start function--------------------') const doc = snap.data() console.log(doc) const idFrom = doc.senderId const idTo = doc.receiverId const contentMessage = doc.message // Get push token user to (receive) admin .firestore() .collection('users') .where('id', '==', idTo) .get() .then(querySnapshot => { querySnapshot.forEach(userTo => { console.log(`Found user to: ${userTo.data().name}`) if (userTo.data().pushToken && userTo.data().chattingWith !== idFrom) { // Get info user from (sent) admin .firestore() .collection('users') .where('id', '==', idFrom) .get() .then(querySnapshot2 => { querySnapshot2.forEach(userFrom => { console.log(`Found user from: ${userFrom.data().name}`) const payload = { notification: { title: `You have a message from "${userFrom.data().name}"`, body: contentMessage, badge: '1', sound: 'default' } } // Let push to the target device admin .messaging() .sendToDevice(userTo.data().pushToken, payload) .then(response => { console.log('Successfully sent message:', response) }) .catch(error => { console.log('Error sending message:', error) }) }) }) } else { console.log('Can not find pushToken target user') } }) }) return null })
f1098f26801c322125502732212261de10c615a8
[ "Markdown", "JavaScript", "INI", "Java", "Kotlin" ]
5
INI
tejasbirsingh/Chatify-Video-Calling-and-Chatting
e386f89406ca6fefc26abb50cf9b5ab5c9595e58
ac7ab9f8cbddc6b75e62af3ac0e356faa14ab872
refs/heads/master
<file_sep>#include "monty.h" /** * pint - prints the int at node * @h: node * Return: NULL */ void pint(const stack_t *h) { printf("%d\n", h->n); } <file_sep>#include "monty.h" /** * pop - deletes top node on stack * @h: top of stack * Return: NULL */ void pop(const stack_t *h) { const stack_t *top = h; const stack_t *topNext = h->next; const stack_t *topPrev = h->prev; /* if h == NULL */ /* if *h == NULL */ h = h->prev; free(topNext); free(topPrev); free(top); } <file_sep>#include "monty.h" /** * push - adds new node to stack * @h: top of stack * Return: NULL */ stack_t *push(stack_t **head, int number) { stack_t *new; if (head == NULL) return (NULL); new = malloc(sizeof(stack_t)); if (new == NULL) return (NULL); new->n = number; if ((*head) == NULL) { *head = new; return (new); } new->next = *head; (*head)->prev = new; new->prev = NULL; *head = new; return (new); } <file_sep>#include "monty.h" char *file_reader(const char *filename) { int buffer; char *array; if (filename == NULL) return (0); buffer = open(filename, O_RDONLY); if (buffer == -1) return (0); array = malloc(sizeof(char) * SIZE); read(buffer, array, SIZE); close(buffer); return (array); } <file_sep>#include "monty.h" void (*get_function(char *s)) { instruction_t functions[] = { {"push", push}, {"pall", pall}, /*{"pint", pint}, {"pop", pop}, {"swap", swap}, {"add", add}, {"nop", nop},*/ {NULL, NULL} }; int i = 0; char *func; int argument; func = strtok(s, " \n"); while (func != NULL) { printf("From get function: %s\n", func); argument = atoi(strtok(NULL, " \n")); printf("From get fucntion: %d\n", argument); break; } while (functions[i].opcode != NULL) { if (functions[i].opcode == s) return (functions[i].f); i++; } return (NULL); } <file_sep>#include "monty.h" /** * pall - prints values of all nodes * @h: top of stack * Return: NULL */ void pall(const stack_t *h) { while (h != NULL) { printf("%d\n", h->n); h = h->next; } } <file_sep>#include "monty.h" /** * error_handler - prints corresponding error message then exits * @name: error tag * @var: variable string * @var2: variable string * @num: variable int * Return: void */ void error_handler(char *name, char *var, char *var2, int num) { if (name == "use_err") { void (num); void(var); void(var2); write(STDERR_FILENO, "USAGE: monty file\n", 17); exit(EXIT_FAILURE); } else if (name == "fopen_err") { void(num); void(var2); write(STDERR_FILENO, "Error: Can't open file ", 23); write(STDERR_FILENO, var, strlen(var)); write(STDERR_FILENO, "\n", 1); exit(EXIT_FAILURE); } else if (name == "op_err") { void(var2); write(STDERR_FILENO, "L", 1); printf("%d", num); write(STDERR_FILENO, ":", 1); write(STDERR_FILENO, var, strlen(var)); write(STDERR_FILENO, "\n", 1); exit(EXIT_FAILURE); } else if (name == "malloc_err") { write(STDERR_FILENO, "Error: malloc failed\n", 21); exit(EXIT_FAILURE); } } <file_sep>#include "monty.h" /** * main - entry, error checks * @ac: arg count * @av: args * Return: status - success/fail */ int main(int ac, char **av) { int fdopen; char *buffer; char *tokens; if (ac != 2) error_handler("use_err", "", ""); fdopen = open(filename, O_RDWR); if (fdopen == -1) error_handler("fopen_error" , av[1], ""); buffer = file_reader(argv[1]); tokens = strtok(buffer, " \n"); while (tokens != NULL) { printf("%s\n", tokens); tokens = strtok(NULL, " \n"); } /*if opcode reader returns -1 error_handler("op_err", line, "", lineNumber); */ /*if malloc(len of line) = NULL error_handler("malloc_err", "", "", 0*/ return (EXIT_SUCCESS); }
2755959dd1dead6e5166a8aedaffc7e17fa31b09
[ "C" ]
8
C
guilmeister/el_monty_practice
7af58ce1fe363b37baca25fb4717c219a4878e48
936a253897ab1f7cdf9cc5cf99233790f054fa76
refs/heads/main
<repo_name>bhavithmanapoty/Family_WiFi_Lights<file_sep>/Code/Family_WiFi_Lights_Rithu/Rithu_Light_On.ino void checkIfRithuLightOn() { Adafruit_MQTT_Subscribe * subscription; while ((subscription = mqtt.readSubscription(1500))) { if (subscription == &RithuLightSub) { if (!strcmp((char*) RithuLightSub.lastread, "ON")) { //Switch ON LED Serial.println("Rithu Light ON"); rainbow_wave(25, 10); FastLED.show(); delay(5000); FastLED.clear(); } else if (!strcmp((char*) RithuLightSub.lastread, "OFF")) { //Switch OFF LED Serial.println("Rithu Light OFF"); FastLED.clear(); } else { Serial.println("ERROR"); } } } } void rainbow_wave(uint8_t thisSpeed, uint8_t deltaHue) { // uint8_t thisHue = beatsin8(thisSpeed,0,255); uint8_t thisHue = beat8(thisSpeed,255); fill_rainbow(Light1, NUM_LEDS, thisHue, deltaHue); fill_rainbow(Light2, NUM_LEDS, thisHue, deltaHue); } <file_sep>/Code/Family_WiFi_Lights_Rithu/Family_WiFi_Lights_Rithu.ino //Include required libraries #include <ESP8266WiFi.h> #include <FastLED.h> #include "Adafruit_MQTT.h" #include "Adafruit_MQTT_Client.h" //Connect Adafruit Account #define MQTT_SERV "io.adafruit.com" #define MQTT_PORT 1883 #define MQTT_NAME "tstark20486" #define MQTT_PASS "<PASSWORD>" //Adafruit Ping #define MQTT_KEEP_ALIVE 300 unsigned long previousTime = 0; //Light State int LightState = 0; //ADD WIFI DETAILS #define WIFI_SSID "PLUSNET-GFMNNG" #define WIFI_PASS "<PASSWORD>" //#define WIFI_SSID "OnePlus 6" //#define WIFI_PASS "<PASSWORD>" //Define Hardware Setup //LIGHTS #define RithuLight1 D2 #define RithuLight2 D3 //SWITCHES #define BhaviTouchSw D5 #define HomeTouchSw D6 #define LightOnSw D7 //LED Strip Setup #define FASTLED_ALLOW_INTERRUPTS 0 #define NUM_LEDS 15 struct CRGB Light1[NUM_LEDS]; struct CRGB Light2[NUM_LEDS]; //Initialize Connection to Adafruit WiFiClient client; Adafruit_MQTT_Client mqtt(&client, MQTT_SERV, MQTT_PORT, MQTT_NAME, MQTT_PASS); //Adafruit Subscription Feeds Adafruit_MQTT_Subscribe RithuLightSub = Adafruit_MQTT_Subscribe(&mqtt, MQTT_NAME "/f/RithuLightState"); //Adafruit Publishing Feeds Adafruit_MQTT_Publish HomeLightPub = Adafruit_MQTT_Publish(&mqtt, MQTT_NAME "/f/HomeLightState"); Adafruit_MQTT_Publish BhaviLightPub = Adafruit_MQTT_Publish(&mqtt, MQTT_NAME "/f/BhaviLightState"); void setup() { //Begin Serial Connection Serial.begin(9600); //Hardware Setup pinMode(BhaviTouchSw, INPUT_PULLUP); pinMode(HomeTouchSw, INPUT_PULLUP); pinMode(LightOnSw, INPUT_PULLUP); //Connect to WiFi Serial.print("\n\nConnecting Wifi>"); WiFi.begin(WIFI_SSID, WIFI_PASS); while (WiFi.status() != WL_CONNECTED) { Serial.print(">"); delay(50); } Serial.println("OK!"); //Subscribe to Adafruit Feeds mqtt.subscribe(&RithuLightSub); //LED Strip Setup LEDS.addLeds<WS2812, RithuLight1, GRB>(Light1, NUM_LEDS); LEDS.addLeds<WS2812, RithuLight2, GRB>(Light2, NUM_LEDS); FastLED.setBrightness(255); FastLED.setMaxPowerInVoltsAndMilliamps(5, 1000); FastLED.clear(); } void loop() { //Connect/Reconnect to MQTT Server if(!mqtt.connected()){ MQTT_connect(); } //If Touch Light Switch if (!digitalRead(LightOnSw)) { if(LightState == 0){ LightState = 1; } else { LightState = 0; } } //If Touch Bhavith Switch else if (!digitalRead(BhaviTouchSw)) { BhaviSwitchTouched(); } //If Touch Rithu Switch else if (!digitalRead(HomeTouchSw)) { HomeSwitchTouched(); } //Checks is someone is contacting Home light else { checkIfRithuLightOn(); } //Turn on Light depending on current state RithuSwitchTouched(LightState); } <file_sep>/Code/Family_WiFi_Lights_Bhavi/Bhavi_Light_On.ino void checkIfBhaviLightOn() { Adafruit_MQTT_Subscribe * subscription; while ((subscription = mqtt.readSubscription(5000))) { if (subscription == &BhaviLightSub) { if (!strcmp((char*) BhaviLightSub.lastread, "ON")) { //Switch ON LED Serial.println("Bhavi Light ON"); rainbow_wave(25, 10); FastLED.show(); delay(5000); FastLED.clear(); } else if (!strcmp((char*) BhaviLightSub.lastread, "OFF")) { //Switch OFF LED Serial.println("Bhavi Light OFF"); FastLED.clear(); } else { Serial.println("ERROR"); } } } } void rainbow_wave(uint8_t thisSpeed, uint8_t deltaHue) { // uint8_t thisHue = beatsin8(thisSpeed,0,255); uint8_t thisHue = beat8(thisSpeed,255); fill_rainbow(Light1, NUM_LEDS, thisHue, deltaHue); fill_rainbow(Light2, NUM_LEDS, thisHue, deltaHue); } <file_sep>/Code/Family_WiFi_Lights_Home/Switch_Touched.ino void HomeSwitchTouched(int state) { if (state == 1) { LED_On('w'); Serial.println("LIGHT ON"); } else if (state == 0) { LED_On('0'); Serial.println("LIGHT OFF"); } } void BhaviSwitchTouched() { Serial.println("CALLING BHAVITH"); //Touch Detected LED Indication for (int i = 0; i < 5; i++) { LED_On('r'); delay(400); LED_On('0'); delay(400); } //Adafruit Publish BhaviLightPub.publish("ON"); delay(2000); BhaviLightPub.publish("OFF"); } void RithuSwitchTouched() { Serial.println("CALLING RITHIKA"); //Touch Detected LED Indication for (int i = 0; i < 5; i++) { LED_On('r'); delay(400); LED_On('0'); delay(400); } //Adafruit Publish RithuLightPub.publish("ON"); delay(2000); RithuLightPub.publish("OFF"); } void LED_On(char color) { int r, g, b; switch (color) { //COLORS OF RAINBOW case 'v': //VIOLET r = 127; g = 0; b = 255; break; case 'i': //INDIGO r = 75; g = 0; b = 130; break; case 'b': //BLUE r = 0; g = 0; b = 255; break; case 'g': //GREEN r = 0; g = 255; b = 0; break; case 'y': //YELLOW r = 255; g = 255; b = 0; break; case 'o': //ORANGE r = 255; g = 165; b = 0; break; case 'r': //RED r = 255; g = 0; b = 0; break; //EXTRA COLORS case 'c': //CYAN r = 0; g = 255; b = 255; break; case 'p': //PURPLE r = 191; g = 64; b = 191; break; case 'w': //WHITE r = 255; g = 255; b = 255; break; case 'a': //AQUAMARINE r = 127; g = 255; b = 212; break; //SWITCH OFF LED case '0': //OFF r = 0; g = 0; b = 0; break; default: r = 0; g = 0; b = 0; break; } for (int i = 0; i <= NUM_LEDS; i++) { Light1[i] = CRGB(r, g, b); Light2[i] = CRGB(r, g, b); } FastLED.show(); delay(500); } <file_sep>/README.md # Family_WiFi_Lights NodeMCU Project to use wifi and contact my family members
517d796e14786bbfdd4a5087881b324a0c3eb84b
[ "Markdown", "C++" ]
5
C++
bhavithmanapoty/Family_WiFi_Lights
6ed9b3ee9ab7617764c77a9e9530854ea18553e1
22aa208931d9b584532beebb6b70df367217d91f
refs/heads/master
<repo_name>vitorsoarescosta344/apikotlinspring<file_sep>/src/main/kotlin/com/victorsoares/kotlinapi/controller/UserController.kt package com.victorsoares.kotlinapi.controller import com.victorsoares.kotlinapi.entity.User import com.victorsoares.kotlinapi.repository.UserRepository import com.victorsoares.kotlinapi.requests.LoginRequest import com.victorsoares.kotlinapi.requests.UserRequest import org.bson.types.ObjectId import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.web.bind.annotation.* @RestController @RequestMapping("/users") class UserController ( private val userRepository : UserRepository ) { @GetMapping fun getAllUsers() : ResponseEntity<List<User>> { val users = userRepository.findAll() return ResponseEntity.ok(users) } @GetMapping("/{id}") fun getOneTask(@PathVariable("id") id: String): ResponseEntity<User> { val user = userRepository.findOneById(ObjectId(id)) return ResponseEntity.ok(user) } @PostMapping fun createUser(@RequestBody request: UserRequest) : ResponseEntity<User> { val password = BCryptPasswordEncoder().encode(request.senha) val user = userRepository.save(User( nome = request.nome, email = request.email, senha = password )) return ResponseEntity(user, HttpStatus.CREATED) } @PostMapping("/login" ) fun login(@RequestBody request: LoginRequest) : ResponseEntity<User> { val user = userRepository.findByEmail(request.email) val password = BCryptPasswordEncoder().matches(request.senha, user.senha) if(password == true){ return ResponseEntity.ok(user) }else { return ResponseEntity(user, HttpStatus.BAD_REQUEST) } } }<file_sep>/src/main/resources/application.properties spring.data.mongodb.uri=mongodb+srv://victor:********@cluster0.hrfo0.mongodb.net/KotlinApi spring.data.mongodb.database=KotlinApi<file_sep>/src/main/kotlin/com/victorsoares/kotlinapi/requests/UserRequest.kt package com.victorsoares.kotlinapi.requests class UserRequest ( val nome: String, val email: String, val senha: String ) class LoginRequest ( val email: String, val senha: String )<file_sep>/src/main/kotlin/com/victorsoares/kotlinapi/repository/UserRepository.kt package com.victorsoares.kotlinapi.repository import com.victorsoares.kotlinapi.entity.User import org.bson.types.ObjectId import org.springframework.data.mongodb.repository.MongoRepository interface UserRepository : MongoRepository<User, String> { fun findOneById(id: ObjectId): User fun findByEmail(email: String) : User }<file_sep>/src/main/kotlin/com/victorsoares/kotlinapi/entity/User.kt package com.victorsoares.kotlinapi.entity import org.bson.types.ObjectId import org.springframework.data.annotation.Id import org.springframework.data.mongodb.core.mapping.Field class User ( @Id val id: ObjectId = ObjectId.get(), @Field val nome: String, @Field val email: String, @Field val senha: String )
ceb6ee87d7da80624a917660e48b33a94c7cfd04
[ "Kotlin", "INI" ]
5
Kotlin
vitorsoarescosta344/apikotlinspring
d238e62af0c29a98af67fe28ba6fb88b249d99f5
581a3b1b6959c95848837d90000f46a0ccd5745d
refs/heads/master
<repo_name>pulading1988/composer-car<file_sep>/src/Ford/Fiesta/Fiesta2018.php <?php namespace Ford\Fiesta; class Fiesta2018 { public function info() { echo "This is Ford Fiesta2018!<br>"; } }
972f30c90e660a7f373de07e76767e4c994b007a
[ "PHP" ]
1
PHP
pulading1988/composer-car
e59aeefeb5e54daa399a359116c931b54bbdd44d
8be2a635991a199eea3df3cbf9905758d5e53c66
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MyBidGenerator { public partial class Form1 : Form { private Dictionary<string, string> bidDictionary = new Dictionary<string, string>(); private String bidDir = "bids"; public Form1() { InitializeComponent(); initializeBidDictionary(); } private void initializeBidDictionary() { bidDictionary.Clear(); loadFromDir(bidDir); } private void loadFromDir(String bidDir) { if(!Directory.Exists(bidDir)) { Directory.CreateDirectory(bidDir); return; } string[] filePaths = Directory.GetFileSystemEntries(bidDir); for(int i=0;i<filePaths.Length;i++) { string text = File.ReadAllText(filePaths[i]); if(text != "") { bidDictionary.Add(Path.GetFileName(filePaths[i]), text); } } } private void OnButtonClick(object sender, EventArgs e) { string senderName = ((Button)sender).Text; string senderColor = ((Button)sender).BackColor.Name; senderName = senderColor + senderName; string text = ""; if (this.checkBox1.Checked) { text = this.rich_bid.Text; if (text == "") return; File.WriteAllText("bids/" + senderName, text); this.checkBox1.Checked = false; initializeBidDictionary(); this.rich_bid.Clear(); return; } if (bidDictionary.TryGetValue(senderName,out text)) { string randomStr = this.generateRandomString("-"); text = text.Replace("**line**", randomStr); randomStr = this.generateRandomString("★"); text = text.Replace("**star**", randomStr); randomStr = this.generateRandomString("*"); text = text.Replace("**multi**", randomStr); randomStr = this.generateRandomString("."); text = text.Replace("**dot**", randomStr); this.rich_bid.Text = text; Clipboard.SetText(text); } else { this.rich_bid.Clear(); } } private string generateRandomString(string one) { Random rand = new Random(); int num = rand.Next(10, 100); string randomDots = ""; for (int i = 0; i < num; i++) { randomDots += one; } return randomDots; } } }
00245755194548321f01f84049903690fa682c96
[ "C#" ]
1
C#
Topstack-first/my-bid-generator
1ff732f2e64bb302d717d90976828a231567be02
da107138fb1c806e0da92f22eb61ee28448964bb
refs/heads/master
<file_sep>import Vue from 'vue'; import 'bootstrap/dist/css/bootstrap.css'; import './libs/mui/css/mui.min.css'; import './libs/mui/css/icons-extra.css'; import VueResource from 'vue-resource'; import moment from 'moment'; import Mint from 'mint-ui'; import 'mint-ui/lib/style.css'; import VuePreview from 'vue-preview'; import Vuex from 'vuex'; import app from './App.vue'; import router from './router.js'; Vue.use(VueResource); Vue.use(Mint); Vue.use(VuePreview); Vue.use(Vuex); Vue.http.options.root = 'http://vue.studyit.io'; // 设置请求路径前缀 Vue.http.options.emulateJSON = true; // 设置post请求为表单方式提交 Vue.filter('dataF',function(info, option = 'YYYY-MM-DD HH:mm:ss'){ return moment(info).format(option); }) let car = JSON.parse(localStorage.getItem('car')||'[]'); var store = new Vuex.Store({ state:{ // car: [{id:97,count:1,select:true,price:998}] car:car }, mutations:{ addToCar(state,info){ let flag = false; state.car.some(item=>{ if(item.id==info.id){ item.count+=parseInt(info.count); flag = true; return true; } }) if(!flag){ console.log(11); state.car.push(info); } localStorage.setItem('car',JSON.stringify(state.car)); }, changecount(state,info){ state.car.some(item=>{ if(item.id==info.id){ item.count = parseInt(info.count); } }) localStorage.setItem('car',JSON.stringify(state.car)); }, removeData(state,id){ state.car.some((item,i)=>{ if(item.id==id){ state.car.splice(i,1); } }) localStorage.setItem('car',JSON.stringify(state.car)); }, changeS(state,info){ state.car.some(item=>{ if(item.id==info.id){ item.select = info.select; } }) localStorage.setItem('car',JSON.stringify(state.car)); } }, getters: { getCount(state){ let count = 0; state.car.forEach(item=>{ count+=item.count; }) return count; }, getIdCount(state){ let arr = []; state.car.forEach(item=>{ arr[item.id] = item.count; }) return arr; }, getSelect(state){ let arr = []; state.car.forEach(item=>{ arr[item.id] = item.select; }) return arr; }, getAllCount(state){ let obj = { count:0, price:0 }; state.car.forEach(item=>{ if(item.select == true){ obj.count += item.count; obj.price += item.count * item.price; } }) return obj; } } }) var vm = new Vue({ el: '#app', render:c => c(app); router, store })<file_sep>import Vue from 'vue'; import VueRouter from 'vue-router'; import home from './components/tabbar/Home.vue'; import user from './components/tabbar/User.vue'; import shopcar from './components/tabbar/Shopcar.vue'; import search from './components/tabbar/Search.vue'; import newslist from './components/news/newsList.vue'; import newsinfo from './components/news/newsInfo.vue'; import share from './components/photo/share.vue'; import info from './components/photo/info.vue'; import shoplist from './components/shop/list.vue'; import shopinfo from './components/shop/info.vue'; import shopdetail from './components/shop/detail.vue'; import shopcomment from './components/shop/comment.vue'; Vue.use(VueRouter); var router = new VueRouter({ routes:[ {path:'/',redirect:'/home'}, {path:'/home',component:home}, {path:'/user',component:user}, {path:'/shopcar',component:shopcar}, {path:'/search',component:search}, {path:'/news/list',component:newslist}, {path:'/news/info/:id',component:newsinfo}, {path:'/photo/share',component:share}, {path:'/photo/info/:id',component:info}, {path:'/shop/list',component:shoplist}, {path:'/shop/shopinfo/:id',component:shopinfo,name:'shopinfo'}, {path:'/shop/shopdetail/:id',component:shopdetail,name:'shopdetail'}, {path:'/shop/shopcomment/:id',component:shopcomment,name:'shopcomment'}, ], linkActiveClass:'mui-active' }) export default router;
bb7d5c360c4ddbaacfa13cd333c36d066cc696b4
[ "JavaScript" ]
2
JavaScript
lihuanghuangshang/my-vue
2dab79a7289ad948a146f57008866e3cb52f19f1
d25375a38bfc4b848eedac4e81ccdc7ba4691764
refs/heads/main
<repo_name>sohila20/Notification-Web-Service<file_sep>/Project/src/main/resources/application.properties spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url= jdbc:mysql://localhost:3306/notification_schema spring.datasource.username=splunk_user spring.datasource.password=*****<file_sep>/demo/src/main/java/com/software/demo/EmailNotification.java package com.software.demo; import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement public class EmailNotification extends Notification { public EmailNotification() {} // this function to check if the email exists public boolean validateContact() { String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$"; java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern); java.util.regex.Matcher m = p.matcher(this.getContact()); return m.matches(); } } <file_sep>/demo/src/main/java/com/software/demo/SMSNotificationFactory.java package com.software.demo; import java.util.ArrayList; public class SMSNotificationFactory implements INotificationFactory { @Override public Notification CreateNotification(String[] placeholders ,String message,String Contact) { Notification notification = new SMSNotification(); if(notification.placeholdersSizeValidation(placeholders.length, message)) { notification.prepareContent(message, placeholders); notification.setContact(Contact); } else { System.out.println("Invalid placeholders"); return null; } return notification; } } <file_sep>/README.md # Notification-Web-Service<file_sep>/demo/src/main/java/com/software/demo/NotificationResources.java package com.software.demo; import java.sql.SQLException; import java.util.List; import java.util.Scanner; import jakarta.ws.rs.Consumes; import jakarta.ws.rs.DELETE; import jakarta.ws.rs.GET; import jakarta.ws.rs.POST; import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; @Path("notifications") public class NotificationResources { //we applied singleton design pattern on this class because this class is responsible for accessing notif DB so it have to be of one object EmailNotificationOperations repoEmail= EmailNotificationOperations.getInstance(); SMSNotificationOperations repoSMS= SMSNotificationOperations.getInstance(); @POST @Path("create/{contact}") @Consumes(MediaType.TEXT_PLAIN) public void CreateNotification(@PathParam("contact")String contact,String ClientRequest) throws SQLException{ //to create the notification INotificationFactory factory; Notification notification; String[] arr = ClientRequest.split(" "); String language = arr[0]; String templateType = arr[1]; String clientContact = arr[2]; String placeholders=""; for(int i=3;i<arr.length;i++) placeholders += arr[i] + " "; String[] placeholderArr= placeholders.split(" "); Template t = new Template(); TemplateOperations operation= new TemplateOperations(); String st=templateType; t= operation.readTemplate(st); String message= t.getTemplateMessage(language); // to know it will add it in emai or sms notification table in database if(contact.equalsIgnoreCase("email")) { factory= new EmailNotificationFactory(); notification= factory.CreateNotification(placeholderArr, message, clientContact); if(notification!=null) repoEmail.CreateNotification(notification, notification.validateContact()); else System.out.println("Error occurred"); } else { factory= new SMSNotificationFactory(); notification= factory.CreateNotification(placeholderArr, message, clientContact); if(notification!=null) repoSMS.CreateNotification(notification, notification.validateContact()); else System.out.println("Error occurred"); } } public void readNotification(int ID, String contact) { Notification notification; if(contact.equalsIgnoreCase("email")) { notification= new EmailNotification(); notification=repoEmail.readNotification(ID); } else { notification = new SMSNotification(); notification=repoSMS.readNotification(ID); } System.out.println(notification); } public void deleteNotification(int ID, String contact) { Notification notification; if(contact.equalsIgnoreCase("email")) { notification= new EmailNotification(); repoEmail.deleteNotification(ID); } else { notification = new SMSNotification(); repoSMS.deleteNotification(ID); } } } <file_sep>/demo/src/main/java/com/software/demo/SMSNotification.java package com.software.demo; import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement public class SMSNotification extends Notification { public SMSNotification() {} //this function to check if phone number is valid public boolean validateContact() { if(this.getContact().length()!=13) return false; return true; } } <file_sep>/demo/src/main/java/com/software/demo/EmailNotificationOperations.java package com.software.demo; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class EmailNotificationOperations implements INotificationDataBaseOperations { private static EmailNotificationOperations uniqueInstance =new EmailNotificationOperations(); public static EmailNotificationOperations getInstance(){ return uniqueInstance; } Connection con; private EmailNotificationOperations() { String url="jdbc:mysql://localhost:3306/hb_student_tracker"; String username="hbstudent"; String pass="<PASSWORD>"; try { Class.forName("com.mysql.cj.jdbc.Driver"); con=DriverManager.getConnection(url, username, pass); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } } @Override public void CreateNotification(Notification notification, boolean status) throws SQLException { String sql="insert into emailnotification (contact , content) values(?,?)"; String sql2= "insert into notification (content , contact , status) values (?,?,?)"; PreparedStatement st= con.prepareStatement(sql); PreparedStatement st2= con.prepareStatement(sql2); st2.setString(1, notification.getContent()); st2.setString(2, notification.getContact()); if(status) { try { st.setString(1, notification.getContact()); st.setString(2, notification.getContent()); st.executeUpdate(); st2.setString(3, "successful"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else st2.setString(3, "failed"); st2.executeUpdate(); } @Override public Notification readNotification(int ID) { String sql="select * from emailnotification where Id ='"+ ID +"'"; EmailNotification notification= new EmailNotification(); try { Statement st= con.createStatement(); ResultSet rs=st.executeQuery(sql); if(rs.next()) { notification.setContact(rs.getString(2)); notification.setContent(rs.getString(3)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return notification; } @Override public void deleteNotification(int ID) { String sql="delete from emailnotification where ID = ?"; try { java.sql.PreparedStatement st = con.prepareStatement(sql); st.setInt(1, ID); st.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>/demo/src/main/java/com/software/demo/Main.java package com.software.demo; import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner scanner = new Scanner (System.in); String contact = scanner.nextLine(); int ID = scanner.nextInt(); NotificationResources resources= new NotificationResources(); resources.readNotification(ID, contact); resources.deleteNotification(ID, contact); } } <file_sep>/demo/src/main/java/com/software/demo/INotificationFactory.java package com.software.demo; import java.util.ArrayList; public interface INotificationFactory { public Notification CreateNotification(String[] placeholders,String message,String Contact); } <file_sep>/Project/src/main/java/com/example/notificationwebservice/business_logic/NotificationFactory.java package com.example.notificationwebservice.business_logic; public class NotificationFactory { }
e692fd567a29fae36dd3c3670a5fd941ab314927
[ "Markdown", "Java", "INI" ]
10
INI
sohila20/Notification-Web-Service
9d3afaf8986a0a806aecf4508b30a3f920dd1d17
758c785c8ca495c29b5640d62f49ee2e0373f2dd
refs/heads/master
<repo_name>stvhwrd/DAOpresentation<file_sep>/Deck/presentation/markdown/introduction.md # DAO Attack ### 3.6 million ether ($1.1 billion CAD) &nbsp; Presented by: - <NAME> - <NAME> - <NAME> - <NAME> <file_sep>/Deck/presentation/markdown/slide1.md # Slide 1 <file_sep>/Deck/presentation/markdown/slide3.md # Slide 3 <file_sep>/Deck/presentation/markdown/index.js import introduction from './introduction.md'; import slide1 from './slide1.md'; import slide2 from './slide2.md'; import slide3 from './slide3.md'; import conclusion from './conclusion.md'; const markdown = { introduction, slide1, slide2, slide3, conclusion }; export default markdown; <file_sep>/Deck/presentation/markdown/slide2.md # Slide 2 <file_sep>/README.md # DAO Attack ![](https://www.ethereum.org/images/logos/ETHEREUM-LOGO_LANDSCAPE_Black.png) This is a 12 minute presentation on [The DAO attack](https://www.coindesk.com/understanding-dao-hack-journalists/) for UVic's SENG 360 class. ### [Live demo](https://steviehoward.com/DAOpresentation/) We assume that the audience is technically savvy but unfamiliar with blockchain technology - specifically Ethereum. This presentation aims to address the following points: - What is the nature of the vulnerability? - How can an attacker exploit it? - What controls can mitigate this vulnerability? - How to learn more about this vulnerability? (By providing reference to information resources) ## Deck Dev The slides are written in [Markdown](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) and can be edited in the `Deck/presentation/markdown` folder. Any renames or file additions must be reflected accordingly in the `Deck/presentation/markdown/index.js` file. To run the dev server locally with Yarn/NPM and NodeJS: - Clone repo - `cd` into `Deck/` - `yarn` or `npm install` - `npm run dev` The presentation will run at [localhost:8080](http://localhost:8080). Updates to project files will trigger a rebuild, and changes will be reflected in browser. ## Deployment The presentation is served by [GitHub Pages](https://pages.github.com/) and GitHub Pages dictates that static files be served from the `/docs` folder at the root of the repository. - `npm run predeploy` to build to `/docs` - `git add /docs` - `git commit -m "deploy updated presentation $(date +"%r") on $(date +"%Y/%m/%d")"` - `git push origin master` ## Credit **ALL** credit for this particular [Spectacle](http://formidable.com/open-source/spectacle/) boilerplate goes to [UVic SDAML](https://sdaml.club). This is a direct fork of [SDAML's 2017 Introduction](http://introduction.sdaml.club/) presentation.
74e2c072dbf6205fb007f0da55b59e0a603e8c3b
[ "Markdown", "JavaScript" ]
6
Markdown
stvhwrd/DAOpresentation
254b36e386c0133dd0dc123f3ff8905c9354daa9
b920a803c56a50ab2a883c43501c7879970e1d7c
refs/heads/main
<repo_name>igorw765/Kotlin<file_sep>/projekty_z_zaj--master/src/Tasks.kt enum class Tasks(val order: String) { BUILDING(Orders.BUILD.name), COLLECTING(Orders.COLLECT.name), ATTACKING(Orders.ATTACK.name), DEFENDING(Orders.DEFEND.name), NOTHING(Orders.NOTHING.name); companion object{ //zmienna z () a w {} można dodać warunek fun getByOrder(order : String) = values().firstOrNull { task -> task.order == order } } }<file_sep>/projekty_z_zaj--master/src/Main.kt import java.util.* object Main{ @JvmStatic fun main(args: Array<String>){ val antnest = Antnest() showMainScreen(antnest) println("1. Shop\n" + "2. Operatings of Commander Ants\n" + "3. Exit" ) val start = System.`in`.read() when(start) { 49 -> { println("1. Buy Worker\n" + "2. Buy Commander\n" + "3. Buy Queen\n" + "4. Exit" ) val whatToBuy = System.`in`.read() when(whatToBuy){ 49 -> antnest.buyWorker() 50 -> antnest.buyCommander() 51 -> antnest.buyQueen() 52 -> ("not working yet" /*clear consol and go back*/) } } 50 -> { antnest.showNumberOfWorkersAndCommandersWithOptions() } 51 -> { System.exit(-1) } 52 -> { } } } }<file_sep>/projekty_z_zaj--master/src/Ant.kt open class Ant( val capacity: Int = 10, var speed: Int = 5, var age: Int = 0, var HP: Int = 100, var damage: Int = 20 )<file_sep>/projekty_z_zaj--master/src/Materials.kt enum class Materials { FOOD, WOOD, STONE }<file_sep>/projekty_z_zaj--master/src/CommanderAnt.kt class CommanderAnt( var orders: ArrayList<Orders> = arrayListOf(Orders.NOTHING), capacity: Int = 2, speed: Int = 15, age: Int = 6, var level: Int = 1 ) :Ant(2, 15, 6, 200, 100){ fun assignTask(workerAnt: WorkerAnt, orders: Orders){ when { this.orders.contains(orders).not() -> return else -> { println("Wydałem rozkaz ${orders.name}") workerAnt.task = Tasks.getByOrder(orders.name) ?: Tasks.NOTHING } } } }<file_sep>/projekty_z_zaj--master/src/Antnest.kt import java.util.* class Antnest( var freeAnts : Int = 10, var food : Int = 10, var wood : Int = 5, var stone : Int = 2, var storage : Int = 100, var currentLevel : Int = 1, var commandersNumber: Int = 1, var queensNumber: Int = 0, var workersNumber: Int = 2, var listOfAnts: MutableList<Ant> = mutableListOf(WorkerAnt(), CommanderAnt(), WorkerAnt()) ) { fun checkStorage() = food + wood + stone > storage fun levelUP() { var foodNeeded = currentLevel * 1 var woodNeeded = currentLevel * 2 var stoneNeeded = currentLevel * 1 if (currentLevel > 5) { when { foodNeeded > food -> System.err.println("posiadasz za mało zmiennej food by wejść na wyższy poziom") woodNeeded > wood -> System.err.println("posiadasz za mało zmiennej wood by wejść na wyższy poziom") stoneNeeded > stone -> System.err.println("posiadasz za mało zmiennej stone by wejść na wyższy poziom") else -> { currentLevel++ println("Zdobywasz poziom !!!") println("aktualny poziom: ${currentLevel}") } } } else { when { foodNeeded > food -> System.err.println("posiadasz za mało zmiennej food by wejść na wyższy poziom") woodNeeded > wood -> System.err.println("posiadasz za mało zmiennej wood by wejść na wyższy poziom") else -> { currentLevel++ println("Zdobywasz poziom !!!") println("aktualny poziom: ${currentLevel}") } } } } fun buyWorker() { when { freeAnts < 1 -> System.err.println("Posiadasz za mało mrówek by kupić workera") food < 1 -> System.err.println("Posiadasz za mało zmiennej food by kupić workera") else -> { println("Zakupiono Worker") food-- freeAnts-- // val newWorker = WorkerAnt(age = 1, task = Tasks.NOTHING, earnings = 1000) workersNumber++ println("Aktualna liczba Queenów: ${workersNumber}") } } } fun buyCommander() { when { freeAnts < 2 -> System.err.println("Posiadasz za mało mrówek by kupić Commandera") food < 1 -> System.err.println("Posiadasz za mało zmiennej food by kupić Commandera") wood < 2 -> System.err.println("Posiadasz za mało zmiennej wood by kupić Commandera") else -> { println("Zakupiono Comander") food-- freeAnts -= 2 wood -= 2 commandersNumber++ println("Aktualna liczba Comanderów: ${commandersNumber}") } } } fun buyQueen() { when { freeAnts < 5 -> System.err.println("Posiadasz za mało mrówek by kupić QueenAnt") food < 5 -> System.err.println("Posiadasz za mało zmiennej food by kupić QueenAnt") wood < 10 -> System.err.println("Posiadasz za mało zmiennej wood by kupić QueenAnt") stone < 2 -> System.err.println("Posiadasz za mało zmiennej stone by kupić QueenAnt") else -> { println("Zakupiono Queen") freeAnts -= 5 food -= 5 wood -= 10 stone -= 2 queensNumber++ println("Aktualna liczba Queenów: ${queensNumber}") } } } fun createAnt(antType: Any) = when(antType){ is WorkerAnt -> WorkerAnt() is CommanderAnt -> CommanderAnt() is QueenAnt -> QueenAnt() else -> null } fun showNumberOfWorkersAndCommandersWithOptions(){ var x = numberOfWorkers() var y = numberOfCommanders() var i = 0 if (x > 0 && y > 0){ println("Number of Workers is equals to: ${x} \n" + "Number of Commanders is equal to: ${y} \n" + "Choose one of this: ") for (i in 0 until x){ println("${i} Worker") } for (i in 0 until y){ println("${i} Commander") } }else{ System.err.println("You have not got any commander or worker") print("x: ${x}, y: ${y}") } } } <file_sep>/projekty_z_zaj--master/src/Orders.kt enum class Orders { BUILD, COLLECT, ATTACK, DEFEND, NOTHING }<file_sep>/projekty_z_zaj--master/src/Extension.kt @file:Suppress("UNUSED_CHANGED_VALUE") fun String.isSlash5(number: Int, word: String) { when { word.length % number == 0 -> println("${word} is / by ${number}") else -> println("${word} is not / by ${number}") } } fun String.numberOfChars(char: Char, word: String) { var count: Int = 0 if (word.contains(char)) { count++ } } fun Antnest.isAnyFreeAnts() = freeAnts >= 1 fun Antnest.isStorageIsntToFull() { val totalNumberOfItems: Int = wood + stone + food if (storage < totalNumberOfItems) { System.err.println("Storage is too full") } } fun Antnest.deleteOldestQueenAnt() { val index = listOfAnts .filter { it is QueenAnt } .map { it as QueenAnt } .withIndex() .maxBy { it.value.age }?.index index?.let { listOfAnts.removeAt(it) } } fun Main.showMainScreen(antnest: Antnest){ println("Your resources:\n" + "food: ${antnest.food}, wood: ${antnest.wood}, stone: ${antnest.stone}.\n" + "Your ants: \n" + "Ants: ${antnest.freeAnts}, Workers: ${antnest.workersNumber}, Commanders: ${antnest.commandersNumber}, Queens: ${antnest.queensNumber}") } fun Antnest.numberOfCommanders() = listOfAnts .filter { it is CommanderAnt } .map { it as CommanderAnt } .count() fun Antnest.NumberOfQueens() = listOfAnts .filter { it is QueenAnt } .map { it as QueenAnt } .filter { !it.ruleEnded == false } .count() fun Antnest.numberOfWorkers() = listOfAnts .filter { it is WorkerAnt } .map { it as WorkerAnt } .count()<file_sep>/projekty_z_zaj--master/src/QueenAnt.kt class QueenAnt( capacity: Int = 4, speed: Int = 2, age: Int = 10, var ruleYearsLeft: Int = 5, var ruleEnded: Boolean = false ):Ant(4,2,10, 400, 50) { fun checkRuleYearsLeft() = when{ ruleYearsLeft == 1 -> println("został już tylko rok panowania") ruleYearsLeft< 1-> println("Zakończyła panowanie") else -> println("Zostało jeszcze $ruleYearsLeft lat panowania") } }<file_sep>/projekty_z_zaj--master/src/WorkerAnt.kt class WorkerAnt( capacity: Int = 20, speed: Int = 3, age: Int = 1, earnings: Int = 0, var workHours: Int = 10, var task: Tasks = Tasks.NOTHING ):Ant(20, 3, 1, 50, 15) { //seter jest do zmiennej nad nim var earnings = earnings set(value) { if (value > 10000) { println("Za dużo zarabiasz") return } field = value } var food: Int = 0 var wood : Int = 0 var stone : Int = 0 fun collect(resourcesType: Materials, antnest: Antnest ){ if(checkResources() >=capacity){ System.err.println() return } val boost = antnest.NumberOfQueens() * 2 when(resourcesType){ Materials.FOOD ->food += 1 + boost Materials.STONE -> stone += 1 + boost Materials.WOOD -> wood += 1 + boost } } // fun collect(what: Materials) { // if (checkResources() >= capacity) { // System.err.println("You have not got enought capacity to collect more materials") // // }else{ // if (what.equals("wood")) { // wood++ // } else if (what.equals("food")) { // food++ // } else if (what.equals("stone")) { // stone++ // }else { // System.err.println("ERROR: ${what} is not alloved operation") // System.err.println("Posible solutions: ") // System.err.println("1. Mistake in the name of material (alloved : food, wood, stone).") // System.err.println("2. Code problem.") // } // } // } fun WorkerAnt.checkResources()= food+wood+stone fun addResourcesToAntnest(antnest: Antnest){ for (foodCounter in 1 until food) { if(antnest.checkStorage()){ System.err.println("You reach resources limit in Antnest") return } antnest.food ++ } for (stoneCounter in 1 until stone) { if(antnest.checkStorage()){ System.err.println("You reach resources limit in Antnest") return } antnest.stone ++ } for (woodCounter in 1 until wood) { if(antnest.checkStorage()){ System.err.println("You reach resources limit in Antnest") return } antnest.wood ++ } } fun showTask() = println("Doing ${task.name}") }
3e9d7d9e3b0ce67c769814b3099c0a6781dd55b8
[ "Kotlin" ]
10
Kotlin
igorw765/Kotlin
86546b0a66a87f71e34602c19047eb2d3c13e322
fc2aee3a7045c477224b6838d6ea8de68d669f1d
refs/heads/master
<file_sep>package com.company; import java.io.*; public class Main { public static void main(String[] args) throws IOException { // try { // RandomAccessFile rf = new RandomAccessFile("1.dat", "rw"); //// Записать в файл 10 чисел и закрыть файл // for(int i = 0; i < 10; i++) // rf.writeDouble(i * 1.414); // rf.close(); //// Открыть файл, записать в него еще одно число и снова закрыть // rf = new RandomAccessFile("1.dat", "rw"); // rf.seek(5 * 8); // rf.writeDouble(47.0001); // rf.close(); //// Открыть файл с возможностью только чтения "r" // rf = new RandomAccessFile("1.dat", "r"); //// Прочитать 10 чисел и показать их на экране // for(int i = 0; i < 10; i++) // System.out.println("Value " + i + ": " + rf.readDouble()); // rf.close(); // } catch (IOException ex) { // // Обработать исключение // } /* File path = new File("."); File[] list = path.listFiles(); for(int i = 0; i < list.length; i++) System.out.println(list[i].getName()); */ try { // Создаем буферизованный символьный входной поток BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); // Используем класс PrintWriter для вывода PrintWriter out = new PrintWriter(new FileWriter("2.txt")); // Записываем строки, пока не введем строку "stop" while (true) { String s = in.readLine(); if (s.equals("stop")) break; out.println(s); } out.close(); } catch (IOException ex) { // Обработать исключение try { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("1.txt")); BufferedInputStream bis = new BufferedInputStream(new FileInputStream("2.txt")); int c = 0; while (true) { c = bis.read(); if (c != -1) bos.write(c); else break; bis.close(); bos.flush(); //освобождаем буфер (принудительно записываем содержимое буфера вфайл) bos.close(); //закрываем поток записи (обязательно!) } } catch (FileNotFoundException e) { e.printStackTrace(); } File path = new File("."); // Получить массив объектов File[] list = path.listFiles(new FileFilter() { public boolean accept(File file) { String f = file.getName(); return f.indexOf(args[0]) != -1; } }); // Напечатать имена файлов for (int i = 0; i < list.length; i++) { System.out.println(list[i].getName()); } } } }
fd791d95af9e8a7fcf7b5761b0292caa22c7943e
[ "Java" ]
1
Java
RomanVerhoturov/pract1
4fe655204bf839c38a7ca16e92cb10fee2e48551
3a6272f9d9292411ca09d5ea190a76ae89ed2aec
refs/heads/dev
<file_sep>export const village = { state: () => ({ x: 0, y: 0, points: 0 }), getters: { coords(state) { return { x: state.x, y: state.y } }, points(state) { return state.points } }, mutations: {}, actions: {} }<file_sep>import Vue from 'vue'; import VueRouter from 'vue-router'; import OverviewPage from '../views/village/OverviewPage'; import MapPage from '../views/map/MapPage'; import TribePage from '../views/tribe/TribePage'; import TribeBrowser from '../views/tribe/content/TribeBrowser'; import LoginPage from '../views/login/LoginPage'; import EmailVerification from '../views/emailVerification/EmailVerification'; import RegisterPage from '../views/Register/Register'; import HomePage from '../views/home/HomePage'; import BarracksPage from '../views/barracks/BarracksPage'; import TribeCreate from "../views/tribe/content/TribeCreate"; import AttackPage from '../views/attack/AttackPage'; import TribeViewer from "../views/tribe/content/TribeViewer"; Vue.use(VueRouter); const routes = [ { path: '/overview', name: 'OverviewPage', component: OverviewPage }, { path: '/map', name: 'MapPage', component: MapPage }, { path: '/login', name: 'LoginPage', component: LoginPage }, { path: '/tribe', name: 'TribePage', component: TribePage }, { path: '/tribe-browser', name: 'TribeBrowser', component: TribeBrowser }, { path: '/', name: 'HomePage', component: HomePage }, { path: '/register', name: 'Register', component: RegisterPage }, { path: '/emailVerification/:code', name: 'EmailVerificationPage', component: EmailVerification }, { path: '/barracks', name: 'BarracksPage', component: BarracksPage }, { path: '/createTribe', name: 'TribeCreate', component: TribeCreate }, { path: '/attack', name: 'AttackPage', component: AttackPage }, { path: '/tribe-viewer', name: 'TribeViewer', component: TribeViewer }, ]; const router = new VueRouter({ routes }); export default router; <file_sep>export const code = [{ required: true, message: "Insert an verification code", trigger: "blur", }, ];<file_sep>class Unit { constructor(imageSrc, span = 5) { this.imageSrc = imageSrc this.span = span } } let infantry = [ new Unit(require('@/assets/image/units/pic.png'), 4), new Unit(require('@/assets/image/units/sword.png')), new Unit(require('@/assets/image/units/axe.png')), ] let cavalry = [ new Unit(require('@/assets/image/units/light.png')), new Unit(require('@/assets/image/units/heavy.png')), ] export default {infantry, cavalry}<file_sep>export const tribe = { state: () => ({ name: "", id: null, description: "", numberOfMembers: 0, ownerName: "" }), getters: { tribe(state) { return { name: state.name, id: state.id, description: state.description, membersCount: state.membersCount } } }, mutations: { setTribeInfo(state, data) { state.name = data.tribeName state.id = data.id state.description = data.description state.membersCount = data.numberOfMembers state.owner = data.ownerName } }, actions: { setTribeInfo({commit}, data) { commit("setTribeInfo", data) } } }<file_sep>import axios from "axios"; import store from "./store" axios.defaults.baseURL = "https://localhost:44305/" axios.interceptors.response.use( response => response, ) axios.interceptors.request.use( request => { const token = store.getters.token if (token) { request.headers.Authorization = `Bearer ${token}` } return request }, error => Promise.reject(error) ) export default {}<file_sep>export const units = { state: () => ({ infantry: { pikes: 0, swords: 0, axes: 0 }, cavalry: { light: 0, heavy: 0 } }), getters: { infantry(state) { return { pikes: state.infantry.pikes, swords: state.infantry.swords, axes: state.infantry.axes, } }, cavalry(state) { return { light: state.cavalry.light, heavy: state.cavalry.heavy, } }, }, mutations: {}, actions: {} }<file_sep>import slugger from "slugger"; class Building { constructor(name, imageSrc, span = 8, offset = 0) { this.name = name this.imageSrc = imageSrc this.span = span this.offset = offset this.path = slugger(this.name) } } let buildingsRows = { firstRow: [ new Building("mine", require('@/assets/image/materials/wood.png')), new Building("farm", require('@/assets/image/materials/wood.png'), 8, 16), ], secondRow: [ new Building("granary", require('@/assets/image/materials/wood.png')), new Building("town hall", require('@/assets/image/materials/wood.png')), new Building("barracks", require('@/assets/image/materials/wood.png')), ], thirdRow: [ new Building("brick yard", require('@/assets/image/materials/wood.png'), 4), new Building("lumber mill", require('@/assets/image/materials/wood.png'), 4, 20), ] } export default buildingsRows<file_sep>import router from "../router"; export const user = { state: () => ({ isPlaying: false, username: "" }), mutations: { setIsUserPlaying(state, isPlaying) { state.isPlaying = isPlaying }, setUsername(state, name) { state.name = name } }, actions: { setIsUserPlaying({commit}, isPlaying) { commit("setIsUserPlaying", isPlaying) if (isPlaying === "true") router.push("overview") }, setUserInfo({commit}, data) { commit("setUsername", data.userName) commit("setToken", data.accessToken) } }, getters: { isPlaying(state) { return state.isPlaying }, username(state) { return state.username } } }<file_sep>import "../assets/sass/imports.scss"; export default {};<file_sep>export const materials = { state: () => ({ wood: 0, clay: 0, iron: 0, villagers: 0 }), getters: { materials(state) { return { wood: state.wood, clay: state.clay, iron: state.iron, villagers: state.villagers, } } }, mutations: {}, actions: {} }
fcaa2f5d176e3c033d1a4f86c916bd922d60d760
[ "JavaScript" ]
11
JavaScript
Plemiona-2-5/web
6630a9c9204af445ad1e002f622c858a464ae90f
566df6796eb82af2ce785266e2d0196370b0bf2d
refs/heads/master
<repo_name>netes/finanser-api<file_sep>/spec/fabricators/income_fabricator.rb Fabricator(:income) do income_category name { Faker::Commerce.product_name } recurrent_period { Faker::Number.between(1, 31) } date { Faker::Time.between(DateTime.now - 31, DateTime.now + 31) } amount { Faker::Commerce.price } received { %w(true false).sample } recurrent { %w(true false).sample } end <file_sep>/test/controllers/expense_categories_controller_test.rb require 'test_helper' class ExpenseCategoriesControllerTest < ActionController::TestCase setup do @expense_category = expense_categories(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:expense_categories) end test "should create expense_category" do assert_difference('ExpenseCategory.count') do post :create, expense_category: { name: @expense_category.name } end assert_response 201 end test "should show expense_category" do get :show, id: @expense_category assert_response :success end test "should update expense_category" do put :update, id: @expense_category, expense_category: { name: @expense_category.name } assert_response 204 end test "should destroy expense_category" do assert_difference('ExpenseCategory.count', -1) do delete :destroy, id: @expense_category end assert_response 204 end end <file_sep>/app/serializers/expense_serializer.rb class ExpenseSerializer < ActiveModel::Serializer attributes :id, :name, :amount, :paid, :due_date, :recurrent, :recurrent_period belongs_to :expense_category belongs_to :user end <file_sep>/app/serializers/income_serializer.rb class IncomeSerializer < ActiveModel::Serializer attributes :id, :name, :amount, :received, :date, :recurrent, :recurrent_period belongs_to :income_category belongs_to :user end <file_sep>/app/models/user.rb class User < ActiveRecord::Base include DeviseTokenAuth::Concerns::User devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable has_many :expenses has_many :incomes has_many :expense_categories has_many :income_categories end <file_sep>/app/models/income_category.rb class IncomeCategory < ActiveRecord::Base has_many :incomes belongs_to :user end <file_sep>/app/controllers/expense_categories_controller.rb class ExpenseCategoriesController < ApplicationController before_action :set_expense_category, only: [:show, :update, :destroy] # GET /expense_categories # GET /expense_categories.json def index @expense_categories = ExpenseCategory.all render json: @expense_categories end # GET /expense_categories/1 # GET /expense_categories/1.json def show render json: @expense_category end # POST /expense_categories # POST /expense_categories.json def create @expense_category = ExpenseCategory.new(expense_category_params) if @expense_category.save render json: @expense_category, status: :created, location: @expense_category else render json: @expense_category.errors, status: :unprocessable_entity end end # PATCH/PUT /expense_categories/1 # PATCH/PUT /expense_categories/1.json def update @expense_category = ExpenseCategory.find(params[:id]) if @expense_category.update(expense_category_params) head :no_content else render json: @expense_category.errors, status: :unprocessable_entity end end # DELETE /expense_categories/1 # DELETE /expense_categories/1.json def destroy @expense_category.destroy head :no_content end private def set_expense_category @expense_category = ExpenseCategory.find(params[:id]) end def expense_category_params params.permit(:name) end end <file_sep>/app/controllers/income_categories_controller.rb class IncomeCategoriesController < ApplicationController before_action :set_income_category, only: [:show, :update, :destroy] # GET /income_categories # GET /income_categories.json def index @income_categories = IncomeCategory.all render json: @income_categories end # GET /income_categories/1 # GET /income_categories/1.json def show render json: @income_category end # POST /income_categories # POST /income_categories.json def create @income_category = IncomeCategory.new(income_category_params) if @income_category.save render json: @income_category, status: :created, location: @income_category else render json: @income_category.errors, status: :unprocessable_entity end end # PATCH/PUT /income_categories/1 # PATCH/PUT /income_categories/1.json def update @income_category = IncomeCategory.find(params[:id]) if @income_category.update(income_category_params) head :no_content else render json: @income_category.errors, status: :unprocessable_entity end end # DELETE /income_categories/1 # DELETE /income_categories/1.json def destroy @income_category.destroy head :no_content end private def set_income_category @income_category = IncomeCategory.find(params[:id]) end def income_category_params params.permit(:name) end end <file_sep>/app/models/expense_category.rb class ExpenseCategory < ActiveRecord::Base has_many :expenses belongs_to :user end <file_sep>/app/serializers/user_serializer.rb class UserSerializer < ActiveModel::Serializer attributes :id, :email has_many :expenses has_many :expense_categories has_many :incomes has_many :income_categories end <file_sep>/app/controllers/wallets_controller.rb class WalletsController < ApplicationController before_action :set_wallet, only: [:show, :update, :destroy] # GET /wallets # GET /wallets.json def index @wallets = Wallet.all render json: @wallets end # GET /wallets/1 # GET /wallets/1.json def show render json: @wallet, include: ['expenses'] end # POST /wallets # POST /wallets.json def create @wallet = Wallet.new(wallet_params) if @wallet.save render json: @wallet, status: :created, location: @wallet else render json: @wallet.errors, status: :unprocessable_entity end end # PATCH/PUT /wallets/1 # PATCH/PUT /wallets/1.json def update @wallet = Wallet.find(params[:id]) if @wallet.update(wallet_params) head :no_content else render json: @wallet.errors, status: :unprocessable_entity end end # DELETE /wallets/1 # DELETE /wallets/1.json def destroy @wallet.destroy head :no_content end private def set_wallet @wallet = Wallet.find(params[:id]) end def wallet_params params.permit(:name) end end <file_sep>/app/models/wallet.rb class Wallet < ActiveRecord::Base has_many :expenses has_many :incomes end <file_sep>/db/seeds.rb user1 = User.create(password: '<PASSWORD>', email: '<EMAIL>') user1.skip_confirmation! user1.save! 20.times { Fabricate(:expense) } 10.times { Fabricate(:income) } # wallet1 = Wallet.create(name: 'Main Wallet', user: user1) # income_category1 = IncomeCategory.create(name: 'Salary') # income_category2 = IncomeCategory.create(name: 'Company incomes') # income_category3 = IncomeCategory.create(name: 'Other') # income_category4 = IncomeCategory.create(name: 'Other 2') # income_category5 = IncomeCategory.create(name: 'Very long income category') # income_category6 = IncomeCategory.create(name: 'Some more') # income_category7 = IncomeCategory.create(name: 'Something else') # # income1 = Income.create(name: 'The Great Escape', user: user1, income_category: income_category1, amount: 24.20, received: false, recurrent: false) # income2 = Income.create(name: 'Saving Myself', user: user1, income_category: income_category2, amount: 14.13, received: false, recurrent: false) # income3 = Income.create(name: 'The Killer Doctors', user: user1, income_category: income_category2, amount: 15.12, received: false, recurrent: false) # income4 = Income.create(name: 'Marianne', user: user1, income_category: income_category3, amount: 10.50, received: false, recurrent: false) <file_sep>/app/models/income.rb class Income < ActiveRecord::Base belongs_to :income_category belongs_to :user end <file_sep>/test/controllers/incomes_controller_test.rb require 'test_helper' class IncomesControllerTest < ActionController::TestCase setup do @income = incomes(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:incomes) end test "should create income" do assert_difference('Income.count') do post :create, income: { amount: @income.amount, date: @income.date, income_category_id: @income.income_category_id, name: @income.name, received: @income.received, recurrent: @income.recurrent, recurrent_period: @income.recurrent_period, user_id: @income.user_id } end assert_response 201 end test "should show income" do get :show, id: @income assert_response :success end test "should update income" do put :update, id: @income, income: { amount: @income.amount, date: @income.date, income_category_id: @income.income_category_id, name: @income.name, received: @income.received, recurrent: @income.recurrent, recurrent_period: @income.recurrent_period, user_id: @income.user_id } assert_response 204 end test "should destroy income" do assert_difference('Income.count', -1) do delete :destroy, id: @income end assert_response 204 end end
0f4f74d89b81bd17fad3ef6bb9d97551dba1e4a1
[ "Ruby" ]
15
Ruby
netes/finanser-api
4d947dce80e76167ec16fd668223d2d4cb7a0407
ff5c7dc63b42e9d1b1383cce4294317b3031a2d7
refs/heads/master
<file_sep>#!/bin/bash ##### # makesymlinks.sh # This script creates symlinks from the home directory to any desired dotfiles in ~/dotfiles ##### ##### Variables dir=~/.dotfiles # dotfiles directory olddir=~/.dotfiles/dotfiles_old # old dotfiles backup directory files="vimrc gitconfig-extension" ##### # create dotfiles_old in homedir echo -n "Creating $olddir for backup of any existing dotfiles in ~ ..." mkdir -p $olddir echo "done" # change to the dotfiles directory echo -n "Changing to the $dir directory ..." cd $dir echo "done" # move any existing dotfiles in homedir to $olddir, then create symlinks from homedir to any files $dir specified in $files for file in $files; do if [ -f $olddir/.$file ]; then echo "$file already under version control, not backing up" else echo "$file not yet under version control" echo "Moving any existing dotfiles from ~ to $olddir" mv ~/.$file $olddir echo "done" echo "Creating symlink to $file in home directory" ln -s $dir/$file ~/.$file echo "done" fi done
1f9c75746dc2960881cf3e49cdfb300e2394609c
[ "Shell" ]
1
Shell
jonasty/dotfiles
84f85cebe21c983cffa0c620f5306e4c24b8512f
4b257db5cd626718bdfaf8a1c638bc9aa2960120
refs/heads/master
<repo_name>thijstriemstra/py-wasmi<file_sep>/wasmi/spec/section.py CUSTOM = 0 TYPE = 1 IMPORT = 2 FUNCTION = 3 TABLE = 4 MEMORY = 5 GLOBAL = 6 EXPORT = 7 START = 8 ELEMENT = 9 CODE = 10 DATA = 11 info = {} info[CUSTOM] = 'custom' info[TYPE] = 'type' info[IMPORT] = 'import' info[FUNCTION] = 'function' info[TABLE] = 'table' info[MEMORY] = 'memory' info[GLOBAL] = 'global' info[EXPORT] = 'export' info[START] = 'start' info[ELEMENT] = 'element' info[CODE] = 'code' info[DATA] = 'data' <file_sep>/wasmi/stack.py import typing import wasmi.num import wasmi.spec.valtype class Entry: def __init__(self, valtype: int, n): self.valtype = valtype self.n = n def __repr__(self): return f'{wasmi.spec.valtype.info[self.valtype]}({self.n})' @classmethod def from_i32(cls, n): return Entry(wasmi.spec.valtype.I32, wasmi.num.int2i32(n)) @classmethod def from_i64(cls, n): return Entry(wasmi.spec.valtype.I64, wasmi.num.int2i64(n)) @classmethod def from_f32(cls, n): return Entry(wasmi.spec.valtype.F32, n) @classmethod def from_f64(cls, n): return Entry(wasmi.spec.valtype.F64, n) def into_i32(self): return self.n def into_i64(self): return self.n def into_u32(self): return wasmi.num.int2u32(self.n) def into_u64(self): return wasmi.num.int2u64(self.n) def into_f32(self): return self.n def into_f64(self): return self.n class Stack: def __init__(self): self.data: typing.List[Entry] = [None for _ in range(1024)] self.i: int = -1 def add(self, n: Entry): self.i += 1 self.data[self.i] = n def pop(self) -> Entry: r = self.data[self.i] self.i -= 1 return r def len(self) -> int: return self.i + 1 def top(self) -> Entry: return self.data[self.i] def add_i32(self, n): self.add(Entry.from_i32(n)) def add_i64(self, n): self.add(Entry.from_i64(n)) def add_f32(self, n): self.add(Entry.from_f32(n)) def add_f64(self, n): self.add(Entry.from_f64(n)) def pop_i32(self): return self.pop().into_i32() def pop_i64(self): return self.pop().into_i64() def pop_u32(self): return self.pop().into_u32() def pop_u64(self): return self.pop().into_u64() def pop_f32(self): return self.pop().into_f32() def pop_f64(self): return self.pop().into_f64() <file_sep>/examples/env.py import wasmi def env_fib(_, args): def fib(a): if a <= 1: return a return fib(a - 1) + fib(a - 2) return fib(args[0].into_i32()) env = wasmi.Env() env.import_func['env.fib'] = env_fib path = './examples/env.wasm' mod = wasmi.Module.open(path) vm = wasmi.Vm(mod, env) r = vm.exec('get', [10]) print(r) <file_sep>/wasmi/section.py import io import typing import wasmi.common import wasmi.error import wasmi.spec.external import wasmi.spec.op import wasmi.spec.section import wasmi.spec.valtype class Limits: """Limits are encoded with a preceding flag indicating whether a maximum is present. limits ::= 0x00 n:u32 ⇒ {min n,max ϵ} | 0x01 n:u32 m:u32 ⇒ {min n,max m} """ def __init__(self, flag: int, minimum: int, maximum: int): self.flag = flag self.minimum = minimum self.maximum = maximum def __repr__(self): if self.flag: return f'Limits<minimum={self.minimum} maximum={self.maximum}>' return f'Limits<minimum={self.minimum} maximum=inf>' @classmethod def from_reader(cls, r: typing.BinaryIO): flag = ord(r.read(1)) minimum = wasmi.common.read_leb(r, 32)[1] if flag == 1: maximum = wasmi.common.read_leb(r, 32)[1] return Limits(flag, minimum, maximum) return Limits(flag, minimum, 0) class Expression: """Expressions are encoded by their instruction sequence terminated with an explicit 0x0B opcode for end. expr ::= (in:instr)∗ 0x0B ⇒ in∗ end """ def __init__(self, data: bytearray): self.data = data def __repr__(self): return f'Expression<data={self.data.hex()}>' @classmethod def skip(cls, opcode: int, r: typing.BinaryIO): data = bytearray() for e in wasmi.spec.op.info[opcode][1]: if e == 'leb_1': a = wasmi.common.read_leb(r, 1)[2] data.extend(a) continue if e == 'leb_7': a = wasmi.common.read_leb(r, 7)[2] data.extend(a) continue if e == 'leb_32': a = wasmi.common.read_leb(r, 32)[2] data.extend(a) continue if e == 'leb_64': a = wasmi.common.read_leb(r, 64)[2] data.extend(a) continue if e == 'bit_32': a = r.read(4) data.extend(a) continue if e == 'bit_64': a = r.read(8) data.extend(a) continue if e == 'leb_32xleb_32': _, c, a = wasmi.common.read_leb(r, 64) data.extend(a) for _ in range(c): a = wasmi.common.read_leb(r, 64)[2] data.extend(a) continue return data @classmethod def from_reader(cls, r: typing.BinaryIO): data = bytearray() d = 1 for _ in range(1 << 32): op = ord(r.read(1)) data.append(op) if op in [wasmi.spec.op.BLOCK, wasmi.spec.op.LOOP, wasmi.spec.op.IF]: d += 1 if op == wasmi.spec.op.END: d -= 1 if not d: break data.extend(cls.skip(op, r)) return Expression(data) class FuncType: """Function types are encoded by the byte 0x60 followed by the respective vectors of parameter and result types. functype ::= 0x60 t1∗:vec(valtype) t2∗:vec(valtype) ⇒ [t1∗] → [t2∗] """ def __init__(self, args: typing.List[int], rets: typing.List[int]): self.args = args self.rets = rets def __repr__(self): args = [wasmi.spec.valtype.info[i] for i in self.args] rets = [wasmi.spec.valtype.info[i] for i in self.rets] return f'FuncType<args={args} rets={rets}>' @classmethod def from_reader(cls, r: typing.BinaryIO): assert ord(r.read(1)) == 0x60 n = wasmi.common.read_leb(r, 32)[1] args = r.read(n) n = wasmi.common.read_leb(r, 32)[1] rets = r.read(n) return FuncType(list(args), list(rets)) class GlobalType: """Global types are encoded by their value type and a flag for their mutability. globaltype ::= t:valtype m:mut ⇒ m t mut ::= 0x00 ⇒ const | 0x01 ⇒ var """ def __init__(self, valtype: int, mut: int): self.valtype = valtype self.mut = mut def __repr__(self): return f'GlobalType<valtype={wasmi.spec.valtype.info[self.valtype]} mut={self.mut}>' @classmethod def from_reader(cls, r: typing.BinaryIO): valtype = ord(r.read(1)) mut = ord(r.read(1)) return GlobalType(valtype, mut) class Global: """ global ::= gt:globaltype e:expr ⇒ {type gt, init e} """ def __init__(self, globaltype: GlobalType, expr: Expression): self.globaltype = globaltype self.expr = expr def __repr__(self): return f'Global<globaltype={self.globaltype} expr={self.expr}>' @classmethod def from_reader(cls, r: typing.BinaryIO): globaltype = GlobalType.from_reader(r) expr = Expression.from_reader(r) return Global(globaltype, expr) class Export: """The exports component of a module defines a set of exports that become accessible to the host environment once the module has been instantiated. export ::= {name name, desc exportdesc} exportdesc ::= func funcidx | table tableidx | mem memidx | global globalidx Each export is labeled by a unique name. Exportable definitions are functions, tables, memories, and globals, which are referenced through a respective descriptor. """ def __init__(self, kind: int, name: str, idx: int): self.kind = kind self.name = name self.idx = idx def __repr__(self): return f'Export<kind={wasmi.spec.external.info[self.kind]} name={self.name} idx={self.idx}>' class Locals: """ locals ::= n:u32 t:valtype ⇒ tn """ def __init__(self, n: int, valtype: int): self.n = n self.valtype = valtype def __repr__(self): return f'Locals<n={self.n} valtype={self.valtype}>' @classmethod def from_reader(cls, r: typing.BinaryIO): n = wasmi.common.read_leb(r, 32)[1] valtype = ord(r.read(1)) return Locals(n, valtype) class Block: def __init__(self, opcode, kind, pos_head): self.opcode = opcode # block opcode (0x00 for init_expr) self.kind = kind # valtype self.pos_head = pos_head self.pos_stop = 0 self.pos_else = 0 self.pos_br = 0 def __repr__(self): name = 'Block' seps = [] seps.append(f'opcode={wasmi.spec.op.info[self.opcode][0]}') seps.append(f'kind={wasmi.spec.valtype.info[self.kind]}') seps.append(f'pos_head={self.pos_head}') seps.append(f'pos_stop={self.pos_stop}') seps.append(f'pos_else={self.pos_else}') seps.append(f'pos_br={self.pos_br}') return f'{name}<{" ".join(seps)}>' class Code: """The funcs component of a module defines a vector of functions with the following structure: func ::= {type typeidx, locals vec(valtype), body expr} """ def __init__(self, locs: typing.List[int], expr: Expression): self.locals = locs self.expr = expr self.bmap = self.imap() self.pos_br = len(self.expr.data) - 1 def __repr__(self): return f'Code<locals={self.locals} expr={self.expr}>' def imap(self) -> typing.Dict[int, Block]: pc = 0 bmap: typing.Dict[int, Block] = {} bstack: typing.List[Block] = [] code = self.expr.data for _ in range(1 << 32): op = code[pc] pc += 1 if op >= wasmi.spec.op.BLOCK and op <= wasmi.spec.op.IF: b = Block(op, code[pc], pc - 1) bstack.append(b) bmap[pc - 1] = b data = Expression.skip(op, io.BytesIO(code[pc:])) pc += len(data) continue if op == wasmi.spec.op.ELSE: if bstack[-1].opcode != wasmi.spec.op.IF: raise wasmi.error.WAException('else not matched with if') bstack[-1].pos_else = pc bmap[bstack[-1].pos_head].pos_else = pc continue if op == wasmi.spec.op.END: if pc == len(code): break b = bstack.pop() if b.opcode == wasmi.spec.op.LOOP: b.pos_stop = pc - 1 b.pos_br = b.pos_head + 2 continue b.pos_stop = pc - 1 b.pos_br = pc - 1 continue data = Expression.skip(op, io.BytesIO(code[pc:])) pc += len(data) if op != wasmi.spec.op.END: raise wasmi.error.WAException('function block did not end with 0xb') if bstack: raise wasmi.error.WAException('function ended in middle of block') return bmap @classmethod def from_reader(cls, r: typing.BinaryIO): n = wasmi.common.read_leb(r, 32)[1] n = wasmi.common.read_leb(r, 32)[1] locs = [Locals.from_reader(r) for _ in range(n)] expr = Expression.from_reader(r) return Code(locs, expr) class Data: """The initial contents of a memory are zero-valued bytes. The data component of a module defines a vector of data segments that initialize a range of memory, at a given offset, with a static vector of bytes. data ::= {data memidx, offset expr, init vec(byte)} The offset is given by a constant expression. Note: In the current version of WebAssembly, at most one memory is allowed in a module. Consequently, the only valid memidx is 0. """ def __init__(self, memidx: int, expr: Expression, init: bytearray): self.memidx = memidx self.expr = expr self.init = init def __repr__(self): return f'Data<memidx={self.memidx} expr={self.expr} init={self.init.hex()}>' @classmethod def from_reader(cls, r: typing.BinaryIO): memidx = wasmi.common.read_leb(r, 32)[1] expr = Expression.from_reader(r) n = wasmi.common.read_leb(r, 32)[1] init = r.read(n) return Data(memidx, expr, bytearray(init)) class Table: """Table types are encoded with their limits and a constant byte indicating their element type. tabletype ::= et:elemtype lim:limits ⇒ lim et elemtype ::= 0x70 ⇒ funcref """ def __init__(self, elemtype: int, limits: Limits): self.elemtype = elemtype self.limits = limits def __repr__(self): return f'Table<elemtype={wasmi.spec.valtype.info[self.elemtype]} limits={self.limits}>' @classmethod def from_reader(cls, r: typing.BinaryIO): elemtype = ord(r.read(1)) limits = Limits.from_reader(r) return Table(elemtype, limits) class Memory: """Memory types are encoded with their limits. memtype ::= lim:limits ⇒ lim """ def __init__(self, limits: Limits): self.limits = limits def __repr__(self): return f'Memory<limits={self.limits}>' @classmethod def from_reader(cls, r: typing.BinaryIO): limits = Limits.from_reader(r) return Memory(limits) class Import: """The imports component of a module defines a set of imports that are required for instantiation. import ::= {module name, name name, desc importdesc} importdesc ::= func typeidx | table tabletype | mem memtype | global globaltype Each import is labeled by a two-level name space, consisting of a module name and a name for an entity within that module. Importable definitions are functions, tables, memories, and globals. Each import is specified by a descriptor with a respective type that a definition provided during instantiation is required to match. Every import defines an index in the respective index space. In each index space, the indices of imports go before the first index of any definition contained in the module itself. """ def __init__(self, kind: int, module: str, name: str): self.kind = kind self.module = module self.name = name self.desc = None def __repr__(self): return f'Import<kind={self.kind} module={self.module} name={self.name} desc={self.desc}>' @classmethod def from_reader(cls, r: typing.BinaryIO): n = wasmi.common.read_leb(r, 32)[1] module = r.read(n).decode() n = wasmi.common.read_leb(r, 32)[1] name = r.read(n).decode() kind = ord(r.read(1)) sec = Import(kind, module, name) if kind == wasmi.spec.external.FUNCTION: n = wasmi.common.read_leb(r, 32)[1] sec.desc = n if kind == wasmi.spec.external.TABLE: sec.desc = Table.from_reader(r) if kind == wasmi.spec.external.MEMORY: sec.desc = Memory.from_reader(r) if kind == wasmi.spec.external.GLOBAL: sec.desc = GlobalType.from_reader(r) return sec class Element: """The initial contents of a table is uninitialized. The elem component of a module defines a vector of element segments that initialize a subrange of a table, at a given offset, from a static vector of elements. elem ::= {table tableidx, offset expr, init vec(funcidx)} The offset is given by a constant expression. Note: In the current version of WebAssembly, at most one table is allowed in a module. Consequently, the only valid tableidx is 0. """ def __init__(self, tableidx: int, expr: Expression, init: typing.List[int]): self.tableidx = tableidx self.expr = expr self.init = init def __repr__(self): return f'Element<tableidx={self.tableidx} expr={self.expr} init={self.init}>' @classmethod def from_reader(cls, r: typing.BinaryIO): tableidx = wasmi.common.read_leb(r, 32)[1] expr = Expression.from_reader(r) n = wasmi.common.read_leb(r, 32)[1] init = [] for _ in range(n): e = wasmi.common.read_leb(r, 32)[1] init.append(e) return Element(tableidx, expr, init) class Section: """Each section consists of 1. a one-byte section id 2. the u32 size of the contents, in bytes 3. the actual contents, whose structure is depended on the section id """ def __init__(self): self.section_id: int self.contents: bytearray def __repr__(self): section_id = wasmi.spec.section.info[self.section_id] return f'Section<section_id={section_id} contents={self.contents.hex()}>' @classmethod def from_reader(cls, r: typing.BinaryIO): section_id = wasmi.common.read_leb(r, 32)[1] n = wasmi.common.read_leb(r, 32)[1] contents = r.read(n) sec = Section() sec.section_id = section_id sec.contents = bytearray(contents) return sec class SectionCustom: """Custom sections have the id 0. They are intended to be used for debugging information or third-party extensions, and are ignored by the WebAssembly semantics. Their contents consist of a name further identifying the custom section, followed by an uninterpreted sequence of bytes for custom use. customsec ::= section0(custom) custom ::= name byte∗ """ def __init__(self): self.name: str = None self.data: bytearray = None def __repr__(self): return f'SectionCustom<name={self.name} data={self.data}>' @classmethod def from_section(cls, f: Section): sec = SectionCustom() r = io.BytesIO(f.contents) n = wasmi.common.read_leb(r, 32)[1] sec.name = r.read(n).decode() sec.data = bytearray(r.read(-1)) return sec class SectionType: """The type section has the id 1. It decodes into a vector of function types that represent the types component of a module. typesec ::= ft∗:section1(vec(functype)) ⇒ ft∗ """ def __init__(self): self.entries: typing.List[FuncType] = [] def __repr__(self): return f'SectionType<entries={self.entries}>' @classmethod def from_section(cls, f: Section): sec = SectionType() r = io.BytesIO(f.contents) n = wasmi.common.read_leb(r, 32)[1] for _ in range(n): e = FuncType.from_reader(r) sec.entries.append(e) return sec class SectionImport: """The import section has the id 2. It decodes into a vector of imports that represent the imports component of a module. importsec ::= im∗:section2(vec(import)) ⇒ im∗ import ::= mod:name nm:name d:importdesc ⇒ {module mod, name nm, desc d} importdesc ::= 0x00 x:typeidx ⇒ func x | 0x01 tt:tabletype ⇒ table tt | 0x02 mt:memtype ⇒ mem mt | 0x03 gt:globaltype ⇒ global gt """ def __init__(self): self.entries: typing.List[Import] = [] def __repr__(self): return f'SectionImport<entries={self.entries}>' @classmethod def from_section(cls, f: Section): sec = SectionImport() r = io.BytesIO(f.contents) n = wasmi.common.read_leb(r, 32)[1] for _ in range(n): e = Import.from_reader(r) sec.entries.append(e) return sec class SectionFunction: """The function section has the id 3. It decodes into a vector of type indices that represent the type fields of the functions in the funcs component of a module. The locals and body fields of the respective functions are encoded separately in the code section. funcsec ::= x∗:section3(vec(typeidx)) ⇒ x∗ """ def __init__(self): self.entries: typing.List[int] = [] def __repr__(self): return f'SectionFunction<entries={self.entries}>' @classmethod def from_section(cls, f: Section): sec = SectionFunction() r = io.BytesIO(f.contents) n = wasmi.common.read_leb(r, 32)[1] for _ in range(n): _, e, _ = wasmi.common.read_leb(r, 32) sec.entries.append(e) return sec class SectionTable: """The table section has the id 4. It decodes into a vector of tables that represent the tables component of a module. tablesec ::= tab∗:section4(vec(table)) ⇒ tab∗ table ::= tt:tabletype ⇒ {type tt} """ def __init__(self): self.entries: typing.List[Table] = [] self.dict = {} def __repr__(self): return f'SectionTable<entries={self.entries} dict={self.dict}>' @classmethod def from_section(cls, f: Section): sec = SectionTable() r = io.BytesIO(f.contents) n = wasmi.common.read_leb(r, 32)[1] for _ in range(n): e = Table.from_reader(r) sec.entries.append(e) sec.dict[e.elemtype] = [0] * e.limits.minimum return sec class SectionMemory: """The memory section has the id 5. It decodes into a vector of memories that represent the mems component of a module. memsec ::= mem∗:section5(vec(mem)) ⇒ mem∗ mem ::= mt:memtype ⇒ {type mt} """ def __init__(self): self.entries: typing.List[Memory] = [] def __repr__(self): return f'SectionMemory<entries={self.entries}>' @classmethod def from_section(cls, f: Section): sec = SectionMemory() r = io.BytesIO(f.contents) n = wasmi.common.read_leb(r, 32)[1] for _ in range(n): e = Memory.from_reader(r) sec.entries.append(e) return sec class SectionGlobal: """The global section has the id 6. It decodes into a vector of globals that represent the globals component of a module. globalsec ::= glob*:section6(vec(global)) ⇒ glob∗ global ::= gt:globaltype e:expr ⇒ {type gt, init e} """ def __init__(self): self.entries: typing.List[Global] = [] def __repr__(self): return f'SectionGlobal<entries={self.entries}>' @classmethod def from_section(cls, f: Section): sec = SectionGlobal() r = io.BytesIO(f.contents) n = wasmi.common.read_leb(r, 32)[1] for _ in range(n): e = Global.from_reader(r) sec.entries.append(e) return sec class SectionExport: """The export section has the id 7. It decodes into a vector of exports that represent the exports component of a module. exportsec ::= ex∗:section7(vec(export)) ⇒ ex∗ export :: =nm:name d:exportdesc ⇒ {name nm, desc d} exportdesc ::= 0x00 x:funcidx ⇒ func x | 0x01 x:tableidx ⇒ table x | 0x02 x:memidx ⇒ mem x | 0x03 x:globalidx⇒global x """ def __init__(self): self.entries: typing.List[Export] = [] def __repr__(self): return f'SectionExport<entries={self.entries}>' @classmethod def from_section(cls, f: Section): sec = SectionExport() r = io.BytesIO(f.contents) n = wasmi.common.read_leb(r, 32)[1] for _ in range(n): n = wasmi.common.read_leb(r, 32)[1] name = r.read(n).decode() kind = ord(r.read(1)) n = wasmi.common.read_leb(r, 32)[1] sec.entries.append(Export(kind, name, n)) return sec class SectionStart: """The start section has the id 8. It decodes into an optional start function that represents the start component of a module. startsec ::= st?:section8(start) ⇒ st? start ::= x:funcidx ⇒ {func x} """ def __init__(self): self.funcidx: int def __repr__(self): return f'SectionStart<funcidx={self.funcidx}>' @classmethod def from_section(cls, f: Section): sec = SectionStart() r = io.BytesIO(f.contents) n = wasmi.common.read_leb(r, 32)[1] sec.funcidx = n return sec class SectionElement: """The element section has the id 9. It decodes into a vector of element segments that represent the elem component of a module. elemsec ::= seg∗:section9(vec(elem)) ⇒ seg elem ::= x:tableidx e:expr y∗:vec(funcidx) ⇒ {table x, offset e, init y∗} """ def __init__(self): self.entries: typing.List[Element] = [] def __repr__(self): return f'SectionElement<entries={self.entries}>' @classmethod def from_section(cls, f: Section): sec = SectionElement() r = io.BytesIO(f.contents) n = wasmi.common.read_leb(r, 32)[1] for _ in range(n): e = Element.from_reader(r) sec.entries.append(e) return sec class SectionCode: """The code section has the id 10. It decodes into a vector of code entries that are pairs of value type vectors and expressions. They represent the locals and body field of the functions in the funcs component of a module. The type fields of the respective functions are encoded separately in the function section. The encoding of each code entry consists of 1. the u32 size of the function code in bytes, 2. the actual function code, which in turn consists of 1. the declaration of locals, 2. the function body as an expression. Local declarations are compressed into a vector whose entries consist of 1. a u32 count, 2. a value type, denoting count locals of the same value type. codesec ::= code∗:section10(vec(code)) ⇒ code∗ code ::= size:u32 code:func ⇒ code(ifsize=||func||) func ::= (t∗)∗:vec(locals) e:expr ⇒ concat((t∗)∗), e∗(if|concat((t∗)∗)|<232) locals ::= n:u32 t:valtype⇒tn """ def __init__(self): self.entries: typing.List[Code] = [] def __repr__(self): return f'SectionCode<entries={self.entries}>' @classmethod def from_section(cls, f: Section): sec = SectionCode() r = io.BytesIO(f.contents) n = wasmi.common.read_leb(r, 32)[1] for _ in range(n): e = Code.from_reader(r) sec.entries.append(e) return sec class SectionData: """The data section has the id 11. It decodes into a vector of data segments that represent the data component of a module. datasec ::= seg∗:section11(vec(data)) ⇒ seg data ::= x:memidx e:expr b∗:vec(byte) ⇒ {data x,offset e,init b∗} """ def __init__(self): self.entries: typing.List[Data] = [] def __repr__(self): return f'SectionData<entries={self.entries}>' @classmethod def from_section(cls, f: Section): sec = SectionData() r = io.BytesIO(f.contents) n = wasmi.common.read_leb(r, 32)[1] for _ in range(n): e = Data.from_reader(r) sec.entries.append(e) return sec <file_sep>/examples/__main__.py import os import sys sys.path.append(os.getcwd()) import wasmi name = sys.argv[1] path = os.path.join('examples', f'{name}.wasm') mod = wasmi.Module.open(path) wvm = wasmi.Vm(mod) r = wvm.exec(name, [int(i) for i in sys.argv[2:]]) print(r) <file_sep>/wasmi/__init__.py import math import typing import wasmi.common import wasmi.error import wasmi.log import wasmi.num import wasmi.section import wasmi.spec.section import wasmi.spec.op import wasmi.spec.external import wasmi.spec.valtype import wasmi.stack class Module: def __init__(self): self.section_custom: wasmi.section.SectionUnknown = None self.section_type: wasmi.section.SectionType = None self.section_import: wasmi.section.SectionImport = None self.section_function: wasmi.section.SectionFunction = None self.section_table: wasmi.section.SectionTable = None self.section_memory: wasmi.section.SectionMemory = None self.section_global: wasmi.section.SectionGlobal = None self.section_export: wasmi.section.SectionExport = None self.section_start: wasmi.section.SectionStart = None self.section_element: wasmi.section.SectionElement = None self.section_code: wasmi.section.SectionCode = None self.section_data: wasmi.section.SectionData = None @classmethod def open(cls, name: str): with open(name, 'rb') as f: return cls.from_reader(f) @classmethod def from_reader(cls, r: typing.BinaryIO): mod = Module() mag = wasmi.num.LittleEndian.u32(r.read(4)) if mag != 0x6d736100: raise wasmi.error.WAException('invalid magic number') ver = wasmi.num.LittleEndian.u32(r.read(4)) if ver != 0x01: raise wasmi.error.WAException('invalid version') wasmi.log.println('Section slice'.center(80, '-')) sections: typing.List[wasmi.section.Section] = [] for _ in range(1 << 32): try: sec = wasmi.section.Section.from_reader(r) except Exception as e: break wasmi.log.println(sec) sections.append(sec) wasmi.log.println('Section parse'.center(80, '-')) for sec in sections: if sec.section_id == wasmi.spec.section.CUSTOM: mod.section_custom = wasmi.section.SectionCustom.from_section(sec) wasmi.log.println(mod.section_custom) continue if sec.section_id == wasmi.spec.section.TYPE: mod.section_type = wasmi.section.SectionType.from_section(sec) wasmi.log.println(f'SectionType') for i, e in enumerate(mod.section_type.entries): wasmi.log.println(f' 0x{i:02x} {e}') continue if sec.section_id == wasmi.spec.section.IMPORT: mod.section_import = wasmi.section.SectionImport.from_section(sec) wasmi.log.println(f'SectionImport') for i, e in enumerate(mod.section_import.entries): wasmi.log.println(f' 0x{i:02x} {e}') continue if sec.section_id == wasmi.spec.section.FUNCTION: mod.section_function = wasmi.section.SectionFunction.from_section(sec) wasmi.log.println(f'SectionFunction') for i, e in enumerate(mod.section_function.entries): wasmi.log.println(f' 0x{i:02x} {e}') continue if sec.section_id == wasmi.spec.section.TABLE: mod.section_table = wasmi.section.SectionTable.from_section(sec) wasmi.log.println(f'SectionTable') for i, e in enumerate(mod.section_table.entries): wasmi.log.println(f' 0x{i:02x} {e}') continue if sec.section_id == wasmi.spec.section.MEMORY: mod.section_memory = wasmi.section.SectionMemory.from_section(sec) wasmi.log.println(f'SectionMemory') for i, e in enumerate(mod.section_memory.entries): wasmi.log.println(f' 0x{i:02x} {e}') continue if sec.section_id == wasmi.spec.section.GLOBAL: mod.section_global = wasmi.section.SectionGlobal.from_section(sec) wasmi.log.println(f'SectionGlobal') for i, e in enumerate(mod.section_global.entries): wasmi.log.println(f' 0x{i:02x} {e}') continue if sec.section_id == wasmi.spec.section.EXPORT: mod.section_export = wasmi.section.SectionExport.from_section(sec) wasmi.log.println(f'SectionExport') for i, e in enumerate(mod.section_export.entries): wasmi.log.println(f' 0x{i:02x} {e}') continue if sec.section_id == wasmi.spec.section.START: mod.section_start = wasmi.section.SectionStart.from_section(sec) wasmi.log.println(mod.section_start) continue if sec.section_id == wasmi.spec.section.ELEMENT: mod.section_element = wasmi.section.SectionElement.from_section(sec) wasmi.log.println(f'SectionElement') for i, e in enumerate(mod.section_element.entries): wasmi.log.println(f' 0x{i:02x} {e}') continue if sec.section_id == wasmi.spec.section.CODE: mod.section_code = wasmi.section.SectionCode.from_section(sec) wasmi.log.println(f'SectionCode') for i, e in enumerate(mod.section_code.entries): wasmi.log.println(f' 0x{i:02x} {e}') continue if sec.section_id == wasmi.spec.section.DATA: mod.section_data = wasmi.section.SectionData.from_section(sec) wasmi.log.println(f'SectionData') for i, e in enumerate(mod.section_data.entries): wasmi.log.println(f' 0x{i:02x} {e}') continue return mod class Env: def __init__(self): self.import_func = {} class Ctx: def __init__(self, data: typing.List[wasmi.stack.Entry]): self.stack = wasmi.stack.Stack() self.ctack = [] self.locals_data = data class Function: def __init__(self, signature: wasmi.section.FuncType): self.signature = signature self.code: wasmi.section.Code = None self.envb = False self.module: str self.name: str def __repr__(self): name = 'Function' seps = [] seps.append(f'envb={self.envb}') seps.append(f'signature={self.signature}') if self.envb: seps.append(f'module={self.module}') seps.append(f'name={self.name}') return f'{name}<{" ".join(seps)}>' @classmethod def from_sec(cls, signature: wasmi.section.FuncType, code: wasmi.section.Code): func = Function(signature) func.code = code return func @classmethod def from_env(cls, signature: wasmi.section.FuncType, module: str, name: str): func = Function(signature) func.envb = True func.module = module func.name = name return func class Vm: def __init__(self, mod: Module, env: Env = None): self.mod = mod self.global_data: typing.List[wasmi.stack.Entry] = [] self.mem = bytearray() self.mem_len = 0 self.table = {} self.functions: typing.List[Function] = [] self.env = env if env else Env() if self.mod.section_custom: pass if self.mod.section_type: pass if self.mod.section_import: for e in self.mod.section_import.entries: if e.kind == wasmi.spec.external.FUNCTION: func = Function.from_env( self.mod.section_type.entries[e.desc], e.module, e.name ) self.functions.append(func) if e.kind == wasmi.spec.external.TABLE: continue if e.kind == wasmi.spec.external.MEMORY: continue if e.kind == wasmi.spec.external.GLOBAL: continue if self.mod.section_function: for fun_idx, sig_idx in enumerate(self.mod.section_function.entries): func = Function.from_sec( self.mod.section_type.entries[sig_idx], self.mod.section_code.entries[fun_idx] ) self.functions.append(func) if self.mod.section_table: self.table = self.mod.section_table.dict if self.mod.section_memory: if self.mod.section_memory.entries: if len(self.mod.section_memory.entries) > 1: raise wasmi.error.Exception('multiple linear memories') self.mem_len = self.mod.section_memory.entries[0].limits.minimum self.mem = bytearray([0 for _ in range(self.mem_len * 64 * 1024)]) if self.mod.section_global: for e in self.mod.section_global.entries: v = self.exec_init_expr(e.expr.data) self.global_data.append(wasmi.stack.Entry(e.globaltype.valtype, v)) if self.mod.section_export: pass if self.mod.section_start: pass if self.mod.section_element: for e in self.mod.section_element.entries: offset = self.exec_init_expr(e.expr.data) for i, sube in enumerate(e.init): self.table[wasmi.spec.valtype.FUNCREF][offset + i] = sube if self.mod.section_code: pass if self.mod.section_data: for e in self.mod.section_data.entries: assert e.memidx == 0 offset = self.exec_init_expr(e.expr.data) self.mem[offset: offset + len(e.init)] = e.init def exec_init_expr(self, code: bytearray): stack = wasmi.stack.Stack() if not code: raise wasmi.error.WAException('empty init expr') pc = 0 for _ in range(1 << 32): opcode = code[pc] pc += 1 if opcode == wasmi.spec.op.I32_CONST: n, i, _ = wasmi.common.read_leb(code[pc:], 32, True) pc += n stack.add_i32(i) continue if opcode == wasmi.spec.op.I64_CONST: n, i, _ = wasmi.common.read_leb(code[pc:], 64, True) pc += n stack.add_i64(i) continue if opcode == wasmi.spec.op.F32_CONST: v = wasmi.common.read_f32(code[pc:]) pc += 4 stack.add_f32(v) continue if opcode == wasmi.spec.op.F64_CONST: v = wasmi.common.read_f64(code[pc:]) pc += 8 stack.add_f64(v) continue if opcode == wasmi.spec.op.GET_GLOBAL: n, i, _ = wasmi.common.read_leb(code[pc:], 32) pc += n v = self.global_data[i] stack.add(v) continue if opcode == wasmi.spec.op.END: break if not stack.len(): return 0 return stack.pop().n def exec_step(self, f_idx: int, ctx: Ctx): f_fun = self.functions[f_idx] f_sig = f_fun.signature f_sec = f_fun.code for eloc in f_sec.locals: for _ in range(eloc.n): e = wasmi.stack.Entry(eloc.valtype, 0) ctx.locals_data.append(e) ctx.ctack.append([f_sec, ctx.stack.i]) code = f_sec.expr.data wasmi.log.println('Code', code.hex()) wasmi.log.println('Locals', ctx.locals_data) wasmi.log.println('Global', self.global_data) pc = 0 for _ in range(1 << 32): opcode = code[pc] pc += 1 name = wasmi.spec.op.info[opcode][0] wasmi.log.println(f'0x{wasmi.common.fmth(opcode, 2)}({name}) {ctx.stack.data[:ctx.stack.i + 1]}') if opcode == wasmi.spec.op.UNREACHABLE: raise wasmi.error.WAException('reached unreachable') if opcode == wasmi.spec.op.NOP: continue if opcode == wasmi.spec.op.BLOCK: n, _, _ = wasmi.common.read_leb(code[pc:], 32) b = f_sec.bmap[pc - 1] pc += n ctx.ctack.append([b, ctx.stack.i]) continue if opcode == wasmi.spec.op.LOOP: n, _, _ = wasmi.common.read_leb(code[pc:], 32) b = f_sec.bmap[pc - 1] pc += n ctx.ctack.append([b, ctx.stack.i]) continue if opcode == wasmi.spec.op.IF: n, _, _ = wasmi.common.read_leb(code[pc:], 32) b = f_sec.bmap[pc - 1] pc += n ctx.ctack.append([b, ctx.stack.i]) cond = ctx.stack.pop_i32() if cond: continue if b.pos_else == 0: ctx.ctack.pop() pc = b.pos_br + 1 continue pc = b.pos_else continue if opcode == wasmi.spec.op.ELSE: b, _ = ctx.ctack[-1] pc = b.pos_br continue if opcode == wasmi.spec.op.END: b, sp = ctx.ctack.pop() if isinstance(b, wasmi.section.Code): if not ctx.ctack: if f_sig.rets: if f_sig.rets[0] != ctx.stack.top().valtype: raise wasmi.error.WAException('signature mismatch in call_indirect') return ctx.stack.pop().n return None return if sp < ctx.stack.i: v = ctx.stack.pop() ctx.stack.i = sp ctx.stack.add(v) continue if opcode == wasmi.spec.op.BR: n, c, _ = wasmi.common.read_leb(code[pc:], 32) pc += n for _ in range(c): ctx.ctack.pop() b, _ = ctx.ctack[-1] pc = b.pos_br continue if opcode == wasmi.spec.op.BR_IF: n, br_depth, _ = wasmi.common.read_leb(code[pc:], 32) pc += n cond = ctx.stack.pop_i32() if cond: for _ in range(br_depth): ctx.ctack.pop() b, _ = ctx.ctack[-1] pc = b.pos_br continue if opcode == wasmi.spec.op.BR_TABLE: n, lcount, _ = wasmi.common.read_leb(code[pc:], 32) pc += n depths = [] for c in range(lcount): n, ldepth, _ = wasmi.common.read_leb(code[pc:], 32) pc += n depths.append(ldepth) n, ddepth, _ = wasmi.common.read_leb(code[pc:], 32) pc += n didx = ctx.stack.pop_i32() if didx >= 0 and didx < len(depths): ddepth = depths[didx] for _ in range(ddepth): ctx.ctack.pop() b, _ = ctx.ctack[-1] pc = b.pos_br continue if opcode == wasmi.spec.op.RETURN: while ctx.ctack: if isinstance(ctx.ctack[-1][0], wasmi.section.Code): break ctx.ctack.pop() b, _ = ctx.ctack[-1] pc = len(b.expr.data) - 1 continue if opcode == wasmi.spec.op.CALL: n, f_idx, _ = wasmi.common.read_leb(code[pc:], 32) pc += n son_f_fun = self.functions[f_idx] son_f_sig = son_f_fun.signature if son_f_fun.envb: name = son_f_fun.module + '.' + son_f_fun.name func = self.env.import_func[name] r = func(self.mem, [ctx.stack.pop() for _ in son_f_sig.args][::-1]) e = wasmi.stack.Entry(son_f_sig.rets[0], r) ctx.stack.add(e) continue pre_locals_data = ctx.locals_data ctx.locals_data = [ctx.stack.pop() for _ in son_f_sig.args][::-1] self.exec_step(f_idx, ctx) ctx.locals_data = pre_locals_data continue if opcode == wasmi.spec.op.CALL_INDIRECT: n, _, _ = wasmi.common.read_leb(code[pc:], 32) pc += n n, _, _ = wasmi.common.read_leb(code[pc:], 1) pc += n t_idx = ctx.stack.pop_i32() if not 0 <= t_idx < len(self.table[wasmi.spec.valtype.FUNCREF]): raise wasmi.error.WAException('undefined element index') f_idx = self.table[wasmi.spec.valtype.FUNCREF][t_idx] son_f_fun = self.functions[f_idx] son_f_sig = son_f_fun.signature a = list(son_f_sig.args) b = [ctx.stack.pop() for _ in son_f_sig.args][::-1] for i in range(len(a)): ia = a[i] ib = b[i] if not ib or ia != ib.valtype: raise wasmi.error.WAException('signature mismatch in call_indirect') pre_locals_data = ctx.locals_data ctx.locals_data = b self.exec_step(f_idx, ctx) ctx.locals_data = pre_locals_data continue if opcode == wasmi.spec.op.DROP: ctx.stack.pop() continue if opcode == wasmi.spec.op.SELECT: cond = ctx.stack.pop_i32() a = ctx.stack.pop() b = ctx.stack.pop() if cond: ctx.stack.add(b) else: ctx.stack.add(a) continue if opcode == wasmi.spec.op.GET_LOCAL: n, i, _ = wasmi.common.read_leb(code[pc:], 32) pc += n ctx.stack.add(ctx.locals_data[i]) continue if opcode == wasmi.spec.op.SET_LOCAL: v = ctx.stack.pop() n, i, _ = wasmi.common.read_leb(code[pc:], 32) pc += n if i >= len(ctx.locals_data): ctx.locals_data.extend( [wasmi.stack.Entry.from_i32(0) for _ in range(i - len(ctx.locals_data) + 1)] ) ctx.locals_data[i] = v continue if opcode == wasmi.spec.op.TEE_LOCAL: v = ctx.stack.top() n, i, _ = wasmi.common.read_leb(code[pc:], 32) pc += n ctx.locals_data[i] = v continue if opcode == wasmi.spec.op.GET_GLOBAL: n, i, _ = wasmi.common.read_leb(code[pc:], 32) pc += n ctx.stack.add(self.global_data[i]) continue if opcode == wasmi.spec.op.SET_GLOBAL: v = ctx.stack.pop() n, i, _ = wasmi.common.read_leb(code[pc:], 32) pc += n self.global_data[i] = v continue if opcode >= wasmi.spec.op.I32_LOAD and opcode <= wasmi.spec.op.I64_LOAD32_U: # memory_immediate has two fields, the alignment and the offset. # The former is simply an optimization hint and can be safely # discarded. pc += 1 n, mem_offset, _ = wasmi.common.read_leb(code[pc:], 32) pc += n a = ctx.stack.pop_i64() + mem_offset if a + wasmi.spec.op.info[opcode][2] > len(self.mem): raise wasmi.error.WAException('out of bounds memory access') if opcode == wasmi.spec.op.I32_LOAD: r = wasmi.num.LittleEndian.i32(self.mem[a:a + 4]) ctx.stack.add_i32(r) continue if opcode == wasmi.spec.op.I64_LOAD: r = wasmi.num.LittleEndian.i64(self.mem[a:a + 8]) ctx.stack.add_i64(r) continue if opcode == wasmi.spec.op.F32_LOAD: r = wasmi.num.LittleEndian.f32(self.mem[a:a + 4]) ctx.stack.add_f32(r) continue if opcode == wasmi.spec.op.F64_LOAD: r = wasmi.num.LittleEndian.f64(self.mem[a:a + 8]) ctx.stack.add_f64(r) continue if opcode == wasmi.spec.op.I32_LOAD8_S: r = wasmi.num.LittleEndian.i8(self.mem[a:a + 1]) ctx.stack.add_i32(r) continue if opcode == wasmi.spec.op.I32_LOAD8_U: r = wasmi.num.LittleEndian.u8(self.mem[a:a + 1]) ctx.stack.add_i32(r) continue if opcode == wasmi.spec.op.I32_LOAD16_S: r = wasmi.num.LittleEndian.i16(self.mem[a:a + 2]) ctx.stack.add_i32(r) continue if opcode == wasmi.spec.op.I32_LOAD16_U: r = wasmi.num.LittleEndian.u16(self.mem[a:a + 2]) ctx.stack.add_i32(r) continue if opcode == wasmi.spec.op.I64_LOAD8_S: r = wasmi.num.LittleEndian.i8(self.mem[a:a + 1]) ctx.stack.add_i64(r) continue if opcode == wasmi.spec.op.I64_LOAD8_U: r = wasmi.num.LittleEndian.u8(self.mem[a:a + 1]) ctx.stack.add_i64(r) continue if opcode == wasmi.spec.op.I64_LOAD16_S: r = wasmi.num.LittleEndian.i16(self.mem[a:a + 2]) ctx.stack.add_i64(r) continue if opcode == wasmi.spec.op.I64_LOAD16_U: r = wasmi.num.LittleEndian.u16(self.mem[a:a + 2]) ctx.stack.add_i64(r) continue if opcode == wasmi.spec.op.I64_LOAD32_S: r = wasmi.num.LittleEndian.i32(self.mem[a:a + 4]) ctx.stack.add_i64(r) continue if opcode == wasmi.spec.op.I64_LOAD32_U: r = wasmi.num.LittleEndian.u32(self.mem[a:a + 4]) ctx.stack.add_i64(r) continue if opcode >= wasmi.spec.op.I32_STORE and opcode <= wasmi.spec.op.I64_STORE32: v = ctx.stack.pop() pc += 1 n, mem_offset, _ = wasmi.common.read_leb(code[pc:], 32) pc += n a = ctx.stack.pop_i64() + mem_offset if a + wasmi.spec.op.info[opcode][2] > len(self.mem): raise wasmi.error.WAException('out of bounds memory access') if opcode == wasmi.spec.op.I32_STORE: self.mem[a:a + 4] = wasmi.num.LittleEndian.pack_i32(v.into_i32()) continue if opcode == wasmi.spec.op.I64_STORE: self.mem[a:a + 8] = wasmi.num.LittleEndian.pack_i64(v.into_i64()) continue if opcode == wasmi.spec.op.F32_STORE: self.mem[a:a + 4] = wasmi.num.LittleEndian.pack_f32(v.into_f32()) continue if opcode == wasmi.spec.op.F64_STORE: self.mem[a:a + 8] = wasmi.num.LittleEndian.pack_f64(v.into_f64()) continue if opcode == wasmi.spec.op.I32_STORE8: self.mem[a:a + 1] = wasmi.num.LittleEndian.pack_i8(wasmi.num.int2i8(v.into_i32())) continue if opcode == wasmi.spec.op.I32_STORE16: self.mem[a:a + 2] = wasmi.num.LittleEndian.pack_i16(wasmi.num.int2i16(v.into_i32())) continue if opcode == wasmi.spec.op.I64_STORE8: self.mem[a:a + 1] = wasmi.num.LittleEndian.pack_i8(wasmi.num.int2i8(v.into_i64())) continue if opcode == wasmi.spec.op.I64_STORE16: self.mem[a:a + 2] = wasmi.num.LittleEndian.pack_i16(wasmi.num.int2i16(v.into_i64())) continue if opcode == wasmi.spec.op.I64_STORE32: self.mem[a:a + 4] = wasmi.num.LittleEndian.pack_i32(wasmi.num.int2i32(v.into_i64())) continue if opcode == wasmi.spec.op.CURRENT_MEMORY: pc += 1 ctx.stack.add_i32(self.mem_len) continue if opcode == wasmi.spec.op.GROW_MEMORY: pc += 1 cur_len = self.mem_len n = ctx.stack.pop_i32() self.mem_len += n self.mem.extend([0 for _ in range(n * 64 * 1024)]) ctx.stack.add_i32(cur_len) continue if opcode >= wasmi.spec.op.I32_CONST and opcode <= wasmi.spec.op.F64_CONST: if opcode == wasmi.spec.op.I32_CONST: n, r, _ = wasmi.common.read_leb(code[pc:], 32, True) pc += n ctx.stack.add_i32(r) continue if opcode == wasmi.spec.op.I64_CONST: n, r, _ = wasmi.common.read_leb(code[pc:], 64, True) pc += n ctx.stack.add_i64(r) continue if opcode == wasmi.spec.op.F32_CONST: r = wasmi.common.read_f32(code[pc:]) pc += 4 ctx.stack.add_f32(r) continue if opcode == wasmi.spec.op.F64_CONST: r = wasmi.common.read_f64(code[pc:]) pc += 8 ctx.stack.add_f64(r) continue if opcode == wasmi.spec.op.I32_EQZ: ctx.stack.add_i32(ctx.stack.pop_i32() == 0) continue if opcode >= wasmi.spec.op.I32_EQ and opcode <= wasmi.spec.op.I32_GEU: b = ctx.stack.pop() a = ctx.stack.pop() if opcode == wasmi.spec.op.I32_EQ: ctx.stack.add_i32(a.into_i32() == b.into_i32()) continue if opcode == wasmi.spec.op.I32_NE: ctx.stack.add_i32(a.into_i32() != b.into_i32()) continue if opcode == wasmi.spec.op.I32_LTS: ctx.stack.add_i32(a.into_i32() < b.into_i32()) continue if opcode == wasmi.spec.op.I32_LTU: ctx.stack.add_i32(a.into_u32() < b.into_u32()) continue if opcode == wasmi.spec.op.I32_GTS: ctx.stack.add_i32(a.into_i32() > b.into_i32()) continue if opcode == wasmi.spec.op.I32_GTU: ctx.stack.add_i32(a.into_u32() > b.into_u32()) continue if opcode == wasmi.spec.op.I32_LES: ctx.stack.add_i32(a.into_i32() <= b.into_i32()) continue if opcode == wasmi.spec.op.I32_LEU: ctx.stack.add_i32(a.into_u32() <= b.into_u32()) continue if opcode == wasmi.spec.op.I32_GES: ctx.stack.add_i32(a.into_i32() >= b.into_i32()) continue if opcode == wasmi.spec.op.I32_GEU: ctx.stack.add_i32(a.into_u32() >= b.into_u32()) continue if opcode == wasmi.spec.op.I64_EQZ: ctx.stack.add_i32(ctx.stack.pop_i64() == 0) continue if opcode >= wasmi.spec.op.I64_EQ and opcode <= wasmi.spec.op.I64_GEU: b = ctx.stack.pop() a = ctx.stack.pop() if opcode == wasmi.spec.op.I64_EQ: ctx.stack.add_i32(a.into_i64() == b.into_i64()) continue if opcode == wasmi.spec.op.I64_NE: ctx.stack.add_i32(a.into_i64() != b.into_i64()) continue if opcode == wasmi.spec.op.I64_LTS: ctx.stack.add_i32(a.into_i64() < b.into_i64()) continue if opcode == wasmi.spec.op.I64_LTU: ctx.stack.add_i32(a.into_u64() < b.into_u64()) continue if opcode == wasmi.spec.op.I64_GTS: ctx.stack.add_i32(a.into_i64() > b.into_i64()) continue if opcode == wasmi.spec.op.I64_GTU: ctx.stack.add_i32(a.into_u64() > b.into_i64()) continue if opcode == wasmi.spec.op.I64_LES: ctx.stack.add_i32(a.into_i64() <= b.into_i64()) continue if opcode == wasmi.spec.op.I64_LEU: ctx.stack.add_i32(a.into_u64() <= b.into_u64()) continue if opcode == wasmi.spec.op.I64_GES: ctx.stack.add_i32(a.into_i64() >= b.into_i64()) continue if opcode == wasmi.spec.op.I64_GEU: ctx.stack.add_i32(a.into_u64() >= b.into_u64()) continue if opcode >= wasmi.spec.op.F32_EQ and opcode <= wasmi.spec.op.F64_GE: b = ctx.stack.pop() a = ctx.stack.pop() if opcode == wasmi.spec.op.F32_EQ: ctx.stack.add_i32(a.into_f32() == b.into_f32()) continue if opcode == wasmi.spec.op.F32_NE: ctx.stack.add_i32(a.into_f32() != b.into_f32()) continue if opcode == wasmi.spec.op.F32_LT: ctx.stack.add_i32(a.into_f32() < b.into_f32()) continue if opcode == wasmi.spec.op.F32_GT: ctx.stack.add_i32(a.into_f32() > b.into_f32()) continue if opcode == wasmi.spec.op.F32_LE: ctx.stack.add_i32(a.into_f32() <= b.into_f32()) continue if opcode == wasmi.spec.op.F32_GE: ctx.stack.add_i32(a.into_f32() >= b.into_f32()) continue if opcode == wasmi.spec.op.F64_EQ: ctx.stack.add_i32(a.into_f64() == b.into_f64()) continue if opcode == wasmi.spec.op.F64_NE: ctx.stack.add_i32(a.into_f64() != b.into_f64()) continue if opcode == wasmi.spec.op.F64_LT: ctx.stack.add_i32(a.into_f64() < b.into_f64()) continue if opcode == wasmi.spec.op.F64_GT: ctx.stack.add_i32(a.into_f64() > b.into_f64()) continue if opcode == wasmi.spec.op.F64_LE: ctx.stack.add_i32(a.into_f64() <= b.into_f64()) continue if opcode == wasmi.spec.op.F64_GE: ctx.stack.add_i32(a.into_f64() >= b.into_f64()) continue if opcode >= wasmi.spec.op.I32_CLZ and opcode <= wasmi.spec.op.I32_POPCNT: v = ctx.stack.pop_i32() if opcode == wasmi.spec.op.I32_CLZ: c = 0 while c < 32 and (v & 0x80000000) == 0: c += 1 v *= 2 ctx.stack.add_i32(c) continue if opcode == wasmi.spec.op.I32_CTZ: c = 0 while c < 32 and (v % 2) == 0: c += 1 v /= 2 ctx.stack.add_i32(c) continue if opcode == wasmi.spec.op.I32_POPCNT: c = 0 for i in range(32): if 0x1 & v: c += 1 v /= 2 ctx.stack.add_i32(c) continue if opcode >= wasmi.spec.op.I32_ADD and opcode <= wasmi.spec.op.I32_ROTR: b = ctx.stack.pop_i32() a = ctx.stack.pop_i32() if opcode == wasmi.spec.op.I32_ADD: r = wasmi.num.int2i32(a + b) ctx.stack.add_i32(r) continue if opcode == wasmi.spec.op.I32_SUB: r = wasmi.num.int2i32(a - b) ctx.stack.add_i32(r) continue if opcode == wasmi.spec.op.I32_MUL: r = wasmi.num.int2i32(a * b) ctx.stack.add_i32(r) continue if opcode == wasmi.spec.op.I32_DIVS: if b == 0: raise wasmi.error.WAException('integer divide by zero') if a == 0x80000000 and b == -1: raise wasmi.error.WAException('integer overflow') r = wasmi.common.idiv_s(a, b) ctx.stack.add_i32(r) continue if opcode == wasmi.spec.op.I32_DIVU: if b == 0: raise wasmi.error.WAException('integer divide by zero') r = wasmi.num.int2u32(a) // wasmi.num.int2u32(b) ctx.stack.add_i32(r) continue if opcode == wasmi.spec.op.I32_REMS: if b == 0: raise wasmi.error.WAException('integer divide by zero') r = wasmi.common.irem_s(a, b) ctx.stack.add_i32(r) continue if opcode == wasmi.spec.op.I32_REMU: if b == 0: raise wasmi.error.WAException('integer divide by zero') r = wasmi.num.int2u32(a) % wasmi.num.int2u32(b) continue if opcode == wasmi.spec.op.I32_AND: ctx.stack.add_i32(a & b) continue if opcode == wasmi.spec.op.I32_OR: ctx.stack.add_i32(a | b) continue if opcode == wasmi.spec.op.I32_XOR: ctx.stack.add_i32(a ^ b) continue if opcode == wasmi.spec.op.I32_SHL: ctx.stack.add_i32(a << (b % 0x20)) continue if opcode == wasmi.spec.op.I32_SHRS: ctx.stack.add_i32(a >> (b % 0x20)) continue if opcode == wasmi.spec.op.I32_SHRU: ctx.stack.add_i32(wasmi.num.int2u32(a) >> (b % 0x20)) continue if opcode == wasmi.spec.op.I32_ROTL: r = wasmi.common.rotl_u32(a, b) r = wasmi.num.int2i32(r) ctx.stack.add_i32(r) continue if opcode == wasmi.spec.op.I32_ROTR: r = wasmi.common.rotr_u32(a, b) r = wasmi.num.int2i32(r) ctx.stack.add_i32(r) continue if opcode >= wasmi.spec.op.I64_CLZ and opcode <= wasmi.spec.op.I64_POPCNT: v = ctx.stack.pop_i64() if opcode == wasmi.spec.op.I64_CLZ: if v < 0: ctx.stack.add_i32(0) continue c = 1 while c < 63 and (v & 0x4000000000000000) == 0: c += 1 v *= 2 ctx.stack.add_i64(c) continue if opcode == wasmi.spec.op.I64_CTZ: c = 0 while c < 64 and (v % 2) == 0: c += 1 v /= 2 ctx.stack.add_i64(c) continue if opcode == wasmi.spec.op.I64_POPCNT: c = 0 for i in range(64): if 0x1 & v: c += 1 v /= 2 ctx.stack.add_i64(c) continue if opcode >= wasmi.spec.op.I64_ADD and opcode <= wasmi.spec.op.I64_ROTR: b = ctx.stack.pop_i64() a = ctx.stack.pop_i64() if opcode == wasmi.spec.op.I64_ADD: r = wasmi.num.int2i64(a + b) ctx.stack.add_i64(r) continue if opcode == wasmi.spec.op.I64_SUB: r = wasmi.num.int2i64(a - b) ctx.stack.add_i64(r) continue if opcode == wasmi.spec.op.I64_MUL: r = wasmi.num.int2i64(a * b) ctx.stack.add_i64(r) continue if opcode == wasmi.spec.op.I64_DIVS: if b == 0: raise wasmi.error.WAException('integer divide by zero') r = wasmi.common.idiv_s(a, b) ctx.stack.add_i64(r) continue if opcode == wasmi.spec.op.I64_DIVU: if b == 0: raise wasmi.error.WAException('integer divide by zero') r = wasmi.num.int2u64(a) // wasmi.num.int2u64(b) r = wasmi.num.int2i64(r) ctx.stack.add_i64(r) continue if opcode == wasmi.spec.op.I64_REMS: if b == 0: raise wasmi.error.WAException('integer divide by zero') r = wasmi.common.irem_s(a, b) ctx.stack.add_i64(r) if opcode == wasmi.spec.op.I64_REMU: if b == 0: raise wasmi.error.WAException('integer divide by zero') r = wasmi.num.int2u64(a) % wasmi.num.int2u64(b) ctx.stack.add_i64(r) continue if opcode == wasmi.spec.op.I64_AND: ctx.stack.add_i64(a & b) continue if opcode == wasmi.spec.op.I64_OR: ctx.stack.add_i64(a | b) continue if opcode == wasmi.spec.op.I64_XOR: ctx.stack.add_i64(a ^ b) continue if opcode == wasmi.spec.op.I64_SHL: ctx.stack.add_i64(a << (b % 0x40)) continue if opcode == wasmi.spec.op.I64_SHRS: ctx.stack.add_i64(a >> (b % 0x40)) continue if opcode == wasmi.spec.op.I64_SHRU: ctx.stack.add_i64(wasmi.num.int2u64(a) >> (b % 0x40)) continue if opcode == wasmi.spec.op.I64_ROTL: r = wasmi.common.rotl_u64(a, b) r = wasmi.num.int2i64(r) ctx.stack.add_i64(r) continue if opcode == wasmi.spec.op.I64_ROTR: r = wasmi.common.rotr_u64(a, b) r = wasmi.num.int2i64(r) ctx.stack.add_i64(r) continue if opcode >= wasmi.spec.op.F32_ABS and opcode <= wasmi.spec.op.F32_SQRT: v = ctx.stack.pop_f32() if opcode == wasmi.spec.op.F32_ABS: ctx.stack.add_f32(abs(v)) continue if opcode == wasmi.spec.op.F32_NEG: ctx.stack.add_f32(-v) continue if opcode == wasmi.spec.op.F32_CEIL: ctx.stack.add_f32(math.ceil(v)) continue if opcode == wasmi.spec.op.F32_FLOOR: ctx.stack.add_f32(math.floor(v)) continue if opcode == wasmi.spec.op.F32_TRUNC: ctx.stack.add_f32(math.trunc(v)) continue if opcode == wasmi.spec.op.F32_NEAREST: ceil = math.ceil(v) if ceil - v >= 0.5: r = ceil else: r = ceil - 1 ctx.stack.add_f32(r) continue if opcode == wasmi.spec.op.F32_SQRT: ctx.stack.add_f32(math.sqrt(v)) continue if opcode >= wasmi.spec.op.F32_ADD and opcode <= wasmi.spec.op.F32_COPYSIGN: b = ctx.stack.pop_f32() a = ctx.stack.pop_f32() if opcode == wasmi.spec.op.F32_ADD: ctx.stack.add_f32(a + b) continue if opcode == wasmi.spec.op.F32_SUB: ctx.stack.add_f32(a - b) continue if opcode == wasmi.spec.op.F32_MUL: ctx.stack.add_f32(a * b) continue if opcode == wasmi.spec.op.F32_DIV: ctx.stack.add_f32(a / b) continue if opcode == wasmi.spec.op.F32_MIN: ctx.stack.add_f32(min(a, b)) continue if opcode == wasmi.spec.op.F32_MAX: ctx.stack.add_f32(max(a, b)) continue if opcode == wasmi.spec.op.F32_COPYSIGN: ctx.stack.add_f32(math.copysign(a, b)) continue if opcode >= wasmi.spec.op.F64_ABS and opcode <= wasmi.spec.op.F64_SQRT: v = ctx.stack.pop_f64() if opcode == wasmi.spec.op.F64_ABS: ctx.stack.add_f64(abs(v)) continue if opcode == wasmi.spec.op.F64_NEG: ctx.stack.add_f64(-v) continue if opcode == wasmi.spec.op.F64_CEIL: ctx.stack.add_f64(math.ceil(v)) continue if opcode == wasmi.spec.op.F64_FLOOR: ctx.stack.add_f64(math.floor(v)) continue if opcode == wasmi.spec.op.F64_TRUNC: ctx.stack.add_f64(math.trunc(v)) continue if opcode == wasmi.spec.op.F64_NEAREST: ceil = math.ceil(v) if ceil - v >= 0.5: r = ceil else: r = ceil - 1 ctx.stack.add_f64(r) continue if opcode == wasmi.spec.op.F64_SQRT: ctx.stack.add_f64(math.sqrt(v)) continue if opcode >= wasmi.spec.op.F64_ADD and opcode <= wasmi.spec.op.F64_COPYSIGN: b = ctx.stack.pop_f64() a = ctx.stack.pop_f64() if opcode == wasmi.spec.op.F64_ADD: ctx.stack.add_f64(a + b) continue if opcode == wasmi.spec.op.F64_SUB: ctx.stack.add_f64(a - b) continue if opcode == wasmi.spec.op.F64_MUL: ctx.stack.add_f64(a * b) continue if opcode == wasmi.spec.op.F64_DIV: ctx.stack.add_f64(a / b) continue if opcode == wasmi.spec.op.F64_MIN: ctx.stack.add_f64(min(a, b)) continue if opcode == wasmi.spec.op.F64_MAX: ctx.stack.add_f64(max(a, b)) continue if opcode == wasmi.spec.op.F64_COPYSIGN: ctx.stack.add_f64(math.copysign(a, b)) continue if opcode >= wasmi.spec.op.I32_WRAP_I64 and opcode <= wasmi.spec.op.F64_PROMOTE_F32: v = ctx.stack.pop() if opcode == wasmi.spec.op.I32_WRAP_I64: r = wasmi.num.int2i32(v.into_i64()) ctx.stack.add_i32(r) continue if opcode == wasmi.spec.op.I32_TRUNC_SF32: v = v.into_f32() if math.isnan(v): raise wasmi.error.WAException("invalid conversion to integer") if v > 2**31 - 1 or v < -2**32: raise wasmi.error.WAException('integer overflow') ctx.stack.add_i32(int(v)) continue if opcode == wasmi.spec.op.I32_TRUNC_UF32: v = v.into_f32() if math.isnan(v): raise wasmi.error.WAException("invalid conversion to integer") if v > 2 ** 32 - 1 or v < -1: raise wasmi.error.WAException('integer overflow') ctx.stack.add_i32(int(v)) continue if opcode == wasmi.spec.op.I32_TRUNC_SF64: v = v.into_f64() if math.isnan(v): raise wasmi.error.WAException("invalid conversion to integer") if v > 2**31 - 1 or v < -2**31: raise wasmi.error.WAException('integer overflow') ctx.stack.add_i32(int(v)) continue if opcode == wasmi.spec.op.I32_TRUNC_UF64: v = v.into_f64() if math.isnan(v): raise wasmi.error.WAException("invalid conversion to integer") if v > 2**32 - 1 or v < -1: raise wasmi.error.WAException('integer overflow') ctx.stack.add_i32(int(v)) continue if opcode == wasmi.spec.op.I64_EXTEND_SI32: v = v.into_i32() ctx.stack.add_i64(v) continue if opcode == wasmi.spec.op.I64_EXTEND_UI32: v = v.into_u32() ctx.stack.add_i64(v) continue if opcode == wasmi.spec.op.I64_TRUNC_SF32: v = v.into_f32() if math.isnan(v): raise wasmi.error.WAException("invalid conversion to integer") if v > 2**63 - 1 or v < -2**63: raise wasmi.error.WAException('integer overflow') ctx.stack.add_i64(int(v)) continue if opcode == wasmi.spec.op.I64_TRUNC_UF32: v = v.into_f32() if math.isnan(v): raise wasmi.error.WAException("invalid conversion to integer") if v > 2**63 - 1 or v < -1: raise wasmi.error.WAException('integer overflow') ctx.stack.add_i64(int(v)) continue if opcode == wasmi.spec.op.I64_TRUNC_SF64: v = v.into_f64() if math.isnan(v): raise wasmi.error.WAException("invalid conversion to integer") ctx.stack.add_i64(int(v)) continue if opcode == wasmi.spec.op.I64_TRUNC_UF64: v = v.into_f64() if math.isnan(v): raise wasmi.error.WAException("invalid conversion to integer") if v < -1: raise wasmi.error.WAException('integer overflow') ctx.stack.add_i64(int(v)) continue if opcode == wasmi.spec.op.F32_CONVERT_SI32: v = v.into_i32() ctx.stack.add_f32(v) continue if opcode == wasmi.spec.op.F32_CONVERT_UI32: v = v.into_u32() ctx.stack.add_f32(r) continue if opcode == wasmi.spec.op.F32_CONVERT_SI64: v = v.into_i64() ctx.stack.add_f32(v) continue if opcode == wasmi.spec.op.F32_CONVERT_UI64: v = v.into_u64() ctx.stack.add_f32(v) continue if opcode == wasmi.spec.op.F32_DEMOTE_F64: v = v.into_f64() ctx.stack.add_f32(v) continue if opcode == wasmi.spec.op.F64_CONVERT_SI32: v = v.into_i32() ctx.stack.add_f64(v) continue if opcode == wasmi.spec.op.F64_CONVERT_UI32: v = v.into_u32() ctx.stack.add_f64(v) continue if opcode == wasmi.spec.op.F64_CONVERT_SI64: v = v.into_i64() ctx.stack.add_f64(v) continue if opcode == wasmi.spec.op.F64_CONVERT_UI64: v = v.into_u64() ctx.stack.add_f64(v) continue if opcode == wasmi.spec.op.F64_PROMOTE_F32: v = v.into_f32() ctx.stack.add_f64(v) continue if opcode >= wasmi.spec.op.I32_REINTERPRET_F32 and opcode <= wasmi.spec.op.F64_REINTERPRET_I64: if opcode == wasmi.spec.op.I32_REINTERPRET_F32: ctx.stack.add_i32(wasmi.num.f322i32(ctx.stack.pop().into_f32())) continue if opcode == wasmi.spec.op.I64_REINTERPRET_F64: ctx.stack.add_i64(wasmi.num.f642i64(ctx.stack.pop().into_f64())) continue if opcode == wasmi.spec.op.F32_REINTERPRET_I32: ctx.stack.add_f32(wasmi.num.i322f32(ctx.stack.pop().into_i32())) continue if opcode == wasmi.spec.op.F64_REINTERPRET_I64: ctx.stack.add_f64(wasmi.num.i642f64(ctx.stack.pop().into_i64())) continue def exec(self, name: str, args: typing.List): export: wasmi.section.Export = None for e in self.mod.section_export.entries: if e.kind == wasmi.spec.external.FUNCTION and e.name == name: export = e break if not export: raise wasmi.error.WAException(f'function not found') f_idx = export.idx f_sig = self.functions[f_idx].signature ergs = [] for i, valtype in enumerate(f_sig.args): ergs.append(wasmi.stack.Entry(valtype, args[i])) ctx = Ctx(ergs) wasmi.log.println('Exec'.center(80, '-')) return self.exec_step(f_idx, ctx) <file_sep>/wasmi/spec/external.py FUNCTION = 0x00 TABLE = 0x01 MEMORY = 0x02 GLOBAL = 0x03 info = {} info[FUNCTION] = 'function' info[TABLE] = 'table' info[MEMORY] = 'memory' info[GLOBAL] = 'global' <file_sep>/wasmi/spec/valtype.py I32 = 0x7f I64 = 0x7e F32 = 0x7d F64 = 0x7c NIL = 0x40 FUNC = 0x60 FUNCREF = 0x70 info = {} info[I32] = 'i32' info[I64] = 'i64' info[F32] = 'f32' info[F64] = 'f64' info[NIL] = 'nil' info[FUNC] = 'func' info[FUNCREF] = 'funcref' <file_sep>/wasmi/spec/op.py UNREACHABLE = 0x00 NOP = 0x01 BLOCK = 0x02 LOOP = 0x03 IF = 0x04 ELSE = 0x05 END = 0x0b BR = 0x0c BR_IF = 0x0d BR_TABLE = 0x0e RETURN = 0x0f CALL = 0x10 CALL_INDIRECT = 0x11 DROP = 0x1a SELECT = 0x1b GET_LOCAL = 0x20 SET_LOCAL = 0x21 TEE_LOCAL = 0x22 GET_GLOBAL = 0x23 SET_GLOBAL = 0x24 I32_LOAD = 0x28 I64_LOAD = 0x29 F32_LOAD = 0x2a F64_LOAD = 0x2b I32_LOAD8_S = 0x2c I32_LOAD8_U = 0x2d I32_LOAD16_S = 0x2e I32_LOAD16_U = 0x2f I64_LOAD8_S = 0x30 I64_LOAD8_U = 0x31 I64_LOAD16_S = 0x32 I64_LOAD16_U = 0x33 I64_LOAD32_S = 0x34 I64_LOAD32_U = 0x35 I32_STORE = 0x36 I64_STORE = 0x37 F32_STORE = 0x38 F64_STORE = 0x39 I32_STORE8 = 0x3a I32_STORE16 = 0x3b I64_STORE8 = 0x3c I64_STORE16 = 0x3d I64_STORE32 = 0x3e CURRENT_MEMORY = 0x3f GROW_MEMORY = 0x40 I32_CONST = 0x41 I64_CONST = 0x42 F32_CONST = 0x43 F64_CONST = 0x44 I32_EQZ = 0x45 I32_EQ = 0x46 I32_NE = 0x47 I32_LTS = 0x48 I32_LTU = 0x49 I32_GTS = 0x4a I32_GTU = 0x4b I32_LES = 0x4c I32_LEU = 0x4d I32_GES = 0x4e I32_GEU = 0x4f I64_EQZ = 0x50 I64_EQ = 0x51 I64_NE = 0x52 I64_LTS = 0x53 I64_LTU = 0x54 I64_GTS = 0x55 I64_GTU = 0x56 I64_LES = 0x57 I64_LEU = 0x58 I64_GES = 0x59 I64_GEU = 0x5a F32_EQ = 0x5b F32_NE = 0x5c F32_LT = 0x5d F32_GT = 0x5e F32_LE = 0x5f F32_GE = 0x60 F64_EQ = 0x61 F64_NE = 0x62 F64_LT = 0x63 F64_GT = 0x64 F64_LE = 0x65 F64_GE = 0x66 I32_CLZ = 0x67 I32_CTZ = 0x68 I32_POPCNT = 0x69 I32_ADD = 0x6a I32_SUB = 0x6b I32_MUL = 0x6c I32_DIVS = 0x6d I32_DIVU = 0x6e I32_REMS = 0x6f I32_REMU = 0x70 I32_AND = 0x71 I32_OR = 0x72 I32_XOR = 0x73 I32_SHL = 0x74 I32_SHRS = 0x75 I32_SHRU = 0x76 I32_ROTL = 0x77 I32_ROTR = 0x78 I64_CLZ = 0x79 I64_CTZ = 0x7a I64_POPCNT = 0x7b I64_ADD = 0x7c I64_SUB = 0x7d I64_MUL = 0x7e I64_DIVS = 0x7f I64_DIVU = 0x80 I64_REMS = 0x81 I64_REMU = 0x82 I64_AND = 0x83 I64_OR = 0x84 I64_XOR = 0x85 I64_SHL = 0x86 I64_SHRS = 0x87 I64_SHRU = 0x88 I64_ROTL = 0x89 I64_ROTR = 0x8a F32_ABS = 0x8b F32_NEG = 0x8c F32_CEIL = 0x8d F32_FLOOR = 0x8e F32_TRUNC = 0x8f F32_NEAREST = 0x90 F32_SQRT = 0x91 F32_ADD = 0x92 F32_SUB = 0x93 F32_MUL = 0x94 F32_DIV = 0x95 F32_MIN = 0x96 F32_MAX = 0x97 F32_COPYSIGN = 0x98 F64_ABS = 0x99 F64_NEG = 0x9a F64_CEIL = 0x9b F64_FLOOR = 0x9c F64_TRUNC = 0x9d F64_NEAREST = 0x9e F64_SQRT = 0x9f F64_ADD = 0xa0 F64_SUB = 0xa1 F64_MUL = 0xa2 F64_DIV = 0xa3 F64_MIN = 0xa4 F64_MAX = 0xa5 F64_COPYSIGN = 0xa6 I32_WRAP_I64 = 0xa7 I32_TRUNC_SF32 = 0xa8 I32_TRUNC_UF32 = 0xa9 I32_TRUNC_SF64 = 0xaa I32_TRUNC_UF64 = 0xab I64_EXTEND_SI32 = 0xac I64_EXTEND_UI32 = 0xad I64_TRUNC_SF32 = 0xae I64_TRUNC_UF32 = 0xaf I64_TRUNC_SF64 = 0xb0 I64_TRUNC_UF64 = 0xb1 F32_CONVERT_SI32 = 0xb2 F32_CONVERT_UI32 = 0xb3 F32_CONVERT_SI64 = 0xb4 F32_CONVERT_UI64 = 0xb5 F32_DEMOTE_F64 = 0xb6 F64_CONVERT_SI32 = 0xb7 F64_CONVERT_UI32 = 0xb8 F64_CONVERT_SI64 = 0xb9 F64_CONVERT_UI64 = 0xba F64_PROMOTE_F32 = 0xbb I32_REINTERPRET_F32 = 0xbc I64_REINTERPRET_F64 = 0xbd F32_REINTERPRET_I32 = 0xbe F64_REINTERPRET_I64 = 0xbf info = {} info[UNREACHABLE] = ('unreachable', [], 0) info[NOP] = ('nop', [], 0) info[BLOCK] = ('block', ['leb_7'], 0) info[LOOP] = ('loop', ['leb_7'], 0) info[IF] = ('if', ['leb_7'], 0) info[ELSE] = ('else', [], 0) info[END] = ('end', [], 0) info[BR] = ('br', ['leb_32'], 0) info[BR_IF] = ('br_if', ['leb_32'], 0) info[BR_TABLE] = ('br_table', ['leb_32xleb_32', 'leb_32'], 0) info[RETURN] = ('return', [], 0) info[CALL] = ('call', ['leb_32'], 0) info[CALL_INDIRECT] = ('call_indirect', ['leb_32', 'leb_1'], 0) info[DROP] = ('drop', [], 0) info[SELECT] = ('select', [], 0) info[GET_LOCAL] = ('local.get', ['leb_32'], 0) info[SET_LOCAL] = ('local.set', ['leb_32'], 0) info[TEE_LOCAL] = ('local.tee', ['leb_32'], 0) info[GET_GLOBAL] = ('global.get', ['leb_32'], 0) info[SET_GLOBAL] = ('global.set', ['leb_32'], 0) info[I32_LOAD] = ('i32.load', ['leb_32', 'leb_32'], 4) info[I64_LOAD] = ('i64.load', ['leb_32', 'leb_32'], 8) info[F32_LOAD] = ('f32.load', ['leb_32', 'leb_32'], 4) info[F64_LOAD] = ('f64.load', ['leb_32', 'leb_32'], 8) info[I32_LOAD8_S] = ('i32.load8_s', ['leb_32', 'leb_32'], 1) info[I32_LOAD8_U] = ('i32.load8_u', ['leb_32', 'leb_32'], 1) info[I32_LOAD16_S] = ('i32.load16_s', ['leb_32', 'leb_32'], 2) info[I32_LOAD16_U] = ('i32.load16_u', ['leb_32', 'leb_32'], 2) info[I64_LOAD8_S] = ('i64.load8_s', ['leb_32', 'leb_32'], 1) info[I64_LOAD8_U] = ('i64.load8_u', ['leb_32', 'leb_32'], 1) info[I64_LOAD16_S] = ('i64.load16_s', ['leb_32', 'leb_32'], 2) info[I64_LOAD16_U] = ('i64.load16_u', ['leb_32', 'leb_32'], 2) info[I64_LOAD32_S] = ('i64.load32_s', ['leb_32', 'leb_32'], 4) info[I64_LOAD32_U] = ('i64.load32_u', ['leb_32', 'leb_32'], 4) info[I32_STORE] = ('i32.store', ['leb_32', 'leb_32'], 4) info[I64_STORE] = ('i64.store', ['leb_32', 'leb_32'], 8) info[F32_STORE] = ('f32.store', ['leb_32', 'leb_32'], 4) info[F64_STORE] = ('f64.store', ['leb_32', 'leb_32'], 8) info[I32_STORE8] = ('i32.store8', ['leb_32', 'leb_32'], 1) info[I32_STORE16] = ('i32.store16', ['leb_32', 'leb_32'], 2) info[I64_STORE8] = ('i64.store8', ['leb_32', 'leb_32'], 1) info[I64_STORE16] = ('i64.store16', ['leb_32', 'leb_32'], 2) info[I64_STORE32] = ('i64.store32', ['leb_32', 'leb_32'], 4) info[CURRENT_MEMORY] = ('memory.size', ['leb_1'], 0) info[GROW_MEMORY] = ('memory.grow', ['leb_1'], 1) info[I32_CONST] = ('i32.const', ['leb_32'], 2) info[I64_CONST] = ('i64.const', ['leb_64'], 1) info[F32_CONST] = ('f32.const', ['bit_32'], 2) info[F64_CONST] = ('f64.const', ['bit_64'], 4) info[I32_EQZ] = ('i32.eqz', [], 0) info[I32_EQ] = ('i32.eq', [], 0) info[I32_NE] = ('i32.ne', [], 0) info[I32_LTS] = ('i32.lt_s', [], 0) info[I32_LTU] = ('i32.lt_u', [], 0) info[I32_GTS] = ('i32.gt_s', [], 0) info[I32_GTU] = ('i32.gt_u', [], 0) info[I32_LES] = ('i32.le_s', [], 0) info[I32_LEU] = ('i32.le_u', [], 0) info[I32_GES] = ('i32.ge_s', [], 0) info[I32_GEU] = ('i32.ge_u', [], 0) info[I64_EQZ] = ('i64.eqz', [], 0) info[I64_EQ] = ('i64.eq', [], 0) info[I64_NE] = ('i64.ne', [], 0) info[I64_LTS] = ('i64.lt_s', [], 0) info[I64_LTU] = ('i64.lt_u', [], 0) info[I64_GTS] = ('i64.gt_s', [], 0) info[I64_GTU] = ('i64.gt_u', [], 0) info[I64_LES] = ('i64.le_s', [], 0) info[I64_LEU] = ('i64.le_u', [], 0) info[I64_GES] = ('i64.ge_s', [], 0) info[I64_GEU] = ('i64.ge_u', [], 0) info[F32_EQ] = ('f32.eq', [], 0) info[F32_NE] = ('f32.ne', [], 0) info[F32_LT] = ('f32.lt', [], 0) info[F32_GT] = ('f32.gt', [], 0) info[F32_LE] = ('f32.le', [], 0) info[F32_GE] = ('f32.ge', [], 0) info[F64_EQ] = ('f64.eq', [], 0) info[F64_NE] = ('f64.ne', [], 0) info[F64_LT] = ('f64.lt', [], 0) info[F64_GT] = ('f64.gt', [], 0) info[F64_LE] = ('f64.le', [], 0) info[F64_GE] = ('f64.ge', [], 0) info[I32_CLZ] = ('i32.clz', [], 0) info[I32_CTZ] = ('i32.ctz', [], 0) info[I32_POPCNT] = ('i32.popcnt', [], 0) info[I32_ADD] = ('i32.add', [], 0) info[I32_SUB] = ('i32.sub', [], 0) info[I32_MUL] = ('i32.mul', [], 0) info[I32_DIVS] = ('i32.div_s', [], 0) info[I32_DIVU] = ('i32.div_u', [], 0) info[I32_REMS] = ('i32.rem_s', [], 0) info[I32_REMU] = ('i32.rem_u', [], 0) info[I32_AND] = ('i32.and', [], 0) info[I32_OR] = ('i32.or', [], 0) info[I32_XOR] = ('i32.xor', [], 0) info[I32_SHL] = ('i32.shl', [], 0) info[I32_SHRS] = ('i32.shr_s', [], 0) info[I32_SHRU] = ('i32.shr_u', [], 0) info[I32_ROTL] = ('i32.rotl', [], 0) info[I32_ROTR] = ('i32.rotr', [], 0) info[I64_CLZ] = ('i64.clz', [], 0) info[I64_CTZ] = ('i64.ctz', [], 0) info[I64_POPCNT] = ('i64.popcnt', [], 0) info[I64_ADD] = ('i64.add', [], 0) info[I64_SUB] = ('i64.sub', [], 0) info[I64_MUL] = ('i64.mul', [], 0) info[I64_DIVS] = ('i64.div_s', [], 0) info[I64_DIVU] = ('i64.div_u', [], 0) info[I64_REMS] = ('i64.rem_s', [], 0) info[I64_REMU] = ('i64.rem_u', [], 0) info[I64_AND] = ('i64.and', [], 0) info[I64_OR] = ('i64.or', [], 0) info[I64_XOR] = ('i64.xor', [], 0) info[I64_SHL] = ('i64.shl', [], 0) info[I64_SHRS] = ('i64.shr_s', [], 0) info[I64_SHRU] = ('i64.shr_u', [], 0) info[I64_ROTL] = ('i64.rotl', [], 0) info[I64_ROTR] = ('i64.rotr', [], 0) info[F32_ABS] = ('f32.abs', [], 0) info[F32_NEG] = ('f32.neg', [], 0) info[F32_CEIL] = ('f32.ceil', [], 0) info[F32_FLOOR] = ('f32.floor', [], 0) info[F32_TRUNC] = ('f32.trunc', [], 0) info[F32_NEAREST] = ('f32.nearest', [], 0) info[F32_SQRT] = ('f32.sqrt', [], 0) info[F32_ADD] = ('f32.add', [], 0) info[F32_SUB] = ('f32.sub', [], 0) info[F32_MUL] = ('f32.mul', [], 0) info[F32_DIV] = ('f32.div', [], 0) info[F32_MIN] = ('f32.min', [], 0) info[F32_MAX] = ('f32.max', [], 0) info[F32_COPYSIGN] = ('f32.copysign', [], 0) info[F64_ABS] = ('f64.abs', [], 0) info[F64_NEG] = ('f64.neg', [], 0) info[F64_CEIL] = ('f64.ceil', [], 0) info[F64_FLOOR] = ('f64.floor', [], 0) info[F64_TRUNC] = ('f64.trunc', [], 0) info[F64_NEAREST] = ('f64.nearest', [], 0) info[F64_SQRT] = ('f64.sqrt', [], 0) info[F64_ADD] = ('f64.add', [], 0) info[F64_SUB] = ('f64.sub', [], 0) info[F64_MUL] = ('f64.mul', [], 0) info[F64_DIV] = ('f64.div', [], 0) info[F64_MIN] = ('f64.min', [], 0) info[F64_MAX] = ('f64.max', [], 0) info[F64_COPYSIGN] = ('f64.copysign', [], 0) info[I32_WRAP_I64] = ('i32.wrap_i64', [], 0) info[I32_TRUNC_SF32] = ('i32.trunc_f32_s', [], 0) info[I32_TRUNC_UF32] = ('i32.trunc_f32_u', [], 0) info[I32_TRUNC_SF64] = ('i32.trunc_f64_s', [], 0) info[I32_TRUNC_UF64] = ('i32.trunc_f64_u', [], 0) info[I64_EXTEND_SI32] = ('i64.extend_i32_s', [], 0) info[I64_EXTEND_UI32] = ('i64.extend_i32_u', [], 0) info[I64_TRUNC_SF32] = ('i64.trunc_f32_s', [], 0) info[I64_TRUNC_UF32] = ('i64.trunc_f32_u', [], 0) info[I64_TRUNC_SF64] = ('i64.trunc_f64_s', [], 0) info[I64_TRUNC_UF64] = ('i64.trunc_f64_u', [], 0) info[F32_CONVERT_SI32] = ('f32.convert_i32_s', [], 0) info[F32_CONVERT_UI32] = ('f32.convert_i32_u', [], 0) info[F32_CONVERT_SI64] = ('f32.convert_i64_s', [], 0) info[F32_CONVERT_UI64] = ('f32.convert_i64_u', [], 0) info[F32_DEMOTE_F64] = ('f32.demote_f64', [], 0) info[F64_CONVERT_SI32] = ('f64.convert_i32_s', [], 0) info[F64_CONVERT_UI32] = ('f64.convert_i32_u', [], 0) info[F64_CONVERT_SI64] = ('f64.convert_i64_s', [], 0) info[F64_CONVERT_UI64] = ('f64.convert_i64_u', [], 0) info[F64_PROMOTE_F32] = ('f64.promote_f32', [], 0) info[I32_REINTERPRET_F32] = ('i32.reinterpret_f32', [], 0) info[I64_REINTERPRET_F64] = ('i64.reinterpret.f64', [], 0) info[F32_REINTERPRET_I32] = ('f32.reinterpret.i32', [], 0) info[F64_REINTERPRET_I64] = ('f64.reinterpret.i64', [], 0) <file_sep>/README.md # py-wasmi: A WebAssembly interpreter written in pure Python. [![Build Status](https://travis-ci.org/mohanson/py-wasmi.svg?branch=master)](https://travis-ci.org/mohanson/py-wasmi) A WebAssembly interpreter written in pure Python. WASM version: [WebAssembly Core Specification W3C Working Draft, 4 September 2018](https://www.w3.org/TR/2018/WD-wasm-core-1-20180904/) Get some helps from [warpy](https://github.com/kanaka/warpy) and [wagon](https://github.com/go-interpreter/wagon). Thanks open source authors. # Requirements - py-wasmi has been tested and is known to run on Linux/Ubuntu, macOS and Windows(10). It will likely work fine on most OS. - No third party dependences. - Python3.6 or newer. # Installition ```sh $ git clone https://github.com/mohanson/py-wasmi && python3 setup.py install # or $ pip3 install wasmi # run tests. py-wasmi has 100% passed all cases from official spec python3 tests/test_spec.py ``` # Example A few small examples have been provided in the `examples` directory, you can try these examples quickly just: ```sh $ cd py-wasmi $ python3 examples add 40 2 => (i32.add) 42 $ python3 examples fib 10 => (10th of fibonacci) 55 ``` With detailed, we use `./examples/fib.wasm` as an example, write some c code belows: ```c int fib(int n) { if (n <= 1) { return n; } return fib(n - 1) + fib(n - 2); } ``` Generate `fib.wasm` by [WasmFiddle](https://wasdk.github.io/WasmFiddle/), and then: ```py import wasmi path = './examples/fib.wasm' mod = wasmi.Module.open(path) vm = wasmi.Vm(mod) r = vm.exec('fib', [10]) print(r) # 55 ``` # FAQ Q: How is the py-wasmi performance? <br> A: Fine. But if you have strict requirements on speed, please use others such as `wasm-interp`. # License [WTFPL](https://choosealicense.com/licenses/wtfpl/) <file_sep>/setup.py import setuptools setuptools.setup( name='wasmi', version='0.2.2', url='https://github.com/mohanson/py-wasmi', license='WTFPL', author='mohanson', author_email='<EMAIL>', description='WebAssembly Interpreter by pure Python', packages=['wasmi'], ) <file_sep>/wasmi/common.py import io import math import wasmi.num as num def read_f32(reader): if isinstance(reader, (bytes, bytearray)): reader = io.BytesIO(reader) return num.LittleEndian.f32(reader.read(4)) def read_f64(reader): if isinstance(reader, (bytes, bytearray)): reader = io.BytesIO(reader) return num.LittleEndian.f64(reader.read(8)) def read_leb(reader, maxbits=32, signed=False): if isinstance(reader, (bytes, bytearray)): reader = io.BytesIO(reader) r = 0 s = 0 b = 0 i = 0 a = bytearray() while True: byte = ord(reader.read(1)) i += 1 a.append(byte) r |= ((byte & 0x7f) << s) s += 7 if (byte & 0x80) == 0: break b += 1 assert b <= math.ceil(maxbits / 7.0) if signed and (s < maxbits) and (byte & 0x40): r |= - (1 << s) return (i, r, a) def rotl_u32(x: int, k: int): x = num.int2u32(x) k = num.int2u32(k) n = 32 s = k & (n - 1) return x << s | x >> (n - s) def rotl_u64(x: int, k: int): x = num.int2u64(x) k = num.int2u64(k) n = 64 s = k & (n - 1) return x << s | x >> (n - s) def rotr_u32(x: int, k: int): return rotl_u32(x, -k) def rotr_u64(x: int, k: int): return rotl_u64(x, -k) def fmth(n: int, l: int): a = hex(n) return a[2:].rjust(l, '0') def idiv_s(a, b): return a // b if a * b > 0 else (a + (-a % b)) // b def irem_s(a, b): return a % b if a * b > 0 else -(-a % b) <file_sep>/tests/test_spec.py import json import math import os import wasmi def parse_vype(s: str): t, v = s.split(':') if t in ['i32', 'i64']: if v.startswith('0x'): return int(v, 16) return int(v) if t in ['f32', 'f64']: if v.startswith('0x'): return float.fromhex(v) return float(v) raise NotImplementedError def test_spec(): with open('./tests/spec/modules.json', 'r') as f: data = json.load(f) for case in data: file = case['file'] mod = wasmi.Module.open(os.path.join('./tests/spec/', file)) vm = wasmi.Vm(mod) for test in case['tests']: function = test['function'] args = [parse_vype(e) for e in test['args']] if 'trap' in test: trap = test['trap'] try: vm.exec(function, args) except wasmi.error.WAException as e: print(f'{file} {function} {args}: {trap} == {e.message}', end='') assert e.message == trap.split(':')[1].strip() print(' (ok)') else: assert False continue rets = None if test.get('return', False): rets = parse_vype(test['return']) r = vm.exec(function, args) print(f'{file} {function} {args}: {rets} == {r}', end='') if isinstance(r, float): assert abs(r - rets) < 0.005 or (math.isnan(r) and math.isnan(rets)) print(' (ok)') continue assert r == rets print(' (ok)') test_spec()
1b8f752aebfd3b1968f8559b3b0858ee6f192610
[ "Markdown", "Python" ]
13
Python
thijstriemstra/py-wasmi
04ffd6eb69fa8f113d32d1c80a0a3ed237697645
ef23fc2605feaa073e470d6f9e7cf6ec7f5f089c
refs/heads/master
<file_sep> <?php namespace SfWebApp\FrontOfficeBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class SfWebAppFrontOfficeBundle extends Bundle { public function getParent() { return 'FOSUserBundle'; } }
cc3b56fdee5ca50ecfaaaee7c78c9afa8b443bb4
[ "PHP" ]
1
PHP
daniel-dahan/testadmin
b92c4ca5cfe54986ca35f514b8c29791b518326b
27c9d891eaec4966efd5b1d92521a48708aa8a85
refs/heads/master
<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Level extends Model { protected $visible = ['level_id', 'floor_xp', 'ceiling_xp']; protected $hidden = [ 'created_at', 'updated_at' ]; protected $fillable = [ 'level_id', 'floor_xp', 'ceiling_xp' ]; public function course(){ return $this->belongsTo('App\Course'); } } <file_sep><?php use Illuminate\Database\Seeder; use Carbon\Carbon; class StudentsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // $studentsData = [ // [ // 'name' => 'testuser01', // 'image' => 'image.jpg', // 'password' => '<PASSWORD>', // 'overall_xp' => '1', // 'level' => '1', // 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), // 'updated_at' => Carbon::now()->format('Y-m-d H:i:s') // ], // [ // 'name' => 'testuser02', // 'image' => 'image.jpg', // 'password' => '<PASSWORD>', // 'overall_xp' => '1', // 'level' => '1', // 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), // 'updated_at' => Carbon::now()->format('Y-m-d H:i:s') // ] // ]; // // DB::table('students')->insert($studentsData); } } <file_sep><?php namespace App\Http\Controllers; use App\Modules\ActivationService; use Auth; use App\User; use Illuminate\Http\Request; use JWTAuth; use Tymon\JWTAuth\Exceptions\JWTException; class AuthController extends Controller { public function __construct(ActivationService $activationService) { $this->middleware('inactive_user_auth', ['only' => 'signin']); $this->middleware('jwt.auth', [ 'only' => [ ] ]); $this->activationService = $activationService; } public function store(Request $request) { } public function registration(Request $request) { $password = $request->input('password'); $email = $request->input('email'); $image = $request->input('image'); $title = $request->input('title'); $name = $request->input('name'); $position = $request->input('position'); $id_card = $request->input('id_card'); $phone = $request->input('phone'); $address = $request->input('address'); $teaching_level = $request->input('teaching_level'); $institution = $request->input('institution'); $province = $request->input('province'); $fileName = $name . date('-Ymd-His-') . ".png"; $role = "teacher"; $decodedImg = $this->base64_to_jpeg($image, $fileName, $role); $user = new User([ 'password' => <PASSWORD>($<PASSWORD>), 'email' => $email, 'role' => 'teacher' ]); $user->save(); $user = User::where('email', $email)->first(); $user->teacher()->create([ 'image' => $decodedImg, 'title' => $title, 'name' => $name, 'position' => $position, 'id_card' => $id_card, 'phone' => $phone, 'address' => $address, 'teaching_level' => $teaching_level, 'institution' => $institution, 'province' => $province ]); $email = User::where('email', $email)->get()->toArray(); $this->activationService->sendActivationMail($email); return response()->json(['status'=>'success'], 200); } protected $redirectURL = "http://localhost:3000/#/login"; public function activateUser($token) { if ($user = $this->activationService->activateUser($token)) { return redirect($this->redirectURL); } return response()->json(['status'=>'inactive', 'errorcode'=>'62', 'errormessage'=>'Invalid confirmation link']); } public function signin(Request $request) { $credentials = $request->only('email', 'password'); try { // verify the credentials and create a token for the user if (! $token = JWTAuth::attempt($credentials)) { // return response()->json(['error' => 'invalid_credentials'], 401); return response()->json([ 'status'=>'failed', 'errorcode' => '12', 'errormessage' => 'Your email or password does not match!']); } } catch (\Exception $e) { // something went wrong return response()->json([ 'status' => 'failed', 'errorcode' => '12', 'errormessage' => 'Could not create token!' ]); } // if no errors are encountered we can return a JWT return response()->json( [ 'status' => 'success', 'data' => [ 'token' => $token, 'id' => Auth::user()->id, 'name' => Auth::user()->name, 'email'=> Auth::user()->email, 'role' => Auth::user()->role ] ], 200); } public function base64_to_jpeg($base64_string, $output_file, $role) { switch ($role){ case "teacher" : $destination = public_path() . '/teachers/logo/' . $output_file; break; } $ifp = fopen($destination, "wb"); $data = explode(',', $base64_string); fwrite($ifp, base64_decode($data[1])); fclose($ifp); return $output_file; } } <file_sep><?php namespace App\Http\Controllers; use App\Course; use App\Modules\ActivationService; use App\User; use App\Badge; use App\Level; use App\Teacher; use App\Student; use Illuminate\Http\Request; use Illuminate\Support\Facades\File; use JWTAuth; use Auth; use DB; class CourseController extends Controller { public function __construct(ActivationService $activationService) { $this->activationService = $activationService; $this->middleware('jwt.auth', [ 'only' => [ 'createCourse', 'getAllCourse', 'getCourseById', 'getCourseByStatus', 'editCourse', 'settingCourse', 'updateStudentsOfCourse', 'updateStatusCourse', 'getBadgeOfCourse', 'createBadge', 'editBadge', 'deleteBadge', 'getHighScoreOfCourse' ] ]); } public function createCourse(Request $request) { $course = new Course([ 'name' => $request->input('name'), 'description' => $request->input('description'), 'start_xp' => $request->input('start_xp'), 'leader_board' => $request->input('leader_board') ]); $teacher = Auth::user()->teacher()->get()->toArray(); $teacher_course = Teacher::find($teacher[0]['id'])->first(); $teacher_course->courses()->save($course); // $courseLevels = array(); if ($request->has('levels')) { foreach ($request->input('levels') as $level) { $levelObject = new Level([ 'level_id' => $level['level_id'], 'floor_xp' => $level['floor_xp'], 'ceiling_xp' => $level['ceiling_xp'], ]); array_push($courseLevels, $levelObject); } $course->levels()->saveMany($courseLevels); } $courseStudents = array(); if ($request->has('students')) { foreach ($request->input('students') as $student) { $image = $student['image']; $fileName = $student['name'] . date('-Ymd-His-') . ".png"; $destination = '/students/logo/'; $decodedImg = $this->base64_to_jpeg($image, $fileName, $destination); $password_gen = $this->generateStringRandom(10); $user = new User([ 'password' => <PASSWORD>($<PASSWORD>), 'email' => $this->generateStringRandom(10), 'role' => 'student', 'activated' => 1 ]); $user->save(); $studentObject = new Student([ 'student_id' => $student['student_id'], 'name' => $student['name'], 'image' => $decodedImg, 'username' => $user->email, 'password' => <PASSWORD>, 'overall_xp' => $student['overall_xp'], 'level' => $student['level'] ]); $studentObject->user()->associate($user); $studentObject->course()->associate($course); $studentObject->save(); } // $course->students()->saveMany($courseStudents); } return response()->json( [ 'status' => 'success', 'data' => [ 'course' => $course ] ], 200); } public function getAllCourse(Request $request) { $teacher = Auth::user()->teacher()->first(); $courses = Course::where('teacher_id','=',$teacher->id)->get(); return response()->json(['data' => $courses], 200); } public function getCourseByStatus($id) { $courses = Auth::user()->courses() ->where('status', $id) ->get(); return response()->json([ 'status' => 'success', 'data' => $courses ], 200); } public function getCourseById($id) { $course = Course::find($id); $students = Student::where('course_id', '=', $id)->get(); $levels = Level::where('course_id', '=', $id)->get(); $badges = Badge::where('course_id', '=', $id)->get(); return response()->json( [ 'status' => 'success', 'data' => [ 'course' => $course, 'students' => $students, 'levels' => $levels, 'badges' => $badges ] ], 200); } public function editCourse(Request $request) { $course_id = $request->input('course_id'); $name = $request->input('name'); $description = $request->input('description'); $course = Course::find($course_id); $course->name = $name; $course->description = $description; $course->save(); return response()->json( [ 'status' => 'success', 'data' => [ 'course' => $course ] ], 200); } public function settingCourse(Request $request) { $course_id = $request->input('course_id'); $start_xp = $request->input('start_xp'); $leader_board = $request->input('leader_board'); $students_level = $request->input('students_level'); $course = Course::find($course_id); $course->start_xp = $start_xp; $course->leader_board = $leader_board; $course->save(); Level::where('course_id', '=', $course_id)->delete(); $courseLevels = array(); if ($request->has('levels')) { foreach ($request->input('levels') as $level) { $levelObject = new Level([ 'level_id' => $level['level_id'], 'floor_xp' => $level['floor_xp'], 'ceiling_xp' => $level['ceiling_xp'], ]); array_push($courseLevels, $levelObject); } $course->levels()->saveMany($courseLevels); } $levels = Level::where('course_id', '=', $course_id)->get(); $students = Student::where('course_id', '=', $course_id)->get(); //$overall_xp = $request->input('overall_xp'); foreach ($students as $student) { foreach ($levels as $level) { if (($student['$overall_xp'] >= $level->floor_xp) && ($student['$overall_xp'] <= $level->ceiling_xp)) { $student_level = $level->level_id; Student::find($student['id'])->update(array('level' => $student_level)); }else{ $student_level = $level->level_id; Student::find($student['id'])->update(array('level' => $student_level)); } } } // ->update(array('level' => $students_level)); return response()->json( [ 'status' => 'success', 'data' => [ 'course' => $course ] ], 200); } public function updateStudentsOfCourse(Request $request) { $course_id = $request->input('course_id'); $course = Course::find($course_id); $start_xp = $course->start_xp; $levels = Level::where('course_id', '=', $course_id)->get(); foreach ($levels as $level) { if (($start_xp >= $level->floor_xp) && ($start_xp <= $level->ceiling_xp)) { $student_level = $level->level_id; } } $courseStudents = array(); if ($request->has('students')) { foreach ($request->input('students') as $student) { $user = new User([ 'password' => $this->generateStringRandom(10), 'email' => $this->generateStringRandom(10), 'role' => 'student' ]); $user->save(); $image = $student['image']; $fileName = $student['name'] . date('-Ymd-His-') . ".png"; $destination = '/students/logo/'; $decodedImg = $this->base64_to_jpeg($image, $fileName, $destination); $studentObject = new Student([ 'student_id' => $student['student_id'], 'name' => $student['name'], 'image' => $decodedImg, 'username' => $user->email, 'password' => $<PASSWORD>, 'overall_xp' => $start_xp, 'level' => $student_level ]); $studentObject->user()->associate($user); $studentObject->course()->associate($course); $studentObject->save(); // array_push($courseStudents, $studentObject); } // $course->students()->saveMany($courseStudents); } return response()->json( [ 'status' => 'success', 'data' => [ 'course' => $course ] ], 200); } public function updateStatusCourse(Request $request) { $course_id = $request->input('course_id'); $status_id = $request->input('status_id'); $course = Course::find($course_id); $course->status = $status_id; $course->save(); return response()->json( [ 'status' => 'success', 'data' => [ 'course' => $course ] ], 200); } public function getBadgeOfCourse($id) { $course = Course::find($id); $badge = $course->badges()->get(); return response()->json( [ 'status' => 'success', 'data' => [ 'course' => $course, 'badge' => $badge ] ], 200); } public function createBadge(Request $request) { $course_id = $request->input('course_id'); $course = Course::find($course_id); $image = $request->input('image'); $fileName = $request->input('name') . date('-Ymd-His-') . ".png"; $destination = '/students/badges/'; $decodedImg = $this->base64_to_jpeg($image, $fileName, $destination); $badge = new Badge([ 'name' => $request->input('name'), 'image' => $decodedImg, 'xp' => $request->input('xp') ]); $course->badges()->save($badge); return response()->json( [ 'status' => 'success', 'data' => [ 'badge' => $badge ] ], 200); } public function editBadge(Request $request) { $id = $request->input('id'); $image = $request->input('image'); if (preg_match("~data:image/[a-zA-Z]*;base64,~", $image)) { $fileName = $request->input('name') . date('-Ymd-His-') . ".png"; $destination = '/students/badges/'; $decodedImg = $this->base64_to_jpeg($image, $fileName, $destination); $old_badge = Badge::where('id', '=', $id)->first(); $old_image = $old_badge->image; $file = public_path() . $destination . $old_image; File::Delete($file); $badge = Badge::where('id', '=', $id)->update(array( 'name' => $request->input('name'), 'image' => $decodedImg, 'xp' => $request->input('xp'))); } else { $badge = Badge::where('id', '=', $id)->update(array( 'name' => $request->input('name'), 'image' => $image, 'xp' => $request->input('xp'))); } return response()->json( [ 'status' => 'success', 'data' => [ 'badge' => $badge ] ], 200); } public function deleteBadge($id) { $destination = '/students/badges/'; $old_badge = Badge::where('id', '=', $id)->first(); $old_image = $old_badge->image; $file = public_path() . $destination . $old_image; File::Delete($file); $result = $old_badge->delete(); return response()->json( [ 'status' => 'success', 'data' => [ 'result deleted' => $result ] ], 200); } public function getHighScoreOfCourse($id) { $course = Course::find($id); $leader_board = $course->leader_board; $students = $course->students() ->orderBy('overall_xp', 'desc') ->limit($leader_board)->get(); return response()->json( [ 'status' => 'success', 'data' => [ 'course' => $course->id, 'students' => $students ] ], 200); } public function base64_to_jpeg($base64_string, $output_file, $destination) { $destination = public_path() . $destination . $output_file; $ifp = fopen($destination, "wb"); $data = explode(',', $base64_string); fwrite($ifp, base64_decode($data[1])); fclose($ifp); return $output_file; } public function generateStringRandom($number) { return str_random($number); } }<file_sep><?php header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE'); header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization, X-CSRF-Token, X-XSRF-Token'); Route::group(['prefix' => 'api/v1'], function(){ Route::get('activation/{token}', 'AuthController@activateUser') ->name('user.activate'); //Permission Required Route::get('course', 'CourseController@getAllCourse'); Route::get('courses/status/{id}','CourseController@getCourseByStatus'); Route::get('course/{id}', 'CourseController@getCourseById'); Route::post('course/create', 'CourseController@createCourse'); Route::post('course/add/students','CourseController@updateStudentsOfCourse'); Route::put('course/status','CourseController@updateStatusCourse'); Route::put('course/edit', 'CourseController@editCourse'); Route::post('course/setting', 'CourseController@settingCourse'); Route::post('course/create/badge', 'CourseController@createBadge'); Route::put('course/edit/badge', 'CourseController@editBadge'); Route::get('course/{id}/badge', 'CourseController@getBadgeOfCourse'); Route::delete('course/delete/badge/{id}', 'CourseController@deleteBadge'); Route::get('course/highscore/{id}','CourseController@getHighScoreOfCourse'); //Student Api //Student Route::get('student/{id}','StudentController@getStudentProfile'); Route::put('student/edit', 'StudentController@editProfile'); //Teacher Route::get('student/{id}/badge','StudentController@getBadgeOfStudent'); Route::post('student/delete/badge','StudentController@deleteBadgeOfStudent'); Route::put('student/edit/profile', 'StudentController@editProfilebyTeacher'); Route::post('students/update/score', 'StudentController@updateScoreStudent'); Route::post('students/update/scoreandbadge', 'StudentController@updateScoreAndBadgeStudent'); Route::post('students/delete', 'StudentController@deleteStudentOfCourse'); Route::get('teacher',['uses' => 'TeacherController@index']); Route::put('teacher/edit/profile', 'TeacherController@editProfileOfUser'); Route::delete('teacher/delete/{id}', 'TeacherController@deleteUser'); //Post Api Route::post('post/create', 'PostController@createPost'); Route::post('post/edit', 'PostController@editPost'); Route::post('post/delete', 'PostController@deletePost'); Route::post('post/comment', 'PostController@commentPost'); Route::post('post/replycomment', 'PostController@replyComment'); Route::get('post/course/{id}', 'PostController@getPost'); Route::post('post/comment/edit','PostController@editComment'); Route::post('post/comment/delete','PostController@deleteComment'); Route::post('post/replycomment/delete','PostController@deleteReplyComment'); Route::post('post/replycomment/edit','PostController@editReplyComment'); //Authen Api Route::post('user/registration',[ 'uses' => 'AuthController@registration' ]); Route::post('user/signin',[ 'uses' => 'AuthController@signin' ]); Route::post('student/signin','AuthController@studentsignin'); //Excel Route::get('import',['as' => 'import','uses'=>'ExcelController@importExport']); Route::post('import',['as' => 'import','uses'=>'ExcelController@importExcel']); Route::get('downloadExcel/{id}', 'ExcelController@downloadExcel'); //Password Controller Route::get('password/reset/{token?}', 'PasswordController@showResetForm'); // Route::post('password/reset/forgot', 'PasswordController@resetForgotScenario'); Route::post('password/reset', 'PasswordController@reset'); Route::post('password/email', 'PasswordController@sendResetLinkEmail'); });<file_sep><?php use Illuminate\Database\Seeder; class BadgesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $badgesData = [ [ 'course_id' => 1, 'name' => 'badge_example', 'image' => '/students/badges/badge_example.png', 'xp' => 1 ] ]; DB::table('badges')->insert($badgesData); } } <file_sep><?php namespace App\Http\Controllers; use App\Teacher; use App\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\File; use JWTAuth; use Auth; use DB; class TeacherController extends Controller { public function __construct() { $this->middleware('jwt.auth', [ 'only' => [ 'index', 'editProfileOfUser', 'deleteUser' ] ]); $this->middleware('teacher'); } public function index() { $teacher = Teacher::where('user_id', '=', Auth::user()->id)->first(); return response()->json([ 'status' => 'success', 'data' => [ 'teacher_profile' => [ [ 'id' => $teacher->id, 'email' => Auth::user()->email, 'image' => $teacher->image, 'title' => $teacher->title, 'address' => $teacher->address, 'name' => $teacher->name, 'position' => $teacher->position, 'id_card' => $teacher->id_card, 'phone' => $teacher->phone, 'institution' => $teacher->institution, 'province' => $teacher->province, 'teaching_level' => $teacher->teaching_level ], ], ] ], 200); } public function editProfileOfUser(Request $request) { $id = $request->input('id'); $user = Teacher::where('id', '=', $id)->first(); $image = $request->input('image'); $user->title = $request->input('title'); $user->name = $request->input('name'); $user->position = $request->input('position'); $user->id_card = $request->input('id_card'); $user->phone = $request->input('phone'); $user->address = $request->input('address'); $user->teaching_level = $request->input('teaching_level'); $user->institution = $request->input('institution'); $user->province = $request->input('province'); if(preg_match("~data:image/[a-zA-Z]*;base64,~", $image)){ $destination = '/teachers/logo/'; $old_image = $user->image; $file = public_path() . $destination . $old_image; $old_image_deleted = File::Delete($file); $fileName = $user->name . date('-Ymd-His-') . ".png"; $decodedImg = $this->base64_to_jpeg($image, $fileName, $destination); $user->image = $decodedImg; }else{ $user->image = $image; } $user->save(); return response()->json( [ 'status' => 'success', 'data' => [ 'user' => $user ] ], 200); } public function deleteUser($id) { $user = User::find($id)->first(); $destination = '/teachers/logo/'; $old_image = $user->image; $file = public_path() . $destination . $old_image; File::Delete($file); $user->delete(); return response()->json( [ 'status' => 'success', 'user deleted' => $user ], 200); } public function base64_to_jpeg($base64_string, $output_file, $destination) { $destination = public_path() . $destination . $output_file; $ifp = fopen($destination, "wb"); $data = explode(',', $base64_string); fwrite($ifp, base64_decode($data[1])); fclose($ifp); return $output_file; } } <file_sep><?php use Illuminate\Database\Seeder; use Carbon\Carbon; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $usersData = [ [ 'name' => 'Nattaya', 'password' => bcrypt('<PASSWORD>'), 'email' => '<EMAIL>', 'image' => 'http://fakeimg.pl/300/', 'position' => 'Developer', 'id_card' => '1100800985084', 'phone' => '66982810499', 'address' => 'bangkhen', 'teaching_level' => '1', 'institution' => 'kmutt', 'province' => 'bkk', 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), 'updated_at' => Carbon::now()->format('Y-m-d H:i:s') ] ]; DB::table('users')->insert($usersData); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Comment extends Model { protected $visible = ['id', 'user_id','post_id', 'name', 'detail','created_at', 'updated_at']; protected $hidden = [ ]; protected $fillable = [ 'user_id', 'name', 'post_id', 'detail' ]; public function user() { return $this->belongsTo('App\User'); } public function post(){ return $this->belongsTo('App\Post'); } public function reply_comments() { return $this->hasMany('App\ReplyComment'); } } <file_sep><?php namespace App\Http\Controllers; use App\Badge; use App\Course; use App\Level; use App\Student; use App\Teacher; use Illuminate\Http\Request; use App\Http\Requests; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\File; class StudentController extends Controller { public function __construct() { $this->middleware('jwt.auth', [ 'only' => [ 'getBadgeOfStudent', 'deleteBadgeOfStudent', 'editProfilebyTeacher', 'updateScoreStudent', 'updateScoreAndBadgeStudent', 'deleteStudentOfCourse', 'getStudentProfile', 'editProfile' ] ]); $this->middleware('teacher', [ 'except' => [ 'getStudentProfile', 'editProfile' ] ]); $this->middleware('student', [ 'only' => [ 'getStudentProfile', 'editProfile' ] ]); } public function getStudentProfile($id) { if(Auth::user()->id == $id){ $student = Student::where('user_id', '=', Auth::user()->id)->first(); $course = Course::find($student->course_id); $teacher = Teacher::find($course->teacher_id) ->get(['title', 'name', 'position', 'image']); $tempStudent = array(); array_push($tempStudent,array('student' => $student, 'badge' => $student->badges)); $leader_board = $course->leader_board; $student_leaderboard = $course->students() ->orderBy('overall_xp', 'desc') ->limit($leader_board)->get(); $tempLeaderboard = array(); foreach ($student_leaderboard as $student) { $student = Student::where('id', '=', $student['id'])->first(); $badge = $student->badges; array_push($tempLeaderboard, array('student' => $student, 'badge' => $badge)); } return response()->json( [ 'status' => 'success', 'data' => [ 'student' => $tempStudent, 'course' => $course, 'teacher' => $teacher, 'leaderboard' => $tempLeaderboard ] ], 200); }else{ return response()->json( [ 'status' => 'cant get student profile' ],200); } } public function editProfile(Request $request) { $id = $request->input('id'); $student = Student::where('id', '=', $id)->first(); $student->name = $request->input('name'); $student->student_id = $request->input('student_id'); $image = $request->input('image'); if (preg_match("~data:image/[a-zA-Z]*;base64,~", $image)) { $destination = '/students/logo/'; $old_image = $student->image; $file = public_path() . $destination . $old_image; File::Delete($file); $fileName = $request->input('name') . date('-Ymd-His-') . ".png"; $decodedImg = $this->base64_to_jpeg($image, $fileName, $destination); $student->image = $decodedImg; } else { $student->image = $image; } $student->save(); return response()->json( [ 'status' => 'success', 'data' => [ 'student' => $student, ] ], 200); } public function getBadgeOfStudent($id) { $student = Student::where('id', '=', $id)->first(); $badge = $student->badges; return response()->json( [ 'status' => 'success', 'data' => [ 'badge' => $badge ] ], 200); } public function deleteBadgeOfStudent(Request $request) { $student = Student::findOrFail($request->input('id')); if ($request->has('badges')) { foreach ($request->input('badges') as $badge) { $student->badges()->detach($badge['id']); } } return response()->json( [ 'status' => 'success' ], 200); } public function editProfilebyTeacher(Request $request) { $course_id = $request->input('course_id'); $id = $request->input('id'); $student = Student::where('id', '=', $id)->first(); $levels = Level::where('course_id', '=', $course_id)->get(); $image = $request->input('image'); if (preg_match("~data:image/[a-zA-Z]*;base64,~", $image)) { $destination = '/students/logo/'; $old_image = $student->image; $file = public_path() . $destination . $old_image; File::Delete($file); $fileName = $request->input('name') . date('-Ymd-His-') . ".png"; $decodedImg = $this->base64_to_jpeg($image, $fileName, $destination); $student->image = $decodedImg; } else { $student->image = $image; } $overall_xp = $request->input('overall_xp'); foreach ($levels as $level) { if (($overall_xp >= $level->floor_xp) && ($overall_xp <= $level->ceiling_xp)) { $student_level = $level->level_id; }else{ $student_level = $level->level_id; } } $student->student_id = $request->input('student_id'); $student->name = $request->input('name'); $student->overall_xp = $overall_xp; $student->level = $student_level; $student->save(); $badge = $student->badges; return response()->json( [ 'status' => 'success', 'data' => [ 'student' => $student, 'badge' => $badge, '$student->image' => $student->image ] ], 200); } public function updateScoreStudent(Request $request) { $course_id = $request->input('course_id'); $score = $request->input('score'); $max_score = $request->input('max_score'); $students = $request->input('students'); $levels = Level::where('course_id', '=', $course_id)->get(); foreach ($students as $student) { $student_update = Student::where('id', '=', $student['id'])->first(); $new_score = $student_update->overall_xp += $score; if($new_score < $max_score) { $temp = $new_score; $student_update->overall_xp = $new_score; }else{ $temp = $max_score; $student_update->overall_xp = $max_score; } foreach ($levels as $level) { if (($temp >= $level->floor_xp) && ($temp <= $level->ceiling_xp)) { $student_update->level = $level->level_id; } elseif ($temp >= $level->ceiling_xp) { $student_update->level = $level->level_id; } } $student_update->save(); } return response()->json( [ 'status' => 'success', 'data' => [ 'students' => $student_update ] ], 200); } public function updateScoreAndBadgeStudent(Request $request) { $course_id = $request->input('course_id'); $badge_id = $request->input('badge_id'); $score = $request->input('score'); $students = $request->input('students'); $levels = Level::where('course_id', '=', $course_id)->get(); foreach ($students as $student) { $student_update = Student::where('id', '=', $student['id'])->first(); if (!$student_update->badges->contains($badge_id)) { $student_update->badges()->attach($badge_id); } $temp = $student_update->overall_xp += $score; foreach ($levels as $level) { if (($temp >= $level->floor_xp) && ($temp <= $level->ceiling_xp)) { $student_update->level = $level->level_id; } elseif ($temp >= $level->ceiling_xp) { $student_update->level = $level->level_id; } } $student_update->save(); } return response()->json( [ 'status' => 'success', 'data' => [ 'students' => $student_update ] ], 200); } public function deleteStudentOfCourse(Request $request) { $course_id = $request->input('course_id'); $students = $request->input('students'); $course = Course::find($course_id); $destination = '/students/logo/'; foreach ($students as $student) { $student_update = $course->students()->where('user_id', '=', $student['user_id'])->first(); $old_image = $student_update->image; $file = public_path() . $destination . $old_image; File::Delete($file); $student_update->delete(); } return response()->json( [ 'status' => 'success' ], 200); } public function base64_to_jpeg($base64_string, $output_file, $destination) { $destination = public_path() . $destination . $output_file; $ifp = fopen($destination, "wb"); $data = explode(',', $base64_string); fwrite($ifp, base64_decode($data[1])); fclose($ifp); return $output_file; } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Course extends Model { protected $visible = ['id', 'name', 'description', 'start_xp', 'leader_board','status']; protected $hidden = [ 'created_at', 'updated_at' ]; protected $fillable = [ 'name', 'description', 'start_xp', 'leader_board', 'status' ]; public function teacher(){ return $this->belongsTo('App\Teacher'); } public function students() { return $this->hasMany('App\Student'); } public function levels() { return $this->hasMany('App\Level'); } public function badges() { return $this->hasMany('App\Badge'); } public function posts() { return $this->hasMany('App\Post'); } } <file_sep><?php namespace App\Http\Controllers; use Illuminate\Foundation\Auth\ResetsPasswords; use Illuminate\Http\Request; use App\Http\Requests; use Tymon\JWTAuth\Facades\JWTAuth; use Validator; use Password; use Hash; use Auth; use Mail; use App\User; class PasswordController extends Controller { use ResetsPasswords; protected $redirectTo = 'http://54.169.87.71/auth/signin'; protected $email_token; public function __construct() { $this->middleware('jwt.auth', [ 'only' => '' ]); } public function reset(Request $request) { $validator = Validator::make($request->all(), [ 'token' => 'required', 'email' => 'required|email', 'password' => '<PASSWORD>', ]); $messages = $validator->errors(); if ($validator->fails()) { if ($messages->has('token')) { return response()->json(['status'=>'failed', 'errorcode' => '32', 'errormessage' => $messages->first('token')]); } if ($messages->has('email')) { return response()->json(['status'=>'failed', 'errorcode' => '32', 'errormessage' => $messages->first('email')]); } if ($messages->has('password')) { return response()->json(['status'=>'failed', 'errorcode' => '32', 'errormessage' => $messages->first('password')]); } return response()->json(['status'=>'failed', 'errorcode'=>'32', 'errorname'=> $messages->all()]); } $credentials = $this->getResetCredentials($request); $broker = $this->getBroker(); $response = Password::broker($broker)->reset($credentials, function ($user, $password) { $this->resetPassword($user, $password); }); switch ($response) { case Password::PASSWORD_RESET: return $this->getResetSuccessResponse($response); default: return $this->getResetFailureResponse($request, $response); } } public function sendResetLinkEmail(Request $request) { $this->validateSendResetLinkEmail($request); $validator = Validator::make($request->all(), [ 'email' => 'required|email', ]); $messages = $validator->errors(); if ($validator->fails()) { if ($messages->has('email')) { return response()->json(['status'=>'failed', 'errorcode' => '32', 'errormessage' => $messages->first('email')]); } } $broker = $this->getBroker(); $response = Password::broker($broker)->sendResetLink( $this->getSendResetLinkEmailCredentials($request), $this->resetEmailBuilder() ); switch ($response) { case Password::RESET_LINK_SENT: return $this->getSendResetLinkEmailSuccessResponse($response); case Password::INVALID_USER: default: return $this->getSendResetLinkEmailFailureResponse($response); } } /** * Get the response for after the reset link has been successfully sent. * * @param string $response * @return \Symfony\Component\HttpFoundation\Response */ protected function getSendResetLinkEmailSuccessResponse($response) { // return redirect()->back()->with('status', trans($response)); return response()->json(['status'=>'success', 'message'=>trans($response)], 200); } /** * Get the response for after the reset link could not be sent. * * @param string $response * @return \Symfony\Component\HttpFoundation\Response */ protected function getSendResetLinkEmailFailureResponse($response) { // return redirect()->back()->withErrors(['email' => trans($response)]); return response()->json(['status'=>'failed', 'errorcode'=>'62', 'errormessage'=>trans($response)]); } public function showResetForm(Request $request, $token = null) { if(is_null($token)) { return response()->json(['status'=>'unauthorized', 'errormessage'=>'Token for reset password is required!'], 401); } $email = $request->input('email'); // $user=User::where('email','=',$email)->first(); // $userToken=JWTAuth::fromUser($user); if(property_exists($this, 'resetView')){ return view($this->resetView)->with(compact('token','email')); } // // Call Front-End page // if (is_null($token)) { // return response()->json(['status'=>'unauthorized', // 'errormessage'=>'Token for reset password is required!'], 401); // } // return response()->json(['status'=>'success', // 'token'=> $token, // 'email'=> $request->email ], 200); if(view()->exists('auth.passwords.reset')){ return view('auth.passwords.reset', compact('token', 'email')); } } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Auth\User as Authenticatable; class Student extends Model { protected $visible = ['id', 'user_id','student_id', 'course_id','name', 'image', 'overall_xp', 'level', 'username', 'password']; protected $hidden = [ 'created_at', 'updated_at' ]; protected $fillable = [ 'user_id', 'student_id', 'course_id', 'name', 'image', 'username', 'password', 'overall_xp', 'level' ]; public function user() { return $this->belongsTo('App\User'); } public function course(){ return $this->belongsTo('App\Course'); } public function badges() { return $this->belongsToMany('App\Badge'); } } <file_sep><?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTeachersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('teachers', function (Blueprint $table) { $table->engine = 'InnoDB'; $table->increments('id'); $table->integer('user_id')->unsigned(); $table->string('image'); $table->string('title'); $table->string('name'); $table->string('position'); $table->string('id_card'); $table->string('phone'); $table->string('address'); $table->string('teaching_level'); $table->string('institution'); $table->string('province'); $table->rememberToken(); $table->timestamps(); $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('teachers'); } } <file_sep><?php namespace App\Http\Middleware; use Closure; use App\User; class AuthenticationMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { try{ $user = User::where('email', $request->email)->get(); // Account activation status validation if(!$user[0]['activated']){ return response()->json([ 'status' => "failed", 'errormessage' => "please activated your account first!" ], 401); }elseif($user[0]['archived']){ return response()->json([ 'status' => "failed", 'errormessage' => "your account has been archived!" ], 401); } return $next($request); } catch(\Exception $e){ return response()->json([ 'status'=>'failed', 'errorcode' => '12', 'errormessage' => 'Your email or password does not match!' ]); } } } <file_sep><?php namespace App\Http\Controllers; use App\Comment; use App\Course; use App\Post; use App\ReplyComment; use App\User; use Carbon\Carbon; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Http\Request; use App\Http\Requests; use Illuminate\Support\Facades\Auth; class PostController extends Controller { public function __construct() { $this->middleware('jwt.auth', [ 'only' => [ 'createPost', 'getPost', 'commentPost', 'editComment', 'deleteComment', 'replyComment', 'deleteReplyComment', 'editReplyComment', 'editPost', 'deletePost' ] ]); $this->middleware('teacher', [ 'only' => [ 'createPost', 'editPost', 'deletePost' ] ]); } public function getPost($id) { try { $post = Post::where('course_id', '=', $id)->firstOrFail(); $comments = Comment::where('post_id', '=', $post->id)->get(); $temp = array(); foreach ($comments as $comment) { $reply_comments = ReplyComment::where('comment_id', '=', $comment->id)->get(); array_push($temp, array('comment' => $comment, 'reply_comments' => $reply_comments)); } return response()->json( [ 'status' => 'success', 'data' => [ 'post' => $post, 'comments' => $temp ] ], 200); } catch (ModelNotFoundException $e) { return response()->json( [ 'status' => 'error' ], 200); } } public function createPost(Request $request) { $course = Course::find($request->input('id')); $post = new Post([ 'title' => $request->input('title'), 'detail' => $request->input('detail') ]); $course->posts()->save($post); return response()->json( [ 'status' => 'success', 'data' => [ 'course' => $course, 'post' => $post ] ], 200); } public function editPost(Request $request) { $post = Post::find($request->input('id')); $post->title = $request->input('title'); $post->detail = $request->input('detail'); $post->save(); return response()->json( [ 'status' => 'success', 'data' => [ 'post' => $post ] ], 200); } public function deletePost(Request $request) { $post = Post::find($request->input('id')); $post->delete(); return response()->json( [ 'status' => 'success' ], 200); } public function commentPost(Request $request) { $course_id = $request->input('id'); $post = Post::where('course_id', '=', $course_id)->first(); $comment = new Comment([ 'name' => $request->input('name'), 'detail' => $request->input('detail') ]); $comment->user()->associate(Auth::user()); $comment->post()->associate($post); $comment->save(); return response()->json( [ 'status' => 'success', 'data' => [ 'post' => $post, 'comment' => $comment ] ], 200); } public function editComment(Request $request) { $comment = Comment::find($request->input('id')); if (Auth::user()->id == $comment->user_id) { $status = 'success'; $comment->detail = $request->input('detail'); $comment->save(); } else { $status = 'cant edit comment'; } return response()->json( [ 'status' => $status, 'data' => [ 'user_id' => Auth::user()->id, 'comment' => $comment->detail ] ], 200); } public function deleteComment(Request $request) { $comment = Comment::find($request->input('id')); if (Auth::user()->id == $comment->user_id) { $status = 'success'; $comment->delete(); } else { $status = 'cant delete comment'; } return response()->json( [ 'status' => $status ], 200); } public function replyComment(Request $request) { $comment_id = $request->input('id'); $comment = Comment::find($comment_id); $reply_comment = new ReplyComment([ 'name' => $request->input('name'), 'detail' => $request->input('detail') ]); $reply_comment->user()->associate(Auth::user()); $reply_comment->comment()->associate($comment); $reply_comment->save(); return response()->json( [ 'status' => 'success', 'data' => [ 'comment' => $comment, 'reply_comment' => $reply_comment ] ], 200); } public function editReplyComment(Request $request) { $comment_id = $request->input('id'); $reply_comment = ReplyComment::find($comment_id); if (Auth::user()->id == $reply_comment->user_id) { $status = 'success'; $reply_comment->detail = $request->input('detail'); $reply_comment->save(); } else { $status = 'cant edit comment'; } return response()->json( [ 'status' => $status, 'data' => [ 'user_id' => Auth::user()->id, 'reply_comment' => $reply_comment->detail ] ], 200); } public function deleteReplyComment(Request $request) { $comment = ReplyComment::find($request->input('id')); if (Auth::user()->id == $comment->user_id) { $status = 'success'; $comment->delete(); } else { $status = 'cant delete comment'; } return response()->json( [ 'status' => $status ], 200); } } <file_sep><?php namespace App\Http\Controllers; use App\Comment; use App\Course; use App\Level; use App\Student; use App\User; use Illuminate\Http\Request; use App\Http\Requests; use Illuminate\Support\Facades\Input; use Maatwebsite\Excel\Facades\Excel; use PHPExcel_Style_Border; use PHPExcel_Style_Protection; class ExcelController extends Controller { public function __construct() { } public function importExport(){ return view('excel.import'); } public function downloadExcel($id) { $course = Course::find($id); $students = $course->students()->select('course_id','id','student_id','name','overall_xp')->get(); $export = User::select('id','email')->get(); //$data = count($students); Excel::create('export_data_lms', function ($excel) use ($students){ $excel->sheet('Sheet 1' , function ($sheet) use($students) { $data = count($students); //$sheet->freezeFirstRow(); $sheet->fromArray($students); }); })->export('xlsx'); } public function importExcel(Request $request){ Excel::load(Input::file('file'), function ($reader){ $reader->each(function ($sheet){ foreach ($sheet->toArray() as $row){ $levels = Level::where('course_id', '=', $sheet->course_id)->get(); $ceiling_xp = $levels->max('ceiling_xp'); $student = Student::find($sheet->id); if($sheet->overall_xp < $ceiling_xp){ $student->overall_xp = $sheet->overall_xp; }else{ $student->overall_xp = $ceiling_xp; } $student->save(); } }); }); // return response()->json( // [ // 'status' => 'success' // // ], 200); return redirect('http://54.169.87.71/course/edit-student-score'); } public function export() { } }
919178681f30e41d83f4a2ae633dde731709dffb
[ "PHP" ]
17
PHP
callmefons/laravel-lms
f41500e80a3b9d77cb5dde3ab307f77f58bbc059
12f2620694c6d364ba5ca0117fe5803ccaf5f810
refs/heads/master
<repo_name>waltherwj/AI-and-FEA-model<file_sep>/README.md # FEA and AI project ## Introduction This project has as objectives to 1. Implement a model of a tetrahedral element with many more degrees of freedom than a usual one, and create a dataset of load cases and solutions 2. With this model, train a neural network that emulates the model 3. Use the trained neural network to create a new element ### How? * Feed inputs and geometry, target is displacement field > learns mapping to displacement field * This step is only done so that it can learn how to map inputs to displacement and not be reliant on a third party model to generate a displacement field. The end goal is to have the displacement field be directly fed into the network experimentally. * Feed displacement field into another neural network, which learns a mapping from that into a simplified stress and strain output at selected nodes, in essence creating a super-element if the displacement field step, which is intermediary, is not considered. This can in theory be obtained by [digital image correlation](https://en.wikipedia.org/wiki/Digital_image_correlation_and_tracking) however deciding about this is something for the future still * Alternatively, with a network that is able to predict a displacement field directly from inputs, we can go back to engineering principles and calculates stresses and strains from that. This would reintroduce a lot of assumptions, however it might be worth it in terms of computation ### Bonus Objectives 1. Have the network itself impose new conditions on the model in an adversarial way to ensure robustness ## Past Progress #### _Implementing a 2d model for proof of concept_ * Created script for generating correct geometry inside of SpaceClaim * Created script for calling geometry script from Workbench * Create script for generating mesh in Mechanical * Create script for generating model inside of Workbench * Created script for applying forces to element * Automated Geometry and Mesh Generation Step * Created Folder to save Boundary Conditions and Results files * Created script for saving the geometry and mesh * The geometry/mesh comes from any results file, as it has nodal number and coordinate location * Created script for saving the results and boundary conditions * The results, boundary conditions and named selections are all exported to .txt files: * Results - single file * Boundary Conditions - one file for nodal forces and one for displacements * Named Selections - One file for each named selection * Scaled it all to generate data continuously * Pre-processed files to be only 2 files, one with inputs and one with outputs * Created pandas dataframes with nodal displacements and nodal forces for each named selection * Used these dataframes to create final files with nodes and nodal coordinates, and corresponding nodal displacements and forces * Created a way to scale the data * Formatted the data to `.npy` arrays of shape `(BATCH_SIZE x FEATURES x HEIGHT x WIDTH)` * Created a general forward pass for the simplest model showing that the model is partially successful on a toy dataset. In essence, the **proof of concept is complete** ## Current Work #### _Implementing a 2d model for proof of concept_ ##### Tasks * Explore different models with Weights and Biases * backtrack: after some exploration, it became apparent that the models were fitting the empty space around the data instead of the data itself: * Refit the data to the tensor, making them occupy more space * Create a dataloader, so that the data can be augmented if wanted ## Element Shape, Force & Nodal Displacement Generation Justification #### *Element Shape* Triangular shapes have an advantage in relation to quadrilaterals in that it is easier to adapt them to any boundary shape. On the other hand, quadrilaterals tend to exhibit better approximation characteristics than triangles. **By creating triangular elements with the deep learning model comprised of mostly quadrilateral internal elements**, the objective is that the model is able to acquire the better approximation characteristics of quadrilaterals while using triangular elements. #### *Nodal Selection* Since the model has many nodes instead of just a handful, applying forces and displacements to edges and vertices is not equivalent to applying them to an usual FEA model as the simplified behaviour of that model is not applicable anymore, and now stress concentrations and the like arise. To overcome this, a random set of nodes has to be selected to emulate forces and displacements in the super element. The nodal selection is performed with a brownian motion of a coordinate system inside of the element, and all nodes within a certain radius are selected, and to ensure that the selections actually select nodes, the coordinate systems are biased to go toward the centroid of the element, and the direction vector that introduces the bias also has a random distribution attached to it. This creates "blobs" of selections which are contiguous most of the time, however sometimes the offset is enough to overcome the radius of selection and the next selectio is not contiguous with the previous. This entire process is controlled by several hyperparameters, and they have been adjusted until they seemed to generate good quality selections most of the time, while at the same time limiting how complex the behaviour could be since the process of creating selections is relatively time-consuming. If a selection selects no node (usually because it is outside of the super element), then the radius is inflated until the selection is able to reach at least one unselected node. This selection process is exemplified in the gif below, where two "curves" of blobs are formed. ![gif of nodal selection](2D/v10_test/selections_example.gif "gif demonstrates nodal selection happening from two opposite corners and then rotates the element") #### *Forces* **Forces and moments can be applied to any node of a finite element model**. The model is going to be trained with between 0 and 2 "force curves". These "curves" follow a -somewhat- contiguous nodal selection, and each "blob" of force has random forces assigned to it according to a gaussian distribution. #### *Nodal Displacement* In an usual FEA method the nodal displacements and the interpolation within the element is given by : <img src="https://render.githubusercontent.com/render/math?math=\{u\}_e = [N]_e\{\Delta\}_e"> Where u, N and Delta are displacement within the element, shape function and displacement at the nodes, respectively, and N is of a definite shape defined by the type of element and number of nodes. On the other hand, Delta is given by the boundary conditions and the equilibrium equation of the element using the stiffness matrix K, with the equation: <img src="https://render.githubusercontent.com/render/math?math=[K]\{\Delta\} = \{F^L\}"> Where F is the reactions (actions to be more precise, as it is the negative of the actual reactions) at the nodes. The goal is thus that, given a set of boundary conditions and forces along the entire element, the model directly learns a certain equivalent mapping M that that maps into the displacement field within the entire element. <img src="https://render.githubusercontent.com/render/math?math=M: (F_e, \Delta_{BC}) \mapsto u_e"> Therefore the element has to be generated with **arbitrary nodal displacements to train the model.** However during the training process it became obvious that nodal displacements only on the vertices don't work well for the simulation since the "nodes" on the vertices in this case are much more malleable and are stress concentrators than the rest of the element, thus, the simulation doesn't show any interesting behaviour no matter the forces except for a very large distortion at the vertices if the model is only held by them. A similar approach of using random displacements via a gaussian distribution on somewhat contiguous blobs of selection is used for the displacements. Using this approach, the following type of element is generated. The image shows the directional displacement field of the solution during one of the testing iterations: ![image of the element under nodal displacements only](2D/v8_test/nodal_displacement_solution.png "test element under nodal displacements") And after adding forces to another test element, this is a sample result: ![image of the element under nodal displacements and forces](2D/v8_test/total_deformation_nodal_force.gif "test element under nodal displacements and forces") The mapping function will, in essence, encapsulate both the stiffness matrix and the shape function if the model is trained in a simulation set, or, in theory, the real world behaviour of the material if trained on actual experiments. ## Relevant Links [How to execute APDL commands from python session](https://www.youtube.com/watch?v=bSP9pi-4QW0) [Use a Named Selection as Scoping of a Load or Support](https://ansyshelp.ansys.com/account/secured?returnurl=/Views/Secured/corp/v201/en/act_script/act_script_examples_NamedSelection_as_Scoping.html) [Export Result Object to STL](https://ansyshelp.ansys.com/account/secured?returnurl=/Views/Secured/corp/v201/en/act_script/act_script_examples_export_result_object.html) *CAN ONLY ACCES ANSYS SCRIPTING GUIDE THROUGH INSIDE OF MECHANICAL > USE SEARCH FUNCTIONS "SCRIPTING"* [Using IronPython/ACT console](https://www.youtube.com/watch?v=txPimWRh8nM) [Creating XML and Python in Ansys](https://www.youtube.com/watch?v=fURQ-22YKmc) [ANSYS scripting examples](https://ansyshelp.ansys.com/account/secured?returnurl=/Views/Secured/corp/v201/en/act_script/pt03.html) *CAN ONLY ACCES ANSYS SCRIPTING GUIDE THROUGH INSIDE OF MECHANICAL > USE SEARCH FUNCTIONS "SCRIPTING"*<file_sep>/2D/v6_test/TEST_error_handling.py if not IsProjectUpToDate(): print("not upt to date") DSscript = open("D:/Ansys Simulations/Project/2D/v6_test/MESH_error_handling.py", "r") DSscriptcommand=DSscript.read() model1.SendCommand(Command=DSscriptcommand,Language="Python")<file_sep>/2D/preprocessing/PREPROCESSING_scaling.py from pathlib import Path import pandas as pd import numpy as np from PREPROCESSING_splitting import get_number def get_sample_dfs(samples_folder_path, sample_number): ## returns the input and output dataframe for the sample specified input_folder_path = Path(samples_folder_path, 'input') output_folder_path = Path(samples_folder_path, 'output') glob_string = "*_" + str(sample_number) + ".csv" input_sample_glob = input_folder_path.glob(glob_string) for i, sample_input_file in enumerate(input_sample_glob): if i == 0: sample_input_df = pd.read_csv(sample_input_file, index_col = 0) else: raise Exception('error: more than one input sample with label' + str(sample_number)) output_sample_glob = output_folder_path.glob(glob_string) for i, sample_output_file in enumerate(output_sample_glob): if i == 0: sample_output_df = pd.read_csv(sample_output_file, index_col = 0) else: raise Exception('error: more than one output sample with label' + str(sample_number)) return sample_input_df, sample_output_df def sample_iterator(samples_folder_path): ## generates dataframes for each of the samples in the samples folder input_folder_path = Path(samples_folder_path, 'input') output_folder_path = Path(samples_folder_path, 'output') glob_string = "*.csv" ## gets all input files input_sample_glob = input_folder_path.glob(glob_string) for input_sample in input_sample_glob: sample_number = get_number(input_sample.name) input_data, output_data = get_sample_dfs(samples_folder_path, sample_number) yield sample_number, input_data, output_data def get_max_disp_force(samples_folder_path): ## iterates through all data to get the max force and displacement samples = sample_iterator(samples_folder_path) max_force = 0 max_disp = 0 for sample in samples: sample_number, input_data, output_data = sample ## run through input data for displacement and force # first absolute, then max in the columns, then max over the three directions updated = False max_force_temp = (input_data.loc[:,['x_force','y_force','z_force']].abs().max()).max() if max_force_temp > max_force: max_force = max_force_temp updated = True max_disp_temp = (input_data.loc[:,['x_disp','y_disp','z_disp']].abs().max()).max() if max_disp_temp > max_disp: max_disp = max_disp_temp updated = True ## run through output data for displacement max_disp_temp = (output_data.loc[:,['x_disp','y_disp','z_disp']].abs().max()).max() if max_disp_temp > max_disp: max_disp = max_disp_temp updated = True if updated: print(f'UPDATED MAX \t sample #{sample_number} \t force: {max_force:.2f} \t displacement: {max_disp:.6f} ') return max_force, max_disp def scale_dataframe(df_unscaled, max_force, max_disp): df = df_unscaled.copy() try: df.loc[:,['x_disp','y_disp','z_disp']] = df.loc[:,['x_disp','y_disp','z_disp']].values/max_disp except: raise Exception('error: displacement data error during scaling. Check sample') ## handle the error that happens when it's an output because it doesnt force columns try: df.loc[:,['x_force','y_force','z_force']] = df.loc[:,['x_force','y_force','z_force']].values/max_force except: pass return df print('scaling functions imported')<file_sep>/2D/v12_test/SETUP_AND_SAVE.py # encoding: utf-8 # 2020 R1 for i in range(100): ## Create Geometry SetScriptVersion(Version="20.1.164") system1 = GetSystem(Name="SYS") geometry1 = system1.GetContainer(ComponentName="Geometry") geometryProperties1 = geometry1.GetGeometryProperties() geometryProperties1.GeometryImportAnalysisType = "AnalysisType_2D" DSscript = open("D:/Ansys Simulations/Project/2D/v12_test/GEOMETRY_generate.py", "r") DSscriptcommand=DSscript.read() geometry1.SendCommand(Command=DSscriptcommand,Language="Python") geometry1.Edit(IsSpaceClaimGeometry=True) #geometry1.Exit() ## Open Mechanical modelComponent1 = system1.GetComponent(Name="Model") modelComponent1.Refresh() model1 = system1.GetContainer(ComponentName="Model") model1.Edit() ## Create Mesh DSscript = open("D:/Ansys Simulations/Project/2D/v12_test/MESH_generate.py", "r") DSscriptcommand=DSscript.read() model1.SendCommand(Command=DSscriptcommand,Language="Python") ## Create Named Selections DSscript = open("D:/Ansys Simulations/Project/2D/v12_test/NAMED_SELECTIONS_generate.py", "r") DSscriptcommand=DSscript.read() model1.SendCommand(Command=DSscriptcommand,Language="Python") ## Create Displacements DSscript = open("D:/Ansys Simulations/Project/2D/v12_test/DISPLACEMENTS_generate.py", "r") DSscriptcommand=DSscript.read() model1.SendCommand(Command=DSscriptcommand,Language="Python") ## Create Loads DSscript = open("D:/Ansys Simulations/Project/2D/v12_test/LOADS_generate.py", "r") DSscriptcommand=DSscript.read() model1.SendCommand(Command=DSscriptcommand,Language="Python") ##Save Files DSscript = open("D:/Ansys Simulations/Project/2D/v12_test/SAVED_FILES_generate.py", "r") DSscriptcommand=DSscript.read() model1.SendCommand(Command=DSscriptcommand,Language="Python")<file_sep>/2D/v2_test/WORKING_script.py # encoding: utf-8 # 2020 R1 SetScriptVersion(Version="20.1.164") system1 = GetSystem(Name="SYS") geometry1 = system1.GetContainer(ComponentName="Geometry") DSscript = open("D:/Ansys Simulations/Project/2D/v3_test/generate_tetra_and_mesh.py", "r") DSscriptcommand=DSscript.read() geometry1.SendCommand(Command=DSscriptcommand,Language="Python") geometry1.Edit(IsSpaceClaimGeometry=True) #geometry1.Exit() <file_sep>/2D/preprocessing/DISPLAYING_functions.py ## 3d visualization import %gui qt from mayavi import mlab mlab.init_notebook('png') def plot_2d(sample_array, contour = False, clear = True, edges = np.array([])): if clear: mlab.clf() #print(sample_array) m = np.max(np.abs(sample_array)) print(m, len(sample_array.shape)) s = np.abs(sample_array) mlab.figure(figure=None, bgcolor=(0.99,0.99,0.99), fgcolor=None, engine=None, size=(400, 350)) if len(sample_array.shape)==3: sample_array = np.concatenate((sample_array, sample_array), axis=2) sample_array = np.abs(sample_array) try: sample_array = sample_array/m except: ## if m is zero pass n = np.max(np.abs(sample_array)) print(n) sample_array[0,:,:] += 1.2 sample_array[:,0,:] += 1.2 sample_array[-1,:,:] += 1.2 sample_array[:,-1,:] += 1.2 if edges.size > 0: sample_array = sample_array + 0.25*edges volume = mlab.pipeline.volume(mlab.pipeline.scalar_field(sample_array), vmin=0.2, vmax=0.8) if contour: mlab.contour3d(s) return volume %matplotlib inline import matplotlib.pyplot as plt def plot_grid_2d(concat_input, concat_output): f, axarr = plt.subplots(2,5, figsize = (15,6)) axarr[0,0].imshow(np.abs(concat_input[:,:,0])) axarr[0,0].set(title='smoothed map') axarr[0,1].imshow(np.abs(concat_input[:,:,1])) axarr[0,1].set(title='X displacement B.C.') axarr[0,2].imshow(np.abs(concat_input[:,:,2])) axarr[0,2].set(title='Y displacement B.C.') axarr[0,3].imshow(np.abs(concat_input[:,:,3])) axarr[0,3].set(title='Z displacement B.C') axarr[0,4].imshow(np.abs(concat_input[:,:,4])) axarr[0,4].set(title='X force B.C.') axarr[1,0].imshow(np.abs(concat_input[:,:,5])) axarr[1,0].set(title='Y force B.C.') axarr[1,1].imshow(np.abs(concat_input[:,:,6])) axarr[1,1].set(title='Z force B.C.') axarr[1,2].imshow(np.abs(concat_output[:,:,1])) axarr[1,2].set(title='X displacement result') axarr[1,3].imshow(np.abs(concat_output[:,:,2])) axarr[1,3].set(title='Y displacement result') axarr[1,4].imshow(np.abs(concat_output[:,:,3])) axarr[1,4].set(title='Z displacement result') print(sample_number) plt.show() print('displaying functions imported. magics imported: <%matplotlib inline> <%gui qt>')<file_sep>/2D/preprocessing/PREPROCESSING_splitting.py ## Imports necessary functions for the script import os from pathlib import Path import traceback import re import pandas as pd import numpy as np def get_number(filename): # uses regular expression to match a single number in the file name try: return re.search(r'\d+', filename).group(0) except: return 'no number found' def get_named_selections(sample_path): file_list = [] # return all paths that correspond to a named selection for file in sample_path.glob("named_selection_*.txt"): file_list.append(file) return file_list def create_filename(sample_path): #creates a filename based on the sample number sample_number = get_number(sample_path.name) input_filename = Path("input_" + sample_number + '.csv' ) output_filename = Path("output_" + sample_number + '.csv' ) return input_filename, output_filename def bc_files_to_df(sample_folder): # creates three dataframes with the boundary conditions #load in solutions file solutions_file = sample_folder.glob("solutions_*.txt") for file in solutions_file: try: solutions_data = pd.read_csv(file, delimiter = '\t', names = ['node_number', 'x_loc','y_loc','z_loc','x_disp','y_disp','z_disp'], header=0) except Exception: print('File is not in the correct format', file) print("run delelete_malformed_samples() before running this") disp_file = sample_folder.glob("disp_*.txt") #load in displacement boundary conditions for file in disp_file: disp_bc_data = pd.read_csv(file, delimiter = '\t', names = ['named_selection', 'unit','x_disp','y_disp','z_disp'], header=None) #load in force boundary conditions force_file = sample_folder.glob("force_*.txt") for file in force_file: force_bc_data = pd.read_csv(file, delimiter = '\t', names = ['named_selection', 'unit','x_force','y_force','z_force'], header=None) return solutions_data, disp_bc_data, force_bc_data def selection_index(selection, data): # runs through all named selections and returns the index # that corresponds to the selection name for i, ns_in_file in enumerate(data.named_selection.to_list()): if selection == ns_in_file: return i raise Exception('error: String \'' + selection +'\' not found in the rows of the data') def update_selection(sample_folder, disp_data, force_data): # generator function that returns all the relevant data for each of the # named selections in the folder named_selections = get_named_selections(sample_folder) ## Iterate Through Selections for ns_file in named_selections: ## Check selection type and get values for that selection is_disp = False selection_values_updated = False for selec in disp_data.named_selection: if get_number(selec) == get_number(ns_file.name): is_disp = True if get_number(selec) == 'no number found' and get_number(ns_file.name) == '1': is_disp = True if is_disp and not selection_values_updated: try: ns_number = int(get_number(selec)) except: ns_number = 1 index = selection_index(selec, disp_data) values = disp_data.x_disp.loc[index], disp_data.y_disp.loc[index], disp_data.z_disp.loc[index] selection_values_updated = True is_force = False selection_values_updated = False for selec in force_data.named_selection: if get_number(selec) == get_number(ns_file.name): is_force = True if get_number(selec) == 'no number found' and get_number(ns_file.name) == '1': is_force = True if is_force and not selection_values_updated: try: ns_number = int(get_number(selec)) except: ns_number = 1 index = selection_index(selec, force_data) values = force_data.x_force.loc[index], force_data.y_force.loc[index], force_data.z_force.loc[index] selection_values_updated = True ## get named selection in the file ns = pd.read_csv(ns_file, delimiter = '\t', names = ['node_number','x_loc','y_loc','z_loc'], header=0, usecols = range(4)) yield ns_number, ns, is_disp, is_force, values def update_df_with_ns(df, ns_number, ns, is_disp, is_force, values): ## updates the dataframe with a single named selection ns_list = ns.node_number.to_list() for i, node in enumerate(df.node_number.to_list()): if node in ns_list: #selects correct nodes df.loc[i,'named_selection'] = ns_number if is_disp: df.loc[i, 'x_disp'], df.loc[i, 'y_disp'], df.loc[i, 'z_disp'] = values if is_force: df.loc[i, 'x_force'], df.loc[i, 'y_force'], df.loc[i, 'z_force'] = values return df def create_input_df(sample_folder): ## creates a dataframe with the correct columns and neutral values ## start empty dataframe df = pd.DataFrame(columns = ['node_number', 'named_selection' , 'x_loc','y_loc','z_loc', 'x_disp','y_disp','z_disp', 'x_force','y_force', 'z_force']) ##load in partial data into dataframes sol_data, disp_data, force_data = bc_files_to_df(sample_folder) ## start dataframe values ## first fill dataframe nodes and coordinates df.node_number, df.x_loc, df.y_loc, df.z_loc = sol_data.node_number, sol_data.x_loc, sol_data.y_loc, sol_data.z_loc ## fill rest of data with "neutral" values df.named_selection = np.ones_like(df.named_selection, dtype=int)*(-1) zero = np.zeros_like(df.named_selection, dtype = float) df.x_disp, df.y_disp, df.z_disp, df.x_force, df.y_force, df.z_force = zero, zero, zero, zero, zero, zero ##iterate through named selections selection_iterator = update_selection(sample_folder, disp_data, force_data) for selection in selection_iterator: df = update_df_with_ns(df, *selection) return df def write_input_output(sample_path, data_folder_path): ## Writes the files corresponding to the sample to the output folder ## create the two dataframes necessary for writing the files df_input = create_input_df(sample_path) df_output, _, _ = bc_files_to_df(sample_path) ## create the appropriate paths input_folder, output_folder = create_folders(data_folder_path) input_filename, output_filename = create_filename(sample_path) input_file_path = Path(input_folder, input_filename) output_file_path = Path(output_folder, output_filename) df_input.to_csv(input_file_path) df_output.to_csv(output_file_path) def create_folders(data_directory_path): # creates the folders to split the data into input and output, and returns their path try: input_folder = Path('input') output_folder = Path('output') input_path = Path(data_directory_path, input_folder) output_path = Path(data_directory_path, output_folder) input_path.mkdir(parents = True) print(f'folder {input_path} created') except Exception: print(f"folder {input_path} likely already exist") #traceback.print_exc() try: output_path.mkdir(parents = True) print(f'folder {output_path} created') except: print(f"folder {output_path} likely already exist") #traceback.print_exc() return input_path, output_path def delete_malformed_samples(all_samples_glob): #deletes folders that don't have the correct format for sample_folder in all_samples_glob: solutions_file = sample_folder.glob("solutions_*.txt") for file in solutions_file: try: solutions_data = pd.read_csv(file, delimiter = '\t', names = ['node_number', 'x_loc','y_loc','z_loc','x_disp','y_disp','z_disp'], header=0) except Exception: print('File is not in the correct format, deleting parent folder of', file) all_files = sample_folder.glob('*.txt') for file in all_files: os.remove(file) os.rmdir(sample_folder) def split_data(all_samples_path, data_folder_path): # runs all the other functions and separates the data into input and output files # for all samples inside of the samples directory by writing to the data_folder_path # directory all_samples_glob = all_samples_path.glob('data_dir_*') ##all samples_glob is exhausted in delete_malformed samples delete_malformed_samples(all_samples_glob) all_samples_glob = all_samples_path.glob('data_dir_*') for sample in all_samples_glob: print(sample) write_input_output(sample, data_folder_path) print('splitting functions imported')<file_sep>/2D/v2_test/meshing_script_test2.py mesh = Model.Mesh mesh_autosize = mesh.AddAutomaticMethod() mesh_sizing = mesh.AddSizing() geometry = Model.Geometry #mesh.Update() <file_sep>/2D/v4_test/generate_Mesh.py geometry = Model.Geometry #gets body elementID = geometry.Children[0].ObjectId ElementSel = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities) ElementSel = elementID mesh_method = Model.AddMeshEdit. if len(Model.NamedSelections.Children)>4: pass <file_sep>/2D/v3_test/session_start.py Microsoft.Scripting.Actions.NamespaceTracker.SpaceClaim.Api.V19.Session.Start()<file_sep>/2D/preprocessing/PREPROCESSING_formatting.py import numpy as np import PREPROCESSING_scaling as scale import PREPROCESSING_splitting as split from pathlib import Path import pandas as pd import os, sys import torch.nn.functional as F import torch import datetime import time def create_array(dimensionality, features, resolution = 32): ## returns an array of zeros for the correct type of model specified with the dimensionality and the features positional_shape = [resolution]*dimensionality shape = positional_shape + [features] array = np.zeros(shape) return array class HiddenPrints: def __enter__(self): self._original_stdout = sys.stdout sys.stdout = open(os.devnull, 'w') def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout.close() sys.stdout = self._original_stdout def get_max_dimensions(samples_folder_path): ## iterates through all data to get the max dimensions samples = scale.sample_iterator(samples_folder_path) max_x = 0 max_y = 0 max_z = 0 for sample in samples: sample_number, input_data, output_data = sample #print(samples) ## run through all data # first absolute, then max in the columns updated = False ## get ranges of data in sample range_x = [input_data.loc[:,['x_loc']].max().item(), input_data.loc[:,['x_loc']].min().item()] max_x_temp = abs(range_x[0] - range_x[1]) range_y = [input_data.loc[:,['y_loc']].max().item(), input_data.loc[:,['y_loc']].min().item()] max_y_temp = abs(range_y[0] - range_y[1]) range_z = [input_data.loc[:,['z_loc']].max().item(), input_data.loc[:,['z_loc']].min().item()] max_z_temp = abs(range_z[0] - range_z[1]) if max_x_temp > max_x: max_x = max_x_temp updated = True if max_y_temp > max_y: max_y = max_y_temp updated = True if max_z_temp > max_z: max_z = max_z_temp updated = True if updated: print(f'UPDATED MAX \t sample #{sample_number} \t x: {max_x:.4f} \t y: {max_y:.4f} \t z: {max_z:.4f}') return max_x, max_y, max_z def get_element_size(samples_folder_path, resolution = 32): ## runs through all samples to get the element size based on the resolution with HiddenPrints(): max_x, max_y, max_z = get_max_dimensions(samples_folder_path) largest_dim = max([max_x, max_y, max_z]) element_size = largest_dim/resolution return element_size def get_quadrant(sample_df): ## gets the sample's main octant by returning a 3 component vector that points to that octant. ## a zero in the last component means that it is a 2d problem and thus it points to a 2d ## quadrant #gets the maximum absolute values max_x_abs, max_y_abs, max_z_abs = sample_df.loc[:,['x_loc','y_loc','z_loc']].abs().max() ## checks if 2d or 3d problem Is_2D = True if max_z_abs != 0: Is_2D = False ## get index of the maximum absolute values x_index = np.where(sample_df.loc[:,['x_loc']].abs().values.squeeze() == [max_x_abs]) y_index = np.where(sample_df.loc[:,['y_loc']].abs().values.squeeze() == [max_y_abs]) if not(Is_2D): z_index = np.where(sample_df.loc[:,['z_loc']].abs().values.squeeze() == [max_z_abs]) else: z_index = [[0]] ## gets the value in that index values = np.array([sample_df.loc[x_index[0],['x_loc']].values[0][0], sample_df.loc[y_index[0],['y_loc']].values[0][0], sample_df.loc[z_index[0],['z_loc']].values[0][0]]) ## create array with information about the octant via a vector octant = np.zeros(3) octant[0:2] = values[0:2]/abs(values[0:2]) if not(Is_2D): octant[2] = values[2]/abs(values[2]) return octant def translate_df(sample_df, max_dimensions): ## gets a dataframe and translates the values to the correct position to place in the tensor octant = get_quadrant(sample_df) df_temp = sample_df.copy() largest_dim = max(*max_dimensions) ## general translation: translates according to the overall octant for i, direction in enumerate(octant): direction_is_negative = direction < 0 if direction_is_negative: if i == 0: df_temp.loc[:,['x_loc']] = df_temp.loc[:,['x_loc']] + largest_dim - df_temp.loc[:,['x_loc']].max().item() if i == 1: df_temp.loc[:,['y_loc']] = df_temp.loc[:,['y_loc']] + largest_dim - df_temp.loc[:,['y_loc']].max().item() if i == 2: df_temp.loc[:,['z_loc']] = df_temp.loc[:,['z_loc']] + largest_dim - df_temp.loc[:,['z_loc']].max().item() ## minor translation: if some parts of the element are still "sticking out" ## after the general translation, move it just enough to ensure that it fits inside if not(direction_is_negative): min_val = df_temp.loc[:,['x_loc','y_loc', 'z_loc']].iloc[:, i].min() if min_val < 0.0: if i == 0: df_temp.loc[:,['x_loc']] = df_temp.loc[:,['x_loc']] + abs(min_val) #print('0',min_val) if i == 1: df_temp.loc[:,['y_loc']] = df_temp.loc[:,['y_loc']] + abs(min_val) #print('1',min_val) if i == 2: df_temp.loc[:,['z_loc']] = df_temp.loc[:,['z_loc']] + abs(min_val) #print('2',min_val) return df_temp def interpolate_array_spatially_2D(sample_array): ## use gaussian blur kernel to smooth out the tensor ## define kernel kernel_blur = 1/256*torch.Tensor([[1, 4, 6, 4, 1], [4, 16, 24, 16, 4], [6, 24, 36, 24, 6], [4, 16, 24, 16, 4], [1, 4, 6, 4, 1]]) ## add redundant batch_size and _feature dimensions because of torch requirements kernel_blur = kernel_blur.view([1,1,5,5]) ## convert tensor = torch.from_numpy(sample_array) ## convolve filter and tensor smoothed_array = F.conv2d(input = tensor.view([1,1,32,32]), weight = kernel_blur.double(), stride = 1, padding=2) ## return it as a correctly shaped numpy arra return smoothed_array.view([32,32,1]).numpy() def convolve_with_kernel(sample_array, kernel_name='edge_detection'): ## use kernel on sample ## define kernel if kernel_name == 'edge_detection': kernel = torch.Tensor([[-1,-1,-1], [-1,8,-1], [-1,-1,-1]]) ## add redundant batch_size and _feature dimensions because of torch requirements kernel = kernel.view([1,1,3,3]) ## convert tensor = torch.from_numpy(sample_array) ## convolve filter and tensor convolved_array = F.conv2d(input = tensor.view([1,1,32,32]), weight = kernel.double(), stride = 1, padding=1) ## return it as a correctly shaped numpy array return convolved_array.view([32,32,1]).numpy() def create_concat_array(sample_df, empty_array, element_size, dataframe_type): ## takes a sample dataframe and creates the concatenated tensor with it ## initialize empty array copy concat_array = empty_array.copy() ## get resolution of array resolution = len(empty_array[0]) ## check dimensionality of array if len(concat_array.shape) == 3: dimensionality = 2 if len(concat_array.shape) == 4: dimensionality = 3 ## create dictionary to store number of nodes for each array location nodes_dictionary = {} for i, row in enumerate(sample_df.itertuples()): #itertuples is much faster than iterrows ## get spacial locations x_loc, y_loc, z_loc = row.x_loc, row.y_loc, row.z_loc ## calculate tensor locations ## points at the very edge of an element at the edge of the array ## should fall to the previous index, not to the next x = x_loc / element_size y = y_loc / element_size z = z_loc / element_size x,y,z = int(x), int(y), int(z) ## check for upper edge case if x >= resolution: x -= 1 if y >= resolution: y -= 1 if z >= resolution: z -= 1 ## create feature vector to update location if dataframe_type.lower() == 'input': feature_vector = np.array([1, row.x_disp, row.y_disp, row.z_disp, row.x_force, row.y_force, row.z_force]) if dataframe_type.lower() == 'output': feature_vector = np.array([1, row.x_disp, row.y_disp, row.z_disp]) elif dataframe_type.lower() != 'input': raise Exception(f'Incorrect dataframe type. Expected \'input\' or \'output\', got {dataframe_type}') ## update values at location if dimensionality == 2: try: ## update material existence concat_array[x,y,0] = feature_vector[0] ## only do operation if there is a value to add if any(feature_vector[1:] != 0.0): if any(feature_vector[1:4] != 0.0): ## add displacements concat_array[x,y,1:4] += feature_vector[1:4] ## add item to dictionary ## control whether to create or update dictionary entry if (x,y) in nodes_dictionary: nodes_dictionary[(x,y)] +=1 else: nodes_dictionary[(x,y)] = 1 ## add forces if input if dataframe_type.lower() == 'input': concat_array[x,y,4:7] += feature_vector[4:7] except IndexError: print(f'out of bounds, check sample at x:{x_loc} y:{y_loc} z:{z_loc}, indices {x,y,z}') elif dimensionality > 2: raise Exception(f'Three dimensional or higher not implemented yet') ## divide the displacements by the number of nodes for key in nodes_dictionary.keys(): #print(concat_array[*key,1], concat_array[*key,1]/nodes_dictionary[key]) concat_array[(*key, [1,2,3])] = concat_array[(*key, [1,2,3])]/nodes_dictionary[key] ## smooth out arrays if dataframe_type.lower() == 'input': concat_array[:,:,0:1] = interpolate_array_spatially_2D(concat_array[:,:,0:1]) concat_array[:,:,1:2] = interpolate_array_spatially_2D(concat_array[:,:,1:2]) concat_array[:,:,2:3] = interpolate_array_spatially_2D(concat_array[:,:,2:3]) concat_array[:,:,3:4] = interpolate_array_spatially_2D(concat_array[:,:,3:4]) concat_array[:,:,4:5] = interpolate_array_spatially_2D(concat_array[:,:,4:5]) concat_array[:,:,5:6] = interpolate_array_spatially_2D(concat_array[:,:,5:6]) concat_array[:,:,6:7] = interpolate_array_spatially_2D(concat_array[:,:,6:7]) if dataframe_type.lower() == 'output': concat_array[:,:,0:1] = interpolate_array_spatially_2D(concat_array[:,:,0:1]) concat_array[:,:,1:2] = interpolate_array_spatially_2D(concat_array[:,:,1:2]) concat_array[:,:,2:3] = interpolate_array_spatially_2D(concat_array[:,:,2:3]) concat_array[:,:,3:4] = interpolate_array_spatially_2D(concat_array[:,:,3:4]) elif dataframe_type.lower() != 'input': raise Exception(f'Incorrect dataframe type. Expected \'input\' or \'output\', got {dataframe_type}') return concat_array def get_unscaled_arrays(data_folder_path, resolution = 32): ## takes the path to the folder with all samples and creates ## an iterator that goes through all of them and returns the corresponding ## array to each sample with HiddenPrints(): # get max dimensions for the dataset max_dimensions = get_max_dimensions(data_folder_path) # get element size for this dataset element_size = get_element_size(data_folder_path, resolution) # create an iterator for all samples samples_iterator = scale.sample_iterator(data_folder_path) # create empty arrays to use in functions dimensionality = 2 input_features = 7 output_features = 4 empty_arr_input = create_array(dimensionality, input_features, resolution) empty_arr_output = create_array(dimensionality, output_features, resolution) # iterates through all samples for sample_number, input_dataframe, output_dataframe in samples_iterator: # translate the data translated_input_df = translate_df(input_dataframe, max_dimensions) translated_output_df = translate_df(output_dataframe, max_dimensions) # creates the arrays concatenated_input = create_concat_array(translated_input_df, empty_arr_input, element_size, dataframe_type='input') concatenated_output = create_concat_array(translated_output_df, empty_arr_output, element_size, dataframe_type='output') yield sample_number, concatenated_input, concatenated_output def save_arrays(array_iterator, save_path, array_type = 'unscaled'): # take the folder where the samples are and the folder where the samples are going to be # saved to, create the folder and save the arrays ## create save path save_path = Path(save_path, 'arrays') ## create save folders input_save_path, output_save_path = split.create_folders(save_path) #sample_number, input_array, output_array = next(array_iterator) if 'nscaled' in array_type.lower(): input_file_root = array_type.lower() output_file_root = array_type.lower() elif 'scaled' in array_type.lower(): input_file_root = array_type.lower() output_file_root = array_type.lower() else: raise Exception(f'Expected \'scaled\' or \'unscaled\' strings for argument <array_type>, got \'{array_type}\'') ## create log file log_file = Path(save_path,'log.txt') with open(log_file, mode = '+a') as log: log.write('\n' + str(datetime.datetime.now()) + '\n') log.write(f"{'SAMPLE': <20} {'INPUT': <20} {'OUTPUT': <20} {'PATH': <20} {'TIME': >40}\n") initial_time = time.time() for sample_number, input_array, output_array in array_iterator: tic = time.time() input_file_ending = '_input_' + str(sample_number) + '.npy' output_file_ending = '_output_' + str(sample_number) + '.npy' input_array_path = Path(input_save_path, input_file_root + input_file_ending) output_array_path = Path(output_save_path, output_file_root + output_file_ending) if not(input_array_path.is_file()) : action_input = 'CREATE' else: action_input = 'OVRWRT' if not(output_array_path.is_file()): action_output = 'CREATE' else: action_output = 'OVRWRT' np.save(input_array_path, input_array) np.save(output_array_path, output_array) log.write(f'{sample_number: <20} {action_input: <20} {action_output: <20} {str(save_path): <20} {time.time()-tic: >40}s \n') log.write(f'OVERALL TIME: {time.time()-initial_time}s \n') def saved_array_iterator(array_folder_path, glob_parameter = '*.npy'): ## generates arrays for each of the saved arrays in the arrays folder input_array_folder_path = Path(array_folder_path,'input') output_array_folder_path = Path(array_folder_path,'output') ## gets array file iterator input_array_iterator = input_array_folder_path.glob(glob_parameter) output_array_iterator = output_array_folder_path.glob(glob_parameter) array_iterators = zip(input_array_iterator, output_array_iterator) ## iterate over array files for input_array_path, output_array_path in array_iterators: sample_number = split.get_number(input_array_path.name) input_array = np.load(input_array_path) output_array = np.load(output_array_path) yield sample_number, input_array, output_array def get_max_array(array_folder_path, glob_parameter = '*.npy'): ## takes a path and for all the files inside of the folder ## input and output that match glob, rescale and reshape them # create array iterator array_iterator = saved_array_iterator(array_folder_path, glob_parameter) # initialize displacemente and forces max_disp = 0 max_force = 0 updated = False ## open log file log_file = Path(array_folder_path,'log.txt') with open(log_file, 'a+') as log: log.write(f" UPDATE MAX VALUES \n") log.write(f"{'SAMPLE': <20} {'FORCE': <20} {'DISPLACEMENT': <20}\n") # iterate through all arrays updates max displacement and force for sample_number, unscaled_input_array, unscaled_output_array in array_iterator: # get sample max values max_disp_temp = max(np.abs(unscaled_input_array[:,:,1:4]).max(), np.abs(unscaled_output_array[:,:,1:4]).max()) max_force_temp = np.abs(unscaled_input_array[:,:,4:7]).max() if max_disp_temp > max_disp: max_disp = max_disp_temp updated = True if max_force_temp > max_force: max_force = max_force_temp updated = True if updated: print(f'UPDATED MAX \t sample #{sample_number} \t force: {max_force:.5f} \t disp: {max_disp:.6f} ') log.write(f'{sample_number:<20} {max_force: <20} {max_disp: <20} \n') updated = False return max_disp, max_force def create_scaled_arrays_iterator(array_folder_path, max_values, glob_parameter = '*.npy'): #takes a file path and creates all the arrays scaled between -1 and 1, and shaped # correctly for the convolutional layers # create array iterator array_iterator = saved_array_iterator(array_folder_path, glob_parameter) # get max values max_disp, max_force = max_values for sample_number, unscaled_input_array, unscaled_output_array in array_iterator: scaled_input_array = unscaled_input_array.copy() scaled_output_array = unscaled_output_array.copy() scaled_input_array[:,:,1:4] = (unscaled_input_array[:,:,1:4]/max_disp) scaled_output_array[:,:,1:4] = (unscaled_output_array[:,:,1:4]/max_disp) scaled_input_array[:,:,4:7] = (unscaled_input_array[:,:,4:7]/max_force) #first move the features axis to be the first scaled_input_array = np.moveaxis(scaled_input_array, source = 2, destination = 0) scaled_output_array = np.moveaxis(scaled_output_array, source = 2, destination = 0) #add empty dimension at beggining of array scaled_input_array = np.expand_dims(scaled_input_array, axis = 0) scaled_output_array = np.expand_dims(scaled_output_array, axis = 0) yield sample_number, scaled_input_array, scaled_output_array def get_df_dim_element_size(element_dataframe, resolution = 32): # get the max dimensions of one sample ## get ranges of data in sample range_x = [element_dataframe.loc[:,['x_loc']].max().item(), element_dataframe.loc[:,['x_loc']].min().item()] max_x = abs(range_x[0] - range_x[1]) range_y = [element_dataframe.loc[:,['y_loc']].max().item(), element_dataframe.loc[:,['y_loc']].min().item()] max_y = abs(range_y[0] - range_y[1]) range_z = [element_dataframe.loc[:,['z_loc']].max().item(), element_dataframe.loc[:,['z_loc']].min().item()] max_z = abs(range_z[0] - range_z[1]) max_dimension = max(max_x, max_y, max_z) element_size = max_dimension/resolution return max_dimension, element_size def get_unscaled_arrays_elementmax(data_folder_path, resolution = 32): ## takes the path to the folder with all samples and creates ## an iterator that goes through all of them and returns the corresponding ## array to each sample # create an iterator for all samples samples_iterator = scale.sample_iterator(data_folder_path) # create empty arrays to use in functions dimensionality = 2 input_features = 7 output_features = 4 empty_arr_input = create_array(dimensionality, input_features, resolution) empty_arr_output = create_array(dimensionality, output_features, resolution) # iterates through all samples for sample_number, input_dataframe, output_dataframe in samples_iterator: # get element size for this dataset max_dimensions, element_size = get_df_dim_element_size(input_dataframe, resolution) # translate the data translated_input_df = translate_df_elementwise(input_dataframe, max_dimensions) translated_output_df = translate_df_elementwise(output_dataframe, max_dimensions) # creates the arrays concatenated_input = create_concat_array(translated_input_df, empty_arr_input, element_size, dataframe_type='input') concatenated_output = create_concat_array(translated_output_df, empty_arr_output, element_size, dataframe_type='output') yield sample_number, concatenated_input, concatenated_output def translate_df_elementwise(sample_df, max_dimensions): ## gets a dataframe and translates the values to the correct position to place in the tensor octant = get_quadrant(sample_df) df_temp = sample_df.copy() largest_dim = max_dimensions ## general translation: translates according to the overall octant for i, direction in enumerate(octant): direction_is_negative = direction < 0 if direction_is_negative: if i == 0: df_temp.loc[:,['x_loc']] = df_temp.loc[:,['x_loc']] + largest_dim - df_temp.loc[:,['x_loc']].max().item() if i == 1: df_temp.loc[:,['y_loc']] = df_temp.loc[:,['y_loc']] + largest_dim - df_temp.loc[:,['y_loc']].max().item() if i == 2: df_temp.loc[:,['z_loc']] = df_temp.loc[:,['z_loc']] + largest_dim - df_temp.loc[:,['z_loc']].max().item() ## minor translation: if some parts of the element are still "sticking out" ## after the general translation, move it just enough to ensure that it fits inside if not(direction_is_negative): min_val = df_temp.loc[:,['x_loc','y_loc', 'z_loc']].iloc[:, i].min() if min_val < 0.0: if i == 0: df_temp.loc[:,['x_loc']] = df_temp.loc[:,['x_loc']] + abs(min_val) #print('0',min_val) if i == 1: df_temp.loc[:,['y_loc']] = df_temp.loc[:,['y_loc']] + abs(min_val) #print('1',min_val) if i == 2: df_temp.loc[:,['z_loc']] = df_temp.loc[:,['z_loc']] + abs(min_val) #print('2',min_val) return df_temp print('formatting functions imported')<file_sep>/2D/v3_test/save_mesh_separate.py # encoding: utf-8 # 2020 R1 SetScriptVersion(Version="20.1.164") system1 = GetSystem(Name="SYS") model1 = system1.GetContainer(ComponentName="Model") simulationMeshProperties1 = model1.GetMeshProperties() simulationMeshProperties1.saveMeshFileInSeparateFile = True <file_sep>/2D/v11_test/LOADS_generate.py import random import itertools ## Load-in the body part = Model.Geometry.Children[0] #Get first "geometry" body = part.Children[0] #Get first body geobody = body.GetGeoBody() #selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities) # Create an empty selection. ## Delete previously assigned forces analysis = Model.Analyses[0] for force in analysis.GetChildren(DataModelObjectCategory.NodalForce, False): force.Delete() ## Assign Material part.Material = 'Structural Steel' forces = [] ## set parameters number_created = 5 ## can't find a way to trasmit this between scripts number_selections = len(Model.NamedSelections.Children)//number_created number_displacements = len(analysis.GetChildren(DataModelObjectCategory.NodalDisplacement, False))//number_created number_forces = number_selections - number_displacements named_selections = [] number_rows = number_created number_columns = number_forces + number_displacements for i in range(number_columns): selec_temp = [] for j in range(number_rows): selec_temp.append(Model.NamedSelections.Children[i*number_rows+j]) named_selections.append(selec_temp) for i in range(number_displacements, number_displacements + number_forces): #iterates displacement nodal selections for j in range(number_created): selection = named_selections[i][j] forces.append(analysis.AddNodalForce()) #creates displacement and store in list forces[-1].Location = selection #applies to named selection ## set values for displacements components = [] for ii in range(3): #create list of Quantities for displacements components.append(Quantity(random.gauss(0,100).ToString() + '[N]')) ## displacements for both 3d and 2d cases try: forces[-1].XComponent.Output.DiscreteValues = [components[0]] forces[-1].YComponent.Output.DiscreteValues = [components[1]] Is_3D = False for vertex in geobody.Vertices: #check if problem is 2d or 3d if vertex.Z != 0: Is_3D = True break if Is_3D: #displacement for 3d case forces[-1].ZComponent.Output.DiscreteValues = [components[2]] else: forces[-1].ZComponent.Output.DiscreteValues = [Quantity['0 [N]']] except IndexError: pass <file_sep>/2D/v12_test/SETUP_all.py # encoding: utf-8 # 2020 R1 ## Create Geometry SetScriptVersion(Version="20.1.164") system1 = GetSystem(Name="SYS") geometry1 = system1.GetContainer(ComponentName="Geometry") DSscript = open("D:/Ansys Simulations/Project/2D/v11_test/GEOMETRY_generate.py", "r") DSscriptcommand=DSscript.read() geometry1.SendCommand(Command=DSscriptcommand,Language="Python") geometry1.Edit(IsSpaceClaimGeometry=True) #geometry1.Exit() ## Open Mechanical modelComponent1 = system1.GetComponent(Name="Model") modelComponent1.Refresh() model1 = system1.GetContainer(ComponentName="Model") model1.Edit() ## Create Mesh DSscript = open("D:/Ansys Simulations/Project/2D/v11_test/MESH_generate.py", "r") DSscriptcommand=DSscript.read() model1.SendCommand(Command=DSscriptcommand,Language="Python") ## Create Named Selections DSscript = open("D:/Ansys Simulations/Project/2D/v11_test/NAMED_SELECTIONS_generate.py", "r") DSscriptcommand=DSscript.read() model1.SendCommand(Command=DSscriptcommand,Language="Python") ## Create Displacements DSscript = open("D:/Ansys Simulations/Project/2D/v11_test/DISPLACEMENTS_generate.py", "r") DSscriptcommand=DSscript.read() model1.SendCommand(Command=DSscriptcommand,Language="Python") ## Create Loads DSscript = open("D:/Ansys Simulations/Project/2D/v11_test/LOADS_generate.py", "r") DSscriptcommand=DSscript.read() model1.SendCommand(Command=DSscriptcommand,Language="Python")<file_sep>/2D/v12_test/change_2D.py # encoding: utf-8 # 2020 R1 SetScriptVersion(Version="20.1.164") system1 = GetSystem(Name="SYS") geometry1 = system1.GetContainer(ComponentName="Geometry") geometryProperties1 = geometry1.GetGeometryProperties() geometryProperties1.GeometryImportAnalysisType = "AnalysisType_2D" <file_sep>/2D/v13_test/SAVED_FILES_generate.py import os ## Creates solutions and exports them ## Load-in the body part = Model.Geometry.Children[0] #Get first "geometry" body = part.Children[0] #Get first body geobody = body.GetGeoBody() #selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities) # Create an empty selection. analysis = Model.Analyses[0] solution = analysis.Solution number_udr = len(solution.GetChildren(DataModelObjectCategory.UserDefinedResult, False)) if number_udr < 1: solution.AddUserDefinedResult() number_udr = len(solution.GetChildren(DataModelObjectCategory.UserDefinedResult, False)) udr = solution.Children[number_udr] udr.Expression = 'UVECTORS' ## ## Solves the model Model.Solve() ## Create folders to store solutions sample_number=1 folder_name = "data_dir_" directory = folder_name + sample_number.ToString() parent_dir = "D:\\Ansys Simulations\\Project\\2D\\data\\v12_test" try: os.mkdir(parent_dir) except: pass path = os.path.join(parent_dir, directory) ## Update Sample Number for root, dirs, files in os.walk(path+"\\.."): for sample_dir in dirs: if (folder_name in sample_dir): sample_number += 1 directory = folder_name + sample_number.ToString() path = os.path.join(parent_dir, directory) ## Create log file log_file = "log.txt" log_file_path = os.path.join(path + '\\..', log_file) log_file_created = False for root, dirs, files in os.walk(path+"\\.."): for file in files: if log_file in file: log_file_created = True if not(log_file_created): f_log= open(log_file_path ,"w+") row = ['SAMPLE',"ACTION","PATH"] f_log.write("{: <20} {: <20} {: <20}\n".format(*row)) f_log.close() f_log= open(log_file_path ,"a+") try: os.mkdir(path) row = [sample_number.ToString(),"CREATE", path] f_log.write("{: <20} {: <20} {: <20}\n".format(*row)) f_log.close() except: row = [sample_number.ToString(),"OVERWRITE", path] f_log.write("{: <20} {: <20} {: <20}\n".format(*row)) f_log.close() ##Create files in this directory to store displacements and forces filename = "disp_test_"+ sample_number.ToString() +".txt" file_path = os.path.join(path, filename) f_disp= open(file_path ,"w+") filename = "force_test_"+ sample_number.ToString() +".txt" file_path = os.path.join(path, filename) f_force= open(file_path ,"w+") ##Create List With relevant Boundary Conditions boundary_conditions = [] for item in analysis.GetChildren(DataModelObjectCategory.NodalDisplacement, False): boundary_conditions.append(item) for item in analysis.GetChildren(DataModelObjectCategory.NodalForce, False): boundary_conditions.append(item) ##Write BCs in file for bc in boundary_conditions: x = bc.XComponent.Output.DiscreteValues[0].Value y = bc.YComponent.Output.DiscreteValues[0].Value z = bc.ZComponent.Output.DiscreteValues[0].Value unit = bc.XComponent.Output.DiscreteValues[0].Unit if bc.DataModelObjectCategory == DataModelObjectCategory.NodalDisplacement: line = bc.Location.Name +"\t" + "["+unit+"]" +"\t" + x.ToString()+"\t" + y.ToString()+"\t" + z.ToString() f_disp.write( line + "\n") if bc.DataModelObjectCategory == DataModelObjectCategory.NodalForce: line = bc.Location.Name +"\t" + "["+unit+"]" +"\t" + x.ToString()+"\t" + y.ToString()+"\t" + z.ToString() f_force.write( line + "\n") ## Close files f_disp.close() f_force.close() ## Export Solution to another file filename = "solutions_test_"+ sample_number.ToString() +".txt" file_path = os.path.join(path, filename) udr.ExportToTextFile(file_path) ## Export Named Selections for i, ns in enumerate(Model.NamedSelections.Children): filename = "named_selection_test_"+ (i+1).ToString() +".txt" file_path = os.path.join(path, filename) ns.ExportToTextFile(file_path) <file_sep>/2D/v4_test/open_model_and_mesh.wbjn # encoding: utf-8 # 2020 R1 SetScriptVersion(Version="20.1.164") system1 = GetSystem(Name="SYS") modelComponent1 = system1.GetComponent(Name="Model") modelComponent1.Refresh() model1 = system1.GetContainer(ComponentName="Model") model1.Edit() <file_sep>/2D/preprocessing/wandb/run-20200616_011538-3ehj45xt/requirements.txt apptools==4.4.0 attrs==19.3.0 backcall==0.1.0 bleach==3.1.4 certifi==2020.4.5.1 cffi==1.14.0 chardet==3.0.4 click==7.1.2 colorama==0.4.3 configobj==5.0.6 configparser==5.0.0 cycler==0.10.0 decorator==4.4.2 defusedxml==0.6.0 docker-pycreds==0.4.0 docker==4.2.1 entrypoints==0.3 envisage==4.8.0 future==0.18.2 gitdb==4.0.5 gitpython==3.1.3 gql==0.2.0 graphql-core==1.1 idna==2.9 importlib-metadata==1.6.0 ipyevents==0.7.1 ipykernel==5.1.4 ipython-genutils==0.2.0 ipython==7.13.0 ipywidgets==7.5.1 jedi==0.17.0 jinja2==2.11.2 jsonschema==3.2.0 jupyter-client==6.1.3 jupyter-console==6.1.0 jupyter-core==4.6.3 jupyter==1.0.0 kiwisolver==1.2.0 markupsafe==1.1.1 matplotlib==3.1.3 mayavi==4.7.1 mistune==0.8.4 mkl-fft==1.0.15 mkl-random==1.1.1 mkl-service==2.3.0 nbconvert==5.6.1 nbformat==5.0.6 notebook==6.0.3 numpy==1.18.1 nvidia-ml-py3==7.352.0 olefile==0.46 pandas==1.0.3 pandocfilters==1.4.2 parso==0.7.0 pathtools==0.1.2 pickleshare==0.7.5 pillow==7.1.2 pint==0.12 pip==20.0.2 prometheus-client==0.7.1 promise==2.3 prompt-toolkit==3.0.4 psutil==5.7.0 pycparser==2.20 pyface==6.1.2 pygments==2.6.1 pyparsing==2.4.7 pypiwin32==223 pyrsistent==0.16.0 python-dateutil==2.8.1 pytz==2020.1 pywin32==227 pywinpty==0.5.7 pyyaml==5.3.1 pyzmq==18.1.1 qtconsole==4.7.4 qtpy==1.9.0 requests==2.23.0 send2trash==1.5.0 sentry-sdk==0.14.4 setuptools==46.4.0.post20200518 shortuuid==1.0.1 six==1.14.0 smmap==3.0.4 sortedcontainers==2.1.0 subprocess32==3.5.4 terminado==0.8.3 testpath==0.4.4 torch==1.5.0 torchvision==0.6.0 tornado==6.0.4 traitlets==4.3.3 traits==5.2.0 traitsui==6.1.3 urllib3==1.25.9 vtk==-PKG-VERSION wandb==0.9.1 watchdog==0.10.2 wcwidth==0.1.9 webencodings==0.5.1 websocket-client==0.57.0 wheel==0.34.2 widgetsnbextension==3.5.1 wincertstore==0.2 zipp==3.1.0<file_sep>/2D/v5_test/DISPLACEMENTS_generate.py import random import itertools import time ## Load-in the body part = Model.Geometry.Children[0] #Get first "geometry" body = part.Children[0].GetGeoBody() #Get geometrical entities of first body selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities) # Create an empty selection. ## General Analysis Settings settings = Model.Analyses[0].AnalysisSettings settings.LargeDeflection = True settings.WeakSprings = WeakSpringsType.ProgramControlled settings.StoreResultsAt = TimePointsOptions.LastTimePoints ## Create vector to choose vertices n_vertices = len(body.Vertices) displaced_vertices = random.choice(range(0, n_vertices+1)) #number of vertices w/ a boundary displacement condition choose_vertices = [] vert_chosen = [True] * displaced_vertices vert_not_chosen = [False] * (n_vertices-displaced_vertices) choose_vertices = vert_chosen + vert_not_chosen random.shuffle(choose_vertices) #shuffles the list to not always choose the first vertices ## Delete conditions from previous analysis analysis = Model.Analyses[0] for disp in analysis.GetChildren(DataModelObjectCategory.Displacement, False): disp.Delete() for fixed in analysis.GetChildren(DataModelObjectCategory.FixedSupport, False): fixed.Delete() ## Set displacement locations & values displacements = [] for i, vertex in enumerate(body.Vertices): #iterates vertices if choose_vertices[i]: #chooses correct vertices selection.Entities = [vertex] displacements.append(analysis.AddDisplacement()) #creates displacement and store in list displacements[-1].Location = selection #applies to vertex ## set values for displacements components = [] for j in range(3): #create list of strings for displacements components.append(Quantity(random.gauss(0,0.01).ToString() + '[in]')) ## displacements for both 3d and 2d cases try: displacements[-1].XComponent.Output.DiscreteValues = [components[0]] displacements[-1].YComponent.Output.DiscreteValues = [components[1]] Is_3D = False for vertex in body.Vertices: #check if problem is 2d or 3d if vertex.Z != 0: Is_3D = True break if Is_3D: #displacement for 3d case displacements[-1].ZComponent.Output.DiscreteValues = [components[2]] else: displacements[-1].ZComponent.Output.DiscreteValues = [Quantity['0 [in]']] except IndexError: pass ## Handling case of no vertex diplacements if not any(choose_vertices): fixed = [] while not any(choose_vertices): #while choose vertices has no True values for i, vertex in enumerate(choose_vertices): choose_vertices[i] = (random.random()<0.5) for i, vertex in enumerate(body.Vertices): if choose_vertices[i]: selection.Entities = [vertex] fixed.append(analysis.AddFixedSupport()) fixed[-1].Location = selection <file_sep>/2D/v12_test/DISPLACEMENTS_generate.py import random import itertools import time part = Model.Geometry.Children[0] #Get first "geometry" body = part.Children[0] #Get first body geobody = body.GetGeoBody() #selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities) # Create an empty selection. ## Delete conditions from previous analysis analysis = Model.Analyses[0] for disp in analysis.GetChildren(DataModelObjectCategory.NodalDisplacement, False): disp.Delete() ## General Analysis Settings settings = Model.Analyses[0].AnalysisSettings settings.LargeDeflection = False settings.WeakSprings = WeakSpringsType.ProgramControlled settings.StoreResultsAt = TimePointsOptions.LastTimePoints ## Create vector with all selections divided by curve named_selections = [] number_created = 3 ## can't find a way to trasmit this between scripts number_selections = len(Model.NamedSelections.Children)//number_created number_displacements = random.choice(range(1,number_selections+1)) number_forces = number_selections - number_displacements number_rows = number_created number_columns = number_forces + number_displacements for i in range(number_columns): selec_temp = [] for j in range(number_rows): selec_temp.append(Model.NamedSelections.Children[i*number_rows+j]) named_selections.append(selec_temp) ## Set displacement locations & values displacements = [] for i in range(number_displacements): #iterates displacement nodal selections for j in range(number_created): selection = named_selections[i][j] displacements.append(analysis.AddNodalDisplacement()) #creates displacement and store in list displacements[-1].Location = selection #applies to named selection ## set values for displacements components = [] for j in range(3): #create list of Quantities for displacements components.append(Quantity(random.gauss(0,0.001).ToString() + '[m]')) ## displacements for both 3d and 2d cases try: displacements[-1].XComponent.Output.DiscreteValues = [components[0]] displacements[-1].YComponent.Output.DiscreteValues = [components[1]] Is_3D = False for vertex in geobody.Vertices: #check if problem is 2d or 3d if vertex.Z != 0: Is_3D = True break if Is_3D: #displacement for 3d case displacements[-1].ZComponent.Output.DiscreteValues = [components[2]] else: displacements[-1].ZComponent.Output.DiscreteValues = [Quantity('0 [in]')] except IndexError: pass <file_sep>/2D/v4_test/generate_mesh_working_set_method.py part1 = Model.Geometry.Children[0] # Get the first part. body1 = part1.Children[0] # Get the first body. body = body1.GetGeoBody() # Cast to Geobody selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities) # Create an empty selection. selection.Entities = [body] # Add the body to the selection. ## deletes previous mesh # note: [0] because deleting moves the list up try: for i in range(len(Model.Mesh.Children)): Model.Mesh.Children[0].Delete() except: pass mesh_method = Model.Mesh.AddAutomaticMethod() # Adds the automatic method mesh_method.Location = selection #Properties mesh_method.Method = MethodType.HexDominant mesh_method.ElementOrder = ElementOrder.Quadratic # General Mesh Settings mesh = Model.Mesh mesh.Resolution = 4 # Corner node refinement vertex_size = [] for i, corner in enumerate(body.Vertices): selection = corner vertex_size.append(Model.Mesh.AddSizing()) #Generate Mesh Model.Mesh.GenerateMesh() #gets body #elementID = geometry.Children[0].ObjectId #ElementSel = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities) #ElementSel = elementID #mesh_method = Model.AddMeshEdit. # #if len(Model.NamedSelections.Children)>4: # pass #"""The following example creates a pressure on the first face of the first body for the first part.""" #pressure = Model.Analyses[0].AddPressure() # Add a pressure. #part1 = Model.Geometry.Children[0] # Get the first part. #body1 = part1.Children[0] # Get the first body. #face1 = body1.GetGeoBody().Faces[0] # Get the first face of the body. #selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities) # Create an empty selection. #selection.Entities = [face1] # Add the face to the selection. #pressure.Location = selection # Assign the selection to the pressure. #pressure.Magnitude.Inputs[0].DiscreteValues = [Quantity("0 [s]"), Quantity("1 [s]")] # Set the time values. #pressure.Magnitude.Output.DiscreteValues = [Quantity("10 [Pa]"), Quantity("20 [Pa]")] # Set the magnitudes. <file_sep>/2D/v6_test/LOADS_generate.py import random import itertools ## Load-in the body part = Model.Geometry.Children[0] #Get first "geometry" body = part.Children[0].GetGeoBody() #Get geometrical entities of first body selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities) # Create an empty selection. ## Delete previously assigned forces analysis = Model.Analyses[0] for force in analysis.GetChildren(DataModelObjectCategory.Force, False): force.Delete() for body_force in analysis.GetChildren(DataModelObjectCategory.Acceleration, False): body_force.Delete() ## Assign Material part.Material = 'Structural Steel' ## Create vector to chose edges n_edges = len(body.Edges) n_loaded_edges = random.choice(range(0, n_edges+1)) #number of vertices w/ a boundary displacement condition choose_edges = [] edge_chosen = [True] * n_loaded_edges edge_not_chosen = [False] * (n_edges-n_loaded_edges) choose_edges = edge_chosen + edge_not_chosen random.shuffle(choose_edges) #shuffles the list to not always choose the first vertices ## Create vector to choose vertices n_vertices = len(body.Vertices) n_loaded_vertices = random.choice(range(0, n_vertices+1)) #number of vertices w/ a boundary displacement condition choose_vertices = [] vertices_chosen = [True] * n_loaded_vertices vertices_not_chosen = [False] * (n_vertices-n_loaded_vertices) choose_vertices = vertices_chosen + vertices_not_chosen random.shuffle(choose_vertices) #shuffles the list to not always choose the first vertices forces = [] for i, edge in enumerate(body.Edges): # forces on edges selection.Entities = [edge] if choose_edges[i]: forces.append(analysis.AddForce()) forces[-1].Location = selection # create forces force_magnitudes = [random.gauss(0,100), random.gauss(0,100), random.gauss(0,100)] forces[-1].DefineBy = LoadDefineBy.Components forces[-1].XComponent.Output.DiscreteValues = [Quantity(force_magnitudes[0].ToString() + '[N]')] forces[-1].YComponent.Output.DiscreteValues = [Quantity(force_magnitudes[1].ToString() + '[N]')] Is_3D= False for vertex in body.Vertices: #check if problem is 2d or 3d if vertex.Z != 0: Is_3D = True break if Is_3D: forces[-1].ZComponent.Output.DiscreteValues = [Quantity(force_magnitudes[2].ToString() + '[N]')] else: forces[-1].ZComponent.Output.DiscreteValues = [Quantity('0 [N]')] for i, vertex in enumerate(body.Vertices): selection.Entities = [vertex] if choose_vertices[i]: forces.append(analysis.AddForce()) forces[-1].Location = selection # create forces force_magnitudes = [random.gauss(0,100), random.gauss(0,100), random.gauss(0,100)] forces[-1].DefineBy = LoadDefineBy.Components forces[-1].XComponent.Output.DiscreteValues = [Quantity(force_magnitudes[0].ToString() + '[N]')] forces[-1].YComponent.Output.DiscreteValues = [Quantity(force_magnitudes[1].ToString() + '[N]')] Is_3D= False for vertex in body.Vertices: #check if problem is 2d or 3d if vertex.Z != 0: Is_3D = True break if Is_3D: forces[-1].ZComponent.Output.DiscreteValues = [Quantity(force_magnitudes[2].ToString() + '[N]')] else: forces[-1].ZComponent.Output.DiscreteValues = [Quantity('0 [N]')] # apply body force selection.Entities = [body] forces.append(analysis.AddAcceleration()) force_magnitudes = [random.gauss(0,300), random.gauss(0,300), random.gauss(0,300)] forces[-1].DefineBy = LoadDefineBy.Components forces[-1].XComponent.Output.DiscreteValues = [Quantity(force_magnitudes[0].ToString() + '[in s^-2]')] forces[-1].YComponent.Output.DiscreteValues = [Quantity(force_magnitudes[1].ToString() + '[in s^-2]')] Is_3D= False for vertex in body.Vertices: #check if problem is 2d or 3d if vertex.Z != 0: Is_3D = True break if Is_3D: forces[-1].ZComponent.Output.DiscreteValues = [Quantity(force_magnitudes[2].ToString() + '[in s^-2]')] else: forces[-1].ZComponent.Output.DiscreteValues = [Quantity('0 [in s^-2]')] <file_sep>/2D/v3_test/generate_random_triangular_element.py # Python Script, API Version = V18 import random import math from itertools import combinations from System import Random n_points = 4 n_dimensions = 3 points = [] curves = List[ITrimmedCurve]() for i in range(n_points): # creates all points points_temp = [0,0,0] for j in range(n_dimensions): if (j<=1 or i>2) and i>0: points_temp[j] = random.random() #random.jumpahead #scrambles the generated numbers to reduce correlation # print(random.getstate) points.append(points_temp) # Delete Selection try: selection = Selection.Create(GetRootPart().Bodies[:]) result = Delete.Execute(selection) except: pass # EndBlock for iter, x in enumerate(combinations(points, 3)): #iterates through all combinations of 3 #print(iter) #curves = List[ITrimmedCurve]() for i in range(len(x)): #iterates through points to create curves if i<2: #SketchPoint.Create(Point.Create(*x[i])) curveSegment = CurveSegment.Create(Point.Create(*x[i]), Point.Create(*x[i+1])) curves.Add(curveSegment) elif i==2: #SketchPoint.Create(Point.Create(*x[i])) curveSegment = CurveSegment.Create(Point.Create(*x[i]), Point.Create(*x[0])) curves.Add(curveSegment) else: #print("else") SketchPoint.Create(Point.Create(MM(x[i][0]),MM(x[i][1]),MM(x[i][2]))) #Create Perpendicular Vector direc = [] for ii in range(1,3): # print(x) # print(x[ii]) direc_temp = [0,0,0] for jj, coord in enumerate(x[ii]): #print(ii) direc_temp[jj]= x[0][jj] - coord direc.append(direc_temp) a = Vector.Create(*direc[0]) b = Vector.Create(*direc[1]) perp_vec = Vector.Cross(a, b) #Create frame with perpendicular vector p = Point.Create(*x[0]) frame = Frame.Create(p, perp_vec.Direction) #print(perp_vec.Direction) #print(x) if iter==0: plane = Plane.PlaneXY else: plane = Plane.Create(frame) designResult = PlanarBody.Create(plane, curves) #creates the curve designBody = designResult.CreatedBody if n_points >= 4: selec =[] for surf in GetRootPart().Bodies[:]: #transforms array of surfaces into list of surfaces selec.append(surf) targets = Selection.Create(*selec) #merges them result = Combine.Merge(targets) # EndBlock # Rename 'temp 1' to 'Body' selection = Selection.Create(GetRootPart().Bodies[0]) result = RenameObject.Execute(selection,"Body") # EndBlock #ViewHelper.ZoomToEntity() # Solidify Sketch #mode = InteractionMode.Solid #result = ViewHelper.SetViewMode(mode, None) # EndBlock <file_sep>/2D/v7_test/DISPLACEMENTS_generate.py import random import itertools import time ## Load-in the body part = Model.Geometry.Children[0] #Get first "geometry" body = part.Children[0].GetGeoBody() #Get geometrical entities of first body selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities) # Create an empty selection. ## General Analysis Settings settings = Model.Analyses[0].AnalysisSettings settings.LargeDeflection = True settings.WeakSprings = WeakSpringsType.ProgramControlled settings.StoreResultsAt = TimePointsOptions.LastTimePoints ## Create vector to choose edges n_edges = len(body.Edges) displaced_edges = random.choice(range(0, n_edges+1)) #number of vertices w/ a boundary displacement condition choose_edges = [] edge_chosen = [True] * displaced_edges edge_not_chosen = [False] * (n_edges-displaced_edges) choose_edges = edge_chosen + edge_not_chosen random.shuffle(choose_edges) #shuffles the list to not always choose the first edges ## Delete conditions from previous analysis analysis = Model.Analyses[0] for disp in analysis.GetChildren(DataModelObjectCategory.Displacement, False): disp.Delete() for fixed in analysis.GetChildren(DataModelObjectCategory.FixedSupport, False): fixed.Delete() ## Set displacement locations & values displacements = [] for i, edge in enumerate(body.Edges): #iterates vertices if choose_edges[i]: #chooses correct vertices selection.Entities = [edge] displacements.append(analysis.AddDisplacement()) #creates displacement and store in list displacements[-1].Location = selection #applies to vertex ## set values for displacements components = [] for j in range(3): #create list of strings for displacements components.append(Quantity(random.gauss(0,0.01).ToString() + '[in]')) ## displacements for both 3d and 2d cases try: displacements[-1].XComponent.Output.DiscreteValues = [components[0]] displacements[-1].YComponent.Output.DiscreteValues = [components[1]] Is_3D = False for vertex in body.Vertices: #check if problem is 2d or 3d if vertex.Z != 0: Is_3D = True break if Is_3D: #displacement for 3d case displacements[-1].ZComponent.Output.DiscreteValues = [components[2]] else: displacements[-1].ZComponent.Output.DiscreteValues = [Quantity['0 [in]']] except IndexError: pass ## Handling case of no vertex diplacements if not any(choose_edges): fixed = [] while not any(choose_edges): #while choose vertices has no True values for i, edge in enumerate(choose_edges): choose_edges[i] = (random.random()<0.5) for i, edge in enumerate(body.Edges): if choose_edges[i]: selection.Entities = [edge] fixed.append(analysis.AddFixedSupport()) fixed[-1].Location = selection <file_sep>/2D/v3_test/test_delete_create.py # encoding: utf-8 # 2020 R1 SetScriptVersion(Version="20.1.164") system1 = GetSystem(Name="SYS") # system1.Delete() # template1 = GetTemplate( # TemplateName="Static Structural", # Solver="ANSYS") # system2 = template1.CreateSystem() # OPEN GEOMETRY #geometryComponent1 = system2.GetComponent(Name="Geometry") #geometryComponent1.Update(AllDependencies=True) geometry1 = system1.GetContainer(ComponentName="Geometry") geometry1.Edit(IsSpaceClaimGeometry=True) # LOAD SCRIPT DSscript = open("D:/Ansys Simulations/Project/2D/v3_test/generate_random_triangular_element.py", "r") DSscriptcommand=DSscript.read() #RUN SCRIPT for i in range(8): geometry1.SendCommand(Command=DSscriptcommand,Language="Python") #geometry1.Edit(IsSpaceClaimGeometry=True) #Close #geometry1.Exit()<file_sep>/2D/v9_test/SAVED_FILES_generate.py ## Creates solutions and exports them ## Load-in the body part = Model.Geometry.Children[0] #Get first "geometry" body = part.Children[0] #Get first body geobody = body.GetGeoBody() #selection = ExtAPI.SelectionManager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities) # Create an empty selection. ## Delete previously assigned forces analysis = Model.Analyses[0] solution = analysis.Solution """ number_directional_deformations = len(solution.GetChildren(DataModelObjectCategory.DirectionalDeformation, False)) while number_directional_deformations != 3: number_directional_deformations =len(solution.GetChildren(DataModelObjectCategory.DirectionalDeformation, False)) if number_directional_deformations < 3: solution.AddDirectionalDeformation() if number_directional_deformations > 3: solution.Children[number_directional_deformations].Delete() ## Set Directions deformationX = solution.Children[1] deformationY = solution.Children[2] deformationZ = solution.Children[3] deformationX.NormalOrientation = NormalOrientationType.XAxis deformationY.NormalOrientation = NormalOrientationType.YAxis deformationZ.NormalOrientation = NormalOrientationType.ZAxis """ number_udr = len(solution.GetChildren(DataModelObjectCategory.UserDefinedResult, False)) if number_udr < 1: solution.AddUserDefinedResult() number_udr = len(solution.GetChildren(DataModelObjectCategory.UserDefinedResult, False)) udr = solution.Children[number_udr] udr.Expression = 'UVECTORS' ## """ nodal.XComponent.Output.DiscreteValues[0].Value """ ## Solves the model Model.Solve() <file_sep>/2D/v6_test/MESH_error_handling.py #helper file to handle if mesh can't be generated with hexa components mesh_method.Method = MethodType.Automatic Model.Mesh.GenerateMesh() <file_sep>/2D/v7_test/NAMED_SELECTIONS_generate.py import math import random ## Script to generate named selections for forces and displacements ##Delete Previous named selection and coordinate systems try: for named_selection in Model.NamedSelections.Children: named_selection.Delete() for i, coord_system in enumerate(Model.CoordinateSystems.Children): if i > 0: #to avoid global coord system coord_system.Delete() except: pass ## Gets bounding box part = Model.Geometry.Children[0] body = part.Children[0] geobody = body.GetGeoBody() x1,y1,z1,x2,y2,z2 = geobody.GetBoundingBox() # [x1 y1 z1 x2 y2 z2] coordinates of the bounding box, lower to higher #x1,y1,z1,x2,y2,z2 = x1*39.3701,y1*39.3701,z1*39.3701,x2*39.3701,y2*39.3701,z2 *39.3701 ##Create coord system at centroid for testing """ Model.CoordinateSystems.AddCoordinateSystem() centroid = Model.CoordinateSystems.Children[1] centroid.OriginX = Quantity(geobody.Centroid[0].ToString() + '[m]') centroid.OriginY = Quantity(geobody.Centroid[1].ToString() + '[m]') centroid.OriginZ = Quantity(geobody.Centroid[2].ToString() + '[m]') """ number_forces = random.choice(range(3)) number_displacements = random.choice(range(1,3)) number_of_curves = number_forces + number_displacements for curve in range(number_of_curves): ## Choose one of the vertices as a starting point vertex_choice = random.choice(range(len(geobody.Vertices))) vertex = geobody.Vertices[vertex_choice] vertX = vertex.X vertY = vertex.Y vertZ = vertex.Z ##Create coordinate systems with biased brownian motion number_created = 5 bias_control = 5 for i in range(number_created): number_coord = len(Model.CoordinateSystems.Children) Model.CoordinateSystems.AddCoordinateSystem() cs = Model.CoordinateSystems.Children[number_coord] #last coordinate system if i==0: ## creates initial point close to a vertex but dislocated randomly within an elliptical radius based on the bounding box cs.OriginX = Quantity(random.uniform(x1,x2).ToString() + '[m]')/bias_control + Quantity(vertX.ToString() + '[m]') cs.OriginY = Quantity(random.uniform(y1,y2).ToString() + '[m]')/bias_control + Quantity(vertY.ToString() + '[m]') cs.OriginZ = Quantity(random.uniform(z1,z2).ToString() + '[m]')/bias_control + Quantity(vertZ.ToString() + '[m]') X = cs.OriginX Y = cs.OriginY Z = cs.OriginZ # print(X, Y, Z) ## create a random bias toward the centroid for the random movement p_x = -(X - Quantity(geobody.Centroid[0].ToString() + '[m]')) p_y = -(Y - Quantity(geobody.Centroid[1].ToString() + '[m]')) p_z = -(Z - Quantity(geobody.Centroid[2].ToString() + '[m]')) dir_rand = 1.7 p_direction = [p_x + dir_rand*Quantity(random.uniform(0,p_x.Value).ToString() + '[m]'), p_y + dir_rand*Quantity(random.uniform(0,p_y.Value).ToString() + '[m]'), p_z] ##scale it to be a unit vector p_abs = math.sqrt(p_direction[0].Value**2 + p_direction[1].Value**2 + p_direction[2].Value**2) p_direction = [p_direction[0]/p_abs, p_direction[1]/p_abs,p_direction[2]/p_abs,] #make sure the bias approaches the element initially dist_centr_initial = math.sqrt((X.Value-geobody.Centroid[0])**2 + (Y.Value-geobody.Centroid[1])**2 + (Z.Value-geobody.Centroid[2])**2) dist_centr_final = math.sqrt((X.Value+p_direction[0].Value/number_created-geobody.Centroid[0])**2 + (Y.Value+p_direction[1].Value/number_created-geobody.Centroid[1])**2 + (Z.Value+p_direction[2].Value/number_created-geobody.Centroid[2])**2) if dist_centr_initial < dist_centr_final: for i, direction in enumerate(p_direction): p_direction[i] = p_direction[i]*(-1) #print('entered') else: rand_control = 5 distance_control = 17 X += (Quantity(random.uniform(0,p_direction[0].Value).ToString() + '[m]')*rand_control + p_direction[0]/bias_control)/distance_control Y += (Quantity(random.uniform(0,p_direction[1].Value).ToString() + '[m]')*rand_control + p_direction[1]/bias_control)/distance_control Z += (Quantity(random.uniform(0,p_direction[2].Value).ToString() + '[m]')*rand_control + p_direction[2]/bias_control)/distance_control cs.OriginX = X cs.OriginY = Y cs.OriginZ = Z ## creates a criterion object and stores it criterion = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion #Criterion Options: active: bool, actionType: SelectionActionType, #entityType: SelectionType, criterionType: SelectionCriterionType, #operatorType: SelectionOperatorType, value: object, #lowerBound: Quantity, upperBound: Quantity, #coordinateSystem: CoordinateSystem ##Choose Number of forces ##Choose number of displacements ##Creates named selections number_of_selections = number_created #makes the number of selections for this step the same as the number of coordinate systems created for i in range(number_of_selections): try: num_previous_selections = len(Model.NamedSelections.Children) except: num_previous_selections = 0 Model.AddNamedSelection() #Adds a named selection number_of_ns = len( Model.NamedSelections.Children) ns = Model.NamedSelections.Children[number_of_ns-1] #creates a temporary variable to store it ns.ScopingMethod = GeometryDefineByType.Worksheet #changes the scoping method to be worksheet number_of_criteria = num_previous_selections+1 number_coordinates = len(Model.CoordinateSystems.Children) for ii in range(number_of_criteria): ns.GenerationCriteria.Add(criterion()) ##creates new empty selection criterion ns.GenerationCriteria[ii].EntityType = SelectionType.MeshNode ns.GenerationCriteria[ii].CoordinateSystem = Model.CoordinateSystems.Children[number_coordinates-number_created+i] if ii == 0: ns.GenerationCriteria[ii].Action = SelectionActionType.Add ns.GenerationCriteria[ii].Criterion = SelectionCriterionType.Distance ns.GenerationCriteria[ii].Operator = SelectionOperatorType.LessThanOrEqual ns.GenerationCriteria[ii].Value = Quantity('0.12 [m]') else: ns.GenerationCriteria[ii].Action = SelectionActionType.Filter ns.GenerationCriteria[ii].Criterion = SelectionCriterionType.NamedSelection ns.GenerationCriteria[ii].Operator = SelectionOperatorType.NotEqual ns.GenerationCriteria[ii].Value = Model.NamedSelections.Children[ii-1] ns.Generate() size_increase = 1.3 for j, selection in enumerate(Model.NamedSelections.Children): selec = Model.NamedSelections.Children[j] while selec.TotalSelection == 0: selec.GenerationCriteria[0].Value = selec.GenerationCriteria[0].Value*size_increase selec.Generate() <file_sep>/2D/preprocessing/README.md # README This folder contains the scripts and notebooks used for preprocessing the data. They are all labelled `PREPROCESSING_<action>`. They act as helper modules to process the data when called from a notebook or command line. ## _splitting This module's intent is to get the raw data output from ANSYS and format it into .csv files named `input_<number>`, corresponding to boundary conditions of the sample `<number>` and `output_<number>`, corresponding to the solution displacement data from sample `<number>`. #### .get_number(_str filename_) This function takes a string and extracts the first contiguous integer in it, returning it as a string. It uses a regular expression to do so. If it doesn't find a number, it returns the string `no number found`. #### .get_named_selections(_Path sample_path_) This function takes a `pathlib.Path` object and returns a `list` containing all the files that correspond to `glob("named_selection_*.txt")` `sample_path` is expected to be the path to the folder of of the sample. #### .create_filename(_Path sample_path_) This function takes a `pathlib.Path` object and returns two `pathlib.Path` objects `input_filename, output_filename ` of the format `<input>/<output>_<number>.csv` `sample_path` is expected to be the path to the folder of of the sample. #### .bc_files_to_df(_Path sample_folder_) This function takes a `pathlib.Path` object and three `pandas.Dataframe` objects `solutions_data, disp_bc_data, force_bc_data` of the format with column headers `named_selection, unit,x_<disp>/<force>,y_<disp>/<force>,<disp>/<force>`. `sample_folder` is expected to be the path to the folder of of the sample. It is exactly the same as `sample_path` in the other functions. #### .selection_index(_str selection, pandas.Dataframe data_) This function takes the arguments above, and runs through all the `data.named_selection` entries, comparing them to `selection`. Whenever it finds one that is exactly equal, it returns the row index of that entry on the dataframe. #### .update_selection(_Path sample_folder, pandas.Dataframe disp_data, pandas.Dataframe force_data_) This is a generator function that, given the arguments above, returns relevant data for each of the named selections in the sample folder. `sample_folder` is expected to be the path to the folder of of the sample. It is exactly the same as `sample_path` in the other functions. It returns `ns_number, ns, is_disp, is_force, values`. They are described below: `ns_number` is an integer that corresponds to the number of the named selection `ns` is a pandas.Dataframe object with column names `node_number, x_loc, y_loc, z_loc` which contains the node numbers corresponding to the current named selection `is_disp` and `is_force` are booleans that determine whether the named selection is for a force or for a displacement `values` is a list containing the (x,y,z) components of the selection, whether a force or a displacement #### .create_input_df(_Path sample_folder_) Takes the `sample_folder` path and creates a `pandas.Dataframe` object with columns `node_number, named_selection,x_loc, y_loc, z_loc, x_disp, y_disp, z_disp,x_force, y_force, z_force`, with its `node_number` and nodal coordinate columns filled with relevant data for the sample, `named_selection` filled with `-1` and all the other columns filled with zeros, and returns that dataframe. #### .update_df_with_ns(_pandas.Dataframe df, Int ns_number, pandas.Dataframe ns, bool is_disp, Bool is_force, list values_) Takes the outputs from `.update_selection()` and `.create_input_df()`(refer to those functions for an explanation of their their output values/this function's arguments) and updates the general boundary condition dataframe with the values from the specified named selection, returning the updated dataframe. #### .write_input_output(_Path sample_path, Path data_folder_path_) Takes the path objects to the sample `sample_path`, and the path where the new files are going to be created `data_folder_path_`, and using the other functions write both the boundary conditions file `input_<number>.csv`, and the file with the solutions from ansys `output_<number>.csv` #### .create_folders(_Path data_directory_path_) Takes the directory ` data_directory_path`where the input and output files are going to be created, creates the folder `input` and `output` if they don't exist there, and returns two `pathlib.Path` objects `input_path, output_path` that point to those folders. #### .delete_malformed_samples(_Generator all_samples_glob_) Takes a generator `all_samples_glob` which is expected to generate `pathlib.Path` objects pointing to each of the sample directories, and deletes every directory for which the solutions file is somehow malformed and doesn't have the correct number of columns. This happens because of some solve errors in ANSYS, but is somewhat rare. #### .split_data(_Path all_samples_path, Path data_folder_path_) Takes two `pathlib.Path` objects and splits all the data in all the `all_samples_path` directory into input and output files inside of the `data_folder_path` directory. This function uses all other functions in the script, and by running it the function of this script is fulfilled. ## _scaling This modules purpose is to get the data that the `_splitting` module creates and scale it to a range that can be more successfully/stably used by a neural network: [-1,1] #### .get_sample_dfs(_Path samples_folder_path, Int sample_number_) Takes the path of the directory with the two folders created by `.create_folders()` and the number of a sample, and outputs two `pandas.Dataframe` objects, `sample_input_df, sample_output_df` containing the inputs and outputs of that sample. #### .sample_iterator(_Path samples_folder_path_) Takes the path of the directory with the two folders created by `.create_folders()` and outputs a generator object that yields `sample_number, input_data, output_data`, respectively, a string with the sample number of the current sample, and the two dataframes that are the output of the `.get_sample_dfs()` function. #### .get_max_disp_force(_Path samples_folder_path_) Takes the path of the directory with the two folders created by `.create_folders()` and returns the maximum force and displacement of the entire dataset as two floats `max_force, max_disp` #### .scale_dataframe(_pandas.Dataframe df_unscaled, Float max_force, Float max_disp_) - *NOTE: deprecated for the scaling function in the _formatting module* Takes a `pandas.Dataframe` and two floats `max_force`, `max_disp` and divides the correct columns of the dataframe by these two floats, scaling them. If the two values `max_force` and `max_disp` come from the `get_max_disp_force` function then it is guaranteed that the resulting columns are going to be in the range [-1,1], however it will work if other values are provided as well. ## _formatting This module's purpose is to get the dataframes created by the _scaling module and transform them in arrays usable by a convolutional network. #### .create_array(_int dimensionality, int features, int resolution = 32_) Takes the arguments and returns a numpy array of shape `resolution X resolution X resolution(as many times as dimensionality) X features` filled with zeros. #### _class_ HiddenPrints Class used via the 'with' command to block any prints called inside of the functions inside of the with: block. #### .get_max_dimensions(_pathlib.Path samples_folder_path_) Takes a folder samples_folder_path containing both input and output folders with the raw data, and returns the maximum dimensions of the elements in that database. #### .get_element_size(_pathlib.Path sample_folder_path, int resolution = 32_) Takes a folder samples_folder_path containing both input and output folders with the raw data, and returns the equivalent size of one element inside of tensor with spatial dimensions represented by `resolution` entries in each direction, based on the max dimensions of that raw data, so that every sample can fit inside of the tensor. #### .get_quadrant(_pandas.Dataframe sample_df_) Takes a dataframe `sample_df` and returns what octant that element was primarily created in. It doesn't require the element to be entirely in one octant, and it can handle both 2d and 3d cases. If the element wasn't created in a particular octant, it returns a vector that points to the octant where the element has the highest absolute values. #### .translate_df(_pandas.Dataframe sample_df, tuple max_dimensions_) Takes the raw data from `sample_df` and a tuple or equivalent that can be unpacked with `max(*max_dimensions)` and uses these values to translate the raw dataframe values so that the element is spatially positioned within the first quadrant. It first "pushes" the element on one of the corners of a bounding box of dimensions `max(*max_dimensions)` in the `positive x positive` (2D) or `positive x positive x positive` (3D) , the corner being chosen based on what quadrant is returned by `.get_quadrant()` of the raw dataframe. The element also receives some fine adjustment to make sure it is in fact inside of the tensor's space even if it wasn't created all in one octant. Returns the translated dataframe. #### .interpolate_array_spatially_2D(_pandas.Dataframe sample_array_) Takes an array of dimensions [32, 32, 1] and convolves it with a 5x5 gaussian blur kernel. Returns the convolved array of same dimensions. #### .convolve_with_kernel(_pandas.Dataframe sample_array, str kernel_name = 'edge_detection'_) Takes an array of dimensions [32, 32, 1] and convolves it with a 3x3 kernel selected through `kernel_name`. As of yet, only `'edge_detection'` has been implemented. #### .create_concat_array(_pandas.Dataframe sample_df, numpy.array empty_array, float element_size, str dataframe_type_) Takes a `sample_df`, and a numpy array `empty_array` of the correct dimension filled with zeros, and based on the `element_size` variable, and what type of dataframe it is (`'input'` or `'output'`), iterates through the dataframe and fills a copy of the empty array with correct values. Returns the filled array. #### .get_unscaled_arrays(_pathlib.Path data_folder_path, int resolution = 32_) This generator function takes a path `data_folder_path` to the folder containing the input and output folders with the raw dataframes, returning `sample_number, concatenated_input, concatenated_output`, which are, respectively, the number of the sample depending on file name, the array with seven features corresponding to `material existence, x_displacement, y_displacement, z_displacement, x_force, y_force, z_force` (the inputs/boundary conditions) and another array with 4 features corresponding to `material existence, x_displacement, y_displacement, z_displacement` (the outputs/results of the simulation) #### .save_arrays(_Iterator array_iterator,pathlib.Path save_path, str array_type = 'unscaled'_) Takes an iterator that returns sample numbers and arrays as the `.get_unscaled_arrays()` function does, and a `array_type` of either `'unscaled'` or `'scaled'` and saves each of the arrays in the iterator to the folders `<input>` and `<output>` created at the `save_path` location. Also writes a log file to that location to record the time it took and if the file was created or overwritten. #### .saved_array_iterator(_pathlib.Path array_folder_path, str glob_parameter = '*.npy'_) Takes the `array_folder_path` that is expected to contain the `<input>` and `<output>` folders created by the `.save_arrays()` function and creates an iterator that returns `sample_number, input_array, output_array`. Only gets the arrays that match the `glob_parameter` in a pathlib.Path.glob statement. #### .get_max_array(_pathlib.Path array_folder_path, str glob_parameter = '*.npy'_) Takes the folder `array_folder_path` that is expected to contain the `<input>` and `<output>` folders created by the `.save_arrays()` function and iterates through all samples to find the maximum absolute force and displacements in the inputs and outputs alike. Returns `max_disp, max_forcce` #### .create_scaled_arrays_iterator(_pathlib.Path array_folder_path, tuple max_values, glob_parameter = '*.npy'_) Takes the folder `array_folder_path` that is expected to contain the `<input>` and `<output>` folders created by the `.save_arrays()` function and iterates through all samples, scaling them based on the `max_disp, max_force` values contained in the `max_values` variable, creates a batch dimension in the beggining of the tensor and moves the features dimension to be the second one. Thus, in 2d, it does `[resolution x resolution x features] -> [1 x features x resolution x resolution]`. Returns `sample_number, scaled_input_array, scaled_output_array`.<file_sep>/2D/v4_test/SETUP_geometry_mesh.py # encoding: utf-8 # 2020 R1 SetScriptVersion(Version="20.1.164") system1 = GetSystem(Name="SYS") geometry1 = system1.GetContainer(ComponentName="Geometry") DSscript = open("D:/Ansys Simulations/Project/2D/v4_test/GEOMETRY_generate.py", "r") DSscriptcommand=DSscript.read() geometry1.SendCommand(Command=DSscriptcommand,Language="Python") geometry1.Edit(IsSpaceClaimGeometry=True) #geometry1.Exit() modelComponent1 = system1.GetComponent(Name="Model") modelComponent1.Refresh() model1 = system1.GetContainer(ComponentName="Model") model1.Edit() DSscript = open("D:/Ansys Simulations/Project/2D/v4_test/MESH_generate.py", "r") DSscriptcommand=DSscript.read() model1.SendCommand(Command=DSscriptcommand,Language="Python")<file_sep>/2D/v4_test/GEOMETRY_generate.py # Python Script, API Version = V19 Beta import random import math from itertools import combinations, product, izip from System import Random #SpaceClaim.Api.V19.Api n_points = 4 n_dimensions = 3 points = [] curves = List[ITrimmedCurve]() for i in range(n_points): # creates all points points_temp = [0,0,0] for j in range(n_dimensions): random.seed() if (j<=1) and i>0: points_temp[j] = random.random() elif (i>2): points_temp[j] = random.gauss(1,0.2) points.append(points_temp) #choose quadrant iter_quad = product([1, -1], repeat = 3) quadrant = [] for quad in iter_quad: quadrant.append(quad) choice = random.choice(range(0,8)) #choice=0 for i, point in enumerate(points): for j, coord in enumerate(point): points[i][j] = coord*quadrant[choice][j] # Delete Selection try: selection = Selection.Create(GetRootPart().Bodies[:]) result = Delete.Execute(selection) except: pass try: selection = Selection.Create(GetRootPart().Curves[:]) result = Delete.Execute(selection) except: pass # EndBlock # create points for named selection for point in points: print(point) SketchPoint.Create(Point.Create(*point)) for iter, x in enumerate(combinations(points, 3)): #iterates through all combinations of 3 #print(iter) #curves = List[ITrimmedCurve]() for i in range(len(x)): #iterates through points to create curves if i<2: #SketchPoint.Create(Point.Create(*x[i])) curveSegment = CurveSegment.Create(Point.Create(*x[i]), Point.Create(*x[i+1])) curves.Add(curveSegment) elif i==2: #SketchPoint.Create(Point.Create(*x[i])) curveSegment = CurveSegment.Create(Point.Create(*x[i]), Point.Create(*x[0])) curves.Add(curveSegment) else: #print("else") SketchPoint.Create(Point.Create(MM(x[i][0]),MM(x[i][1]),MM(x[i][2]))) #Create Perpendicular Vector direc = [] for ii in range(1,3): # print(x) # print(x[ii]) direc_temp = [0,0,0] for jj, coord in enumerate(x[ii]): #print(ii) direc_temp[jj]= x[0][jj] - coord direc.append(direc_temp) a = Vector.Create(*direc[0]) b = Vector.Create(*direc[1]) perp_vec = Vector.Cross(a, b) #Create frame with perpendicular vector p = Point.Create(*x[0]) frame = Frame.Create(p, perp_vec.Direction) #print(perp_vec.Direction) #print(x) if iter==0: plane = Plane.PlaneXY else: plane = Plane.Create(frame) designResult = PlanarBody.Create(plane, curves) #creates the curve designBody = designResult.CreatedBody if n_points >= 4: selec =[] for surf in GetRootPart().Bodies[:]: #transforms array of surfaces into list of surfaces selec.append(surf) targets = Selection.Create(*selec) #merges them result = Combine.Merge(targets) # EndBlock # Rename 'temp 1' to 'Body' selection = Selection.Create(GetRootPart().Bodies[0]) result = RenameObject.Execute(selection,"Body") # EndBlock ViewHelper.ZoomToEntity() # Solidify Sketch mode = InteractionMode.Solid result = ViewHelper.SetViewMode(mode, None) # EndBlock ### NAMED SELECTIONS # Create Named Selection Group primarySelection = Selection.Create(GetRootPart().Bodies[0]) secondarySelection = Selection() result = NamedSelection.Create(primarySelection, secondarySelection) # EndBlock # Rename Named Selection result = NamedSelection.Rename("Group1", "element") # EndBlock # Create Named Selection Group primarySelection = Selection.Create(GetRootPart().Curves[0]) secondarySelection = Selection() result = NamedSelection.Create(primarySelection, secondarySelection) # EndBlock # Rename Named Selection result = NamedSelection.Rename("Group1", "origin_node") # EndBlock if n_points > 3: # Create Named Selection Group primarySelection = Selection.Create(GetRootPart().Curves[3]) secondarySelection = Selection() result = NamedSelection.Create(primarySelection, secondarySelection) # EndBlock # Rename Named Selection result = NamedSelection.Rename("Group1", "top_node") # EndBlock # Create Named Selection Group primarySelection = Selection.Create(GetRootPart().Curves[1]) secondarySelection = Selection() result = NamedSelection.Create(primarySelection, secondarySelection) # EndBlock # Rename Named Selection result = NamedSelection.Rename("Group1", "plane_node_1") # EndBlock # Create Named Selection Group primarySelection = Selection.Create(GetRootPart().Curves[2]) secondarySelection = Selection() result = NamedSelection.Create(primarySelection, secondarySelection) # EndBlock # Rename Named Selection result = NamedSelection.Rename("Group1", "plane_node_2") # EndBlock # NAME EDGES if n_points > 3: # Create Named Selection Group primarySelection = Selection.Create(GetRootPart().Bodies[0].Edges[3]) secondarySelection = Selection() result = NamedSelection.Create(primarySelection, secondarySelection) # EndBlock # Rename Named Selection result = NamedSelection.Rename("Group1", "edge_closest") # EndBlock # Create Named Selection Group primarySelection = Selection.Create(GetRootPart().Bodies[0].Edges[0]) secondarySelection = Selection() result = NamedSelection.Create(primarySelection, secondarySelection) # EndBlock # Rename Named Selection result = NamedSelection.Rename("Group1", "edge_plane_1") # EndBlock # Create Named Selection Group primarySelection = Selection.Create(GetRootPart().Bodies[0].Edges[2]) secondarySelection = Selection() result = NamedSelection.Create(primarySelection, secondarySelection) # EndBlock # Rename Named Selection result = NamedSelection.Rename("Group1", "edge_plane_2") # EndBlock # Create Named Selection Group primarySelection = EdgeSelection.Create(GetRootPart().Bodies[0].Edges[1]) secondarySelection = Selection() result = NamedSelection.Create(primarySelection, secondarySelection) # EndBlock # Rename Named Selection result = NamedSelection.Rename("Group1", "edge_plane_far") # EndBlock if n_points > 3: # Create Named Selection Group primarySelection = Selection.Create(GetRootPart().Bodies[0].Edges[5]) secondarySelection = Selection() result = NamedSelection.Create(primarySelection, secondarySelection) # EndBlock # Rename Named Selection result = NamedSelection.Rename("Group1", "edge_far_1") # EndBlock # Create Named Selection Group primarySelection = Selection.Create(GetRootPart().Bodies[0].Edges[1]) secondarySelection = Selection() result = NamedSelection.Create(primarySelection, secondarySelection) # EndBlock # Rename Named Selection result = NamedSelection.Rename("Group1", "edge_far_2") # EndBlock ## Create/Edit Mesh #options = SpaceClaim.Api.V19.Scripting.Commands.CommandOptions.CreateMeshOptions() #options.SolidElementShape = ElementShapeType.Hexahedral #options.SurfaceElementShape = ElementShapeType.QuadDominant #options.BlockingType = BlockingDecompositionType.Aggressive #options.ElementSize = MM(50) #options.DefeatureSize = MM(1) #options.ConnectTolerance = 0.02 #options.GrowthRate = 5 #options.SizeFunctionType = SizeFunctionType.Fixed #options.CurvatureMinimumSize = 0.00360405540659 #options.CurvatureNormalAngle = 0.523598776 #options.ProximityMinimumSize = 0.002 #options.NumberOfCellsAcrossGap = 100 #options.ProximitySizeFunctionSources = ProximitySizeFunctionSourcesType.Edges #options.MidsideNodes = MidsideNodesType.BasedOnPhysics #bodySelection = BodySelection.Create(GetRootPart().Bodies[0]) #sweepFaceSelection = Selection() #result = CreateMesh.Execute(bodySelection, sweepFaceSelection, options) ## EndBlock
5f5bd5ce11cd86014f3654c4d2cd2c5fe1a5a26a
[ "Markdown", "Python", "Text" ]
31
Markdown
waltherwj/AI-and-FEA-model
4eb3dc462355b49743543445a906ccebe6afa644
10c28ae90315b7f06a06bdbb56f93c677923ad6c
refs/heads/master
<file_sep>const request = require('request-promise'); var stylistSingleSignon = (function () { function getAuthCookies(stylistCredentials, done) { // 1. validate the stylist credentials object if (!stylistCredentials || !stylistCredentials.stylist_username || !stylistCredentials.stylist_password || !stylistCredentials.oauth_consumer_key || !stylistCredentials.grant_type) { done(new Error('invalid stylist credentials object')) return; } // 2. create an Authorization header by encoding the stylist credentials var credentialPair = stylistCredentials.stylist_username + ':' + stylistCredentials.stylist_password; var encoded = Buffer.from(credentialPair).toString('base64'); var authorizationHeaderValue = 'Basic ' + encoded; // 3. make a request to the signon server. note that the stylist // credentials are in the Authorization header, and there are two // values supplied in the form that is submitted. these values // help the signon server determine how to handle your stylist's // credentials request({ method: 'POST', uri: 'https://signon.shortcutssoftware.com/authenticate', headers: { 'Authorization': authorizationHeaderValue }, form: { grant_type: stylistCredentials.grant_type, oauth_consumer_key: stylistCredentials.oauth_consumer_key }, resolveWithFullResponse: true }).then(function (response) { if (response.statusCode != 200) { // stylist was not authenticated throw new Error('authentication failed'); } // stylist was authenticated. we are interested in the OAuth // tokens that were delivered by the signon server. console.log('successful authentication for stylist: %s', stylistCredentials.stylist_username) done(null, getAuthCookiesSetByResponse(response)); }).catch(function (err) { // stylist was not authenticated console.log('error: %s', err); done(err) }) } function getAuthCookiesSetByResponse(response) { var authCookies = {}; var setCookieHeaders = response.headers['set-cookie']; for (var i = 0; i < setCookieHeaders.length; i++) { var setCookieHeader = setCookieHeaders[i]; let cookieName = setCookieHeader.split('=')[0] if (cookieName === 'OAuth' || cookieName === '.ASPAUTH') { console.log('header:', setCookieHeader); authCookies[cookieName] = setCookieHeader; } } if (Object.keys(authCookies).length != 2) { throw new Error('unable to find auth cookies in response'); } return authCookies; } return { getAuthCookies: getAuthCookies } })(); module.exports = stylistSingleSignon <file_sep>apply plugin: 'java' sourceCompatibility = 1.8 apply plugin: 'org.springframework.boot' buildscript { repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5+") } } repositories { mavenCentral() } dependencies { compile "org.springframework.boot:spring-boot-starter-web:1.5+" compile "org.springframework.boot:spring-boot-starter-actuator:1.5+" testCompile group: 'junit', name: 'junit', version: '4.12' } springBoot { mainClass = "com.shortcuts.example.single_signon.ApplicationsOnSeparatePorts" }<file_sep>apply plugin: 'java' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { // json serialization/desrialization compile "com.fasterxml.jackson.datatype:jackson-datatype-jdk8:2.8.9" compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.8.9" compile 'org.springframework.security.oauth:spring-security-oauth:2.1.1.RELEASE' compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.16.20' compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.5' compile group: 'commons-logging', name: 'commons-logging', version: '1.2' compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.8.+' testCompile group: 'junit', name: 'junit', version: '4.12' } <file_sep>package com.shortcuts.example.java.util; public class ShortcutsAPIException extends RuntimeException { public ShortcutsAPIException(Throwable t) { super(t); } } <file_sep>define(['js/config'], function (config) { function initializeWidgets() { return window.shortcuts.widgets.init({ version: config.apiVersion, apiUrl: config.apiUri, widgetUrl: config.widgetBaseUri + '/' + config.culture, consumerKey: config.consumerKey, consumerSecret: config.consumerSecret, enableRegistrationCode: true, protocol: 'https', widgetCredential: { '*': { accessToken: config.accessTokenKey, accessTokenSecret: config.accessTokenSecret } } }).then(function () { shortcuts.widgets.handlers.showAlert = function (message) { console.log(message); }; }); } function renderServiceSelectionWidget(target, siteId) { target.on(shortcuts.widgets.events.WIDGET_DONE, function () { target.shortcutsWidget('booking/service-selection-list', { siteId: siteId }); }); return target.shortcutsWidget('booking/service-selection-list', { siteId: siteId }); } function initializeApplication(target, siteId) { return initializeWidgets().then( function () { renderServiceSelectionWidget(target, siteId); }); } return { initializeApplication: initializeApplication } });<file_sep>package com.shortcuts.example.single_signon.salon; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.util.ArrayDeque; import java.util.Arrays; /** * This is an example token validator. It will attempt to retrieve validated credentials * for the supplied token. If they are found the validator will return them for use by * Shortcuts systems. If they are not found the validator will return an error. */ @RestController public class SalonResourceServer { @Autowired private AuthenticationTokenService authenticationTokenService; @RequestMapping(path = "/validate", method = RequestMethod.GET) private ResponseEntity<String> validate(RequestEntity<String> request) throws IOException { try { // get the token from the Authorization header String authorizationHeader = request.getHeaders().get("Authorization").get(0); // the authorization header is in the form of "Bearer <token>" String token = new ArrayDeque<>(Arrays.asList(authorizationHeader.split("\\s+"))).removeLast(); // validate the token ValidatedCredentials validatedCredentials = authenticationTokenService.validateAuthenticationToken(token); if (validatedCredentials != null) { // token was valid, serialise and return the // validated credentials for use by Shortcuts String body = new ObjectMapper() .configure(SerializationFeature.INDENT_OUTPUT, true) .writeValueAsString(validatedCredentials); return new ResponseEntity<>(body, HttpStatus.OK); } } catch (Exception e) { // unauthorized, fall through } return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); } } <file_sep>const url = require('url'); const _ = require('underscore'); const api = require('./api'); const config = require('./config.js'); const oauth = require('./oauth.js'); var authenticate = (function () { var authenticateHref = url.resolve(config.apiUri, 'authenticate'); function authenticate(done) { var signedAuthorizationHeader = oauth.sign('POST', url.format(authenticateHref)); var authenticateRequest = { credential_type_code: 'oauth' }; api.post( authenticateHref, { 'Authorization': signedAuthorizationHeader }, authenticateRequest, done); } return { authenticate: authenticate } })(); module.exports = authenticate; <file_sep>const expect = require('expect.js'); const oauth = require('../src/oauth.js'); describe('Oauth', function() { describe('sign()', function() { it('should create a valid signature', function() { var authorization = oauth.sign('GET', 'https://api.shortcutssoftware.io/authenticate', { generateNonce: function() { return 'awruFGf4'; }, generateTimestamp: function() { return '1508467466'; } }); expect(authorization).to.eql('OAuth realm="https://api.shortcutssoftware.io/authenticate", oauth_consumer_key="<KEY>", oauth_token="<PASSWORD>P<PASSWORD>S", oauth_nonce="awruFGf4", oauth_timestamp="1508467466", oauth_signature_method="HMAC-SHA1", oauth_version="1.0", oauth_signature="7b0LkEH%2BN64tCu93YlzFNmc9mJc%3D"'); }) }) });<file_sep>package com.shortcuts.example.java.authentication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) public class JWTSerialNumberAuthenticationServiceTest { @Autowired JWTSerialNumberAuthenticationService jwtSerialNumberAuthenticationService; @Test public void testConfigurationIsAvailable() { assertTrue(jwtSerialNumberAuthenticationService.getBaseUrl().startsWith("https://")); assertNotNull(jwtSerialNumberAuthenticationService.getRestTemplateCallingUtil()); assertNotNull(jwtSerialNumberAuthenticationService.getSerialNumber()); assertNotNull(jwtSerialNumberAuthenticationService.getSiteInstallationId()); } @Test public void testAuthenticate() { String jwtToken = jwtSerialNumberAuthenticationService.authenticate(); assertNotNull(jwtToken); } }<file_sep>package com.shortcuts.example.java.util; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class IdExtractionUtilTest { @Test public void testIdExtraction() { IdExtractionUtil idExtractionUtil = new IdExtractionUtil(); assertNull(idExtractionUtil.extractId("", "")); assertNull(idExtractionUtil.extractId("site", "")); assertEquals("35648", idExtractionUtil.extractId("site", "https://api.shortcutssoftware.io/site/35648")); assertEquals("35648", idExtractionUtil.extractId("site", "https://api.shortcutssoftware.io/site/35648/another/site/12345678")); } }<file_sep>site_serial_number=BWQK6ARB77JJ oauth.consumer_key=jv6YflwoCatKYxBNffV5 oauth.consumer_secret=YzIQtHDfqHoecCbua6GM oauth.access_token_key=<KEY> oauth.access_token_secret=<KEY> giftcard.registered.ready=62997400000001248652 <file_sep>define(['js/config'], function (config) { function initializeWidgets() { return window.shortcuts.widgets.init({ version: config.apiVersion, apiUrl: config.apiUri, widgetUrl: config.widgetBaseUri + '/' + config.culture, consumerKey: config.consumerKey, consumerSecret: config.consumerSecret, enableRegistrationCode: true, protocol: 'https', widgetCredential: { '*': { accessToken: config.accessTokenKey, accessTokenSecret: config.accessTokenSecret } } }).then(function () { shortcuts.widgets.handlers.showAlert = function (message) { console.log(message); }; }); } function renderCustomerWidget(target, siteId){ // target.on(shortcuts.widget.events.WIDGET_DONE, function(){ // return target.shortcutsWidget('customer/edit', {siteId: siteId}); // }); return target.shortcutsWidget('customer/edit', {siteId: siteId}); } function initializeApplication(target, siteId) { return initializeWidgets().then( function () { renderCustomerWidget(target, siteId); }); } return { initializeApplication: initializeApplication } });<file_sep>const url = require('url'); const expect = require('expect.js'); const config = require('../src/config.js'); const search = require('../src/search.js'); const authenticate = require('../src/authenticate.js'); const _ = require('underscore'); describe('Common Tasks', function () { this.timeout(10000); describe('Common Appointment Searches', function () { var sharedState = { access_token: undefined }; it('must authenticate', function (done) { authenticate.authenticate(function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.access_token).to.not.be(undefined); sharedState.access_token = result.content.access_token; done(); }) }); var fromDate = new Date(new Date().getTime() + 3 * 24 * 60 * 60 * 1000); var toDate = new Date(new Date().getTime() + 14 * 24 * 60 * 60 * 1000); var dateTimeFilter = { from_date: fromDate.getFullYear().toString() + '-' + (fromDate.getMonth() + 1) + '-' + fromDate.getDate(), to_date: toDate.getFullYear().toString() + '-' + (toDate.getMonth() + 1) + '-' + toDate.getDate(), start_time: '00:00:00', finish_time: '23:59:59', days_of_week: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] }; it('search for appointments by service and date/time window', function (done) { search.byServiceNameAndDateTimeFilter( sharedState.access_token, 'Blowdry', dateTimeFilter, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.not.be.empty(); console.log(JSON.stringify(result.content.available_appointments)); done(); }); }); it('search for appointments by service category and date/time window', function (done) { search.byServiceCategoryAndDateTimeFilter( sharedState.access_token, 'Hair Styling', dateTimeFilter, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.not.be.empty(); console.log(JSON.stringify(result.content.available_appointments)); done(); }); }); it('search for appointments by service and employee and date/time window', function (done) { search.byServiceAndEmployeeNameAndDateTimeFilter( sharedState.access_token, 'Blowdry', 'Katie', dateTimeFilter, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.not.be.empty(); console.log(JSON.stringify(result.content.available_appointments)); done(); }); }); it('search for appointments by service and date/time window and price band - inclusive', function (done) { var priceBand = { upper: 100, lower: 10 }; search.byServiceNameAndDateTimeFilterAndPriceBand( sharedState.access_token, 'Blowdry', dateTimeFilter, priceBand, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.not.be.empty(); console.log(JSON.stringify(result.content.available_appointments)); for (var i = 0; i < result.content.available_appointments.length; i++) { var appointment = result.content.available_appointments[i]; expect(appointment.sell_price).to.be.above(priceBand.lower); expect(appointment.sell_price).to.be.below(priceBand.upper); } done(); }); }); it('search for appointments by service and date/time window and price band - exclusive', function (done) { var priceBand = { upper: 10, lower: 1 }; search.byServiceNameAndDateTimeFilterAndPriceBand( sharedState.access_token, 'Blowdry', dateTimeFilter, priceBand, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.be.empty(); console.log(JSON.stringify(result.content.available_appointments)); done(); }); }); }); });<file_sep>package com.shortcuts.example.giftcard; import com.fasterxml.jackson.databind.ObjectMapper; import com.shortcuts.example.giftcard.Models.RequestBody.AuthenticateRequest; import com.shortcuts.example.giftcard.Models.RequestBody.AuthenticateRequestHeaders; import com.shortcuts.example.giftcard.Models.Response.AuthenticateResponse; import com.shortcuts.example.giftcard.Models.Response.BaseResponse; import lombok.SneakyThrows; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.springframework.http.HttpMethod; import org.springframework.security.oauth.common.signature.SharedConsumerSecretImpl; import org.springframework.security.oauth.consumer.BaseProtectedResourceDetails; import org.springframework.security.oauth.consumer.OAuthConsumerToken; import org.springframework.security.oauth.consumer.client.CoreOAuthConsumerSupport; import org.springframework.security.oauth.provider.BaseConsumerDetails; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; public class AuthenticateService { String authenticateUrl = "https://api.shortcutssoftware.io/authenticate"; ObjectMapper objectMapper = new ObjectMapper(); private AuthenticateRequestHeaders requestHeaders; public AuthenticateService(AuthenticateRequestHeaders requestHeaders){ this.requestHeaders = requestHeaders; } @SneakyThrows public AuthenticateResponse authenticate(){ AuthenticateRequest requestBody = new AuthenticateRequest(); requestBody.setCredential_type_code("oauth"); HttpPost httpPost = new HttpPost(authenticateUrl); httpPost.addHeader("Authorization", getSignedAuthorizationHeader()); httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(requestBody))); CloseableHttpResponse httpResponse = HttpClientBuilder.create().build().execute(httpPost); String jsonResponse = EntityUtils.toString(httpResponse.getEntity()); if(httpResponse.getStatusLine().getStatusCode() != 200){ BaseResponse baseResponse = objectMapper.readValue(jsonResponse, BaseResponse.class); throw new RuntimeException(String.format("Error Type: %s, %s", baseResponse.getError_type_code(), baseResponse.getMessage())); } AuthenticateResponse authenticateResponse = objectMapper.readValue(jsonResponse, AuthenticateResponse.class); return authenticateResponse; } /** * sign request with oauth credentials. we are using * spring-security-oauth here, but you can use any * method that complies with the standard. */ private String getSignedAuthorizationHeader() { BaseConsumerDetails baseConsumerDetails = new BaseConsumerDetails(); baseConsumerDetails.setConsumerKey(requestHeaders.getConsumerKey()); baseConsumerDetails.setSignatureSecret(new SharedConsumerSecretImpl(requestHeaders.getConsumerSecret())); BaseProtectedResourceDetails resource = new BaseProtectedResourceDetails(); resource.setId("GiftCardExample"); resource.setConsumerKey(baseConsumerDetails.getConsumerKey()); resource.setSharedSecret(baseConsumerDetails.getSignatureSecret()); OAuthConsumerToken oAuthConsumerToken = new OAuthConsumerToken(); oAuthConsumerToken.setResourceId(resource.getId()); oAuthConsumerToken.setAccessToken(true); oAuthConsumerToken.setValue(requestHeaders.getAccessKey()); oAuthConsumerToken.setSecret(requestHeaders.getAccessSecret()); URL endpointUrl; try { endpointUrl = new URL(authenticateUrl); } catch (MalformedURLException e) { throw new RuntimeException(e); } return new CoreOAuthConsumerSupport().getAuthorizationHeader( resource, oAuthConsumerToken, endpointUrl, HttpMethod.POST.name(), Collections.emptyMap()); } } <file_sep>const expect = require('expect.js'); const config = require('../src/config.js'); const search = require('../src/search.js'); const appointment = require('../src/appointment.js'); const appointmentReschedule = require('../src/appointment_reschedule.js'); const _ = require('underscore'); describe('Appointment Reschedule', function () { this.timeout(10000); describe('Appointment Create and Reschedule Operation', function () { var sharedState = { customerSessionHref: null, appointmentDetails: null, appointmentHref: null, appointment: null, next_scheduled_date: null, next_start_time: null }; it('must be able to authenticate using user validated by ratner', function (done) { appointmentReschedule.authenticateCustomer(config.customerUsername, config.customerPassword, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.customer).to.not.be(undefined); expect(result.content.customer).to.be.an('object'); sharedState.customerSessionHref = result.content.href; done(); }) }); it('Must be able to search for a bookable service', function (done) { if (!sharedState.customerSessionHref) { done('Authentication failed'); return; } search.byServiceName('Shampoo and Cut', function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.not.be(undefined); expect(result.content.available_appointments).to.be.an('array'); expect(result.content.available_appointments).to.not.be.empty(); sharedState.appointmentDetails = result.content.available_appointments[0]; // remember these details for the reschedule operation later var nextAppointment = result.content.available_appointments[1]; sharedState.next_scheduled_date = nextAppointment.scheduled_date; sharedState.next_start_time = nextAppointment.services[0].start_time; done(); }); }); it('Should be able to book the service', function (done) { if (!sharedState.customerSessionHref || !sharedState.appointmentDetails) { done('Search for bookable appointment failed'); return; } appointment.bookAppointment(sharedState.customerSessionHref, sharedState.appointmentDetails, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.href).to.not.be(undefined); sharedState.appointmentHref = result.content.appointments[0].href; done(); }); }); it('Must be able to retrieve appointment', function (done) { if (!sharedState.appointmentHref) { done('Booking an appointment failed'); return; } appointmentReschedule.retrieveAppointment(sharedState.appointmentHref, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); sharedState.appointment = result.content; done(); }); }); it('Must be able to reschedule an appointment', function (done) { if (!sharedState.appointment) { done('Retrieving a booked appointment failed'); return; } var oldVersion = sharedState.appointment.version; console.log('version before reschedule:', oldVersion) var rescheduleAppointmentRequest = _.clone(sharedState.appointment); rescheduleAppointmentRequest.scheduled_date = sharedState.next_scheduled_date rescheduleAppointmentRequest.start_time = sharedState.next_start_time; appointmentReschedule.rescheduleAppointment(rescheduleAppointmentRequest, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.href).to.not.be(undefined); var newVersion = result.content.version; console.log('version after reschedule:', newVersion); expect(newVersion).to.be.above(oldVersion); done(); }); }); }); });<file_sep>module.exports = { stylist_username: '<...>', stylist_password: '<...>', oauth_consumer_key: '<...>', oauth_consumer_secret: '<...>', grant_type: 'client_credentials', site_url: 'https://pos.shortcutssoftware.com/site/<...>' };<file_sep>package com.shortcuts.example.java.services.site; import com.shortcuts.example.java.services.Paging; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.List; @Data @EqualsAndHashCode(callSuper = false) public class GetSitesResponse { private List<Site> sites; private Paging paging; private String href; } <file_sep>const https = require('https'); const http = require('http'); const url = require('url'); const log = require('./log.js'); var api = (function () { function request(method, href, headers, data, done) { var endpoint, options, request, requestContent; endpoint = url.parse(href); if (!headers) { headers = {}; } options = { method: method, hostname: endpoint.hostname, path: endpoint.path, port: endpoint.port, headers: headers }; if(method === 'POST') { requestContent = JSON.stringify(data || {}); options.headers['Content-Type'] = 'application/json'; options.headers['Content-Length'] = Buffer.byteLength(requestContent); } function apiRequestCallback(response) { var content, jsonContent; content = ''; response.on('data', function (chunk) { return content += chunk; }); response.on('end', function () { try { jsonContent = JSON.parse(content); log.info('Json content: %s', JSON.stringify(jsonContent)); } catch (e) { log.info('Non-json content: %s', content); } var statusCode = response.statusCode; if (statusCode / 100 != 2) { console.log('response is in error:', statusCode, response.req.method, response.req.path) } done(null, { status: statusCode, content: jsonContent || content }); }); request.on('error', function (err) { log.error('Error: %s', err); done(err); }); } log.info('Requesting: %s', url.format(endpoint)); if (endpoint.protocol === 'http:') { request = http.request(options, apiRequestCallback); } else if (endpoint.protocol === 'https:') { request = https.request(options, apiRequestCallback); } else { done('Unknown protocol:' + endpoint.protocol) } if(method === 'POST') { request.write(requestContent); } request.end(); } function get(href, headers, done) { request('GET', href, headers, null, done); } function post(href, headers, data, done) { request('POST', href, headers, data, done); } function del(href, headers, done) { request('DELETE', href, headers, null, done); } return { get: get, post: post, del: del }; })(); module.exports = api;<file_sep>const stylistCredentials = require('./example-stylist-credentials'); const stylistSingleSignon = require('../src/stylist-single-signon.js'); const request = require('request-promise'); describe('Stylist Single Signon', function () { describe('get stylist credentials', function () { it('stylist credentials must be present for test', function (done) { expect(stylistCredentials.stylist_username).toBeDefined(); expect(stylistCredentials.stylist_password).toBeDefined(); expect(stylistCredentials.grant_type).toBeDefined(); expect(stylistCredentials.oauth_consumer_key).toBeDefined(); done(); }) }); var sharedAuthCookies = undefined; describe('getAuthCookies()', function () { it('must return an error when called with empty credentials', function (done) { stylistSingleSignon.getAuthCookies(null, function (err, authCookies) { expect(err).toBeDefined(); expect(authCookies).toBeUndefined(); done(); }); }); it('must return an error when called with invalid credentials', function (done) { var badStylistCredentials = JSON.parse(JSON.stringify(stylistCredentials)); badStylistCredentials.stylist_password = '<PASSWORD>'; stylistSingleSignon.getAuthCookies(badStylistCredentials, function (err, authCookies) { expect(err).toBeDefined(); expect(authCookies).toBeUndefined(); done(); }); }); it('must return auth cookies when called with valid credentials', function (done) { stylistSingleSignon.getAuthCookies(stylistCredentials, function (err, authCookies) { expect(err).toEqual(null); expect(authCookies).toBeDefined(); expect(authCookies['OAuth']).toBeDefined(); expect(authCookies['.ASPAUTH']).toBeDefined(); sharedAuthCookies = authCookies; done(); }); }); it('must return a valid response from the site_url when called with the correct auth cookies', function (done) { expect(sharedAuthCookies).toBeDefined(); // sharedAuthCookies contains the 'Set-Cookie' headers // returned from the signon server when we performed the // stylist single signon. // // this test shows how to extract the cookie values, and // use them in a programmatic request to Shortcuts live. var cookieString = ''; Object.keys(sharedAuthCookies).forEach(function (key) { console.log('adding the [%s] cookie', key); let setCookieString = sharedAuthCookies[key]; let setCookieParts = setCookieString.split(';'); let cookieNameAndValue = setCookieParts[0]; let p = cookieNameAndValue.indexOf('='); let cookieValue = cookieNameAndValue.substr(p + 1); if (cookieString.length > 0) { if (!cookieString.match(/^.*; +$/)) { cookieString += '; '; } } cookieString += (key + '=' + cookieValue + '; '); }); request( { method: 'GET', uri: stylistCredentials.site_url, headers: { 'Cookie': cookieString }, resolveWithFullResponse: true, followRedirect: false } ).then(function (response) { if (response.statusCode != 200) { throw new Error('unable to open site: ' + stylistCredentials.site_url); } console.log('opened site after stylist single signon: ' + stylistCredentials.site_url) done(); }).catch(function (err) { done(err); }) }); it('must reissue a cookie correctly when supplied with the correct auth cookies', function (done) { expect(sharedAuthCookies).toBeDefined(); // sharedAuthCookies contains the 'Set-Cookie' headers // returned from the signon server when we performed the // stylist single signon. // // this test shows how to build a url with query string // parameters, that, when invoked (GET), will reissue // the required cookies to the shortcutssoftware domain. // // this is necessary because a browser operating in a // secure manner can only receive cookies issued on the // same domain that it is requesting from console.log('reissuing the [OAuth] cookie'); let setCookieString = sharedAuthCookies['OAuth']; let encodedSetCookieString = btoa(setCookieString); let cookieIssuerUrl = 'https://cookie.shortcutssoftware.com/issue'; request( { method: 'GET', uri: cookieIssuerUrl + '?cookie=' + encodedSetCookieString, resolveWithFullResponse: true, followRedirect: false } ).then(function (response) { if (response.statusCode != 200) { throw new Error('unable to open site: ' + cookieIssuerUrl); } let setCookieResponseHeaders = response.headers['set-cookie']; console.log('response with %s cookies', setCookieResponseHeaders.length); expect(setCookieResponseHeaders[0]).toEqual(setCookieString); done(); }).catch(function (err) { done(err); }) }); }); });<file_sep>package com.shortcuts.example.java.authentication; import com.shortcuts.example.java.BaseUrlAware; import com.shortcuts.example.java.util.RestTemplateCallingUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Service; @Slf4j @Service public class JWTSerialNumberAuthenticationService extends BaseUrlAware implements JWTAuthentication { @Autowired private RestTemplateCallingUtil restTemplateCallingUtil; @Value("${authentication.onPremise.serialNumber}") private String serialNumber; @Value("${authentication.onPremise.siteInstallationId}") private String siteInstallationId; public RestTemplateCallingUtil getRestTemplateCallingUtil() { return restTemplateCallingUtil; } public String getSerialNumber() { return serialNumber; } public String getSiteInstallationId() { return siteInstallationId; } @Override public String authenticate() { // set up authentication request object with // serial number and site installation id AuthenticationRequest authenticationRequest = new AuthenticationRequest(); authenticationRequest.setCredential_type_code("serial"); authenticationRequest.setSerial_number(getSerialNumber()); authenticationRequest.setSite_installation_id(getSiteInstallationId()); // call the api AuthenticationResponse authenticationResponse = restTemplateCallingUtil.postForObject( getEndpointURI("authenticate"), new HttpHeaders(), authenticationRequest, AuthenticationResponse.class); String jwtToken = authenticationResponse.getAccess_token(); log.info("authentication result: {}", jwtToken); return jwtToken; } } <file_sep>const url = require('url'); const _ = require('underscore'); const api = require('./api'); const config = require('./config.js'); var site = (function () { var siteHref = url.resolve(config.apiUri, 'site/' + config.siteId) // Retrieving the site details function retrieveSiteDetails(jwtToken, done) { api.get( siteHref, {Authorization: 'JWT ' + jwtToken}, done); } // Retrieving the service categories available at the site - ensuring we only list those with customer bookable services currently active in the site catalog. // Only interested in the names and resource URIs. function retrieveServiceCategories(jwtToken, done) { api.get( url.resolve(siteHref + '/', 'service_categories?is_active=true&is_bookable=true&is_customer_bookable=true&fields=display,href'), {Authorization: 'JWT ' + jwtToken}, done); } // Retrieving services within the service category with name {serviceCategoryName} function retrieveServicesByServiceCategoryName(jwtToken, serviceCategoryName, done) { retrieveServiceCategories( jwtToken, function (err, result) { var serviceCategoryHref; if (err) { done(err); return; } serviceCategoryHref = _.findWhere(result.content.service_categories, {'display_name': serviceCategoryName}).href; api.get( url.resolve(serviceCategoryHref + '/', 'services?is_active=true&is_bookable=true&is_customer_bookable=true&fields=display,href'), { Authorization: 'JWT ' + jwtToken }, done); }); } // Retrieving services with name {serviceName} function retrieveServicesByServiceName(jwtToken, serviceName, done) { api.get( url.resolve(siteHref + '/', 'services?search=' + serviceName + '&is_active=true&is_bookable=true&is_customer_bookable=true&fields=display,href'), {Authorization: 'JWT ' + jwtToken}, done); } // Retrieving employee by alias/name {alias} function retrieveEmployeeByEmployeeAlias(jwtToken, employeeAlias, done) { api.get( url.resolve(siteHref + '/', 'employees?search=' + employeeAlias + '&is_active=true&is_bookable=true&is_customer_bookable=true&fields=display,href'), {Authorization: 'JWT ' + jwtToken}, done); } function retrieveServiceEmployeePricing(jwtToken, serviceName, done) { retrieveServicesByServiceName( jwtToken, serviceName, function (err, result) { var serviceHref; if (err) { done(err); return; } serviceHref = result.content.services[0].href; api.get( url.resolve(serviceHref + '/', 'employee_pricing?is_active=true&is_bookable=true&is_customer_bookable=true'), {Authorization: 'JWT ' + jwtToken}, done); }); } function retrieveEmployeeServicePricing(jwtToken, employeeAlias, done) { retrieveEmployeeByEmployeeAlias( jwtToken, employeeAlias, function (err, result) { var employeeHref; if (err) { done(err); return; } employeeHref = result.content.employees[0].href; api.get( url.resolve(employeeHref + '/', 'service_pricing?is_active=true&is_bookable=true&is_customer_bookable=true'), {Authorization: 'JWT ' + jwtToken}, done); }); } return { retrieveSiteDetails: retrieveSiteDetails, retrieveServiceCategories: retrieveServiceCategories, retrieveServicesByServiceCategoryName: retrieveServicesByServiceCategoryName, retrieveServicesByServiceName: retrieveServicesByServiceName, retrieveEmployeeByEmployeeAlias: retrieveEmployeeByEmployeeAlias, retrieveServiceEmployeePricing: retrieveServiceEmployeePricing, retrieveEmployeeServicePricing: retrieveEmployeeServicePricing } })(); module.exports = site;<file_sep>package com.shortcuts.example.giftcard.Models.RequestBody; import lombok.Data; @Data public class AuthenticateRequest { private String credential_type_code; } <file_sep># Shortcuts Widgets THC Sample Sample website implementation over the Shortcuts Widgets. ## Getting Started These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. ### Running website using Node 1. Ensure that Node.JS and NPM are installed. 2. Install node packages ``` npm install ``` 3. Run server ``` npm start ``` ### Running website by static content delivery This website has been designed to be able to be run independently of a dynamic server by copying the files to an accessible web location. It is recommended that the website is not run from the file directory as this can cause issues with AJAX calls. 1. Copy all files other than the package.json and README.md files to a static web server. 2. Browse to the index.html file on your static web server. ## Stripe Upfront Payment Prerequisite 1. Stripe Checkout javascript lib. 1. Stripe Account. This can be done at https://dashboard.stripe.com/register 1. The site is configured to accept Stripe as the payment provider. (Please contact Shortcuts Support to enable the site accepting the Stripe payment). ## How to add in Upfront payment support to webwidget - The Stripe script tag will be loaded during runtime by the WebWidget script. - In the webwidget config (where the OAuth secret key is defined), the following configuration must be added to the config, or the webwidget will not enable the upfront payment capability. [example](js/config.js) ``` authenticationUrl: 'https://pos-api.shortcutssoftware.com/authenticate', paymentGatewayUrl: 'https://7ah8al3ipi.execute-api.us-west-2.amazonaws.com/prod/stripe' ``` - On the [Tenant Console](https://console.shortcutssoftware.com), go to `BookMe Settings > Upfront Payment Settings`, and make sure Stripe is shown as the Upfront Payment provider. Click on `Edit General Settings > Connect with Stripe`. - Authorize Shortcuts to manage your Stripe payment. - Make sure Upfront Payment active is ticked. Save all the changes. - Your client is now able to make upfront payment subject to the upfront payment rules in the Bookme settings. <file_sep>const expect = require('expect.js'); const config = require('../src/config.js'); const site = require('../src/site.js'); const url = require('url'); const authenticate = require('../src/authenticate.js'); describe('Site', function () { this.timeout(5000); var sharedState = { access_token: undefined }; it('must authenticate', function (done) { authenticate.authenticate(function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.access_token).to.not.be(undefined); sharedState.access_token = result.content.access_token; done(); }) }); describe('retrieveEmployeeByEmployeeAlias', function () { it('should be able to retrieve employee', function (done) { site.retrieveEmployeeByEmployeeAlias( sharedState.access_token, 'Katie', function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.employees).to.not.be(undefined); expect(result.content.employees).to.be.an('array'); expect(result.content.employees).to.not.be.empty(); done(); }) }) }); describe('retrieveSiteDetails()', function () { it('should be able to retrieve site details', function (done) { site.retrieveSiteDetails( sharedState.access_token, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content).to.not.be(undefined); expect(result.content).to.be.an('object'); expect(result.content.href).to.not.be(undefined); expect(result.content.href).to.be.an('string'); expect(result.content.href).to.eql(url.resolve(config.apiUri, 'site/' + config.siteId)) done(); }) }) }); describe('retrieveServiceCategories()', function () { it('should be able to retrieve service categories', function (done) { site.retrieveServiceCategories( sharedState.access_token, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.service_categories).to.not.be(undefined); expect(result.content.service_categories).to.be.an('array'); expect(result.content.service_categories).to.not.be.empty(); done(); }) }) }); describe('retrieveServicesByServiceCategoryName()', function () { it('should be able to retrieve service categories', function (done) { site.retrieveServicesByServiceCategoryName( sharedState.access_token, 'Hair Styling', function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.services).to.not.be(undefined); expect(result.content.services).to.be.an('array'); expect(result.content.services).to.not.be.empty(); done(); }) }) }); describe('retrieveServicesByServiceName()', function () { it('should be able to retrieve service', function (done) { site.retrieveServicesByServiceName( sharedState.access_token, 'Blowdry', function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.services).to.not.be(undefined); expect(result.content.services).to.be.an('array'); expect(result.content.services).to.not.be.empty(); done(); }) }) }); describe('retrieveServiceEmployeePricing()', function () { it('should be able to retrieve employee pricing for a service.', function (done) { site.retrieveServiceEmployeePricing( sharedState.access_token, 'Blowdry', function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.employees).to.not.be(undefined); expect(result.content.employees).to.be.an('array'); expect(result.content.employees).to.not.be.empty(); done(); }) }) }); describe('retrieveEmployeeServicePricing', function () { it('should be able to retrieve service pricing for employee', function (done) { site.retrieveEmployeeServicePricing( sharedState.access_token, 'Katie', function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.services).to.not.be(undefined); expect(result.content.services).to.be.an('array'); expect(result.content.services).to.not.be.empty(); done(); }) }) }); });<file_sep>const expect = require('expect.js'); const search = require('../src/search.js'); describe('Search', function () { this.timeout(10000); describe('byServiceCategoryName()', function () { it('should be able to search for availabilities by service category', function (done) { search.byServiceCategoryName('Hair Styling', function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.not.be(undefined); expect(result.content.available_appointments).to.be.an('array'); expect(result.content.available_appointments).to.not.be.empty(); done(); }) }) }); describe('byServiceName()', function () { it('should be able to search for availabilities by service', function (done) { search.byServiceName('Blowdry', function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.not.be(undefined); expect(result.content.available_appointments).to.be.an('array'); expect(result.content.available_appointments).to.not.be.empty(); done(); }) }) }); describe('byServiceAndEmployeeName()', function () { it('should be able to search for availabilities by service and employee', function (done) { search.byServiceAndEmployeeName('Blowdry', 'Katie', function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.not.be(undefined); expect(result.content.available_appointments).to.be.an('array'); expect(result.content.available_appointments).to.not.be.empty(); done(); }) }) }); });<file_sep> # Shortcuts Example: Single Sign On A simple example of how to implement a single signon solution that works with Shortcuts Online Services. ## How it works This is the Shortcuts single signon component diagram: ![Shortcuts single signon component diagram](images/single-signon-components.png) It's describing the components required to make single signon work with Shortcuts Online Services. The diagram is generic because it comes from a design of the single signon solution based on open architectural standards. This example will show you how the various parts of this diagram need to behave and interact with each other, and how to implement them. There are 4 parts _of which you will have to implement only 2_. You can use this example as a starting point for your implementation, by changing it to carry out real authentication using your existing systems. The component parts are: ### 1. The Salon Authorization Server _You will need to implement this component._ The sample implementation of this component is here: [SalonAuthorizationServer.java](src/main/java/com/shortcuts/example/single_signon/salon/SalonAuthorizationServer.java) Essentially this component provides an endpoint where a customer (using a web browser or an app) supplies some credentials for authentication. You will need to implement the actual authentication. The important step is that after you have successfully authenticated the customer, you issue a token and store this token for retrieval later. Along with this token, you will need to store the following information (for later transmission to Shortcuts): ~~~ json { "first_name" : "Orville", "last_name" : "Wright", "email" : "<EMAIL>" } ~~~ ### 2. The Salon Resource Server _You will need to implement this component._ The sample implementation of this component is here: [SalonResourceServer.java](src/main/java/com/shortcuts/example/single_signon/salon/SalonResourceServer.java) This component provides an endpoint that takes a token (obtained in 1 above) and checks to see if it valid. The token is supplied in the `Authorization` header of the request. If the token is valid, then a response containing the information above is returned. That's all you need to implement. However, there are a few additional things that you will need to do: 1. Get valid OAuth credentials to interact with Shortcuts Online Services 2. Let Shortcuts know where your Salon Resource Server (2) is, so that we can use it to validate tokens. ## This is the sequence of events | Step | Who | What | |------|-----------|------| | 1 | You | Authenticate your customer against the Salon Authorization Server, storing the response (customer token) | | 2 | You | Call the `authenticate_customer` endpoint in Shortcuts Online Services, supplying the customer token | | 3 | Shortcuts | Calls your Salon Resource Server using the customer token | | 4 | You | Return customer information if the token is valid | | 5 | Shortcuts | Create a session for the returned customer details | That's essentially all there is to it. There are a few more details that need to be worked through: When you call the `authenticate_customer` endpoint you will still need to authenticate using the OAuth credentials that were issued to your organization. We will only attempt the callback to your Salon Resource Server if these credentials are valid. You supply your OAuth credentials in the `Authorization` header as usual, and you supply the customer token in the request body, formatted as a JSON payload that looks like this: ~~~ json { "credential_type_code": "access_token", "token_type": "<token_type>", "access_token": "<token>" } ~~~ The `<token_type>` is a string value that is agreed between you and Shortcuts when you notify us of the location of your Salon Resource Server. This is often a string like `"dev"` or `"prod"`. Registering multiple token types allows you to specify multiple Salon Resource Servers for different uses. When we call your Salon Resource Server, we will use the HTTP `GET` verb. You can see in the example that the important information in this request is in the `Authorization` header. Don't confuse the authorization header that you send us (which contains OAuth credentials) with the authorization header that we send to your Salon Resource Server (which contains a string that looks like this: `"Bearer <token>"`) ## How to run the example The sample consists of two HTTP servers. The first server listens on port 8080, and has implementations of the Salon Authorization Server endpoint, and the Salon Resource Server endpoint as described above. The second server listens on port 9090, and contains an implementation of the Shortcuts `authenticate_customer` endpoint. The sample implementation is here: [AuthenticateCustomerServer.java](src/main/java/com/shortcuts/example/single_signon/shortcuts/AuthenticateCustomerServer.java) You can regard the servers as a 'Salon' server (on 8080), and 'Shortcuts' server (on 9090). The example is coded in Java, using Spring Boot and gradle. This is not important though - you can implement your own versions of these servers in any language as long as you match the message format and the HTTP verbs that are used here. To run the example: 1. install [Java 8](https://www.oracle.com/java/index.html) and [Gradle 3.5](https://gradle.org/) or above 1. clone the repository 1. change directory into the cloned repository: `cd <repository folder>` 1. build the example: `gradle clean build` 1. start the servers: `java -jar build/libs/single_signon-1.0-SNAPSHOT.jar` At this stage you should see that the servers are listening on port 8080 and 9090. You can then use an API testing tool (like [Postman](https://www.getpostman.com/)) to execute the following requests: #### 1. Authorize a customer using the Salon Authorization Server ~~~ POST /authenticate HTTP/1.1 Host: localhost:8080 { "firstName": "Orville", "lastName": "Wright", "email": "<EMAIL>", "someOtherProperty": "qwertyuiop" } ~~~ which will return a token: ~~~ 77245d1a-49f7-40e6-aa93-6313c43b1ade ~~~ #### 2. Call the Shortcuts `authenticate_customer` endpoint with the customer token ~~~ POST /authenticate_customer HTTP/1.1 Host: localhost:9090 Authorization: OAuth foo { "credential_type_code": "access_token", "token_type": "any", "access_token": "<PASSWORD>" } ~~~ _NB: don't forget to send some OAuth credentials in the `Authorization` header._ The Shortcuts endpoint will return the following response: ~~~ in real life this body would contain a Shortcuts customer session response ~~~ #### 3. If you would like to see what is happening in the Salon Resource Server, you can manually execute the following ~~~ GET /validate HTTP/1.1 Host: localhost:8080 Authorization: Bearer 7<PASSWORD>-49f7-40e6-aa93-6<PASSWORD> ~~~ which will return the following response: ~~~ { "first_name" : "Orville", "last_name" : "Wright", "email" : "<EMAIL>" } ~~~ --- Please contact us if you have any questions about this example. <file_sep>const log = require('../src/log.js'); before(function() { log.level('error'); })<file_sep>package com.shortcuts.example.giftcard.Models.Response; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal; @Data @EqualsAndHashCode(callSuper=false) public class CardServiceResponse extends BaseResponse { @JsonProperty("transaction_id") private String transactionId; @JsonProperty("transaction_ex_tax_amount") private BigDecimal transactionExTaxAmount; @JsonProperty("transaction_inc_tax_amount") private BigDecimal transactionIncTaxAmount; @JsonProperty("member_balance") private MemberBalanceResponse memberBalanceResponse; } <file_sep># Shortcuts Code Examples 1. [Overview](#overview) 1. [Getting Started](#getting-started) 1. [Authentication](#authentication) 1. [Examples](#examples) This repository contains code examples and explanations to assist developers with the use of Shortcuts APIs. This is a public repository licensed under the [ISC License](./LICENSE.txt). You can clone or fork this entire repository. Most examples will work out of the box with Shortcuts Demo sites. If you want to run the examples against your own data then you will need to obtain API Access Keys for your site(s). We usually find that this is a good starting point for API developers to try out general code and processes. When you get to the point where you need to implement your own custom code and processes, that require your own data and business rule setup, then we recommend that you start using the APIs with your own Access Keys. ## Overview The interactions in these examples make use of the individual APIs detailed at [Shortcuts API](http://www.shortcutssoftware.io/developer/). In most examples, each API used is covered in a unit test, so you can debug through the code and observe what is happening. Within the [the API documentation](http://www.shortcutssoftware.io/developer/) you will see detailed information about how to call each of the individual APIs that give access to Shortcuts Online Services. However, to make things simple, these examples start you off with working code that shows the way that individual APIs work together, and how they can be called in sequences that implement common business processes. ### A RESTful API The Shortcuts Online Services API is a [RESTful](https://en.wikipedia.org/wiki/Representational_state_transfer) API, so developers will have an immediate familiarity with it if they have worked with other RESTful APIs. Any language or toolset that supports API interactions of this style will be usable here. In the examples below we frequently provide verbose code rather than rely too heavily on toolsets and libraries. This is so that you get the clearest possible picture of what is happening with the API. In your implementations you will make much more use of abstractions over the API. ### There are two API versions Version 2 Shortcuts Online Services APIs are supported on the `api.shortcutssoftware.io` domain. We will continue to support Version 1 API solutions developed against the `pos.shortcutssoftware.com/webapi` domain, however, the emphasis of our research and development efforts is targeted at the Version 2 API, because we are able to offer a superior API experience, with better performance and reliability this way. You will see a mix of version 1 and version 2 API examples in this repository. Examples will be marked as **(version 2)** or **(version 1)** to help you differentiate between them. The functionality available through version 1 of the Shortcuts API is available through version 2. However, newer functionality may be added to version 2 without being available in version 1. **_If necessary, you can use the version 2 API from a solution that was initially built around version 1._** ## Getting Started Start off by installing `git` and cloning or forking this repository. ### Javascript examples Javascript samples run on top of [nodejs](https://nodejs.org/en/), and use the [mocha](https://mochajs.org) framework for testing. 1. Ensure that nodejs and npm are installed. 1. Change directory to the directory containing the sample. 1. Install node packages:`npm install` 1. Run tests: `npm test` You can also run the tests from your favourite IDE or debugging tool. ### Java examples Java samples run on the [Spring Boot](https://projects.spring.io/spring-boot/) framework, and use the [JUnit](http://junit.org/) framework for testing. 1. Ensure that Java 8 and [gradle](https://gradle.org) are installed. 1. Change directory to the directory containing the sample. 1. Build the example: `gradle build -x test` 1. Run tests: `gradle test` You can also run the tests from your favourite IDE or debugging tool. ## Authentication The biggest difference between the version 2 and the version 1 APIs is the way that requests are authenticated. ### JWT tokens **(version 2)** #### Acquiring JWT tokens When you use the version 2 Shortcuts Online Services API, you must acquire a [JWT token](http://jwt.io) by supplying [OAuth 1.0](https://en.wikipedia.org/wiki/OAuth) credentials, issued when you request community access from Shortcuts Software Ltd, or when an individual user is created. These are what you use when you want to call the APIs as if they were being called by an individual user (or community), where you might want to tailor the permissions granted to the API caller. The capabilities that you will have if you authenticate this way can be individually configured without affecting the operation of your on-premise software. When you correctly sign the request to the authenticate endpoint, you will be given a JWT token which will give you access to the API for 30 minutes. The token expiry time is stored in the token itself, so you can see it, and if you wish you can proactively acquire a new token when yours approaches expiry. Tokens are cheap and can be discarded and/or reacquired at will. **_Important: Each time you call the version 2 Shortcuts API you must supply a valid JWT token in the `Authorization` header._** Please take a look at the following class to see an example of version 2 API authentication: - [Version 2 API authentication in Javascript](./v2-examples/js/src/authenticate.js) - [Version 2 API authentication in Java](./v2-examples/java/src/main/java/com/shortcuts/example/java/authentication/JWTOAuthAuthenticationService.java) ### OAuth authentication **(version 1)** #### Signing requests When you use the version 1 Shortcuts Online Services API, you must sign every request according to the [OAuth 1.0](https://en.wikipedia.org/wiki/OAuth) specification. There is no actual _authentication_ operation, rather, each request is processed when it is sent to the version 1 API. If the request's OAuth signature is valid then the request will be processed. OAuth credentials are issued when you request community access from Shortcuts Software Ltd, or when an individual user is created. These are what you use when you want to call the APIs as if they were being called by an individual user (or community), where you might want to tailor the permissions granted to the API caller. Please take a look at the following example: - [Version 1 API authentication](./v1-examples/js/src/oauth.js) **_Important: Each time you call the version 1 Shortcuts API you must sign the request in this way._** ### Comparison The big differences between authentication for the version 1 and the version 2 APIs are: - Using the version 2 API - You only need to authenticate once to acquire a JWT token (until the token expires). - Using the version 1 API - You need to sign every request individually. ## Examples ### Functional areas API usage generally falls into one or more of the areas discussed below. For example, the most common business process is to create a booking. One way that this could be done is as follows: 1. Search for services at a site, 1. Select a service, 1. Search for employees at a site, 1. Select an employee, 1. Search for available appointments for that service and employee, 1. Create a booking. Following these steps will take you through some of the areas below. ##### You are not limited to just the business processes in the examples that follow It is entirely valid for you to make calls to various APIs below, and then make bookings based on your own combinations of the data returned, for your own reasons. For example: you could search for all employees who are struggling to meet their `visit_count` kpi target, and prefer them when making appointments. ### Company The Company APIs are used to retrieve information about the business (the brand) from the Shortcuts API. This is an example of a signed [Postman](https://www.getpostman.com) request to the version 1 API to retrieve the sites that belong to a company: ```text GET /webapi/company/2200/sites HTTP/1.1 Host: pos.shortcutssoftware.com Authorization: OAuth oauth_consumer_key="<KEY>",oauth_token="<KEY>",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1517377823",oauth_nonce="SsMPLr4K3Nb",oauth_version="1.0",oauth_signature="tmHi1kJOlx9lAsePozsqR31%2Bc0I%3D" Cache-Control: no-cache Postman-Token: <PASSWORD> ``` The response is: ```json { "sites": [ { "display_name": "My Business 1", "updated_utc_date_time": "2012-03-30T01:21:47", "created_utc_date_time": "2012-03-30T01:21:47", "version": "0", "description": "", "href": "https://pos.shortcutssoftware.com/webapi/site/17844" }, { "display_name": "My Business 2", "updated_utc_date_time": "2017-06-11T21:16:13", "created_utc_date_time": "2012-03-30T01:21:47", "version": "0", "description": "", "href": "https://pos.shortcutssoftware.com/webapi/site/17843" }, { "display_name": "My Business 3", "updated_utc_date_time": "2017-06-11T21:16:12", "created_utc_date_time": "2012-03-30T01:21:47", "version": "0", "description": "", "href": "https://pos.shortcutssoftware.com/webapi/site/17842" }, { "display_name": "My Business 4", "updated_utc_date_time": "2017-06-19T04:06:11", "created_utc_date_time": "2015-04-21T06:01:45", "version": "0", "href": "https://pos.shortcutssoftware.com/webapi/site/30179" } ], "paging": { "page": 1, "number_of_pages": 1 }, "href": "https://pos.shortcutssoftware.com/webapi/company/2200/sites" } ``` This is the same request made to the version 2 API: ```text GET /company/2200/sites HTTP/1.1 Host: api.shortcutssoftware.io Authorization: JWT <KEY>.<KEY> Cache-Control: no-cache Postman-Token: <PASSWORD> ``` The response is: ```json { "sites": [ { "display_name": "My Business 1", "updated_utc_date_time": "2012-03-30T01:21:47", "created_utc_date_time": "2012-03-30T01:21:47", "version": "0", "description": "", "href": "https://api.shortcutssoftware.io/site/17844" }, { "display_name": "My Business 2", "updated_utc_date_time": "2017-06-11T21:16:13", "created_utc_date_time": "2012-03-30T01:21:47", "version": "0", "description": "", "href": "https://api.shortcutssoftware.io/site/17843" }, { "display_name": "My Business 3", "updated_utc_date_time": "2017-06-11T21:16:12", "created_utc_date_time": "2012-03-30T01:21:47", "version": "0", "description": "", "href": "https://api.shortcutssoftware.io/site/17842" }, { "display_name": "My Business 4", "updated_utc_date_time": "2017-06-19T04:06:11", "created_utc_date_time": "2015-04-21T06:01:45", "version": "0", "href": "https://api.shortcutssoftware.io/site/30179" } ], "paging": { "page": 1, "number_of_pages": 1 }, "href": "https://api.shortcutssoftware.io/company/2200/sites" } ``` As you can see, the responses are identical except for the difference in `href` elements, which indicate the version of the API that should be called to retrieve further details. ### Site The Site APIs are used to retrieve information about the real physical locations of the business through the Shortcuts API. The Sites APIs will give you information about: - Service categories and services, - Employees, - Pricing, - Available appointments. For instance, this code will search for service definitions (by name) in a site: ```js var siteHref = url.resolve(config.apiUri, 'site/' + config.siteId) function retrieveServicesByServiceName(jwtToken, serviceName, done) { api.get( url.resolve(siteHref + '/', 'services?search=' + serviceName + '&is_active=true&is_bookable=true&is_customer_bookable=true&fields=display,href'), {Authorization: 'JWT ' + jwtToken}, done); } ``` Please refer to [site.js version 2 examples](./v2-examples/js/src/site.js), or [site.js version 1 examples](./v1-examples/js/src/site.js) for more ways to interact with the Site APIs. ### Customer The Customer APIs will allow you to manage information related to your customers. This includes information about the customers themselves, like contact details, as well as information about customer bookings. And for apps that are put in the hands of a customer, there are also APIs to manage customer sessions. For instance, this code will attempt to authenticate a customer: ```js var companyHref = url.resolve(config.apiUri, 'company/' + config.companyId); function authenticateCustomer(jwtToken, username, password, done) { api.post( url.resolve(companyHref + '/', 'authenticate_customer'), {Authorization: 'JWT ' + jwtToken}, { credential_type_code: 'password', username: username, password: <PASSWORD> }, done); } ``` ### Appointment The Appointment APIs allow you to manage appointments for customers. The appointment is where services, employees, rosters and customers come together, so the Appointment APIs are never used in isolation. Please refer to [appointment.js version 2 examples](./v2-examples/js/src/appointment.js), or [appointment.js version 1 examples](./v1-examples/js/src/appointment.js) for more ways to interact with the Appointment APIs. ### Common API queries and solutions in the API In this section you will find examples of using the API to solve common scenarios used in the booking process. It is a useful place to start for specific working examples of different scenarios that may occur. An in-depth knowledge of the API is not required to get started with these examples #### Booking [Common booking tasks](./v1-examples/common) ### Calling the Shortcuts API from the Java language Please refer here for an end-to-end example of using the Shortcuts API from the Java language. [Java API Example](./v2-examples/java) ### Calling the Shortcuts API through the Shortcuts Widgets You do not necessarily have to write code to call the Shortcuts APIs. For many common tasks and processes, we provide the Shortcuts Widgets, that can be embedded in your website, and provide seamless access to the Shortcuts APIs to your website users. _The widgets can be styled vi CSS to match your brand._ This example shows a basic workflow using the Shortcuts Widgets and Online Services with minimal changes from the widgets natural workflow order. [Default Worklow using Widgets](./widgets-examples/default-workflow) ### Single Sign-on The single sign-on facility is required when you want to use your own systems to authenticate customers, rather than relying on Shortcuts Online Services. This example shows how the single sign-on process works. It is only intended for implementors of single sign-on. You can still use all the capabilities in the Shortcuts API without implementing single sign-on. [Single Signon](./other/single-signon) --- ## Notes: - When you develop request patterns that allow you to follow complex business processes that are not covered in these examples, we would love to know about them. Please consider forking this repository, and creating a [pull request](https://help.github.com/articles/about-pull-requests/) if you would like to share your creations. - Please [email us](mailto:<EMAIL>) if you have any questions about this example. <file_sep>package com.shortcuts.example.java; import lombok.NonNull; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import java.net.URI; import java.util.Optional; public class BaseUrlAware { @Value("${baseUrl}") private String baseUrl; public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } public String getBaseUrl() { return baseUrl; } public URI getEndpointURI(String path, Object... uriVariables) { return getEndpointURI(path, Optional.empty(), uriVariables); } public URI getEndpointURI( String path, @NonNull Optional<MultiValueMap<String, String>> queryParameters, Object... uriVariables) { UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl(baseUrl); if (path != null) { if (!path.startsWith("/")) { path = String.format("/%s", path); } } else { path = "/"; } uriComponentsBuilder.path(path); queryParameters.ifPresent(uriComponentsBuilder::queryParams); UriComponents uriComponents; if (uriVariables != null) { uriComponents = uriComponentsBuilder.buildAndExpand(uriVariables); } else { uriComponents = uriComponentsBuilder.build(); } return uriComponents.toUri(); } } <file_sep>const expect = require('expect.js'); const config = require('../src/config.js'); const authenticate = require('../src/authenticate.js'); const _ = require('underscore'); const jwtDecode = require('jwt-decode'); describe('Appointment', function () { this.timeout(10000); var sharedState = { access_token: undefined }; describe('Authentication operation', function () { it('should be able to authenticate using configured user', function (done) { authenticate.authenticate(function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.access_token).to.not.be(undefined); expect(result.content.access_token).to.be.an('string'); sharedState.access_token = result.content.access_token; var decoded = jwtDecode(sharedState.access_token); var roles = decoded.roles; var user = decoded.user; var exp = new Date(); exp.setTime(decoded.exp * 1000); // jwt expiry is in seconds console.log('authenticated roles: ', roles); console.log('authenticated user: ', user); console.log('token expiration time: ', new Date(exp)); done(); }) }); }); });<file_sep># Shortcuts Widgets THC Sample Sample website implementation over the Shortcuts Widgets. ## Getting Started These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. ### Running website using Node 1. Ensure that Node.JS and NPM are installed. 2. Install node packages ``` npm install ``` 3. Run server ``` npm start ``` ### Running website by static content delivery This website has been designed to be able to be run independently of a dynamic server by copying the files to an accessible web location. It is recommended that the website is not run from the file directory as this can cause issues with AJAX calls. 1. Copy all files other than the package.json and README.md files to a static web server. 2. Browse to the index.html file on your static web server.<file_sep>package com.shortcuts.example.java.authentication; import com.shortcuts.example.java.BaseUrlAware; import com.shortcuts.example.java.util.RestTemplateCallingUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.security.oauth.common.signature.SharedConsumerSecretImpl; import org.springframework.security.oauth.consumer.BaseProtectedResourceDetails; import org.springframework.security.oauth.consumer.OAuthConsumerToken; import org.springframework.security.oauth.consumer.client.CoreOAuthConsumerSupport; import org.springframework.security.oauth.provider.BaseConsumerDetails; import org.springframework.stereotype.Service; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; @Slf4j @Service public class JWTOAuthAuthenticationService extends BaseUrlAware implements JWTAuthentication { @Autowired private RestTemplateCallingUtil restTemplateCallingUtil; @Value("${authentication.oauth.consumerKey}") private String consumerKey; @Value("${authentication.oauth.consumerSecret}") private String consumerSecret; @Value("${authentication.oauth.accessKey}") private String accessKey; @Value("${authentication.oauth.accessSecret}") private String accessSecret; public RestTemplateCallingUtil getRestTemplateCallingUtil() { return restTemplateCallingUtil; } public String getConsumerKey() { return consumerKey; } public String getConsumerSecret() { return consumerSecret; } public String getAccessKey() { return accessKey; } public String getAccessSecret() { return accessSecret; } @Override public String authenticate() { // set up empty authentication request object with AuthenticationRequest authenticationRequest = new AuthenticationRequest(); authenticationRequest.setCredential_type_code("oauth"); HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add(HttpHeaders.AUTHORIZATION, getSignedAuthorizationHeader()); // call the api AuthenticationResponse authenticationResponse = restTemplateCallingUtil.postForObject( getEndpointURI("authenticate"), httpHeaders, authenticationRequest, AuthenticationResponse.class); String jwtToken = authenticationResponse.getAccess_token(); log.info("authentication result: {}", jwtToken); return jwtToken; } /** * sign request with oauth credentials. we are using * spring-security-oauth here, but you can use any * method that complies with the standard. */ private String getSignedAuthorizationHeader() { BaseConsumerDetails baseConsumerDetails = new BaseConsumerDetails(); baseConsumerDetails.setConsumerKey(getConsumerKey()); baseConsumerDetails.setSignatureSecret(new SharedConsumerSecretImpl(getConsumerSecret())); BaseProtectedResourceDetails resource = new BaseProtectedResourceDetails(); resource.setId("MyExampleApplication"); resource.setConsumerKey(baseConsumerDetails.getConsumerKey()); resource.setSharedSecret(baseConsumerDetails.getSignatureSecret()); OAuthConsumerToken oAuthConsumerToken = new OAuthConsumerToken(); oAuthConsumerToken.setResourceId(resource.getId()); oAuthConsumerToken.setAccessToken(true); oAuthConsumerToken.setValue(getAccessKey()); oAuthConsumerToken.setSecret(getAccessSecret()); URL endpointUrl; try { endpointUrl = getEndpointURI("authenticate").toURL(); } catch (MalformedURLException e) { throw new RuntimeException(e); } return new CoreOAuthConsumerSupport().getAuthorizationHeader( resource, oAuthConsumerToken, endpointUrl, HttpMethod.POST.name(), Collections.emptyMap()); } } <file_sep>const expect = require('expect.js'); const authenticate = require('../src/authenticate.js'); const config = require('../src/config.js'); const api = require('../src/api.js'); const url = require('url'); describe('API', function () { this.timeout(5000); describe('request()', function () { var sharedState = { access_token: undefined }; it('must authenticate', function (done) { authenticate.authenticate(function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.access_token).to.not.be(undefined); sharedState.access_token = result.content.access_token; done(); }) }); it('authenticated request must return 200', function (done) { api.get( url.resolve(config.apiUri, 'site/' + config.siteId), { Authorization: 'JWT ' + sharedState.access_token }, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.href).to.eql(url.resolve(config.apiUri, 'site/' + config.siteId)); done(); }) }); it('unauthenticated request must return 401', function (done) { api.get( url.resolve(config.apiUri, 'site/' + config.siteId), null, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(401); done(); }) }); }) });<file_sep># Common API questions and example solutions ### Customer knows they want a specific service in a specific date/time window but doesn’t know who with. Firstly, prepare a date-time filter ```js var fromDate = new Date(new Date().getTime() + 3 * 24 * 60 * 60 * 1000); var toDate = new Date(new Date().getTime() + 14 * 24 * 60 * 60 * 1000); var dateTimeFilter = { from_date: fromDate.getFullYear().toString() + '-' + (fromDate.getMonth() + 1) + '-' + fromDate.getDate(), to_date: toDate.getFullYear().toString() + '-' + (toDate.getMonth() + 1) + '-' + toDate.getDate(), start_time: '00:00:00', finish_time: '23:59:59', days_of_week: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] }; ``` Then use it when searching for available appointments. Note, in this search, the service is known, and is able to be supplied as a parameter. ```js function byServiceNameAndDateTimeFilter(serviceName, dateTimeFilter, done) { site.retrieveServicesByServiceName(serviceName, function (err, result) { if (err) { done(err); return; } var serviceHref = result.content.services[0].href; api.post( url.resolve(siteHref + '/', 'calculate_available_appointments'), { requested_services: [{ gender_code: 'unknown', links: [ {rel: 'site/service', href: serviceHref} ] }], date_time_filter: [dateTimeFilter] }, done); }); } ``` Please refer to test of `search.byServiceNameAndDateTimeFilter` in [common-tasks.js](../../v2-examples/js/test/common-tasks.js), and also function `byServiceNameAndDateTimeFilter()` in [search.js](../js/src/search.js) ### Customer wants category of service (e.g. massage) in a specific date/time window but doesn’t know which kind of massage or who with. Firstly, prepare a date-time filter as before. Then use it when searching for available appointments. Note, in this search, the service category is known, but is not able to be supplied as a parameter. We use the service category to get a list of services, and then call `calculate_avilable_appointments` for them all. The result is the union of all the individual search results. ```js function byServiceCategoryAndDateTimeFilter(serviceCategoryName, dateTimeFilter, done) { site.retrieveServicesByServiceCategoryName(serviceCategoryName, function (err, result) { if (err) { done(err); return; } var availabilitySearches = []; for (var i = 0; i < result.content.services.length; i++) { var serviceHref = result.content.services[i].href; availabilitySearches.push(new Promise(function (resolve, reject) { api.post( url.resolve(siteHref + '/', 'calculate_available_appointments'), { requested_services: [{ gender_code: 'unknown', links: [ {rel: 'site/service', href: serviceHref} ] }], date_time_filter: [dateTimeFilter] }, function (err, result) { if (err) reject(err); else resolve(result); }); })); } log.info('Searching for %s services', availabilitySearches.length); Promise.all(availabilitySearches).then( function (results) { var result = {status: 200, content: {available_appointments: []}}; log.info('Processing results: %s', JSON.stringify(results)); for (var i = 0; i < results.length; i++) { result.content.available_appointments = _.union(result.available_appointments, results[i].content.available_appointments); } done(null, result); }, function (err) { done(err); } ); }) } ``` Please refer to test of `search.byServiceCategoryAndDateTimeFilter` in [common-tasks.js](../../v2-examples/js/test/common-tasks.js), and also function `byServiceCategoryAndDateTimeFilter()` in [search.js](../js/src/search.js) ### Customer wants specific service with specific stylist/therapist but doesn’t know available times/dates or gives range of date/time. Firstly, prepare a date-time filter as before. Then use it when searching for available appointments. Note, in this search, the service definition is retrieved, as well as the employee definition. these are then used as parameters to call `calculate_avilable_appointments`. ```js function byServiceAndEmployeeNameAndDateTimeFilter(serviceName, employeeAlias, dateTimeFilter, done) { Promise.all([ new Promise(function (resolve, reject) { site.retrieveServicesByServiceName(serviceName, function (err, result) { if (err) reject(err); else resolve(result); }) }), new Promise(function (resolve, reject) { site.retrieveEmployeeByEmployeeAlias(employeeAlias, function (err, result) { if (err) reject(err); else resolve(result); }) }) ]).then( function (results) { var serviceHref = results[0].content.services[0].href; var employeeHref = results[1].content.employees[0].href; api.post( url.resolve(siteHref + '/', 'calculate_available_appointments'), { requested_services: [{ gender_code: 'unknown', links: [ {rel: 'site/service', href: serviceHref}, {rel: 'site/employee', href: employeeHref} ] }], date_time_filter: [dateTimeFilter] }, done); }, function (err) { done(err); } ); } ``` Please refer to test of `search.byServiceAndEmployeeNameAndDateTimeFilter` in [common-tasks.js](../../v2-examples/js/test/common-tasks.js), and also function `byServiceAndEmployeeNameAndDateTimeFilter()` in [search.js](../js/src/search.js) ### Customer wants specific service within time/date window, wants to choose price band, doesn’t know who with. Firstly, prepare a date-time filter as before. Then, prepare a price band definition as follows: ```js var priceBand = { upper: 100, lower: 10 }; ``` Then, since the service is known, we can reuse the logic that allows us to search by specific service and date-time range. After executing this search, we iterate through the results, keeping only the appointments that fall within the price band. ```js function byServiceNameAndDateTimeFilterAndPriceBand(serviceName, dateTimeFilter, priceBand, done) { byServiceNameAndDateTimeFilter(serviceName, dateTimeFilter, function (err, result) { if (err) { done(err) } // filter available appointments by price band var filtered = []; for (var i = 0; i < result.content.available_appointments.length; i++) { var available_appointment = result.content.available_appointments[i]; if (!priceBand) { filtered.push(available_appointment); } else { if ((priceBand.lower <= available_appointment.sell_price) && (priceBand.upper >= available_appointment.sell_price)) { filtered.push(available_appointment); } } } result.content.available_appointments = filtered; done(null, result); }); } ``` Please refer to test of `search.byServiceNameAndDateTimeFilterAndPriceBand` in [common-tasks.js](../../v2-examples/js/test/common-tasks.js), and also function `byServiceNameAndDateTimeFilterAndPriceBand()` in [search.js](../js/src/search.js) ### Customer to be able to cancel booking before cancellation period expiration/cut off. This is a single-step process. The function takes three arguments: 1. the customer session href from the authenticateCustomer step. 1. an appointment href. 1. a callback of the form `function(err, result)`. ```js function cancelAppointment(customerSessionHref, appointmentHref, done) { var siteCustomerSessionHref = customerSessionHref.replace(companyHref, siteHref); var siteCustomerSessionAppointmentHref = appointmentHref.replace(siteHref, siteCustomerSessionHref + '/customer'); api.del(siteCustomerSessionAppointmentHref, done); } ``` Please refer to `cancelAppointment()` in [appointment.js](../js/src/appointment.js) ### Rescheduling The process of rescheduling an existing appointment is not available through the Shortcuts Widgets, but it is easy to implement using direct calls to the Shortcuts API. Please refer to [../js/test/appointment_reschedule.js](../js/test/appointment_reschedule.js) for a set of test cases that go through the process of booking an appointment, and then rescheduling it. The implementation of the calls is in the file [../js/src/appointment_reschedule.js](../js/src/appointment_reschedule.js). The sequence of steps in the test is as follows: First, we authenticate the customer. This example uses a slightly different method of customer authentication - we first authenticate against a 3rd party service, and then call the Shortcuts API using the token provided by the 3rd party service. ```js function authenticateCustomer(username, password, done) { api.get(url.resolve(config.tomaxUri, 'authenticate/' + username + '/' + password), function (err, result) { if (err) { done(err); } if (result.status != 200) { done(new Error('3rd party authentication failed')); } var bearerToken = result.content; var authenticateRequestBody = { credential_type_code: 'access_token', token_type: 'thc', customer_id: config.customerId, access_token: bearerToken }; api.post(url.resolve(companyHref + '/', 'authenticate_customer'), authenticateRequestBody, function (err, result) { if (err) { done(err); } if (result.status != 200) { done(new Error('Shortcuts single sign-on validation failed')); } done(null, result); }) }); } ``` Then, we search for available appointments for a service. The choice of service here is arbitrary. Please see other examples if you require more sophisticated searches for available appointments. Please also note that we select the first available slot for booking, but we also record the time of the second available slot for later rescheduling. ```js sharedState.appointmentDetails = result.content.available_appointments[0]; // remember these details for the reschedule operation later var nextAppointment = result.content.available_appointments[1]; sharedState.next_scheduled_date = nextAppointment.scheduled_date; sharedState.next_start_time = nextAppointment.services[0].start_time; ``` Then, we book an appointment, as in other examples. Then, we retrieve the details of the appointment we have just created, including the appointment version. We create a clone of these details, and change the date and time to match the date and time of the 2nd available slot that we recorded earlier. ```js var rescheduleAppointmentRequest = _.clone(sharedState.appointment); rescheduleAppointmentRequest.scheduled_date = sharedState.next_scheduled_date rescheduleAppointmentRequest.start_time = sharedState.next_start_time; ``` Finally, we use this appointment definition to to reschedule the appointment. After the reschedule operation, you can use the `version` attribute of the appointment to verify that changes have been made to the appointment. You can also inspect the `scheduled_date` and `start_time` attributes. ```js var oldVersion = sharedState.appointment.version; console.log('version before reschedule:', oldVersion) ``` ... ```js var newVersion = result.content.version; console.log('version after reschedule:', newVersion); expect(newVersion).to.be.above(oldVersion); ``` <file_sep>const randomInt = require('random-int'); const CryptoJS = require("crypto-js"); const _ = require('underscore'); const config = require('./config.js') const log = require('./log.js'); var oauth = (function () { function randomString(length, chars) { var result = ''; for (var i = length; i > 0; --i) result += chars[randomInt(0, chars.length)]; return result; } function generateNonce() { return randomString(8, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'); } function generateTimestamp() { return Math.floor((new Date()).getTime() / 1000); } function encode(value) { if (value == null) { return ''; } if (value instanceof Array) { var e = ''; for (var i = 0; i < value.length; ++value) { if (e != '') e += '&'; e += encode(value[i]); } return e; } value = encodeURIComponent(value); value = value.replace(/\!/g, "%21"); value = value.replace(/\*/g, "%2A"); value = value.replace(/\'/g, "%27"); value = value.replace(/\(/g, "%28"); value = value.replace(/\)/g, "%29"); return value; } function sign(method, url, options) { var options = _.extend({}, options); // Parse the URL into parts // Note that we are currently assuming that the url is already in canonical format, i.e. standardized scheme, port and domain. var urlParts = url.split('?'); var url = urlParts[0]; var query = urlParts[1]; var queryParams = []; if (query) { queryParams = _.map(query.split('&'), function (param) { var paramParts = param.split('='); return { key: encode(decodeURIComponent(paramParts[0])), value: encode(decodeURIComponent(paramParts[1])) }; }); } // Generate anti-replay values var nonce = (options.generateNonce || generateNonce)(); var timestamp = (options.generateTimestamp || generateTimestamp)(); // Generate the oauth parameters var oauthParams = [ { key: 'oauth_consumer_key', value: encode(config.consumerKey) }, { key: 'oauth_nonce', value: nonce }, { key: 'oauth_signature_method', value: 'HMAC-SHA1' }, { key: 'oauth_timestamp', value: timestamp }, { key: 'oauth_token', value: encode(config.accessTokenKey) }, { key: 'oauth_version', value: '1.0' } ]; // Combine in the query paramaters and sort them. var sortedParams = _.union(queryParams, oauthParams).sort(function (left, right) { if (left.key < right.key) { return -1; } else if (left.key > right.key) { return 1; } else if (left.value < right.value) { return -1; } else if (left.value > right.value) { return 1; } else { return 0; } }); log.info('URL: %s', url); log.info('Parameters: %s', JSON.stringify(sortedParams)); // Format the parameters back into a single string. var formattedParams = _.map(sortedParams, function (param) { return param.key + '=' + param.value; }).join('&'); // Calculate the OAuth Signature var base = method + '&' + encode(url) + '&' + encode(formattedParams); var key = encode(config.consumerSecret) + '&' + encode(config.accessTokenSecret); var signatureBytes = CryptoJS.HmacSHA1(base, key); var signature = signatureBytes.toString(CryptoJS.enc.Base64); log.info('Signing %s with %s', base, key); log.info('Resulting signature is %s', signature); // Compile the OAuth Header var authHeader = 'OAuth realm="' + url + '", ' + 'oauth_consumer_key="' + encode(config.consumerKey) + '", ' + 'oauth_token="' + encode(config.accessTokenKey) + '", ' + 'oauth_nonce="' + nonce + '", ' + 'oauth_timestamp="' + timestamp + '", ' + 'oauth_signature_method="' + 'HMAC-SHA1' + '", ' + 'oauth_version="' + '1.0' + '", ' + 'oauth_signature="' + encode(signature) + '"'; return authHeader; }; return { sign: sign } })(); module.exports = oauth <file_sep># Shortcuts JavaScript API Sample Sample api implementation using JavaScript. ## Getting Started These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. ### Running website using Node 1. Ensure that Node.JS and NPM are installed. 2. Install node packages ``` npm install ``` 3. Run tests ``` npm test ``` The logging level used during the tests can be updated through the editing the [Test Hooks](src/_hooks.js) directives. ## Source Documentation The following modules are available as part of this example. The ones of particular interest are the [Site](#site), [Search](#search) and [Appointment](#appointment) modules. * The API module ([source](src/api.js)) provides HTTP operations against the Shortcuts API. * The Appointment module([source](src/appointment.js)) provides the ability to manage appointments on behalf of customers, including booking, retrieving and cancelling appointments. * The Config module ([source](src/config.js)) provides configuration of access information, including credentials and target salon identifier. * The Log module ([source](src/log.js)) configures logging parameters. * The OAuth module ([source](src/oauth.js)) provides for calculation of a signature for the purposes of authenticating requests against the API. This is implementated according to the OAuth 1.1 RFC. * The Site module ([source](src/site.js)) provides for API operations to retrieve general information about the target salon. * The Search module ([source](src/search.js)) provides for searching of available appointments at the target salon. The [Site](#site), [Search](#search) and [Appointment](#appointment) modules are described in greater detail below. ### <a name=appointment></a>Appointment Module The Appointment module provides for the following operations: #### <a name=authenticate></a>authenticate Authenticates a customer against the API, providing a customer session hyperlink reference that may be used for the other API endpoints in this module. The function takes three arguments, the first being the customer username, the second being the customer plain-text password and the third being a callback of the form `function(err, result)`. If an error occured, the `err` property will contain the error information. The `result` contains the `status` and the `content` of the response. An example `result.content` that may be retrieved with this function is: Example: ```js appointment.authenticate(username, password, function(err, result) { console.log(result.content); var customerSessionHref = result.content.href; }); ``` Result: ```json { "expiry_utc_date_time":"2017-11-22T03:50:40.8076178Z", "customer":{ "display_name":"<NAME>", "first_name":"Michael", "last_name":"Walters", "is_active":true, "phone_numbers":[ {"type_code":"mobile","number":"12345678"} ], "email":"<EMAIL>", "preferred_contact_method_code":"email", "gender_code":"unknown", "display_image":"https://pos.shortcutssoftware.com/webapi/company/2200/images/customer/91557473.jpg?updated_utc_date_time=2016-08-11T07%3A13%3A38%2B00%3A00", "links":[{ "rel":"resource/preferred_site", "display_name":"My Business 4", "href":"https://pos.shortcutssoftware.com/webapi/site/30179" }], "created_utc_date_time":"0001-01-01T00:00:00", "updated_utc_date_time":"2017-10-23T03:35:19", "version":0, "customer_relationships":[], "href":"https://pos.shortcutssoftware.com/webapi/company/2200/customer/91557473" }, "href":"https://pos.shortcutssoftware.com/webapi/company/2200/customer_session/592a60LCurDNn1om" } ``` #### <a name=bookAppointment></a>bookAppointment Books an appointment for the customer against the API. The function takes three arguments, the first being the customer session href from [authenticate](#authenticate), the second being an available appointment as per the response from the [Search](#search) module and the third being a callback of the form `function(err, result)`. If an error occured, the `err` property will contain the error information. The `result` contains the `status` and the `content` of the response. An example `result.content` that may be retrieved with this function is: Example: ```js appointment.bookAppointment( 'https://pos.shortcutssoftware.com/webapi/company/2200/customer_session/592a60LCurDNn1om', { "services": [ { "start_time":"10:00:00", "sell_price":50, "duration":"PT15M", "links": [ { "rel":"resource/service", "display_name":"<NAME>", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service/6/block/1" },{ "rel":"resource/employee", "display_name":"John", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/employee/1" } ] }], "scheduled_date":"2017-10-21", "duration":"PT15M", "sell_price":50, "links":[{ "rel":"resource/site", "href":"https://pos.shortcutssoftware.com/webapi/site/30179" }] }, function(err, result) { console.log(result.content); } ); ``` Successful Result: ```json { "appointments":[ { "href":"https://pos.shortcutssoftware.com/webapi/site/30179/appointment/387" } ], "href":"https://pos.shortcutssoftware.com/webapi/site/30179/appointments" } ``` Failed Result: ```json { "error_type_code":"system", "message":"Proposed appointment is no longer available" } ``` #### <a name=retrieveAppointments></a>retrieveAppointments Retrieves appointments for the customer against the API. The function takes two arguments, the first being the customer session href from [authenticate](#authenticate) and the second being a callback of the form `function(err, result)`. If an error occured, the `err` property will contain the error information. The `result` contains the `status` and the `content` of the response. An example `result.content` that may be retrieved with this function is: Example: ```js appointment.retrieveAppointments( 'https://pos.shortcutssoftware.com/webapi/company/2200/customer_session/592a60LCurDNn1om', function(err, result) { console.log(result.content); } ); ``` Result: ```json { "appointments": [ { "start_time":"20:00:00", "scheduled_date":"2017-10-32", "duration":"PT15M", "status_code":"awaiting_review", "appointment_type_code":"client_appointment", "links":[{ "phone_numbers":[{"type_code":"mobile","number":"041775183"}], "first_name":"Michael", "last_name":"Walters", "rel":"resource/customer", "updated_utc_date_time":"2017-10-23T03:35:19", "display_name":"<NAME>", "display_image":"https://pos.shortcutssoftware.com/webapi/company/2200/images/customer/91557473.jpg?updated_utc_date_time=2016-08-11T07%3A13%3A38%2B00%3A00", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/customer/91557473" },{ "rel":"resource/employee", "display_name":"John", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/employee/1" },{ "has_prepayment":false, "has_notes":false, "booking_status_code":"booked", "start_date":"2017-10-24", "version":6, "rel":"resource/booking", "created_utc_date_time":"2017-10-23T00:57:51+00:00", "updated_utc_date_time":"2017-10-23T01:55:09+00:00", "display_name":"<NAME>", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/booking/28" },{ "rel":"resource/service", "display_name":"Wax Leg","href":"https://pos.shortcutssoftware.com/webapi/site/30179/service/6" },{ "rel":"resource/site", "display_name":"My Business 4", "href":"https://pos.shortcutssoftware.com/webapi/site/30179" }], "is_active":true, "updated_utc_date_time":"2017-10-23T00:57:51Z", "version":2, "href":"https://pos.shortcutssoftware.com/webapi/site/30179/appointment/387" } ] } ``` #### cancelAppointment Cancels an appointment for the customer against the API. The function takes three arguments, the first being the customer session href from [authenticate](#authenticate) and the second being an appointment href from either [bookAppointment](#bookAppointment) or [retrieveAppointments](#retrieveAppointments) and the third being a callback of the form `function(err, result)`. If an error occured, the `err` property will contain the error information. The `result` contains the `status` and the `content` of the response. An example `result.content` that may be retrieved with this function is: Example: ```js appointment.cancelAppointment( 'https://pos.shortcutssoftware.com/webapi/company/2200/customer_session/592a60LCurDNn1om', 'https://pos.shortcutssoftware.com/webapi/site/30179/appointment/387', function(err, result) { console.log(result.content); } ); ``` Result: ``` OK ``` ### <a name=site></a>Site Module The Site module provides the following operations: #### retrieveSiteDetails Retrieves the site information from the server. The function takes one argument, being a callback of the form `function(err, result)`. If an error occured, the `err` property will contain the error information. The `result` contains the `status` and the `content` of the response. An example `result.content` that may be retrieved with this function is: Example: ```js site.retrieveSiteDetails(function (err, result) { console.log(result.content); }); ``` Result: ```json { "display_name": "My Business 4", "updated_utc_date_time": "2017-06-19T04:06:11","created_utc_date_time":"2015-04-21T06:01:45", "version":"0", "links":[ { ... } ], "is_active":true, "is_subscribed":false, "is_connected":true, "href":"https://pos.shortcutssoftware.com/webapi/site/30179" } ``` #### retrieveServiceCategories Retrieves the service categories from server. The function takes one argument, being a callback of the form `function(err, result)`. If an error occured, the `err` property will contain the error information. The `result` contains the `status` and the `content` of the response. An example `result.content` that may be retrieved with this function is: Example: ```js site.retrieveServiceCategories(function (err, result) { console.log(result.content); }); ``` Result: ```json { "service_categories": [ { "display_name":"Beauty", "version":3, "updated_utc_date_time":"2016-12-11T09:22:28", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/se rvice_category/2" },{ "display_name":"Hair", "version":3, "updated_utc_date_time":"2016-12-11T09:22:28", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service_category/1" } ], "paging": { "page":1, "number_of_pages":1 }, "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service_categories" } ``` #### retrieveServicesByServiceCategoryName Retrieves the services from the server belonging to a service category with a specific name. The function takes two arguments, the first being the `serviceCategoryName`, the second being a callback of the form `function(err, result)`. If an error occured, the `err` property will contain the error information. The `result` contains the `status` and the `content` of the response. An example `result.content` that may be retrieved with this function is: Example: ```js site.retrieveServicesByServiceCategoryName('Beauty', function (err, result) { console.log(result.content); }); ``` Result: ```json { "services": [ { "display_name":"Wax Back", "created_utc_date_time":"2015-04-22T10:13:33", "updated_utc_date_time":"2017-10-20T04:28:43", "version":0, "current_sell_price": { "default_sell_ex_tax_price":100, "default_sell_inc_tax_price":100, "effective_from_date":"1990-01-01", "effective_to_date":"9999-12-31" }, "current_cost_price": { "default_cost_ex_tax_price":0, "default_cost_inc_tax_price":0, "effective_from_date":"1990-01-01", "effective_to_date":"9999-12-31" }, "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service/7" },{ "display_name":"<NAME>", "created_utc_date_time":"2015-04-22T10:13:33", "updated_utc_date_time":"2017-10-20T04:12:51", "version":0, "current_sell_price": { "default_sell_ex_tax_price":50, "default_sell_inc_tax_price":50, "effective_from_date":"1990-01-01", "effective_to_date":"9999-12-31" }, "current_cost_price": { "default_cost_ex_tax_price":0, "default_cost_inc_tax_price":0, "effective_from_date":"1990-01-01", "effective_to_date":"9999-12-31" }, "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service/6" } ], "paging": { "page":1, "number_of_pages":1 }, "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service_category/2/services" } ``` #### retrieveServicesByServiceName Retrieves the services from the server with a specific name. The function takes two arguments, the first being the `serviceName`, the second being a callback of the form `function(err, result)`. If an error occured, the `err` property will contain the error information. The `result` contains the `status` and the `content` of the response. An example `result.content` that may be retrieved with this function is: Example: ```js site.retrieveServicesByServiceName('Wax Leg', function (err, result) { console.log(result.content); }); ``` Result: ```json { "services": [ { "display_name":"Wax Leg", "created_utc_date_time":"2015-04-22T10:13:33", "updated_utc_date_time":"2017-10-20T04:12:51", "version":0, "current_sell_price": { "default_sell_ex_tax_price":50, "default_sell_inc_tax_price":50, "effective_from_date":"1990-01-01", "effective_to_date":"9999-12-31" }, "current_cost_price": { "default_cost_ex_tax_price":0, "default_cost_inc_tax_price":0, "effective_from_date":"1990-01-01", "effective_to_date":"9999-12-31" }, "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service/6" } ], "paging": { "page":1, "number_of_pages":1 }, "href":"https://pos.shortcutssoftware.com/webapi/site/30179/services" } ``` #### retrieveEmployeeByEmployeeAlias Retrieves the employee from the server with a specific alias. The function takes two arguments, the first being the `employeeAlias`, the second being a callback of the form `function(err, result)`. If an error occured, the `err` property will contain the error information. The `result` contains the `status` and the `content` of the response. An example `result.content` that may be retrieved with this function is: Example: ```js site.retrieveEmployeeServicePricing('Wendy', function (err, result) { console.log(result.content); }); ``` Result: ```json { "employees":[{ "created_utc_date_time":"2015-04-22T10:13:31", "updated_utc_date_time":"2016-12-11T09:22:28", "display_name":"Wendy", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/employee/2" }], "paging":{ "page":1, "number_of_pages":1 }, "href":"https://pos.shortcutssoftware.com/webapi/site/30179/employees" } ``` #### retrieveServiceEmployeePricing Retrieves the employee pricing from the server for a service with the specified name. The function takes two arguments, the first being the `serviceName`, the second being a callback of the form `function(err, result)`. If an error occured, the `err` property will contain the error information. The `result` contains the `status` and the `content` of the response. An example `result.content` that may be retrieved with this function is: Example: ```js site.retrieveServiceEmployeePricing('Wax Leg', function (err, result) { console.log(result.content); }); ``` Result: ```json { "on_premise_reference":1003, "employees":[{ "on_premise_reference":2, "effective_date":"2017-10-23T00:00:00", "display_name":"John", "sell_ex_tax_price":50, "sell_inc_tax_price":50, "duration_minutes":15, "base_sell_ex_tax_price":50, "base_sell_inc_tax_price":50, "base_duration_minutes":15, "appointment_book_order":2, "is_available_for_walkin":true, "href":"https://pos.shortcutssoftware.com/webapi/site/30179/employee/1" },{ "on_premise_reference":3, "effective_date":"2017-10-23T00:00:00", "display_name":"Wendy", "sell_ex_tax_price":50, "sell_inc_tax_price":50, "duration_minutes":15, "base_sell_ex_tax_price":50, "base_sell_inc_tax_price":50, "base_duration_minutes":15, "appointment_book_order":3, "is_available_for_walkin":true, "href":"https://pos.shortcutssoftware.com/webapi/site/30179/employee/2" }], "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service/6/employee_pricing?effective_date=2017-10-23T00%3A00%3A00" } ``` #### retrieveEmployeeServicePricing Retrieves the service pricing from the server for an employe with the specified alias. The function takes two arguments, the first being the `employeeAlias`, the second being a callback of the form `function(err, result)`. If an error occured, the `err` property will contain the error information. The `result` contains the `status` and the `content` of the response. An example `result.content` that may be retrieved with this function is: Example: ```js site.retrieveEmployeeServicePricing('Wendy', function (err, result) { console.log(result.content); }); ``` Result: ```json { "services":[{ "effective_date":"2017-10-23T00:00:00", "display_name":"Cut for Child", "sell_ex_tax_price":5, "sell_inc_tax_price":5, "duration_minutes":30, "base_sell_ex_tax_price":5, "base_sell_inc_tax_price":5, "base_duration_minutes":30, "links":[{ "rel":"resource/category", "display_name":"Hair", "href":"https://pos.shortcutssoftware.com/webapi/site/2017-10-23T00%3A00%3A00/service_category/1" }], "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service/5" },{ "effective_date":"2017-10-23T00:00:00", "display_name":"Cut for Men", "sell_ex_tax_price":15, "sell_inc_tax_price":15, "duration_minutes":30, "base_sell_ex_tax_price":15, "base_sell_inc_tax_price":15, "base_duration_minutes":30, "links":[{ "rel":"resource/category", "display_name":"Hair", "href":"https://pos.shortcutssoftware.com/webapi/site/2017-10-23T00%3A00%3A00/service_category/1" }], "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service/4" },{ "effective_date":"2017-10-23T00:00:00", "display_name":"Wax Back", "sell_ex_tax_price":100, "sell_inc_tax_price":100, "duration_minutes":30, "base_sell_ex_tax_price":100, "base_sell_inc_tax_price":100, "base_duration_minutes":30, "links":[{ "rel":"resource/category", "display_name":"Beauty", "href":"https://pos.shortcutssoftware.com/webapi/site/2017-10-23T00%3A00%3A00/service_category/2" }], "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service/7" },{ "effective_date":"2017-10-23T00:00:00", "display_name":"<NAME>", "sell_ex_tax_price":50, "sell_inc_tax_price":50, "duration_minutes":15, "base_sell_ex_tax_price":50, "base_sell_inc_tax_price":50, "base_duration_minutes":15, "links":[{ "rel":"resource/category", "display_name":"Beauty", "href":"https://pos.shortcutssoftware.com/webapi/site/2017-10-23T00%3A00%3A00/service_category/2" }], "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service/6" }], "href":"https://pos.shortcutssoftware.com/webapi/site/30179/employee/2/service_pricing" } ``` ### <a name=search></a>Search Module The Search module retrieves the available appointments from the server. All operations return the same result structure. The `byServiceCategoryName` accepts the name of a service category and returns all available appointments for any service within the specified service category. The `byServiceName` accepts the name of a service and returns all available appointments for the specified service. The `byServiceAndEmployeeName` accepts the name of a service and an employee alias and returns all available appointments for the specified service with the specified employee. The last argument of each function is a callback of the form `function(err, result)`. If an error occured, the `err` property will contain the error information. The `result` contains the `status` and the `content` of the response. An example `result.content` that may be retrieved with this function is: Example: ```js site.byServiceCategoryName('Beauty', function(err, result) { console.log(result.content); }); site.byServiceName('Wax Leg', function (err, result) { console.log(result.content); }); site.byServiceAndEmployeeNameName('Wax Leg', 'John', function (err, result) { console.log(result.content); }); ``` Result: ```json { "available_appointments": [ { "services": [ { "start_time":"00:00:00", "sell_price":50, "duration":"PT15M", "links": [ { "rel":"resource/service", "display_name":"Wax Leg", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service/6/block/1" },{ "rel":"resource/employee", "display_name":"John", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/employee/1" } ] }], "scheduled_date":"2017-10-21", "duration":"PT15M", "sell_price":50, "links":[{ "rel":"resource/site", "href":"https://pos.shortcutssoftware.com/webapi/site/30179" }] }, { "services":[{ "start_time":"00:15:00", "sell_price":50, "duration":"PT15M", "links":[{ "rel":"resource/service", "display_name":"Wax Leg", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service/6/block/1" }, { "rel":"resource/employee", "display_name":"John", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/employee/1" }] }], "scheduled_date":"2017-10-21", "duration":"PT15M", "sell_price":50, "links":[{ "rel":"resource/site", "href":"https://pos.shortcutssoftware.com/webapi/site/30179" }] }, { "services":[{ "start_time":"00:30:00", "sell_price":50, "duration":"PT15M", "links":[{ "rel":"resource/service", "display_name":"Wax Leg", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service/6/block/1" }, { "rel":"resource/employee", "display_name":"John", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/employee/1" }] }], "scheduled_date":"2017-10-21", "duration":"PT15M", "sell_price":50, "links":[{ "rel":"resource/site", "href":"https://pos.shortcutssoftware.com/webapi/site/30179" }] }, { "services":[{ "start_time":"00:45:00", "sell_price":50, "duration":"PT15M", "links":[{ "rel":"resource/service", "display_name":"Wax Leg", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service/6/block/1" }, { "rel":"resource/employee", "display_name":"John", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/employee/1" }] }], "scheduled_date":"2017-10-21", "duration":"PT15M", "sell_price":50, "links":[{ "rel":"resource/site", "href":"https://pos.shortcutssoftware.com/webapi/site/30179" }] }, { "services":[{ "start_time":"01:00:00", "sell_price":50, "duration":"PT15M", "links":[{ "rel":"resource/service", "display_name":"<NAME>", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/service/6/block/1" }, { "rel":"resource/employee", "display_name":"John", "href":"https://pos.shortcutssoftware.com/webapi/site/30179/employee/1" }] }], "scheduled_date":"2017-10-21", "duration":"PT15M", "sell_price":50, "links":[{ "rel":"resource/site", "href":"https://pos.shortcutssoftware.com/webapi/site/30179" }] } ] } ``` <file_sep>package com.shortcuts.example.giftcard.Models.Response; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.EqualsAndHashCode; import java.math.BigDecimal; import java.time.LocalDateTime; @Data @EqualsAndHashCode(callSuper=false) public class TransactionResponse extends BaseResponse{ @JsonProperty("transaction_id") private String transactionId; @JsonProperty("transaction_ex_tax_amount") private BigDecimal transactionExTaxAmount; @JsonProperty("transaction_inc_tax_amount") private BigDecimal transactionIncTaxAmount; @JsonProperty("giftcard_ex_tax_balance") private BigDecimal giftcardExTaxBalance; @JsonProperty("giftcard_inc_tax_balance") private BigDecimal giftcardIncTaxBalance; @JsonProperty("giftcard_expiry_date") private LocalDateTime giftcardExpiryDate; @JsonProperty("giftcard_currency_code") private String giftcardCurrencyCode; } <file_sep>const url = require('url'); const _ = require('underscore'); const api = require('./api'); const config = require('./config.js'); var appointment = (function () { var companyHref = url.resolve(config.apiUri, 'company/' + config.companyId); var siteHref = url.resolve(config.apiUri, 'site/' + config.siteId) function authenticateCustomer(jwtToken, username, password, done) { api.post( url.resolve(companyHref + '/', 'authenticate_customer'), {Authorization: 'JWT ' + jwtToken}, { credential_type_code: 'password', username: username, password: <PASSWORD> }, done); } function bookAppointment(jwtToken, customerSessionHref, appointmentDetails, done) { api.post( url.resolve(customerSessionHref + '/', 'customer/appointments'), {Authorization: 'JWT ' + jwtToken}, _.extend(appointmentDetails, { links: [{rel: 'resource/site', href: siteHref}] }) , done); } function retrieveAppointments(jwtToken, customerSessionHref, done) { api.get( url.resolve(customerSessionHref + '/', 'customer/appointments'), {Authorization: 'JWT ' + jwtToken}, done); } function cancelAppointment(jwtToken, customerSessionHref, appointmentHref, done) { var siteCustomerSessionHref = customerSessionHref.replace(companyHref, siteHref); var siteCustomerSessionAppointmentHref = appointmentHref.replace(siteHref, siteCustomerSessionHref + '/customer'); api.del( siteCustomerSessionAppointmentHref, {Authorization: 'JWT ' + jwtToken}, done); } return { authenticate: authenticateCustomer, bookAppointment: bookAppointment, retrieveAppointments: retrieveAppointments, cancelAppointment: cancelAppointment } })(); module.exports = appointment; <file_sep>const expect = require('expect.js'); const config = require('../src/config.js'); const api = require('../src/api.js'); const url = require('url'); describe('API', function () { this.timeout(5000); describe('request()', function () { it('should be able to make basic request', function (done) { api.get(url.resolve(config.apiUri, 'site/' + config.siteId), function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.href).to.eql(url.resolve(config.apiUri, 'site/' + config.siteId)); done(); }) }) }) });<file_sep> # Shortcuts Example: API usage with the [Java language](http://java.oracle.com). An example of how to work with the Shortcuts API, and drive Shortcuts Online Services. Various common business processes are covered in this example. More will be added over time, and we welcome contributions. The interactions in this example make use of the individual APIs detailed at [Shortcuts API](http://www.shortcutssoftware.io/developer/). Each API used is covered in a unit test, so you can debug through server-side code without starting up the entire application server. If you browse through the API documentation above you will see detailed information about how to call each of the individual APIs that give access to Shortcuts Online Services. These examples, however, start you off with working code that shows the way that individual APIs work together, and how they can be called in sequences that implement common business processes. ## How it works: ### Authentication The first thing you need to do to use the Shortcuts API is to authenticate. #### Using OAuth credentials Authenticate using [OAuth 1.0](https://en.wikipedia.org/wiki/OAuth) credentials, issued when you request API user access from Shortcuts Software Ltd. This is what you do when you want to call the APIs as if they were being called by an individual user (or community), where you might want to tailor the permissions granted to the API caller. The capabilities that you will have if you authenticate this way can be individually configured without affecting the operation of your on-premise software. When you authenticate, you will be given a [JWT token](http://jwt.io) which will give you access to the API for 30 minutes. The token expiry time is stored in the token itself, so you can proactively acquire a new token when it approaches expiry if you wish. Tokens are cheap and can be discarded and/or reacquired at will. _Important:_ Each time you call the Shortcuts API you must supply a JWT token in the `Authorization` header. If you fail to authenticate, you will receive an http status code of `401 Unauthorized` when you call the Shortcuts APIs. Please take a look at the following classes to see examples of the two types of authentication: - [Using oauth credentials](./src/main/java/com/shortcuts/example/java/authentication/JWTOAuthAuthenticationService.java) ### Usage After you authenticate, all that you have to do to invoke an API is to make an HTTP request to the API endpoint. The HTTP request should be built up with a few characteristics, all of which will be familiar to you as an API developer: 1. HTTP method must be specified to match the expected method in [the documentation](http://www.shortcutssoftware.io/developer/). 1. HTTP URI must be specified to match the documentation: 1. path parameters are mandatory, 1. query string parameters are optional. 1. the request body (where required) must match the json schema in the documentation. 1. the `Authorization` header must contain the JWT token (acquired above). After that, it is a matter of submitting the correct requests in the correct sequence. This is easy to do in most cases, as this example will show you. We anticipate that you will not need any in-depth help until you start to implement business processes that are unique to the way you use the Shortcuts Online Services. Please take a look at the following classes to see the simplest example of calling the Shortcuts API: - [GetSitesService.java](./src/main/java/com/shortcuts/example/java/services/site/GetSitesService.java) - [GetSitesServiceTest.java](./src/test/java/com/shortcuts/example/java/services/site/GetSitesServiceTest.java) <file_sep>package com.shortcuts.example.java.services.site; import com.shortcuts.example.java.services.BaseShortcutsAPIService; import com.shortcuts.example.java.services.ShortcutsAPIGetService; import com.shortcuts.example.java.util.ShortcutsAPIException; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Service; import org.springframework.util.MultiValueMap; import java.net.URI; import java.util.Optional; @Slf4j @Service public class GetSiteService extends BaseShortcutsAPIService implements ShortcutsAPIGetService<Void, Site> { public GetSiteService() { super(HttpMethod.GET); } @Override public Site call( String jwtToken, Optional<HttpHeaders> httpHeaders, Optional<MultiValueMap<String, String>> queryParameters, Object... uriVariables) throws ShortcutsAPIException { URI endpoint = getEndpointURI("site/{site_id}", queryParameters, uriVariables); HttpHeaders headers = setupAuthorizationHeader(httpHeaders, jwtToken); Site site = restTemplateCallingUtil.getForObject( endpoint, headers, Site.class, uriVariables); log.info("response: {}", site); return site; } } <file_sep>package com.shortcuts.example.single_signon.salon; import org.springframework.stereotype.Service; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @Service public class AuthenticationTokenService { private final Map<String, ValidatedCredentials> validatedCredentialTokens = new ConcurrentHashMap<>(); /** * Register validated credentials so that they can be retrieved at a later time. * * @param validatedCredentials a set of validated credentials. * @return a token that can be used to retrieve these credentials. */ public String registerValidCredentials(ValidatedCredentials validatedCredentials) { String authenticationToken = UUID.randomUUID().toString(); validatedCredentialTokens.put(authenticationToken, validatedCredentials); return authenticationToken; } /** * Validate a token, return a set of validated credentials if the token is known. * * @param token a token to be validated. * @return validated credentials registered against the supplied token, or null if the token is not known. */ public ValidatedCredentials validateAuthenticationToken(String token) { return validatedCredentialTokens.get(token); } } <file_sep>package com.shortcuts.example.giftcard.Models.RequestBody; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import java.math.BigDecimal; @Data public class ActivateCardRequestBody extends CardServiceRequestBody { @JsonProperty("activation_inc_tax_amount") private BigDecimal activationIncTaxAmount; } <file_sep>const url = require('url'); const _ = require('underscore'); const api = require('./api'); const config = require('./config.js'); var site = (function () { var siteHref = url.resolve(config.apiUri, 'site/' + config.siteId) // Retrieving the site details function retrieveSiteDetails(done) { api.get(siteHref, done); } // Retrieving the service categories available at the site - ensuring we only list those with customer bookable services currently active in the site catalog. // Only interested in the names and resource URIs. function retrieveServiceCategories(done) { api.get(url.resolve(siteHref + '/', 'service_categories?is_active=true&is_bookable=true&is_customer_bookable=true&fields=display,href'), done); } // Retrieving services within the service category with name {serviceCategoryName} function retrieveServicesByServiceCategoryName(serviceCategoryName, done) { retrieveServiceCategories(function (err, result) { var serviceCategoryHref; if (err) { done(err); return; } serviceCategoryHref = _.findWhere(result.content.service_categories, { 'display_name': serviceCategoryName }).href; api.get(url.resolve(serviceCategoryHref + '/', 'services?is_active=true&is_bookable=true&is_customer_bookable=true&fields=display,href'), done); }); } // Retrieving services with name {serviceName} function retrieveServicesByServiceName(serviceName, done) { api.get(url.resolve(siteHref + '/', 'services?search=' + serviceName + '&is_active=true&is_bookable=true&is_customer_bookable=true&fields=display,href'), done); } // Retrieving employee by alias/name {alias} function retrieveEmployeeByEmployeeAlias(employeeAlias, done) { api.get(url.resolve(siteHref + '/', 'employees?search=' + employeeAlias + '&is_active=true&is_bookable=true&is_customer_bookable=true&fields=display,href'), done); } function retrieveServiceEmployeePricing(serviceName, done) { retrieveServicesByServiceName(serviceName, function (err, result) { var serviceHref; if (err) { done(err); return; } serviceHref = result.content.services[0].href; api.get(url.resolve(serviceHref + '/', 'employee_pricing?is_active=true&is_bookable=true&is_customer_bookable=true'), done); }); } function retrieveEmployeeServicePricing(employeeAlias, done) { retrieveEmployeeByEmployeeAlias(employeeAlias, function (err, result) { var employeeHref; if (err) { done(err); return; } employeeHref = result.content.employees[0].href; api.get(url.resolve(employeeHref + '/', 'service_pricing?is_active=true&is_bookable=true&is_customer_bookable=true'), done); }); } return { retrieveSiteDetails: retrieveSiteDetails, retrieveServiceCategories: retrieveServiceCategories, retrieveServicesByServiceCategoryName: retrieveServicesByServiceCategoryName, retrieveServicesByServiceName: retrieveServicesByServiceName, retrieveEmployeeByEmployeeAlias: retrieveEmployeeByEmployeeAlias, retrieveServiceEmployeePricing: retrieveServiceEmployeePricing, retrieveEmployeeServicePricing: retrieveEmployeeServicePricing } })(); module.exports = site;<file_sep>const url = require('url'); const _ = require('underscore'); const api = require('./api'); const config = require('./config.js'); const site = require('./site.js'); const log = require('./log.js'); var search = (function () { var siteHref, defaultFromDate, defaultTodate, defaultDateTimeFilter; siteHref = url.resolve(config.apiUri, 'site/' + config.siteId); defaultFromDate = new Date(new Date().getTime() + 3 * 24 * 60 * 60 * 1000); defaultTodate = new Date(new Date().getTime() + 14 * 24 * 60 * 60 * 1000); defaultDateTimeFilter = { from_date: defaultFromDate.getFullYear().toString() + '-' + (defaultFromDate.getMonth() + 1) + '-' + defaultFromDate.getDate(), to_date: defaultTodate.getFullYear().toString() + '-' + (defaultTodate.getMonth() + 1) + '-' + defaultTodate.getDate(), start_time: '00:00:00', finish_time: '23:59:59', days_of_week: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] }; function byServiceCategoryName(serviceCategoryName, done) { site.retrieveServicesByServiceCategoryName(serviceCategoryName, function (err, result) { if (err) { done(err); return; } var availabilitySearches = []; for (var i = 0; i < result.content.services.length; i++) { var serviceHref = result.content.services[i].href; availabilitySearches.push(new Promise(function (resolve, reject) { api.post( url.resolve(siteHref + '/', 'calculate_available_appointments'), { requested_services: [{ gender_code: 'unknown', links: [ {rel: 'site/service', href: serviceHref} ] }], date_time_filter: [defaultDateTimeFilter] }, function (err, result) { if (err) reject(err); else resolve(result); }); })); } log.info('Searching for %s services', availabilitySearches.length); Promise.all(availabilitySearches).then( function (results) { var result = {status: 200, content: {available_appointments: []}}; log.info('Processing results: %s', JSON.stringify(results)); for (var i = 0; i < results.length; i++) { result.content.available_appointments = _.union(result.available_appointments, results[i].content.available_appointments); } done(null, result); }, function (err) { done(err); } ); }) } function byServiceCategoryAndDateTimeFilter(serviceCategoryName, dateTimeFilter, done) { site.retrieveServicesByServiceCategoryName(serviceCategoryName, function (err, result) { if (err) { done(err); return; } var availabilitySearches = []; for (var i = 0; i < result.content.services.length; i++) { var serviceHref = result.content.services[i].href; availabilitySearches.push(new Promise(function (resolve, reject) { api.post( url.resolve(siteHref + '/', 'calculate_available_appointments'), { requested_services: [{ gender_code: 'unknown', links: [ {rel: 'site/service', href: serviceHref} ] }], date_time_filter: [dateTimeFilter] }, function (err, result) { if (err) reject(err); else resolve(result); }); })); } log.info('Searching for %s services', availabilitySearches.length); Promise.all(availabilitySearches).then( function (results) { var result = {status: 200, content: {available_appointments: []}}; log.info('Processing results: %s', JSON.stringify(results)); for (var i = 0; i < results.length; i++) { result.content.available_appointments = _.union(result.available_appointments, results[i].content.available_appointments); } done(null, result); }, function (err) { done(err); } ); }) } function byServiceName(serviceName, done) { site.retrieveServicesByServiceName(serviceName, function (err, result) { if (err) { done(err); return; } var serviceHref = result.content.services[0].href; api.post( url.resolve(siteHref + '/', 'calculate_available_appointments'), { requested_services: [{ gender_code: 'unknown', links: [ {rel: 'site/service', href: serviceHref} ] }], date_time_filter: [defaultDateTimeFilter] }, done); }); } function byServiceNameAndDateTimeFilter(serviceName, dateTimeFilter, done) { site.retrieveServicesByServiceName(serviceName, function (err, result) { if (err) { done(err); return; } var serviceHref = result.content.services[0].href; api.post( url.resolve(siteHref + '/', 'calculate_available_appointments'), { requested_services: [{ gender_code: 'unknown', links: [ {rel: 'site/service', href: serviceHref} ] }], date_time_filter: [dateTimeFilter] }, done); }); } function byServiceNameAndDateTimeFilterAndPriceBand(serviceName, dateTimeFilter, priceBand, done) { byServiceNameAndDateTimeFilter(serviceName, dateTimeFilter, function (err, result) { if (err) { done(err) } // filter available appointments by price band var filtered = []; for (var i = 0; i < result.content.available_appointments.length; i++) { var available_appointment = result.content.available_appointments[i]; if (!priceBand) { filtered.push(available_appointment); } else { if ((priceBand.lower <= available_appointment.sell_price) && (priceBand.upper >= available_appointment.sell_price)) { filtered.push(available_appointment); } } } result.content.available_appointments = filtered; done(null, result); }); } function byServiceAndEmployeeName(serviceName, employeeAlias, done) { Promise.all([ new Promise(function (resolve, reject) { site.retrieveServicesByServiceName(serviceName, function (err, result) { if (err) reject(err); else resolve(result); }) }), new Promise(function (resolve, reject) { site.retrieveEmployeeByEmployeeAlias(employeeAlias, function (err, result) { if (err) reject(err); else resolve(result); }) }) ]).then( function (results) { var serviceHref = results[0].content.services[0].href; var employeeHref = results[1].content.employees[0].href; api.post( url.resolve(siteHref + '/', 'calculate_available_appointments'), { requested_services: [{ gender_code: 'unknown', links: [ {rel: 'site/service', href: serviceHref}, {rel: 'site/employee', href: employeeHref} ] }], date_time_filter: [defaultDateTimeFilter] }, done); }, function (err) { done(err); } ); } function byServiceAndEmployeeNameAndDateTimeFilter(serviceName, employeeAlias, dateTimeFilter, done) { Promise.all([ new Promise(function (resolve, reject) { site.retrieveServicesByServiceName(serviceName, function (err, result) { if (err) reject(err); else resolve(result); }) }), new Promise(function (resolve, reject) { site.retrieveEmployeeByEmployeeAlias(employeeAlias, function (err, result) { if (err) reject(err); else resolve(result); }) }) ]).then( function (results) { var serviceHref = results[0].content.services[0].href; var employeeHref = results[1].content.employees[0].href; api.post( url.resolve(siteHref + '/', 'calculate_available_appointments'), { requested_services: [{ gender_code: 'unknown', links: [ {rel: 'site/service', href: serviceHref}, {rel: 'site/employee', href: employeeHref} ] }], date_time_filter: [dateTimeFilter] }, done); }, function (err) { done(err); } ); } return { byServiceCategoryName: byServiceCategoryName, byServiceName: byServiceName, byServiceAndEmployeeName: byServiceAndEmployeeName, byServiceNameAndDateTimeFilter: byServiceNameAndDateTimeFilter, byServiceNameAndDateTimeFilterAndPriceBand: byServiceNameAndDateTimeFilterAndPriceBand, byServiceCategoryAndDateTimeFilter: byServiceCategoryAndDateTimeFilter, byServiceAndEmployeeNameAndDateTimeFilter: byServiceAndEmployeeNameAndDateTimeFilter } })(); module.exports = search;<file_sep>include ':other:single-signon' include ':v2-examples:java' include 'other:giftcard' <file_sep>package com.shortcuts.example.java.authentication; import org.springframework.web.client.HttpStatusCodeException; public interface JWTAuthentication { /** * @return String containing the JWT token that resulted from an authentication attempt. */ String authenticate() throws HttpStatusCodeException; } <file_sep>const expect = require('expect.js'); const config = require('../src/config.js'); const search = require('../src/search.js'); const appointment = require('../src/appointment.js'); const authenticate = require('../src/authenticate.js'); const _ = require('underscore'); describe('Appointment', function () { this.timeout(10000); describe('Appointment Lifecycle', function () { var sharedState = { customerSessionHref: null, appointmentDetails: null, appointment: null, cancelledAppointment: null, access_token: null }; it('must authenticate', function (done) { authenticate.authenticate(function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.access_token).to.not.be(undefined); sharedState.access_token = result.content.access_token; done(); }) }); it('should be able to authenticate using configured user', function (done) { appointment.authenticate( sharedState.access_token, config.customerUsername, config.customerPassword, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.customer).to.not.be(undefined); expect(result.content.customer).to.be.an('object'); sharedState.customerSessionHref = result.content.href; done(); }) }); it('should be able to search for a service', function (done) { search.byServiceName( sharedState.access_token, 'Blowdry', function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.not.be(undefined); expect(result.content.available_appointments).to.be.an('array'); expect(result.content.available_appointments).to.not.be.empty(); sharedState.appointmentDetails = result.content.available_appointments[1]; done(); }); }); it('Should be able to book the service', function (done) { if (!sharedState.customerSessionHref || !sharedState.appointmentDetails) { done('Inconclusive - earlier tests failed'); return; } appointment.bookAppointment( sharedState.access_token, sharedState.customerSessionHref, sharedState.appointmentDetails, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.href).to.not.be(undefined); sharedState.appointment = result.content.appointments[0]; done(); }); }); it('Should not be able to double-book the time-slot', function (done) { if (!sharedState.customerSessionHref || !sharedState.appointmentDetails || !sharedState.appointment) { done('Inconclusive - earlier tests failed'); return; } appointment.bookAppointment( sharedState.access_token, sharedState.customerSessionHref, sharedState.appointmentDetails, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(409); // Conflict expect(result.content.error_type_code).to.eql('system'); expect(result.content.message).to.eql('Proposed appointment is no longer available'); done(); }); }); it('Should be able to retrieve the same appointment', function (done) { if (!sharedState.customerSessionHref || !sharedState.appointment) { done('Inconclusive - earlier tests failed'); return; } appointment.retrieveAppointments( sharedState.access_token, sharedState.customerSessionHref, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.appointments).to.not.be(undefined); expect(result.content.appointments).to.be.an('array'); expect(result.content.appointments).to.not.be.empty(); var foundAppointment = _.findWhere(result.content.appointments, {href: sharedState.appointment.href}); expect(foundAppointment).to.not.be(undefined); done(); }); }); it('Should be able to cancel the same appointment', function (done) { if (!sharedState.customerSessionHref || !sharedState.appointment) { done('Inconclusive - earlier tests failed'); return; } appointment.cancelAppointment( sharedState.access_token, sharedState.customerSessionHref, sharedState.appointment.href, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); sharedState.cancelledAppointment = sharedState.appointment; done(); }); }); }); });<file_sep>package com.shortcuts.example.java.authentication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE) public class JWTOAuthAuthenticationServiceTest { @Autowired JWTOAuthAuthenticationService jwtoAuthAuthenticationService; @Test public void testConfigurationIsAvailable() { assertTrue(jwtoAuthAuthenticationService.getBaseUrl().startsWith("https://")); assertNotNull(jwtoAuthAuthenticationService.getRestTemplateCallingUtil()); assertNotNull(jwtoAuthAuthenticationService.getConsumerKey()); assertNotNull(jwtoAuthAuthenticationService.getConsumerSecret()); assertNotNull(jwtoAuthAuthenticationService.getAccessKey()); assertNotNull(jwtoAuthAuthenticationService.getAccessSecret()); } @Test public void testAuthenticate() { String jwtToken = jwtoAuthAuthenticationService.authenticate(); assertNotNull(jwtToken); } }<file_sep>package com.shortcuts.example.single_signon; import com.shortcuts.example.single_signon.salon.SalonApplication; import com.shortcuts.example.single_signon.shortcuts.ShortcutsApplication; import org.springframework.boot.builder.SpringApplicationBuilder; public class ApplicationsOnSeparatePorts { public static void main(String[] args) { new SpringApplicationBuilder(SalonApplication.class) .properties("server.port=8080") .run(); new SpringApplicationBuilder(ShortcutsApplication.class) .properties("server.port=9090") .run(); } } <file_sep>const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const stylistSingleSignon = require('./stylist-single-signon.js'); app.use(bodyParser.json()); app.use(express.static('./')) app.post('/stylist-single-signon', function (req, res) { // receive the stylist credentials as a JSON payload. // Pass this on to authenticate and return the cookie // data if authentication is successful. let stylistCredentials = req.body; stylistSingleSignon.getAuthCookies(stylistCredentials, function (err, authCookies) { if (err) { res.send('{ "message": "Unauthorized" }', 401); return; } // authentication success, send back the cookies res.send(JSON.stringify(authCookies), 200); }); }); app.listen(8080, () => console.log('Stylist single signon server listening on port 8080!'))<file_sep>package com.shortcuts.example.giftcard.Models.Response; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class AuthenticateResponse extends BaseResponse { @JsonProperty("access_token") @JsonInclude(JsonInclude.Include.NON_NULL) private String accessToken; } <file_sep># Shortcuts GiftCard API A series of API endpoint can be used for activating a Shortcuts GiftCard, checking balances, redeem, etc. ## API Endpoints ### GiftCard Activation This endpoint allows you to activate a Shortcuts GiftCard under an existing GiftCard program. It is worth mentioning that users will need to go to Shortcuts GiftCard Console to register a card number first before you activate a GiftCard. Activation endpoint: ```http request, json POST /giftcard/{giftcard_number}/activate Host: api.shortcutssoftware.io ``` Example request: ```http request, json https://api.shortcutssoftware.io/giftcard/62997400000000400401/activate { "site_transaction_id":"0", "site_transaction_date_time":"2018-05-24T12:43:00", "activation_inc_tax_amount":200 } ``` P.S <span style="color:red">```site_transaction_id```</span> can be set to any reference number from your system or leave it as 0 <span style="color:red">```"site_transaction_id":"0"```.</span> example response: ```json { "transaction_id": "0", "transaction_ex_tax_amount": 200, "transaction_inc_tax_amount": 200, "giftcard_ex_tax_balance": 200, "giftcard_inc_tax_balance": 200, "giftcard_expiry_date": "2019-05-30T00:00:00", "giftcard_currency_code": "AUS" } ``` ### Check Balance This endpoint allows you to check the GiftCard balance. By simply providing a GiftCard number, users will be able to retrieve GiftCard balance information as well as GiftCard program name. Check balance endpoint: ```http request, json GET /giftcard/{giftcard_number} Host: api.shortcutssoftware.io ``` Example request: ```http request https://api.shortcutssoftware.io/giftcard/62997400000000400401 ``` Example response : ```json { "transaction_id": "", "transaction_reference_id": "", "authorization_code": "", "transaction_ex_tax_amount": 0, "transaction_inc_tax_amount": 0, "card_holder_information": null, "member_balance": { "balance_ex_tax_amount": 200, "balance_inc_tax_amount": 200, "expiry_date": null, "currency_code": "AUS", "program_code": null, "program_name": "GiftCard", "member_number": "62997400000000400401", "pos_card_type_id": "GC", "balance_points": "0", "available_points": null, "card_type_code": "giftcard", "member_status_code": "none", "benefit_items": [], "payment_plans": [] } } ``` ### Redeem This API endpoint can be used to redeem a Shortcuts GiftCard. It will return the balance amount as well as transaction amount after a successful redemption. Redeem endpoint: ```http request POST /giftcard/{giftcard_number}/redeem Host: api.shortcutssoftware.io ``` Example request: ```http request https://api.shortcutssoftware.io/giftcard/62997400000000400401/redeem { "site_transaction_id":"0", "site_transaction_date_time":"2018-05-24T12:45:00", "redemption_amount":25 } ``` Example response: ```json { "transaction_id": "0", "transaction_reference_id": "", "authorization_code": "", "transaction_ex_tax_amount": -25, "transaction_inc_tax_amount": -25, "card_holder_information": { "is_email_unsubscribed": false }, "member_balance": { "balance_ex_tax_amount": 175, "balance_inc_tax_amount": 175, "expiry_date": null, "currency_code": "AUS", "program_code": "", "program_name": "GiftCard", "member_number": "62997400000000400401", "pos_card_type_id": "GC", "balance_points": "0", "available_points": null, "card_type_code": "giftcard", "member_status_code": "none", "benefit_items": [], "payment_plans": [] } } ``` ### Reload This endpoint can be used to adjust the GiftCard balance. It will return the balance amount as well as the adjusting amount after a successful reload. Reload endpoint: ```http request POST /giftcard/{giftcard_number}/reload Host: api.shortcutssoftware.io ``` Example request: ```http request https://api.shortcutssoftware.io/giftcard/62997400000000400401/reload { "site_transaction_id":"0", "site_transaction_date_time":"2018-05-24T12:45:00", "reload_amount":25 } ``` Example response: ```json { "transaction_id": "0", "transaction_reference_id": "", "transaction_ex_tax_amount": 25, "transaction_inc_tax_amount": 25, "giftcard_ex_tax_balance": 200, "giftcard_inc_tax_balance": 200, "giftcard_expiry_date": "2019-05-30T00:00:00", "giftcard_currency_code": "AUS" } ``` ### Cancel Last Operation Cancel last operation can be used to cancel any redemption or reload operations. It requires the transaction id and the exact amount from the last operation to invoke this endpoint. Cancel last operation endpoint: ```http request POST /giftcard/{giftcard_number}/cancel_last_operation Host: api.shortcutssoftware.io ``` Example request: ```http request https://api.shortcutssoftware.io/giftcard/62997400000000400401/cancel_last_operation { "site_transaction_id":"0", "site_transaction_date_time":"2018-05-24T12:46:00", "original_site_transaction_id":"3", "original_transaction_amount":25, "original_transaction_points":0 } ``` Example response: ```json { "transaction_id": "0", "transaction_reference_id": "", "authorization_code": "", "transaction_ex_tax_amount": -25, "transaction_inc_tax_amount": -25, "card_holder_information": { "is_email_unsubscribed": false }, "member_balance": { "balance_ex_tax_amount": 175, "balance_inc_tax_amount": 175, "expiry_date": null, "currency_code": "AUS", "program_code": null, "program_name": "GiftCard", "member_number": "62997400000000400401", "pos_card_type_id": "GC", "balance_points": "0", "available_points": null, "card_type_code": "giftcard", "member_status_code": "none", "benefit_items": [], "payment_plans": [] } } ``` ##Example test run 1. Gain access to GiftCard program console. Register GiftCard numbers under Number Registration. (Number Registrations -> Register). 2. Go to ```test.properties``` file, change the value of ```site.serial_number``` , OAuth token: ```cosumer_key```, ```consumer_secret```, ```access_token_key```, ```access_token_secret``` 3. In the same file, change the value of```giftcard.registered.ready``` with your registered GiftCard number from step 1. <file_sep># Shortcuts Widgets THC Sample Sample website implementation over the Shortcuts Widgets. ## Getting Started These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. ### Running website using Node 1. Ensure that Node.JS and NPM are installed. 2. Install node packages ``` npm install ``` 3. Run server ``` npm start ``` ### Running website by static content delivery This website has been designed to be able to be run independently of a dynamic server by copying the files to an accessible web location. It is recommended that the website is not run from the file directory as this can cause issues with AJAX calls. 1. Copy all files other than the package.json and README.md files to a static web server. 2. Browse to the index.html file on your static web server. ## Shortcuts Widget Events The widget does not come with AJAX loading indicator. It is up to the host site to provide the loading indicator for the user. > shortcuts.widgets.events.{Event name} |Event name|Raw string name|Purpose| |-----------|-------|-----| |WIDGET_AJAX_BEGIN | shortcutsWidgetAjaxBegin|AJAX call is in progress| |WIDGET_AJAX_END | shortcutsWidgetAjaxEnd|AJAX call has finished | |WIDGET_LOADING| shortcutsWidgetLoading | the widget is fetching the view | |WIDGET_RENDERED | shortcutsWidgetRendered|the widget has finished rendering the view | The event listener is JQuery event listener. For example, $('#shortcuts-widget-anchor').on('shortcutsWidgetLoading', function() { // show the spinner while the widget is fetching the view }) $('#shortcuts-widget-anchor').on(shortcuts.widgets.events.WIDGET_RENDERED, function() { // hide the spinner as the widget has fetched and displayed the view }) `#shortcuts-widget-anchor` is the element that the site host site uses for the Shortcuts Widget to anchor on. <file_sep>const url = require('url'); const expect = require('expect.js'); const config = require('../src/config.js'); const search = require('../src/search.js'); const _ = require('underscore'); describe('Common Tasks', function () { this.timeout(10000); describe('Common Appointment Searches', function () { var siteHref = url.resolve(config.apiUri, 'site/' + config.siteId); var fromDate = new Date(new Date().getTime() + 3 * 24 * 60 * 60 * 1000); var toDate = new Date(new Date().getTime() + 14 * 24 * 60 * 60 * 1000); var dateTimeFilter = { from_date: fromDate.getFullYear().toString() + '-' + (fromDate.getMonth() + 1) + '-' + fromDate.getDate(), to_date: toDate.getFullYear().toString() + '-' + (toDate.getMonth() + 1) + '-' + toDate.getDate(), start_time: '00:00:00', finish_time: '23:59:59', days_of_week: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] }; it('search for appointments by service and date/time window', function (done) { search.byServiceNameAndDateTimeFilter('Blowdry', dateTimeFilter, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.not.be.empty(); console.log(JSON.stringify(result.content.available_appointments)); done(); }); }); it('search for appointments by service category and date/time window', function (done) { search.byServiceCategoryAndDateTimeFilter('Hair Styling', dateTimeFilter, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.not.be.empty(); console.log(JSON.stringify(result.content.available_appointments)); done(); }); }); it('search for appointments by service and employee and date/time window', function (done) { search.byServiceAndEmployeeNameAndDateTimeFilter('Blowdry', 'Katie', dateTimeFilter, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.not.be.empty(); console.log(JSON.stringify(result.content.available_appointments)); done(); }); }); it('search for appointments by service and date/time window and price band - inclusive', function (done) { var priceBand = { upper: 100, lower: 10 }; search.byServiceNameAndDateTimeFilterAndPriceBand('Blowdry', dateTimeFilter, priceBand, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.not.be.empty(); console.log(JSON.stringify(result.content.available_appointments)); for (var i = 0; i < result.content.available_appointments.length; i++) { var appointment = result.content.available_appointments[i]; expect(appointment.sell_price).to.be.above(priceBand.lower); expect(appointment.sell_price).to.be.below(priceBand.upper); } done(); }); }); it('search for appointments by service and date/time window and price band - exclusive', function (done) { var priceBand = { upper: 10, lower: 1 }; search.byServiceNameAndDateTimeFilterAndPriceBand('Blowdry', dateTimeFilter, priceBand, function (err, result) { if (err) { done(err); return; } expect(result.status).to.eql(200); expect(result.content.available_appointments).to.be.empty(); console.log(JSON.stringify(result.content.available_appointments)); done(); }); }); }); });<file_sep># Stylist single sign-on This folder contains example code for the _Stylist single sign-on_ feature. ## Overview _Stylist single sign-on_ refers to the capability where an organization provides a mechanism for Shortcuts to call back to their own systems in order to validate a stylist's credentials, rather than using the Shortcuts signon servers to validate the stylist's credentials. This means that Shortcuts does not have to store or manage the stylist's password, and also allows the organization to provide a seamless path for a stylist to access the Shortcuts Live environment without requiring them to log on twice. ## How does it work? The first step to making this feature work is to contact Shortcuts and arrange for the _Stylist single sign-on_ feature to be enabled for your organization. Because each organization differs in the way that it manages passwords and credentials, we will have to provide a pathway unique to you that allows us to call back to you with stylist credentials in order for you to validate them. The next step is for the organization to put in place some code that will drive the _Stylist single sign-on_ process from your end. The (simple) process is: 1. You will collect the stylist's credentials and supply them to the Shortcuts signon server for validation. 1. Shortcuts will call back to you to validate the supplied credentials 1. If this validation is successful then you will receive 2 cookies that allow the stylist access to their site in the Shortcuts Live environment. 1. You will then make a request to the Shortcuts Live environment, and supply the cookies obtained above. This will be enough to allow access to a site. It is possible to do this programmatically, as the following tests show: [stylist-single-signon.test.js](./js/test/stylist-single-signon.test.js) An example test: ~~~ javascript it('must return auth cookies when called with valid credentials', function (done) { stylistSingleSignon.getAuthCookies(stylistCredentials, function (err, authCookies) { expect(err).toEqual(null); expect(authCookies).toBeDefined(); expect(authCookies['OAuth']).toBeDefined(); expect(authCookies['.ASPAUTH']).toBeDefined(); sharedAuthCookies = authCookies; done(); }); }); ~~~ The code that actually invokes the Shortcuts signon server in the correct way is in [stylist-single-signon.js](./js/src/stylist-single-signon.js) and can be freely altered or reused. The relevant call is: ~~~ javascript request({ method: 'POST', uri: 'https://signon.shortcutssoftware.com/authenticate', headers: { 'Authorization': authorizationHeaderValue }, form: { grant_type: stylistCredentials.grant_type, oauth_consumer_key: stylistCredentials.oauth_consumer_key }, resolveWithFullResponse: true }) ~~~ ## However Due to security safeguards in different browsers, it is not possible to reliably get and set cookies for another domain (`shortcutssoftware.com`), while you are on a web page hosted in your domain. If you are using a web page to perform the _Stylist single sign-on_ process, then you will have to do a little bit of extra legwork, so the process described above becomes: - Collect the stylist's credentials and supply them via a _self-hosted server_ to Shortcuts for validation. - We have provided an example implementation of such a server in NodeJS for you at [server.js](./js/src/server.js), but you can implement a this server in almost any technology. The authentication is done by issuing a request as shown in [stylist-single-signon.js](./js/src/stylist-single-signon.js). - We have also used this server to deliver the html page that is used to gather the stylist's credentials. See [index.html](./js/src/index.html). You do not need to host these two things on the same server. It is done this way in the example purely for convenience. - Take the object that is returned by this call to the server. It contains the two cookies that will enable you to access the Shortcuts Live environment. *Note: because you are not on a webpage hosted by the Shortcuts Live domain, your browser will not allow you to reliably get and set cookies for that domain. These cookies were issued to the `shortcutssoftware.com` domain, and so may only be accepted by your browser if it is on a page hosted on the `shortcutssoftware.com` domain* - To enable this issuing of cookies to work, we use a mechanism whereby the browser page in domain A (your domain) opens a new iframe on the `shortcutssoftware.com` domain, which makes a GET request to domain `shortcutssoftware.com` using these cookie values. Because this request is on the `shortcutssoftware.com` domain, the browser accepts the cookie that is issued. You may not have visibility of the contents of the iframe and the cookies issued to that iframe from your web page, but that is ok. The browser will remember those cookies when they are later required to be sent to the Shortcuts Live pages. - You then open up a browser window for the Shortcuts Live environment. Since the cookies set in the iframe were stored for the `shortcutssoftware.com` domain, the stylist will be able to access to their site in the Shortcuts Live environment. ## How to run this example 1. Clone this repository, then change directory to the `other/stylist-single-signon/js` folder. 1. Run the following command to install dependencies: `npm install` 1. Run the following command to execute all the tests: `npm test`. 1. You can see the results of the tests printed out on the console as they run. 1. Alternatively, you can use the IDE of your choice to run the tests and debug them to get a better understanding of what individual steps are happening. 1. Run the following command to start the http server: `npm start`. 1. You will see a message saying `Stylist single signon server listening on port 8080!`. 1. You can then open up the following page in a browser to test the _Stylist single signon_ feature through the browser of your choice: [http://localhost:8080/index.html](http://localhost:8080/index.html). ## Notes: - The example server implementation does not use HTTPS. Please ensure that when you deliver a real implementation you only support HTTPS for any traffic where passwords are transmitted. - The tests expect a file of the name `example-stylist-credentials.js` that declares stylist credentials. Since the information in this file is sensitive, please copy and use [example-stylist-credentials-template.js](./js/test/example-stylist-credentials-template.js) as a guide to creating this file using your own stylist credentials. - We have not applied any styling to the example web page, but in the case of the iframes, it is not necessary to display these, their only function is to cause the correct cookies to be issued on the correct domain. You can safely hide or dispose of them. - Please [email us](mailto:<EMAIL>) if you have any questions about this example.
4a0ba16c63b21c8733cd740a0f07122370e60199
[ "JavaScript", "Markdown", "INI", "Gradle", "Java" ]
57
JavaScript
shortcutssoftware/sc-ols-examples
57d085af9bbb9c925016f0f94de7006116be91f6
3c4059fd9ae98e2b9733fa8f9134c7bb732aa847
refs/heads/master
<repo_name>Charlvdh/Data-Science<file_sep>/various_projects/README.md # Data Quest This is the home of all of my Data Quest projects <file_sep>/README.md # Data-Science **Welcome to my Data Science repository!** This repository contains some of my projects related to Data Science. These range from simple data cleaning and visualisation projects to reasonably in depth deep learning projects. **Note:** Github has seemed to have some issues rendering **.ipynb** files lately so appologies if you get an error when trying to view these files. If you are unable to view the files on Github and have Jupyter Notebook installed then please feel free to dowload the notebooks and view them locally. If you do not have Jupyter Notebook installed on your local machine then you will be able to view the content in "Raw" mode but this will be far less illustrative of the actual content and purpose of the notebook. Hopefully, however, this issue is sorted by the time you're looking at the files and you will not need to worry about this. <file_sep>/deep_learning/README.md # Deep Learning **This folder contains my projects from [<NAME>'s deeplearning.ai course](https://www.coursera.org/specializations/deep-learning) on Coursera as well as other interesting deep learning themed projects and papers** ---- ## Course 1: Neural Network and Deep Learning** * [Logistic-regression-with-a-neural-network-mindset](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_1/Logistic-regression-with-a-neural-network-mindset) * [Planar-data-classification-with-one-hidden-layer](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_1/Planar-data-classification-with-one-hidden-layer) * [Building-a-deep-neural-network](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_1/Building-a-deep-neural-network) * [Deep-neural-network-cat-classification](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_1/Deep-neural-network-cat-classification) ## Course 2: Improving Deep Neural Networks: Hyperparameter tuning, Regularization and Optimization * [Initialisation](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_2/Initialisation) * [Regularisation](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_2/Regularisation) * [Gradient-checking](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_2/Gradient-checking) * [Optimisation](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_2/Optimisation) * [Tensorflow](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_2/Tensorflow) ## Course 3: Structuring machine Learning Projects * Note that no projects were included in this section ## Course 4: Convolutional Neural Networks * [Numpy-implementation](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_4/Numpy-implementation) * [Keras-tutorial](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_4/Keras-tutorial) ## Course 5: Sequence Models * [Building-a-RNN](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_5/Building-a-RNN) * [Character-level-language-modeling](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_5/Character-level-language-modeling) * [Word-vector-representation](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_5/Word-vector-representation) * [Word-vector-representation](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_5/Word-vector-representation) * [LSTM-network](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_5/LSTM-network) * [Emojify](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Course_5/Emojify) ---- ## Side projects / experiments * [Plotting-a-decision-boundary-in-2D-space](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Plotting-a-decision-boundary-in-2D-space) * [Plotting-a-decision-boundary-in-3D-space](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/Plotting-a-decision-boundary-in-3D-space) ## Interesting reading * [Efficient BackProp](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf) * [ADAM: A METHOD FOR STOCHASTIC OPTIMIZATION](https://arxiv.org/pdf/1412.6980.pdf) * [Convolutional Neural Network Papers](https://github.com/Charlvdh/Data-Science/tree/master/deep_learning/papers) <file_sep>/Rep_Monitor/app.py import dash import dash_core_components as dcc import dash_html_components as html import pandas as pd import plotly.plotly as py import plotly.graph_objs as go from dash.dependencies import Input, Output, State import numpy as np import back_end_integration as bei colors = { 'background': '#ffffff', 'black': '#000000', 'deloitte_green': '#86BC25', 'deloitte_aqua': '#00A3E0', 'deloitte_white': '#ffffff' } # placeholder_df to start off with placeholder_df = pd.DataFrame([[0.0, 0.32682400941848755, 'Deloitte is full of corruption', '2019-06-23', '1', "neg_topic_1"], [0.0, 0.32682400941848755, 'Deloitte is full of corruption', '2019-06-23', '1', "neg_topic_2"], [1.0, 0.8592533469200134, 'Deloitte a favorite amoung listed companies', '2019-06-21', '1', "pos_topic_1"], [1.0, 0.8592533469200134, 'Deloitte a favorite amoung listed companies', '2019-06-21', '1', "pos_topic_2"], [0.0, 0.17859989404678345, 'Deloitte in the middle of yet another accounting scandal', '2019-06-20', '1', "neg_topic_3"], [1.0, 0.841434895992279, 'Deloitte is the best accounting firm in South Africa', '2019-06-20', '1', "pos_topic_3"], [1.0, 0.916645884513855, 'Having an amazing time at Deloitte', '2019-06-19', '1', "pos_topic_3"], [0.0, 0.026026848703622818, 'Deloitte is a lost cause', '2019-06-17', '1', "neg_topic_3"]], columns=["hard_pred", "soft_pred", "original_text", "created_at", "topic_id", "topic"]) # Initialise result_df as empty df as need to draw from this later result_df = pd.DataFrame() # Set up topics list to assist with referencing topic button ids later pos_topic_ids = ['pos_topic_1', 'pos_topic_2', 'pos_topic_3'] neg_topic_ids = ['neg_topic_1', 'neg_topic_2', 'neg_topic_3'] # Set up figure and rep_children to assist with referencing them later figure = 0 rep_children = 0 rep_score = 0 pie_chart = 0 table_1_children = 0 table_2_children = 0 # Set up topic_list topic_list = [] # Topic tables def generate_topic_tables(df, name): # Set topic_ds as empty list initially topic_ids = [] # If statement for button color if df["hard_pred"].unique() == 1: button_background = colors['deloitte_green'] button_text = colors['black'] topic_ids = pos_topic_ids # Empty out topic_list global topic_list topic_list = [] else: button_background = colors['black'] button_text = colors['deloitte_white'] topic_ids = neg_topic_ids # Get unique topics topics = df["topic"].unique() print(topics) for topic in topics: topic_list.append(topic) return html.Div([ html.H3(children=name), html.Div([ html.Div(children=topics[0], style={'display': 'inline-block'} ,className = "seven columns"), html.Button('Explore', id=topic_ids[0], style={'backgroundColor': button_background, 'color': button_text, 'display': 'inline-block'}) ]), html.Div([ html.Div(children=topics[1], style={'display': 'inline-block'} ,className = "seven columns"), html.Button('Explore', id=topic_ids[1], style={'backgroundColor': button_background, 'color': button_text, 'display': 'inline-block'}) ]), html.Div([ html.Div(children=topics[2], style={'display': 'inline-block'} ,className = "seven columns"), html.Button('Explore', id=topic_ids[2], style={'backgroundColor': button_background, 'color': button_text, 'display': 'inline-block'}) ]) ]) # Tweet tables def generate_table(series, topic, max_rows=10): # reset index so can loop over tweets series = series.reset_index() print(series['original_text']) return html.Table( # Header [html.Tr(topic, style={'fontWeight': 'bold'})] + # Body [html.Tr(html.Td(series['original_text'][i])) for i in range(min(series['original_text'].size, max_rows))] ) # Set external stylesheets external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] # Initialise app app = dash.Dash(__name__, external_stylesheets=external_stylesheets) # Set up app layout app.layout = html.Div([ # Headers html.Div([ html.Div([ html.H1( children='Rep Monitor', style={ 'textAlign': 'right', 'color': colors['black'] } ) ], className = "six columns", id = "headerDiv1"), html.Div([ html.H3( children='by ', style={ 'textAlign': 'left', 'color': colors['black'], 'display': 'inline-block' } ), html.Img( src='https://nextreality.com/wp-content/uploads/2019/02/deloitte.png', style={ 'height': '3em', 'width': '8em', 'display': 'inline-block', 'verticalAlign': 'bottom', 'marginBottom': '0.7em' } ) ], className = "six columns", id = "headerDiv2", style={'marginLeft': '1em', 'display':'inline'}) ], className = "row", id = "outerHeaderDiv"), # Inputs and rep_score html.Div([ html.Div([ html.Div([ dcc.Input(id='input-box1', type='text', value = "@DeloitteSA") ], className = "three columns", id = "queryStringDiv", style={'marginRight': '1em'}), html.Div([ dcc.Input(id='input-box2', type='text', value = "2019-05-19") ], className = "three columns", id = "fromStringDiv", style={'marginRight': '1em'}), html.Div([ html.Button('Submit a query', id='submit-button', style={'backgroundColor': colors['deloitte_green'], 'color': colors['black']}) ], className = "three columns", id = "submitButtonDiv", style={'marginLeft': '2em'}) ], className = "six columns", id = "queryDiv"), html.Div([ html.H2( id='rep_score', style={ 'textAlign': 'center', 'color': colors['black'], } ) ], className = "six columns", id = "scoreDiv") ], className = "row", id = "outerQueryDiv", style={'marginTop': '2em'}), # Tables and pie chart html.Div([ html.Div([ html.Div(className = "row", id = "innerTableDiv1", children = generate_topic_tables(placeholder_df.loc[placeholder_df["hard_pred"]==1], "Positive Themes")), html.Div(className = "row", id = "innerTableDiv2", children = generate_topic_tables(placeholder_df.loc[placeholder_df["hard_pred"]==0], "Negative Themes")), ], className = "eight columns", id = "outerTableDiv"), html.Div([ dcc.Graph( id='pie_chart', ) ], className = "four columns", id = "pieDiv") ], className = "row", id = "tableAndPieDiv", style={'marginTop': '2em'}), # Bottom div for tweet table html.Div([ ], className = "row", id = "tweetTableDiv", style={'marginTop': '2em'}) ], id = "mainOuterDiv", style={'padding': '1em'}) # Callbacks # Callback to show themes, plot graphs, calc rep score, etc @app.callback( [Output('pie_chart', 'figure'), Output('rep_score', 'children'), Output('innerTableDiv1', 'children'), Output('innerTableDiv2', 'children'), Output('tweetTableDiv', 'children') ], [Input('submit-button', 'n_clicks'), Input(pos_topic_ids[0], 'n_clicks'), Input(pos_topic_ids[1], 'n_clicks'), Input(pos_topic_ids[2], 'n_clicks'), Input(neg_topic_ids[0], 'n_clicks'), Input(neg_topic_ids[1], 'n_clicks'), Input(neg_topic_ids[2], 'n_clicks')], [State('input-box1', 'value'), State('input-box2', 'value')]) def on_click(*args): global figure global rep_children global table_1_children global table_2_children n_clicks = args[0] q = args[-2] since = args[-1] if n_clicks == None: # Pie chart num_pos_tweets = placeholder_df["hard_pred"].sum() num_neg_tweets = placeholder_df["soft_pred"].shape[0] - num_pos_tweets rep_score = int(np.multiply(placeholder_df["soft_pred"].mean(), 100)) labels = ["Positive","Negative"] values = [num_pos_tweets, num_neg_tweets] pie_chart = go.Pie(labels=labels, values=values, marker=dict(colors=[colors['deloitte_green'], colors['black']], line=dict(color=colors['deloitte_white'], width=2))) figure={ 'data': [ pie_chart ], 'layout': { 'plot_bgcolor': colors['background'], 'paper_bgcolor': colors['background'], 'font': { 'color': colors['black'] }, 'margin':{ 'l':0, 'r':0, 'b':0, 't':0, 'pad':'1em' } } } # rep score rep_children=f'Rep Score: {rep_score}%' #Themes table_1_children = generate_topic_tables(placeholder_df.loc[placeholder_df["hard_pred"]==1], "Positive Themes") table_2_children = generate_topic_tables(placeholder_df.loc[placeholder_df["hard_pred"]==0], "Negative Themes") # Tweet tables (empty) tweet_table_children = html.Div([]) return figure, rep_children, table_1_children, table_2_children, tweet_table_children elif n_clicks > 0 and any(args[1:7]) == False: q = q since = since print(q) print(since) # Get result global result_df result_df = bei.get_predictions(q, since) # Pie chart num_pos_tweets = result_df["hard_pred"].sum() num_neg_tweets = result_df["soft_pred"].shape[0] - num_pos_tweets rep_score = int(np.multiply(result_df["soft_pred"].mean(), 100)) labels = ["Positive","Negative"] values = [num_pos_tweets, num_neg_tweets] pie_chart = go.Pie(labels=labels, values=values, marker=dict(colors=[colors['deloitte_green'], colors['black']], line=dict(color=colors['deloitte_white'], width=2))) figure={ 'data': [ pie_chart ], 'layout': { 'plot_bgcolor': colors['background'], 'paper_bgcolor': colors['background'], 'font': { 'color': colors['black'] }, 'margin':{ 'l':0, 'r':0, 'b':0, 't':0, 'pad':'1em' } } } # rep score rep_children=f'Rep Score: {rep_score}%' #Themes table_1_children = generate_topic_tables(result_df.loc[result_df["hard_pred"]==1], "Positive Themes") table_2_children = generate_topic_tables(result_df.loc[result_df["hard_pred"]==0], "Negative Themes") # Tweet tables (empty) tweet_table_children = html.Div([]) return figure, rep_children, table_1_children, table_2_children, tweet_table_children elif n_clicks > 0 and any(args[1:7]) == True: # Determine which explore button was clicked topic_inputs = args[1:7] selected_topic = topic_list[topic_inputs.index(1)] # Set up new outputs tweets_for_table = result_df.loc[(result_df["topic"] == selected_topic), "original_text"] print(tweets_for_table) tweet_table_children = generate_table(tweets_for_table, selected_topic, max_rows=10) return [figure, rep_children, table_1_children, table_2_children, tweet_table_children] if __name__ == '__main__': app.run_server(debug=True) <file_sep>/various_projects/Predicting_The_S&P500/predict.py # Import required mudules import pandas as pd from datetime import datetime import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_absolute_error from itertools import combinations # Read in the csv file as a DataFrame sap = pd.read_csv("sphist.csv", index_col=False) # Convert the Date column to datetime sap["Date"] = pd.to_datetime(sap["Date"]) # The dataframe is currently sored by date in descending order # Let's change it to ascending order # Also reset index so starts at 0 sap = sap.sort_values(by="Date", ascending=True) sap = sap.reset_index(drop=True) # Calculate 5 days moving average, 30 day moving average # 5 day standard deviation and 30 day standerd deviation and and them as columns # ma_5 def add_moving_average_col(period): control = [] col = [] for row in sap.iterrows(): row = row[1] if len(control) < period: control.append(row["Close"]) col.append(0) else: col.append(np.mean(control)) del control[0] control.append(row["Close"]) sap[f"{period}_day_ma"] = col add_moving_average_col(5) # ma_30 add_moving_average_col(30) # std_5 def add_moving_std_col(period): control = [] col = [] for row in sap.iterrows(): row = row[1] if len(control) < period: control.append(row["Close"]) col.append(0) else: col.append(np.std(control)) del control[0] control.append(row["Close"]) sap[f"{period}_day_std"] = col add_moving_std_col(5) # std_30 add_moving_std_col(30) # Also add the prior day close and volume as columns # pr_day_close def prior_day(attribute): col = sap[attribute].shift(1) sap[f"pr_day_{attribute}".lower()] = col prior_day("Close") # pr-day_volume prior_day("Volume") # Remove the first 30 rows as these rows do not have values for # all indicators sap.drop(range(0,31), inplace=True) # Drop na rows sap.dropna(axis=0, inplace=True) # Split df into train and test sets with train being all datapoints # before 2013-01-01 train = sap.loc[sap["Date"] < datetime(year=2013, month=1, day=1)] test = sap.loc[sap["Date"] >= datetime(year=2013, month=1, day=1)] # Let's build, train and test a model with absolute mean error # as the error metric # For features we can only use metrics we would know at the end # of the previous day all_features = ['5_day_ma', '30_day_ma', '5_day_std', '30_day_std', 'pr_day_close', 'pr_day_volume'] target = "Close" def train_and_test(): # In order to find the best combination of columns to use # generate a model for every combination and calculate and # compare error metrics maes = {} combinations_list = [] for i in range(2, len(all_features)): new_combinations = combinations(all_features, i) for combination in new_combinations: combinations_as_a_list = list(combination) # In order to store the list as a dictionary value it is # necessary to join the items into a string and then # split them out to a list later key = '-'.join(combinations_as_a_list) combinations_list.append(key) for features in combinations_list: features = features.split('-') model = LinearRegression() model.fit(train[features], train[target]) predictions = model.predict(test[features]) mae = mean_absolute_error(test[target], predictions) features = '-'.join(features) maes[features] = mae # Turn the dict into a dataframe df = pd.DataFrame.from_dict(maes, orient="index") df.columns = ["Value"] # As per inspection of a scatter plot ot the mae values, # there are a few high outliers. Remove all maes over 100 # to eliminate these df = df.loc[df["Value"] < 100] # There seem to be some in the range # some in the range 25 - 30 # some in the range 15 - 20 # some in the range 1 plt.scatter(range(1, len(df)+1), df["Value"]) plt.show() # best_mae = min(maes.values()) # best_features = min(maes, key=maes.get) # # worst_mae = max(maes.values()) # worst_features = max(maes, key=maes.get) # # print(f"Best Features: {best_features}\nBest Mean Absolute Error: {best_mae}\nWorst Features: {worst_features}\nWorst Mean Absolute Error {worst_mae}\nAverage MSE: {sum(maes.values())/len(maes.values())}") # Plot the maes # It appears that there are a few very high outlying mae values # Cap mae at 100 to eliminate them train_and_test()
5533b300321e3e7658b9a7e6aca52d1c11b80a4e
[ "Markdown", "Python" ]
5
Markdown
Charlvdh/Data-Science
2415d7aecebcaca812b569af7317f903d974f093
ce8779e11a140dc2159b961ffc14c0dc23bef6b7
refs/heads/master
<repo_name>mengxin1/react<file_sep>/src/components/Nav.js import React,{Component} from 'react'; import {NavLink} from 'react-router-dom'; export default class Nav extends Component{ render(){ return( <div> <ul> <li><NavLink to="/" activeClassName="active" exact>Home</NavLink></li> <li><NavLink to="/basic-routing" activeClassName="active">BasicRouting</NavLink></li> <li><NavLink to="/blocking" activeClassName="active">Blocking</NavLink></li> <li><NavLink to="/miss" activeClassName="active">Miss</NavLink></li> <li><NavLink to="/query-params" activeClassName="active">QueryParams</NavLink></li> </ul> </div> ) } } <file_sep>/src/components/Miss.js import React,{Component} from 'react'; import {Link,Route,Switch} from 'react-router-dom' import {Content,Nomatch} from '../components' export default class Miss extends Component{ render(){ return( <div> Miss <br/> <ul> <li><Link to={this.props.match.url+'/level1'}>Level 1</Link></li> <li><Link to={this.props.match.url+'/level2'}>Level 2</Link></li> <li><Link to={this.props.match.url+'/level3'}>Level 3</Link></li> </ul> <Switch> <Route path={`${this.props.match.url}/:level`} component={Content}></Route> <Route component={Nomatch}></Route> </Switch> </div> ) } }<file_sep>/src/components/index.js export Home from './Home.js'; export Nav from './Nav.js'; export BasicRouting from "./BasicRouting"; export Content from './Content'; export Blocking from "./Blocking"; export Miss from './Miss'; export Nomatch from './Nomatch'; export QueryParams from './QueryParams';<file_sep>/src/Repo.js import React,{Component} from 'react'; export default class Repo extends Component{ render(){ return( <div> Repo <br/> userName:{this.props.params.userName} <br/> repoName:{this.props.params.repoName} </div> ) } }<file_sep>/src/components/Content.js import React,{Component} from 'react'; export default class Content extends Component{ render(){ const location=this.props.location; const params=this.props.match.params; return( <div> Content <br/> Params:{JSON.stringify(params)} <br/> Location:{JSON.stringify(location)} </div> ) } }
ef9608636ae8de824ebb91b4e2f69f9b04a99797
[ "JavaScript" ]
5
JavaScript
mengxin1/react
6fb611cec2fc99b4633fa0a98b59ce7f734c5234
ea6ccf8c76d1c1ccb7fdc731896fb5d4ea91a7fc
refs/heads/master
<file_sep>package main func rotatematrix90AntiClock(inputmatrix [][]int, order int, i int, j int) { inputmatrix[i][j], inputmatrix[order-1-j][i] = inputmatrix[order-1-j][i], inputmatrix[i][j] inputmatrix[i][j], inputmatrix[order-i-1][order-1-j] = inputmatrix[order-i-1][order-1-j], inputmatrix[i][j] inputmatrix[i][j], inputmatrix[j][order-i-1] = inputmatrix[j][order-i-1], inputmatrix[i][j] } func main() { inputmatrix := [][]int{{1, 2, 3}, {5, 6, 7}, {9, 10, 11}} for i := 0; i < len(inputmatrix)/2; i++ { for j := i; j < len(inputmatrix)-i-1; j++ { rotatematrix90AntiClock(inputmatrix, len(inputmatrix), i, j) } } } <file_sep>package main import ( "fmt" "go-dsa/treeformation" ) func spiralView(headNode *treeformation.Node) { count := 1 nodeMap := map[int][]*treeformation.Node{} nodeMap[count] = []*treeformation.Node{headNode} for len(nodeMap[count]) != 0 { if count%2 != 0 { for i := len(nodeMap[count]) - 1; i >= 0; i-- { if nodeMap[count][i].Left != nil { nodeMap[count+1] = append(nodeMap[count+1], nodeMap[count][i].Left) } if nodeMap[count][i].Right != nil { nodeMap[count+1] = append(nodeMap[count+1], nodeMap[count][i].Right) } } } else { for i := len(nodeMap[count]) - 1; i >= 0; i-- { if nodeMap[count][i].Right != nil { nodeMap[count+1] = append(nodeMap[count+1], nodeMap[count][i].Right) } if nodeMap[count][i].Left != nil { nodeMap[count+1] = append(nodeMap[count+1], nodeMap[count][i].Left) } } } count += 1 } for level, nodeData := range nodeMap { fmt.Println(fmt.Sprintf("-----------Level %v ---------", level)) for _, node := range nodeData { fmt.Print(fmt.Sprintf(" %v ", node.Data)) } fmt.Println() } } func main() { treeData := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0, 0, 17, 18} // If you need to create a nil, then send 0 headNode := treeformation.CreateTree(treeData) spiralView(headNode) } <file_sep>package main import "fmt" func main() { arr := []int{4, 6, 3, 9, 5, 1 ,7} nextGreatest := make([]int, len(arr)) var stack []int for index, element := range arr { if len(stack) == 0 { stack = append(stack, index) continue } if element > arr[stack[len(stack)-1]] { for len(stack) > 0 && element > arr[stack[len(stack)-1]] { stackElement := stack[len(stack)-1] stack = stack[0:len(stack)-1] nextGreatest[stackElement] = element } } stack = append(stack, index) } for len(stack) > 0 { nextGreatest[stack[len(stack)-1]] = -1 stack = stack[0:len(stack)-1] } fmt.Println(nextGreatest) }<file_sep>package no_of_max_subsequences import "strings" func next(arr []int, target int) int { start := 0 end := len(arr) - 1 ans := -1 for start <= end { mid := (start + end) / 2 if arr[mid] <= target { start = mid + 1 } else { ans = mid end = mid - 1 } } return ans } /* Given a string s and an array of strings words, return the number of words[i] that is a subsequence of s. A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters. For example, "ace" is a subsequence of "abcde". Example 1: Input: s = "abcde", words = ["a","bb","acd","ace"] Output: 3 Explanation: There are three strings in words that are a subsequence of s: "a", "acd", "ace". Example 2: Input: s = "dsahjpjauf", words = ["ahjpjau","ja","ahbwzgqnuk","tnmlanowax"] Output: 2 */ func numMatchingSubsequences(s string, words []string) int { actualSMap := map[string][]int{} for index, char := range strings.Split(s, "") { actualSMap[char] = append(actualSMap[char], index) } validCount := 0 for _, word := range words { sMapCopy := map[string][]int{} for char, data := range actualSMap { sMapCopy[char] = data } lastIndex := -1 wSplit := strings.Split(word, "") isValidWord := true for _, char := range wSplit { if data, ok := sMapCopy[char]; !ok || len(data) == 0 { isValidWord = false break } if sMapCopy[char][0] <= lastIndex { target := next(sMapCopy[char], lastIndex) if target == -1 { isValidWord = false break } sMapCopy[char] = sMapCopy[char][target:] } lastIndex = sMapCopy[char][0] sMapCopy[char] = sMapCopy[char][1:] } if isValidWord { validCount++ } } return validCount } <file_sep>package main import "sort" /* Given a rectangular cake with height h and width w, and two arrays of integers horizontalCuts and verticalCuts where horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut. Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCuts. Since the answer can be a huge number, return this modulo 10^9 + 7. Example 1: Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3] Output: 4 Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area. Example 2: Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1] Output: 6 Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area. Example 3: Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3] Output: 9 */ func maxArea(h int, w int, horizontalCuts []int, verticalCuts []int) int { horizontalCuts = append([]int{0}, horizontalCuts...) horizontalCuts = append(horizontalCuts, h) verticalCuts = append([]int{0}, verticalCuts...) verticalCuts = append(verticalCuts, w) sort.Ints(horizontalCuts) sort.Ints(verticalCuts) besthc := 0 hlen := len(horizontalCuts) for i := 1; i < hlen; i++ { diff := horizontalCuts[i] - horizontalCuts[i-1] if diff > besthc { besthc = diff } } bestvc := 0 vlen := len(verticalCuts) for i := 1; i < vlen; i++ { diff := verticalCuts[i] - verticalCuts[i-1] if diff > bestvc { bestvc = diff } } return (besthc * bestvc) % 1000000007 } <file_sep>package shortest_path /* In an N by N square grid, each cell is either empty (0) or blocked (1). A clear path from top-left to bottom-right has length k if and only if it is composed of cells C_1, C_2, ..., C_k such that: Adjacent cells C_i and C_{i+1} are connected 8-directionally (ie., they are different and share an edge or corner) C_1 is at location (0, 0) (ie. has value grid[0][0]) C_k is at location (N-1, N-1) (ie. has value grid[N-1][N-1]) If C_i is located at (r, c), then grid[r][c] is empty (ie. grid[r][c] == 0). Return the length of the shortest such clear path from top-left to bottom-right. If such a path does not exist, return -1. */ func updateStackAndReturnSmallestPath(grid [][]int, stack [][2]int) ([][2]int, int) { element := stack[0] gridLen := len(grid) * len(grid) var smallest = gridLen for i := element[0] - 1; i <= element[0]+1; i++ { for j := element[1] - 1; j <= element[1]+1; j++ { if i < 0 || i >= len(grid) || j < 0 || j >= len(grid) || grid[i][j] == -1 { continue } if grid[i][j] == 0 { stack = append(stack, [2]int{i, j}) grid[i][j] = -1 continue } if grid[i][j] > 0 && grid[i][j] < smallest { smallest = grid[i][j] } } } if smallest == gridLen { return stack, 0 } return stack, smallest } func shortestPathBinaryMatrix(grid [][]int) int { if grid[len(grid)-1][len(grid)-1] == 1 || grid[0][0] == 1 { return -1 } gridLen := len(grid) var stack [][2]int for i := 0; i < gridLen; i++ { for j := 0; j < gridLen; j++ { grid[i][j] = -grid[i][j] } } grid[0][0] = -1 stack = [][2]int{{0, 0}} for len(stack) > 0 { var smallest int stack, smallest = updateStackAndReturnSmallestPath(grid, stack) poppedNode := stack[0] stack = stack[1:] grid[poppedNode[0]][poppedNode[1]] = smallest + 1 } if grid[gridLen-1][gridLen-1] == 0 { return -1 } return grid[gridLen-1][gridLen-1] } <file_sep>package main type node struct { left *node key int value int right *node } type LRUCache struct { head *node last *node keyNodeMap map[int]*node filledCount int capacity int } func InitialiseCacheObject(capacity int) LRUCache { return LRUCache{ head: nil, last: nil, keyNodeMap: make(map[int]*node, capacity), filledCount: 0, capacity: capacity, } } func createNewNode(key int, value int) *node { return &node{ key: key, value: value, } } func (cacheObject *LRUCache) moveNodeToLast(nodeAddress *node) { if cacheObject.last == nodeAddress { return } if nodeAddress == cacheObject.head { if nodeAddress.right != nil { cacheObject.head = nodeAddress.right nodeAddress.right.left = nil } } else { if nodeAddress.right != nil { nodeAddress.left.right = nodeAddress.right nodeAddress.right.left = nodeAddress.left } } cacheObject.last.right = nodeAddress nodeAddress.left = cacheObject.last nodeAddress.right = nil cacheObject.last = nodeAddress } func (cacheObject *LRUCache) Get(key int) int { nodeAddress, nodeExists := cacheObject.keyNodeMap[key] if !nodeExists { return -1 } cacheObject.moveNodeToLast(nodeAddress) return nodeAddress.value } func (cacheObject *LRUCache) Put(key int, value int) { nodeAddress, nodeExists := cacheObject.keyNodeMap[key] if nodeExists { cacheObject.moveNodeToLast(nodeAddress) nodeAddress.value = value return } if cacheObject.capacity == cacheObject.filledCount { headValue := cacheObject.head.key if cacheObject.head.right != nil { cacheObject.head.right.left = nil } cacheObject.head = cacheObject.head.right newNode := createNewNode(key, value) newNode.left = cacheObject.last cacheObject.last.right = newNode cacheObject.last = newNode delete(cacheObject.keyNodeMap, headValue) cacheObject.keyNodeMap[key] = newNode return } newNode := createNewNode(key, value) if cacheObject.head == nil { cacheObject.head = newNode cacheObject.last = newNode } else { newNode.left = cacheObject.last cacheObject.last.right = newNode cacheObject.last = newNode } cacheObject.keyNodeMap[key] = newNode cacheObject.filledCount = cacheObject.filledCount + 1 } // Usage ---- func main() { cacheObject := InitialiseCacheObject(10) cacheObject.Put(1, 10) cacheObject.Put(2, 30) cacheObject.Get(3) cacheObject.Get(1) cacheObject.Put(5, 50) } <file_sep>package helpers func StringPermutations(inputStr string) (permutations []string) { for i := 0; i < len(inputStr); i++ { inputStr = inputStr[1:] + inputStr[0:1] if len(inputStr) <= 2 { permutations = append(permutations, inputStr) continue } leftPermutations := StringPermutations(inputStr[0 : len(inputStr)-1]) for _, leftPermutation := range leftPermutations { permutations = append(permutations, leftPermutation+inputStr[len(inputStr)-1:]) } } return } func Abs(a int) int { if a < 0 { return -a } return a } func Min(a,b int) int { if a < b { return a } return b }<file_sep>package main import ( "fmt" "go-dsa/treeformation" ) // One approach would be to get nodes in pre-order and post-order and compare each of them. func checkMirror(headNode *treeformation.Node) bool { leftStack := []*treeformation.Node{headNode.Left} rightStack := []*treeformation.Node{headNode.Right} leftStackLen := len(leftStack) for i := 0; i < leftStackLen; i++ { if leftStack[0] == nil { if rightStack[0] != nil { return false } leftStack = leftStack[1:] rightStack = rightStack[1:] continue } if rightStack[0] == nil { if leftStack[0] != nil { return false } leftStack = leftStack[1:] rightStack = rightStack[1:] continue } if leftStack[0].Data != rightStack[0].Data { return false } leftStack = append(leftStack, []*treeformation.Node{leftStack[0].Left, leftStack[0].Right}...) rightStack = append(rightStack, []*treeformation.Node{rightStack[0].Right, rightStack[0].Left}...) leftStack = leftStack[1:] rightStack = rightStack[1:] leftStackLen = len(leftStack) } return true } func main() { treeNodes := []int64{1, 2, 2, 3, 4, 4, 3, 5, 6, 7, 8, 8, 7, 6, 5} headNode := treeformation.CreateTree(treeNodes) fmt.Println(checkMirror(headNode)) } <file_sep>package main type ListNode struct { Val int Next *ListNode } func getIntersectionNode(headA, headB *ListNode) *ListNode { var headALen, headBLen int tempHeadA := headA for tempHeadA != nil { headALen++ tempHeadA = tempHeadA.Next } tempHeadB := headB for tempHeadB != nil { headBLen++ tempHeadB = tempHeadB.Next } if headALen > headBLen { for i := 0; i < headALen-headBLen; i++ { headA = headA.Next } } else { for i := 0; i < headBLen-headALen; i++ { headB = headB.Next } } for headA != nil { if headA == headB { return headA } headA = headA.Next headB = headB.Next } return nil } <file_sep>package treeformation func CreateNode(nodeData int64) *Node { return &Node{ Data: nodeData, Left: nil, Right: nil, } } func CreateTree(datalist []int64) *Node { stack := []*Node{} var head, temphead *Node var i int dataLength := len(datalist) for i < len(datalist) { if head == nil { head = CreateNode(datalist[i]) stack = append(stack, head) i++ } else { temphead = stack[0] if i < dataLength { if datalist[i] == 0 { if temphead != nil { temphead.Left = nil } i++ } else { temphead.Left = CreateNode(datalist[i]) stack = append(stack, temphead.Left) i++ } } if i < dataLength { if datalist[i] == 0 { if temphead != nil { temphead.Right = nil } i++ } else { temphead.Right = CreateNode(datalist[i]) stack = append(stack, temphead.Right) i++ } } stack = stack[1:] } } return head } func CreateNodeNextRight(nodeData int64) *NodeWihNextRight { return &NodeWihNextRight{ Data: nodeData, Left: nil, Right: nil, NextRight: nil, } } func CreateTreeNextRight(datalist []int64) *NodeWihNextRight { stack := []*NodeWihNextRight{} var head, temphead *NodeWihNextRight var i int dataLength := len(datalist) for i < len(datalist) { if head == nil { head = CreateNodeNextRight(datalist[i]) stack = append(stack, head) i++ } else { temphead = stack[0] if i < dataLength { if datalist[i] == 0 { if temphead != nil { temphead.Left = nil } i++ } else { temphead.Left = CreateNodeNextRight(datalist[i]) stack = append(stack, temphead.Left) i++ } } if i < dataLength { if datalist[i] == 0 { if temphead != nil { temphead.Right = nil } i++ } else { temphead.Right = CreateNodeNextRight(datalist[i]) stack = append(stack, temphead.Right) i++ } } stack = stack[1:] } } return head } <file_sep>package main import "fmt" func rotatematrix(inputmatrix [][]int, order int, inner int) { for i := inner; i < order-inner-1; i++ { inputmatrix[inner][inner], inputmatrix[inner][i+1] = inputmatrix[inner][i+1], inputmatrix[inner][inner] } for i := inner + 1; i < order-inner; i++ { inputmatrix[inner][inner], inputmatrix[i][order-inner-1] = inputmatrix[i][order-inner-1], inputmatrix[inner][inner] } for i := order - inner - 2; i >= inner; i-- { inputmatrix[inner][inner], inputmatrix[order-inner-1][i] = inputmatrix[order-inner-1][i], inputmatrix[inner][inner] } for i := order - inner - 2; i > inner; i-- { inputmatrix[inner][inner], inputmatrix[i][inner] = inputmatrix[i][inner], inputmatrix[inner][inner] } } func main() { inputmatrix := [][]int{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}} fmt.Println(inputmatrix) for i := 0; i < len(inputmatrix)/2; i++ { rotatematrix(inputmatrix, len(inputmatrix), i) } fmt.Println(inputmatrix) } <file_sep>package main import "go-dsa/treeformation" /* Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. Note: A leaf is a node with no children. Example: Input: [1,2,3] 1 / \ 2 3 Output: 25 Explanation: The root-to-leaf path 1->2 represents the number 12. The root-to-leaf path 1->3 represents the number 13. Therefore, sum = 12 + 13 = 25. Example 2: Input: [4,9,0,5,1] 4 / \ 9 0 / \ 5 1 Output: 1026 Explanation: The root-to-leaf path 4->9->5 represents the number 495. The root-to-leaf path 4->9->1 represents the number 491. The root-to-leaf path 4->0 represents the number 40. Therefore, sum = 495 + 491 + 40 = 1026. */ func getSum(root *treeformation.Node, finalSum int64) int64 { if root == nil { return 0 } finalSum = finalSum*10 + root.Data if root.Left == nil && root.Right == nil { return finalSum } return getSum(root.Left, finalSum) + getSum(root.Right, finalSum) } func sumNumbers(root *treeformation.Node) int64 { return getSum(root, 0) } <file_sep>package main import "strings" /* You are given a 0-indexed binary string s and two integers minJump and maxJump. In the beginning, you are standing at index 0, which is equal to '0'. You can move from index i to index j if the following conditions are fulfilled: i + minJump <= j <= min(i + maxJump, s.length - 1), and s[j] == '0'. Return true if you can reach index s.length - 1 in s, or false otherwise. Example 1: Input: s = "011010", minJump = 2, maxJump = 3 Output: true Explanation: In the first step, move from index 0 to index 3. In the second step, move from index 3 to index 5. Example 2: Input: s = "01101110", minJump = 2, maxJump = 3 Output: false */ func canReach(s string, minJump int, maxJump int) bool { sSplit := strings.Split(s, "") if sSplit[0] != "0" || sSplit[len(s)-1] != "0" { return false } stack := []int{0} lastProcessedMax := minJump for len(stack) != 0 { poppedElement := stack[0] if len(stack) > 1 { stack = stack[1:] } else { stack = []int{} } if poppedElement+minJump > len(s)-1 { continue } max := poppedElement + maxJump if poppedElement+maxJump > len(s)-1 { max = len(s) - 1 } min := poppedElement + minJump if poppedElement+minJump < lastProcessedMax { min = lastProcessedMax } for i := min; i <= max; i++ { if sSplit[i] == "0" { if i == len(s)-1 { return true } stack = append(stack, i) } } lastProcessedMax = max + 1 } return false } <file_sep>package main import ( "fmt" "log" "math/rand" "os" "strconv" "time" ) /* Problem Statement :- -> An auto stand had around 5 autos waiting for the passengers -> As soon as the passengers comes, the auto leading the pack will pick the passenger and travel to the destination and return back and wait in the same queue. -> By the time the auto comes back, it can be the leading auto in the group again or it may be at the last depending on the incoming customers. -> If all the auto's are busy, the customer keep waiting -> Once the time comes, all the autos had to be popped from the stand. */ /* Assumptions -> Customer comes at random time interval from anywhere b/w 1-5 seconds. Drop -> May take any time b/w 1-10 seconds. */ type autoChan struct { driverName string autoNumber string } type customerChan struct { customerName string } func main() { autoStand := make(chan autoChan, 5) // Create a auto stand with 5 auto's customers := make(chan customerChan, 5) doneForDay := make(chan bool) for i := int64(0); i < 5; i++ { driver := "driver-" + strconv.FormatInt(i+1, 10) autoNumber := "auto-" + strconv.FormatInt(i+1, 10) log.Println("Driver " + driver + " started waiting for passengers") autoStand <- autoChan{ driverName: driver, autoNumber: autoNumber, } } go func() { customerCount := int64(0) for { customerCount += 1 newCustomerInterval := rand.Int63n(5) customerName := "customer-" + strconv.FormatInt(customerCount, 10) time.Sleep(time.Duration(newCustomerInterval) * time.Second) log.Println("New customer " + customerName + " arrived ") customers <- customerChan{ customerName: customerName, } } }() go func() { <-doneForDay os.Exit(0) }() go func() { time.Sleep(30 * time.Millisecond) doneForDay <- true }() for customerData := range customers { auto := <-autoStand log.Println("customer " + customerData.customerName + " received by auto " + auto.autoNumber) go func(auto autoChan) { dropTime := rand.Int63n(10) time.Sleep(time.Duration(dropTime) * time.Second) log.Println(fmt.Sprintf("Auto %v completed its ride in %v seconds and started waiting in queue", auto.autoNumber, dropTime)) autoStand <- auto }(auto) } } <file_sep>package main import ( heap2 "go-dsa/collections/heap" ) func topKFrequent(nums []int, k int) []int { h := heap2.NewHeap() numsMap := map[int]int{} for _, num := range nums { numsMap[num]++ } for key, value := range numsMap { h.Insert(&heap2.Node{ Val: key, Data: value, }) } returnData := make([]int, k) for i := 0; i < k; i++ { returnData[i] = h.Delete().Val } return returnData } func main() { /* Given a non-empty array of integers, return the k most frequent elements. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1] Note: You may assume k is always valid, 1 ≤ k ≤ number of unique elements. Your algorithm's time complexity must be better than O(n log n), where n is the array's size. It's guaranteed that the answer is unique, in other words the set of the top k frequent elements is unique. You can return the answer in any order. */ } <file_sep>package main import "go-dsa/treeformation" /* Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]] */ func getOrderedElements(root *treeformation.Node, finalSlice [][]int64, index int) [][]int64 { if root == nil { return finalSlice } if len(finalSlice) == index { finalSlice = append(finalSlice, []int64{root.Data}) } else { finalSlice[index] = append(finalSlice[index], root.Data) } index = index + 1 finalSlice = getOrderedElements(root.Left, finalSlice, index) finalSlice = getOrderedElements(root.Right, finalSlice, index) return finalSlice } func levelOrder(root *treeformation.Node) [][]int64 { return getOrderedElements(root, [][]int64{}, 0) } <file_sep>package palindromic_substrings import "strings" /* Given a string s, return the number of palindromic substrings in it. Input: s = "abc" Explanation: Three palindromic strings: "a", "b", "c". Input: s = "aaa" Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa". Approach -> If any string is supposed to be a palindrome, then the string[start+1:end] should also be a palindrome */ func countSubstrings(s string) int { sSplit := strings.Split(s, "") prevData := make([][]bool, len(sSplit)) var trueCount int for i := 0; i < len(prevData); i++ { prevData[i] = make([]bool, len(sSplit)) prevData[i][i] = true trueCount++ } for i := 1; i < len(sSplit); i++ { for j := 0; j < len(sSplit)-i; j++ { startIndex := j endIndex := j + i if startIndex+1 >= endIndex { if sSplit[startIndex] == sSplit[endIndex] { prevData[startIndex][endIndex] = true trueCount++ } continue } if prevData[startIndex+1][endIndex-1] == true && sSplit[startIndex] == sSplit[endIndex] { prevData[startIndex][endIndex] = true trueCount++ } } } return trueCount } <file_sep>package searches import ( "go-dsa/collections" ) type search struct { } func NewBinarySearch() collections.BinarySearch { return &search{} } func (s search) BinarySearchClosest(elements []int, elementToSearch int) (index int) { low := 0 high := len(elements) - 1 if elementToSearch < elements[0] { return 0 } if elementToSearch > elements[high] { return high } for low <= high { mid := (low + high) / 2 if elementToSearch == elements[mid] { return mid } if elementToSearch > elements[mid] { low = mid + 1 } if elementToSearch < elements[mid] { high = mid - 1 } } if (elements[low] - elementToSearch) < (elementToSearch - elements[high]) { return low } return high } <file_sep>package main import ( "fmt" "go-dsa/treeformation" ) func inorderTraversal(headNode *treeformation.NodeWihNextRight) { if headNode == nil { return } inorderTraversal(headNode.Left) fmt.Println(headNode.Data) inorderTraversal(headNode.Right) } func connectNodes(headNode *treeformation.NodeWihNextRight) { count := 0 nodeMap := map[int][]*treeformation.NodeWihNextRight{} nodeMap[0] = []*treeformation.NodeWihNextRight{headNode} for len(nodeMap[count]) != 0 { nodeMapCount := len(nodeMap[count]) for i := 0; i < nodeMapCount; i++ { if nodeMap[count][0].Left != nil { nodeMap[count+1] = append(nodeMap[count+1], nodeMap[count][0].Left) } if nodeMap[count][0].Right != nil { nodeMap[count+1] = append(nodeMap[count+1], nodeMap[count][0].Right) } firstNode := nodeMap[count][0] nodeMap[count] = nodeMap[count][1:] if len(nodeMap[count]) > 0 { firstNode.NextRight = nodeMap[count][0] } } count += 1 } } func printConnectedNodes(headNode *treeformation.NodeWihNextRight) { stack := []*treeformation.NodeWihNextRight{headNode} for len(stack) != 0 { if stack[0].Left != nil { stack = append(stack, stack[0].Left) } if stack[0].Right != nil { stack = append(stack, stack[0].Right) } nodeToDelete := stack[0] stack = stack[1:] if nodeToDelete.NextRight == nil { fmt.Println("Data -> ", nodeToDelete.Data, ". Next Node is nil") } else { fmt.Println("Data -> ", nodeToDelete.Data, ". Next Node is ", nodeToDelete.NextRight.Data) } } } func main() { treeNodes := []int64{10, 3, 5, 4, 1, 0, 2} headNode := treeformation.CreateTreeNextRight(treeNodes) connectNodes(headNode) printConnectedNodes(headNode) } <file_sep>package main import "sort" /* Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2: Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. */ func max(a, b int) int { if a > b { return a } return b } func merge(intervals [][]int) [][]int { sort.Slice(intervals, func(i, j int) bool { return intervals[i][0] <= intervals[j][0] }) i := 0 intLen := len(intervals) newIntervals := [][]int{} for i < intLen { temp := i bestRight := intervals[i][1] for i < intLen-1 && (intervals[i+1][0] >= intervals[temp][0] && intervals[i+1][0] <= bestRight) { if bestRight < max(intervals[i][1], intervals[i+1][1]) { bestRight = max(intervals[i][1], intervals[i+1][1]) } i++ } newIntervals = append(newIntervals, []int{intervals[temp][0], bestRight}) i++ } return newIntervals } <file_sep>package main /* The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. Given an integer n, return the number of distinct solutions to the n-queens puzzle. */ func abs(n int) int { if n < 0 { return -n } return n } func getPossibleSlots(n int, column int, occupiedSlots [][]int) [][]int { var validSlots [][]int for i := 0; i < n; i++ { isValidSlot := true for _, occupiedSlot := range occupiedSlots { if occupiedSlot[0] == i { isValidSlot = false break } if abs(occupiedSlot[0]-i) == abs(occupiedSlot[1]-column) { isValidSlot = false break } } if isValidSlot { validSlots = append(validSlots, []int{i, column}) } } return validSlots } func totalNQueens(n int) int { var count int var occupiedSlots [][]int possibleSlotsPerIndex := make([][][]int, n) var i int for i < n { var possibleSlots [][]int if len(possibleSlotsPerIndex[i]) == 0 { possibleSlots = getPossibleSlots(n, i, occupiedSlots) } else { possibleSlots = possibleSlotsPerIndex[i] } if len(possibleSlots) == 0 || i == n-1 { if i == n-1 && len(possibleSlots) > 0 { count++ } for i >= 0 && len(possibleSlotsPerIndex[i]) == 0 { if i > 0 { occupiedSlots = occupiedSlots[0 : i-1] } i-- } if i < 0 { return count } continue } occupiedSlots = append(occupiedSlots, possibleSlots[0]) if len(possibleSlots) > 1 { possibleSlotsPerIndex[i] = possibleSlots[1:] } else { possibleSlotsPerIndex[i] = [][]int{} } i++ } return 0 } <file_sep>package main /* You are given an array of positive integers nums and want to erase a subarray containing unique elements. The score you get by erasing the subarray is equal to the sum of its elements. Return the maximum score you can get by erasing exactly one subarray. An array b is called to be a subarray of a if it forms a contiguous subsequence of a, that is, if it is equal to a[l],a[l+1],...,a[r] for some (l,r). Example 1: Input: nums = [4,2,4,5,6] Output: 17 Explanation: The optimal subarray here is [2,4,5,6]. Example 2: Input: nums = [5,2,1,2,5,2,1,2,5] Output: 8 Explanation: The optimal subarray here is [5,2,1] or [1,2,5]. */ func maximumUniqueSubarray(nums []int) int { cumSum := make([]int, len(nums)) var sum int for index, num := range nums { cumSum[index] = sum sum = sum + num } var bestSum int numsMap := map[int]int{} startIndex := 0 for index, num := range nums { lastIndex, ok := numsMap[num] if ok && lastIndex >= startIndex { sum := cumSum[index] - cumSum[startIndex] if sum > bestSum { bestSum = sum } startIndex = lastIndex + 1 } numsMap[num] = index } if startIndex <= len(nums)-1 { sum = cumSum[len(nums)-1] - cumSum[startIndex] + nums[len(nums)-1] if sum > bestSum { bestSum = sum } } return bestSum } <file_sep>package main import "strings" /* Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. Example 1: Input: s: "cbaebabacd" p: "abc" Output: [0, 6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc". Example 2: Input: s: "abab" p: "ab" Output: [0, 1, 2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab". */ func findAnagrams(mainString string, request string) []int { if len(mainString) < len(request) { return []int{} } requestMap := make(map[string]int) var requestlen int var requestChar string for requestlen, requestChar = range strings.Split(request, "") { requestMap[requestChar]++ } sub := mainString[0 : requestlen+1] subMap := make(map[string]int) for _, subChar := range strings.Split(sub, "") { subMap[subChar]++ } matchingData := make(map[string]int) var missingCount int for key, requestKeyCount := range requestMap { if subMap[key] < requestKeyCount { missingCount += requestKeyCount - subMap[key] matchingData[key] = subMap[key] } matchingData[key] = subMap[key] } finalList := []int{} if missingCount == 0 { finalList = append(finalList, 0) } for i := 1; i < len(mainString)-requestlen; i++ { newEntry := string(mainString[i+requestlen]) oldEntry := string(mainString[i-1]) if requestMap[oldEntry] > 0 { if matchingData[oldEntry] <= requestMap[oldEntry] { missingCount++ } matchingData[oldEntry]-- } if requestMap[newEntry] > 0 { if matchingData[newEntry] < requestMap[newEntry] { missingCount-- } matchingData[newEntry]++ } if missingCount == 0 { finalList = append(finalList, i) } } return finalList } func main() { // Usage : findAnagrams("cbaebabacd", "abc") } <file_sep>package main import ( "go-dsa/treeformation" ) /* Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be pseudo-palindromic if at least one permutation of the node values in the path is a palindrome. Return the number of pseudo-palindromic paths going from the root node to leaf nodes. Example 1: Input: root = [2,3,1,3,1,null,1] Output: 2 Explanation: The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] ( palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome). */ func recursive(root *treeformation.Node, path []int64) (finalCount int) { if root == nil { return } path = append(path, root.Data) finalCount += recursive(root.Left, path) finalCount += recursive(root.Right, path) if root.Left == nil && root.Right == nil { oddCount := 0 pathCount := map[int64]int{} for _, element := range path { count, exists := pathCount[element] if !exists { pathCount[element] = 1 oddCount++ continue } if count%2 != 0 { oddCount-- } else { oddCount++ } pathCount[element]++ } if oddCount <= 1 { finalCount++ } } return finalCount } func pseudoPalindromicPaths(root *treeformation.Node) int { return recursive(root, []int64{}) } <file_sep>package main /* Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one. Example 1: Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price. Example 2: Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0. */ func bestOfTwo(a, b int) int { if a > b { return a } return b } func maxProfit(prices []int) int { priceLen := len(prices) if priceLen == 0 { return 0 } bestPrices := make([]int, priceLen) bestPrices[priceLen-1] = -1 for i := priceLen - 2; i >= 0; i-- { nextBest := bestOfTwo(prices[i+1], bestPrices[i+1]) if nextBest > prices[i] { bestPrices[i] = nextBest } else { bestPrices[i] = -1 } } maxDiff := 0 for i := 0; i < priceLen; i++ { if bestPrices[i] > 0 && bestPrices[i]-prices[i] > maxDiff { maxDiff = bestPrices[i] - prices[i] } } return maxDiff } <file_sep>package treeformation type Node struct { Data int64 Left *Node Right *Node } type NodeWihNextRight struct { Data int64 Left *NodeWihNextRight Right *NodeWihNextRight NextRight *NodeWihNextRight } <file_sep>package main import ( "fmt" "go-dsa/treeformation" "sort" ) func bottomView(headNode *treeformation.Node, count int, nodeMap map[int][]*treeformation.Node, ltype string) { if headNode == nil { return } if headNode.Left != nil { if ltype == "left" { nodeMap[count-1] = append([]*treeformation.Node{headNode.Left}, nodeMap[count-1]...) } else { nodeMap[count-1] = append(nodeMap[count-1], headNode.Left) } } bottomView(headNode.Left, count-1, nodeMap, "left") if headNode.Right != nil { if ltype == "left" { nodeMap[count+1] = append([]*treeformation.Node{headNode.Right}, nodeMap[count+1]...) } else { nodeMap[count+1] = append(nodeMap[count+1], headNode.Right) } } bottomView(headNode.Right, count+1, nodeMap, "left") } func main() { treeData := []int64{20, 8, 22, 5, 3, 4, 25, 6, 12, 10, 14} // If you need to create a nil, then send 0 headNode := treeformation.CreateTree(treeData) nodeMap := map[int][]*treeformation.Node{} nodeMap[0] = []*treeformation.Node{headNode} bottomView(headNode, 0, nodeMap, "") keys := []int{} for index := range nodeMap { keys = append(keys, index) } sort.Ints(keys) for _, index := range keys { fmt.Println(nodeMap[index][0].Data) } } <file_sep>package main import ( "fmt" "go-dsa/treeformation" ) /* Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” Example 1: Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 Output: 6 Explanation: The LCA of nodes 2 and 8 is 6. */ func lowestCommonAncestor(root, p, q *treeformation.Node) *treeformation.Node { if root == nil { fmt.Println("Root is nil") return root } if p.Data > q.Data { p, q = q, p } if root.Data >= p.Data && root.Data <= q.Data { return root } else if root.Data > p.Data { root = lowestCommonAncestor(root.Left, p, q) } else if root.Data < q.Data { root = lowestCommonAncestor(root.Right, p, q) } return root } <file_sep>package main type tweet struct { sequence int tweetID int left *tweet right *tweet } type userInfo struct { followers map[int]bool following map[int]bool tweetCount int head *tweet last *tweet tweets *tweet } type Twitter struct { UserMap map[int]userInfo totalTweets int } func createTweetNode(tweetID int, sequence int) *tweet { return &tweet{ sequence: sequence, tweetID: tweetID, } } func pickTopTen(tweetHeads []*tweet, capacity int) (newhead, last *tweet, unfollowedCapacity int) { var nilCount int for capacity > 0 && nilCount < capacity { nilCount := 0 best := -1 bestIndex := -1 for index, tweatHead := range tweetHeads { if tweatHead == nil { nilCount++ } else if tweatHead.sequence > best { best = tweatHead.sequence bestIndex = index } } if bestIndex < 0 { break } bestNode := tweetHeads[bestIndex] node := createTweetNode(bestNode.tweetID, bestNode.sequence) if newhead == nil { newhead = node last = node } else { node.left = last last.right = node last = node } unfollowedCapacity++ tweetHeads[bestIndex] = tweetHeads[bestIndex].right capacity-- } return } func mergeLinkedLists(list1Copy, list2Copy *tweet, capacity int) (newhead, last *tweet, mergedCapacity int) { list1 := list1Copy list2 := list2Copy mergedCapacity = capacity for capacity > 0 && (list1 != nil || list2 != nil) { var bestNode *tweet if list2 == nil || (list1 != nil && list1.sequence > list2.sequence) { bestNode = createTweetNode(list1.tweetID, list1.sequence) list1 = list1.right } else { bestNode = createTweetNode(list2.tweetID, list2.sequence) list2 = list2.right } if newhead == nil { newhead = bestNode last = bestNode } else { last.right = bestNode bestNode.left = last last = bestNode } capacity-- } return newhead, last, mergedCapacity - capacity } /** Initialize your data structure here. */ func Constructor() Twitter { return Twitter{ UserMap: make(map[int]userInfo), } } /** Compose a new tweet. */ func (this *Twitter) PostTweet(userId int, tweetId int) { this.totalTweets++ userData, exists := this.UserMap[userId] if !exists { userData = userInfo{ followers: map[int]bool{userId: true}, } this.UserMap[userId] = userData } for followingUser := range userData.followers { followingUserInfo := this.UserMap[followingUser] node := createTweetNode(tweetId, this.totalTweets) if followingUserInfo.head == nil { followingUserInfo.head = node followingUserInfo.last = node followingUserInfo.tweetCount++ } else { if followingUserInfo.tweetCount == 10 { followingUserInfo.last = followingUserInfo.last.left followingUserInfo.last.right = nil } else { followingUserInfo.tweetCount++ } node.right = followingUserInfo.head followingUserInfo.head.left = node followingUserInfo.head = node } this.UserMap[followingUser] = followingUserInfo } userData, _ = this.UserMap[userId] node := createTweetNode(tweetId, this.totalTweets) if userData.tweets == nil { userData.tweets = node } else { node.right = userData.tweets userData.tweets.left = node userData.tweets = node } this.UserMap[userId] = userData } /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */ func (this *Twitter) GetNewsFeed(userId int) (feed []int) { userInfo, _ := this.UserMap[userId] temp := userInfo.head for temp != nil { feed = append(feed, temp.tweetID) temp = temp.right } return } /** Follower follows a followee. If the operation is invalid, it should be a no-op. */ func (this *Twitter) Follow(followerId int, followeeId int) { followerInfo, exists := this.UserMap[followerId] _, followerExists := followerInfo.following[followeeId] if followerExists { return } if !exists { followerInfo.followers = map[int]bool{followerId: true} this.UserMap[followerId] = followerInfo } followeeInfo, exists := this.UserMap[followeeId] if !exists { followeeInfo.followers = map[int]bool{followeeId: true} this.UserMap[followeeId] = followeeInfo } newHead, newLast, newCapacity := mergeLinkedLists(followerInfo.head, followeeInfo.tweets, 10) followerInfo.head = newHead followerInfo.last = newLast followerInfo.tweetCount = newCapacity if followerInfo.following == nil { followerInfo.following = map[int]bool{followeeId: true} } else { followerInfo.following[followeeId] = true } followeeInfo.followers[followerId] = true this.UserMap[followerId] = followerInfo this.UserMap[followeeId] = followeeInfo } /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */ func (this *Twitter) Unfollow(followerId int, followeeId int) { if followerId == followeeId { return } followerInfo, exists := this.UserMap[followerId] if !exists { return } followeeInfo, exists := this.UserMap[followeeId] if !exists { return } tweetHeads := []*tweet{} for followingUser := range followerInfo.following { if followingUser == followeeId { continue } followingUserInfo, _ := this.UserMap[followingUser] tweetHeads = append(tweetHeads, followingUserInfo.tweets) } tweetHeads = append(tweetHeads, followerInfo.tweets) newhead, newLast, newCapacity := pickTopTen(tweetHeads, 10) followerInfo.head = newhead followerInfo.last = newLast followerInfo.tweetCount = newCapacity delete(followerInfo.following, followeeId) delete(followeeInfo.followers, followerId) this.UserMap[followeeId] = followeeInfo this.UserMap[followerId] = followerInfo } /** * Your Twitter object will be instantiated and called as such: * obj := Constructor(); * obj.PostTweet(userId,tweetId); * param_2 := obj.GetNewsFeed(userId); * obj.Follow(followerId,followeeId); * obj.Unfollow(followerId,followeeId); */ <file_sep>package collections type BinarySearch interface { BinarySearchClosest(elements []int, elementToSearch int) (index int) }<file_sep>package main func orangesRotting(grid [][]int) int { rottenOrangeIndexes := [][]int{} freshOrangeCount := 0 steps := 0 for i := 0; i < len(grid); i++ { for j := 0; j < len(grid[i]); j++ { if grid[i][j] == 2 { rottenOrangeIndexes = append(rottenOrangeIndexes, []int{i, j}) } else if grid[i][j] == 1 { freshOrangeCount += 1 } } } for len(rottenOrangeIndexes) > 0 { newRottenOranges := [][]int{} for i := 0; i < len(rottenOrangeIndexes); i++ { var x, y int rottenIndex := rottenOrangeIndexes[i] x = rottenIndex[0] y = rottenIndex[1] if y+1 < len(grid[x]) && grid[x][y+1] == 1 { newRottenOranges = append(newRottenOranges, []int{x, y + 1}) grid[x][y+1] = 2 freshOrangeCount-- } if y-1 >= 0 && grid[x][y-1] == 1 { newRottenOranges = append(newRottenOranges, []int{x, y - 1}) grid[x][y-1] = 2 freshOrangeCount-- } if x+1 < len(grid) && grid[x+1][y] == 1 { newRottenOranges = append(newRottenOranges, []int{x + 1, y}) grid[x+1][y] = 2 freshOrangeCount-- } if x-1 >= 0 && grid[x-1][y] == 1 { newRottenOranges = append(newRottenOranges, []int{x - 1, y}) grid[x-1][y] = 2 freshOrangeCount-- } } rottenOrangeIndexes = newRottenOranges if len(newRottenOranges) > 0 { steps++ } } if freshOrangeCount > 0 { return -1 } return steps } func main() { /* In a given grid, each cell can have one of three values: the value 0 representing an empty cell; the value 1 representing a fresh orange; the value 2 representing a rotten orange. Every minute, any fresh orange that is adjacent (4-directionally) to a rotten orange becomes rotten. Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1 instead. */ orangesRotting([][]int{}) } <file_sep>package main import ( "sort" ) /* There are 2N people a company is planning to interview. The cost of flying the i-th person to city A is costs[i][0], and the cost of flying the i-th person to city B is costs[i][1]. Return the minimum cost to fly every person to a city such that exactly N people arrive in each city. Example 1: Input: [[10,20],[30,200],[400,50],[30,20]] Output: 110 Explanation: The first person goes to city A for a cost of 10. The second person goes to city A for a cost of 30. The third person goes to city B for a cost of 50. The fourth person goes to city B for a cost of 20. The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city */ func twoCitySchedCost(costs [][]int) int { costsLen := len(costs) sort.SliceStable(costs, func(i, j int) bool { return (costs[i][0] - costs[i][1]) < costs[j][0]-costs[j][1] }) sum := 0 for i := 0; i < costsLen/2; i++ { sum = sum + costs[i][0] } for i := costsLen / 2; i < len(costs); i++ { sum = sum + costs[i][1] } return sum } func main() { costs := [][]int{{10, 20}, {30, 200}, {400, 50}, {30, 20}} twoCitySchedCost(costs) } <file_sep>package heap import ( "fmt" "go-dsa/collections" ) type node struct { val int data int } type heapObject struct { heapNodes []*node count int } func NewHeap() collections.Heap { return &heapObject{ heapNodes: []*node{}, count: 0, } } func (s *heapObject) Print() { for _, nodes := range s.heapNodes { fmt.Print(fmt.Sprintf("%d\t", nodes.data)) } fmt.Println("\n--------") } func (s *heapObject) Insert(val, data int, sortFunction func(a int, b int) bool) { newNode := &node{ val: val, data: data, } s.heapNodes = append(s.heapNodes, newNode) s.count++ nodeCount := s.count - 1 parent := (nodeCount - 1) / 2 for parent >= 0 { if sortFunction(s.heapNodes[nodeCount].data, s.heapNodes[parent].data) { return } s.heapNodes[nodeCount], s.heapNodes[parent] = s.heapNodes[parent], s.heapNodes[nodeCount] nodeCount = parent parent = (nodeCount - 1) / 2 } } func (s *heapObject) heapify(parentIndex int, sortFunction func(a int, b int) bool) { leftChild := 2*parentIndex + 1 rightChild := 2 * (parentIndex + 1) bestIndex := parentIndex if leftChild < s.count && sortFunction(s.heapNodes[parentIndex].data, s.heapNodes[leftChild].data) { bestIndex = leftChild } if rightChild < s.count && sortFunction(s.heapNodes[bestIndex].data, s.heapNodes[rightChild].data) { bestIndex = rightChild } if bestIndex == parentIndex { return } s.heapNodes[parentIndex], s.heapNodes[bestIndex] = s.heapNodes[bestIndex], s.heapNodes[parentIndex] s.heapify(bestIndex, sortFunction) } func (s *heapObject) Delete(sortFunction func(a int, b int) bool) (val, data int, exists bool) { if s.count == 0 { return -1, -1, false } firstNode := s.heapNodes[0] lastNode := s.heapNodes[s.count-1] s.heapNodes = s.heapNodes[0 : s.count-1] s.count-- if s.count == 0 { return firstNode.val, firstNode.data, true } s.heapNodes[0] = lastNode s.heapify(0, sortFunction) return firstNode.val, firstNode.data, true } func (s *heapObject) GetDataAtIndex(index int) int { return s.heapNodes[index].data } <file_sep>package main import "go-dsa/treeformation" /* You need to find the largest value in each row of a binary tree. Example: Input: 1 / \ 3 2 / \ \ 5 3 9 Output: [1, 3, 9] */ func largestValues(root *treeformation.Node) []int { if root == nil { return []int{} } cNodes := []*treeformation.Node{root} cNodesCount := 1 bestArr := make([]int, 0) for cNodesCount > 0 { nextLevelNodes := make([]*treeformation.Node, 0) var nextLevelNodesCount int bestInLevel := cNodes[0].Data for i := 0; i < cNodesCount; i++ { if cNodes[i].Left != nil { nextLevelNodes = append(nextLevelNodes, cNodes[i].Left) nextLevelNodesCount++ } if cNodes[i].Right != nil { nextLevelNodes = append(nextLevelNodes, cNodes[i].Right) nextLevelNodesCount++ } if cNodes[i].Data > bestInLevel { bestInLevel = cNodes[i].Data } } cNodes = nextLevelNodes cNodesCount = nextLevelNodesCount bestArr = append(bestArr, int(bestInLevel)) } return bestArr } <file_sep>module go-dsa go 1.12 <file_sep>package main import ( "math" "strings" ) /* Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest occurrence of character c in s. The distance between two indices i and j is abs(i - j), where abs is the absolute value function. Example 1: Input: s = "loveleetcode", c = "e" Output: [3,2,1,0,1,0,0,1,2,2,1,0] Explanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed). The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3. The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 3. For index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1. The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2. */ func shortestToChar(s string, c byte) []int { charSplit := strings.Split(s, "") leftClosest := make([]float64, len(charSplit)) rightClosest := make([]float64, len(charSplit)) finalArr := make([]int, len(charSplit)) var closestLeftIndex = math.Inf(1) var closestRightIndex = math.Inf(1) for i := range charSplit { if charSplit[i] == string(c) { closestLeftIndex = float64(i) } leftClosest[i] = closestLeftIndex if charSplit[len(charSplit)-i-1] == string(c) { closestRightIndex = float64(len(charSplit) - i - 1) } rightClosest[len(charSplit)-i-1] = closestRightIndex } for i := range charSplit { if math.Abs(leftClosest[i]-float64(i)) > math.Abs(rightClosest[i]-float64(i)) { finalArr[i] = int(math.Abs(rightClosest[i] - float64(i))) } else { finalArr[i] = int(math.Abs(leftClosest[i] - float64(i))) } } return finalArr } func main() { shortestToChar("loveleetcode", 'e') } <file_sep>package main import ( "go-dsa/treeformation" "math" ) /* Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: 2 / \ 1 3 Input: [2,1,3] Output: true Example 2: 5 / \ 1 4 / \ 3 6 Input: [5,1,4,null,null,3,6] Output: false Explanation: The root node's value is 5 but its right child's value is 4. */ func checkBST(root *treeformation.Node, min, max int64) bool { if root == nil { return true } if root.Data <= min || root.Data >= max { return false } return checkBST(root.Left, min, root.Data) && checkBST(root.Right, root.Data, max) } func isValidBST(root *treeformation.Node) bool { return checkBST(root, -math.MaxInt64, math.MaxInt64) } <file_sep>package main import "strings" /* Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad". Example 1: Input: A = "ab", B = "ba" Output: true Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B. Example 2: Input: A = "ab", B = "ab" Output: false Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B. */ func buddyStrings(A string, B string) bool { if len(A) != len(B) { return false } aMap := make(map[string]int, len(A)) aSplit := strings.Split(A, "") bSplit := strings.Split(B, "") aDiff := make([]string, 2, 2) bDiff := make([]string, 2, 2) mismatchCount := 0 for i := 0; i < len(aSplit); i++ { aMap[aSplit[i]]++ if mismatchCount > 2 { return false } if aSplit[i] != bSplit[i] { aDiff[mismatchCount] = aSplit[i] bDiff[mismatchCount] = bSplit[i] mismatchCount++ } } // fmt.Println(aMap, bMap, aDiff, bDiff) if mismatchCount == 1 { return false } isBuddy := true if len(aDiff) == 0 { isBuddy = false for _, value := range aMap { if value >= 2 { return true } } return isBuddy } if aDiff[0] != bDiff[1] || aDiff[1] != bDiff[0] { return false } return isBuddy } func main() { buddyStrings("aaab", "aaba") } <file_sep>package main import "go-dsa/treeformation" /* You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000. Example: root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11 */ func calculatePathCount(root *treeformation.Node, sum int64, pathSlice []int64) int { if root == nil { return 0 } var count int var tempSlice []int64 for index := range pathSlice { tempSlice = append(tempSlice, pathSlice[index]+root.Data) if tempSlice[index] == sum { count++ } } if root.Data == sum { count++ } tempSlice = append(tempSlice, root.Data) return count + calculatePathCount(root.Left, sum, tempSlice) + calculatePathCount(root.Right, sum, tempSlice) } func pathSum(root *treeformation.Node, sum int64) int { return calculatePathCount(root, sum, []int64{}) } <file_sep>package main import ( "go-dsa/treeformation" ) func insertNodeAtFirstVacantPos(headNode *treeformation.Node, nodeToInsert int) *treeformation.Node { stack := []*treeformation.Node{headNode} for len(stack) != 0 { element := stack[0] if element.Left == nil { newNode := treeformation.CreateNode(int64(nodeToInsert)) element.Left = newNode break } if element.Right == nil { newNode := treeformation.CreateNode(int64(nodeToInsert)) element.Right = newNode break } stack = append(stack, []*treeformation.Node{element.Left, element.Right}...) stack = stack[1:] } return headNode } func main() { treeData := []int64{10, 11, 9, 7, 12, 15, 0} // If you need to create a nil, then send 0 nodeToBeInserted := 8 headNode := treeformation.CreateTree(treeData) headNode = insertNodeAtFirstVacantPos(headNode, nodeToBeInserted) types.InOrderTraversal(headNode) } <file_sep>package types import ( "fmt" "go-dsa/treeformation" ) func InOrderTraversal(headNode *treeformation.Node) { if headNode == nil { return } InOrderTraversal(headNode.Left) fmt.Println(headNode.Data) InOrderTraversal(headNode.Right) } func PreOrderTraversal(headNode *treeformation.Node) { if headNode == nil { return } fmt.Println(headNode.Data) PreOrderTraversal(headNode.Left) PreOrderTraversal(headNode.Right) } func PostOrderTraversal(headNode *treeformation.Node) { if headNode == nil { return } PostOrderTraversal(headNode.Left) PostOrderTraversal(headNode.Right) fmt.Println(headNode.Data) } <file_sep>package main import ( "go-dsa/treeTraversals/traversals/types" "go-dsa/treeformation" ) func convertBSTToSumTree(root *treeformation.Node, data int64) int64 { if root == nil { return data } right := convertBSTToSumTree(root.Right, data) root.Data = root.Data + right left := convertBSTToSumTree(root.Left, root.Data) return left } func main() { treeData := []int64{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0, 0, 17, 18} // If you need to create a nil, then send 0 headNode := treeformation.CreateTree(treeData) convertBSTToSumTree(headNode, 0) types.PreOrderTraversal(headNode) } <file_sep>package collections type Trie interface { InsertNode(s string, dataToInsertAtEnd interface{}) SearchNode(s string) bool Print() GetDataStartingWith(startsWith string) []Metadata } type Metadata struct { SuffixString string DataStored interface{} } <file_sep>package trie import ( "fmt" "go-dsa/collections" ) type trie struct { children map[rune]*trie edgeData []interface{} } func (t *trie) InsertNode(s string, dataToInsertAtEnd interface{}) { root := t for index, char := range s { if _, ok := root.children[char]; !ok { newNode := &trie{ children: map[rune]*trie{}, edgeData: nil, } root.children[char] = newNode if index == len(s)-1 { root.children[char].edgeData = append(root.children[char].edgeData, dataToInsertAtEnd) return } root = root.children[char] } else { if index == len(s)-1 { root.children[char].edgeData = append(root.children[char].edgeData, dataToInsertAtEnd) return } root = root.children[char] } } } func (t *trie) SearchNode(s string) bool { current := t for index, char := range s { if _, ok := current.children[char]; !ok { return false } if index == len(s)-1 { if current.children[char].edgeData == nil { return false } return true } current = current.children[char] } return false } func (t *trie) Print() { fmt.Println(getSubStrings(t, "")) } func getSubStrings(startNode *trie, str string) (result []collections.Metadata) { for char := range startNode.children { result = append(result, getSubStrings(startNode.children[char], str+string(char))...) if startNode.children[char].edgeData != nil { result = append(result, collections.Metadata{ SuffixString: str + string(char), DataStored: startNode.children[char].edgeData, }) } } return result } func (t *trie) GetDataStartingWith(startsWith string) (result []collections.Metadata) { current := t for index, char := range startsWith { if _, ok := current.children[char]; !ok { return result } if current.children[char].edgeData != nil && index != len(startsWith)-1 { result = append(result, collections.Metadata{ SuffixString: startsWith[index+1:], DataStored: current.children[char].edgeData, }) } if index == len(startsWith)-1 { result = append(result, getSubStrings(current.children[char], "")...) if current.children[char].edgeData != nil { result = append(result, collections.Metadata{ SuffixString: "", DataStored: current.children[char].edgeData, }) } return result } current = current.children[char] } return result } func New() collections.Trie { return &trie{ children: map[rune]*trie{}, } } <file_sep>package collections type Heap interface { Insert(val, data int, sortFunction func(a int, b int) bool) Delete(sortFunction func(a int, b int) bool) (val, data int, exists bool) GetDataAtIndex(index int) int } <file_sep>package main import ( "fmt" "go-dsa/treeformation" ) func leftView(headNode *treeformation.Node) { count := 1 nodeMap := map[int][]*treeformation.Node{} nodeMap[count] = []*treeformation.Node{headNode} for len(nodeMap[count]) != 0 { for _, node := range nodeMap[count] { if node.Left != nil { nodeMap[count+1] = append(nodeMap[count+1], node.Left) } if node.Right != nil { nodeMap[count+1] = append(nodeMap[count+1], node.Right) } } count += 1 } for _, element := range nodeMap { fmt.Println(element[0].Data) } } func main() { treeData := []int64{1, 2, 3, 4, 5, 6, 7, 0, 8} // If you need to create a nil, then send 0 headNode := treeformation.CreateTree(treeData) leftView(headNode) } <file_sep>package main import "strings" /* Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together. We repeatedly make k duplicate removals on s until we no longer can. Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique. */ func removeDuplicates(s string, k int) string { sSplit := strings.Split(s, "") charMap := map[string]bool{} for _, char := range sSplit { charMap[char] = true } contains := true for contains { contains = false for char := range charMap { repChar := strings.Repeat(char, k) if strings.Contains(s, repChar) { contains = true } s = strings.Replace(s, repChar, "", -1) } } return s } <file_sep>package main import ( "fmt" "go-dsa/collections/searches" "go-dsa/helpers" ) func getKClosest(elements []int, k, x int) []int { obj := searches.NewBinarySearch() index := obj.BinarySearchClosest(elements, x) count := 0 leftIndex := index rightIndex := index if rightIndex == len(elements) - 1 { count = 1 rightIndex += 1 } fmt.Println(index) for count < k { if rightIndex > len(elements)-1 || (leftIndex > 0 && helpers.Abs(elements[leftIndex]-x) <= helpers.Abs(elements[rightIndex]-x)) { leftIndex = leftIndex - 1 } else if leftIndex <= 0 || (rightIndex < len(elements)-1 && helpers.Abs(elements[leftIndex]-x) >= helpers.Abs(elements[rightIndex]-x)) { rightIndex = rightIndex + 1 } count = count + 1 } if rightIndex > len(elements) - 1 { return elements[leftIndex:] } fmt.Println(leftIndex, rightIndex) return elements[leftIndex:rightIndex] } func main() { fmt.Println(getKClosest([]int{1, 2, 3, 7, 8, 9}, 1, 7)) } <file_sep>package main import "fmt" /* Given an integer array nums, return the length of the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7]. Input: nums = [10,9,2,5,3,7,101,18] Output: 4 Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. */ func lengthOfLIS(nums []int) int { longestSequence := make([]int, len(nums)) var max int for i := len(nums) - 1; i >= 0; i-- { var maxCount int for j := i; j < len(nums); j++ { if longestSequence[j] > maxCount && nums[i] < nums[j] { maxCount = longestSequence[j] } } longestSequence[i] = maxCount + 1 if max < maxCount+1 { max = maxCount + 1 } } return max } func main() { fmt.Println(lengthOfLIS([]int{10, 9, 2, 5, 3, 7, 101, 18})) } <file_sep>package main import ( "bufio" "fmt" heap2 "go-dsa/collections/heap" "os" "strconv" "strings" ) func main() { leftHeapObject := heap2.NewHeap() rightHeapObject := heap2.NewHeap() var leftNodes, rightNodes int reader := bufio.NewReader(os.Stdin) for { input, err := reader.ReadString('\n') if err != nil { fmt.Println(err) return } intInput, err := strconv.ParseInt(strings.TrimSuffix(input, "\n"), 10, 64) if err != nil { fmt.Println(err) return } if leftNodes == 0 || leftHeapObject.GetDataAtIndex(0) >= int(intInput) { leftHeapObject.Insert(int(intInput), int(intInput), func(a int, b int) bool { return a <= b }) leftNodes++ } else { rightHeapObject.Insert(int(intInput), int(intInput), func(a int, b int) bool { return a >= b }) rightNodes++ } if leftNodes-rightNodes > 1 { val, data, _ := leftHeapObject.Delete(func(a int, b int) bool { return a < b }) leftNodes-- rightHeapObject.Insert(val, data, func(a int, b int) bool { return a >= b }) rightNodes++ } else if rightNodes-leftNodes > 1 { val, data, _ := rightHeapObject.Delete(func(a int, b int) bool { return a > b }) rightNodes-- leftHeapObject.Insert(val, data, func(a int, b int) bool { return a <= b }) leftNodes++ } if leftNodes == rightNodes { fmt.Println("Median", (leftHeapObject.GetDataAtIndex(0)+rightHeapObject.GetDataAtIndex(0))/2) } else if leftNodes > rightNodes { fmt.Println("Median", leftHeapObject.GetDataAtIndex(0)) } else { fmt.Println("Median", rightHeapObject.GetDataAtIndex(0)) } } } <file_sep>package main import "go-dsa/treeformation" /* Given the root of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1 has been removed. A subtree of a node node is node plus every node that is a descendant of node. Example 1: Input: root = [1,null,0,0,1] Output: [1,null,0,null,1] Explanation: Only the red nodes satisfy the property "every subtree not containing a 1". The diagram on the right represents the answer. Example 2: Input: root = [1,0,1,0,0,0,1] Output: [1,null,1,null,1] */ func prune(root *treeformation.Node) bool { if root == nil { return false } left := prune(root.Left) if !left { root.Left = nil } right := prune(root.Right) if !right { root.Right = nil } return left || right || root.Data == 1 } func pruneTree(root *treeformation.Node) *treeformation.Node { if root == nil { return nil } prune(root) if root.Left == nil && root.Right == nil && root.Data == 0 { return nil } return root } <file_sep>package main import ( "go-dsa/treeTraversals/traversals/types" "go-dsa/treeformation" ) func main() { treeData := []int64{10, 11, 9, 7, 0, 15, 8} // If you need to create a nil, then send 0 headNode := treeformation.CreateTree(treeData) types.InOrderTraversal(headNode) types.PreOrderTraversal(headNode) types.PostOrderTraversal(headNode) } <file_sep>package path_sum_11 import "go-dsa/treeformation" /* Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where each path's sum equals targetSum. A leaf is a node with no children. Example 1: Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22 Output: [[5,4,11,2],[5,8,4,5]] */ func findPathSum(root *treeformation.Node, actualSum, targetSum int64, path []int64) [][]int64 { if root.Left == nil && root.Right == nil { if actualSum+root.Data == targetSum { finalPath := append(path, root.Data) return [][]int64{finalPath} } } var leftPaths, rightPaths [][]int64 if root.Left != nil { lenCurPath := len(path) tmp := make([]int64, lenCurPath, lenCurPath+1) _ = copy(tmp, path) leftPaths = findPathSum(root.Left, actualSum+root.Data, targetSum, append(tmp, root.Data)) } if root.Right != nil { lenCurPath := len(path) tmp := make([]int64, lenCurPath, lenCurPath+1) _ = copy(tmp, path) rightPaths = findPathSum(root.Right, actualSum+root.Data, targetSum, append(tmp, root.Data)) } return append(leftPaths, rightPaths...) } func pathSum(root *treeformation.Node, targetSum int64) [][]int64 { if root == nil { return [][]int64{} } return findPathSum(root, 0, targetSum, []int64{}) } <file_sep>package main /* Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence. You must write an algorithm that runs in O(n) time. Example 1: Input: nums = [100,4,200,1,3,2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. Example 2: Input: nums = [0,3,7,2,5,8,4,6,0,1] Output: 9 */ func longestConsecutive(nums []int) int { numsMap := make(map[int]bool) for _, num := range nums { numsMap[num] = false } var maxCount int for _, num := range nums { isVisited, _ := numsMap[num] if isVisited { continue } numsMap[num] = true surroundings := []int{num} count := 1 for len(surroundings) != 0 { poppedElement := surroundings[0] if isVisited, ok := numsMap[poppedElement+1]; ok && !isVisited { numsMap[poppedElement+1] = true surroundings = append(surroundings, poppedElement+1) count = count + 1 } if isVisited, ok := numsMap[poppedElement-1]; ok && !isVisited { numsMap[poppedElement-1] = true surroundings = append(surroundings, poppedElement-1) count = count + 1 } if len(surroundings) > 0 { surroundings = surroundings[1:] } } if count > maxCount { maxCount = count } } return maxCount } func main() { longestConsecutive([]int{0, 3, 7, 2, 5, 8, 4, 6, 0, 1}) } <file_sep># go-dsa This package contains implementations of real world problems solved using Golang. <file_sep>package main import "go-dsa/treeformation" /* Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 */ func invertTree(root *treeformation.Node) *treeformation.Node { if root == nil { return root } temp := root.Left root.Left = root.Right root.Right = temp invertTree(root.Left) invertTree(root.Right) return root } <file_sep>package longest_valid_parantheses import "strings" func getTopElement(stack []int, sSplit []string) (string, int) { return sSplit[stack[len(stack)-1]], stack[len(stack)-1] } func pop(stack []int) []int { if len(stack) > 0 { stack = stack[:len(stack)-1] } return stack } /* Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. Example 1: Input: s = "(()" Output: 2 Explanation: The longest valid parentheses substring is "()". Example 2: Input: s = ")()())" Output: 4 Explanation: The longest valid parentheses substring is "()()". Example 3: Input: s = "" Output: 0 */ func longestValidParentheses(s string) int { bestAtIndex := make([]int, len(s)) var stack []int sSplit := strings.Split(s, "") firstValidIndex := -1 for index, char := range sSplit { if char == "(" { if firstValidIndex == -1 { firstValidIndex = index } stack = append(stack, index) } else if char == ")" { if len(stack) == 0 { firstValidIndex = -1 continue } topElement, topElementIndex := getTopElement(stack, sSplit) if topElement == "(" { bestAtIndex[topElementIndex] = bestAtIndex[topElementIndex] + 2 stack = pop(stack) if len(stack) > 0 { _, topElementIndexPrev := getTopElement(stack, sSplit) bestAtIndex[topElementIndexPrev] = bestAtIndex[topElementIndexPrev] + bestAtIndex[topElementIndex] } else if topElementIndex != firstValidIndex && len(stack) == 0 { bestAtIndex[firstValidIndex] = bestAtIndex[firstValidIndex] + bestAtIndex[topElementIndex] } } } } max := 0 for _, element := range bestAtIndex { if max < element { max = element } } return max } <file_sep>package capture_rain_drops /* Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. Example 1: Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] Output: 6 Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Example 2: Input: height = [4,2,0,3,2,5] Output: 9 */ func getMax(height []int, start, end int) int { if start >= len(height) { return len(height) - 1 } max := start for i := start; i <= end; i++ { if height[i] > height[max] { max = i } } return max } func trap(height []int) int { var stack []int nextBestIndex := make([]int, len(height)) for i := 0; i < len(height); i++ { if len(stack) == 0 { stack = append(stack, i) continue } if height[stack[len(stack)-1]] <= height[i] { for len(stack) > 0 && height[stack[len(stack)-1]] <= height[i] { nextBestIndex[stack[len(stack)-1]] = i stack = stack[0 : len(stack)-1] } } stack = append(stack, i) } lastIndex := len(height) - 1 for len(stack) > 0 { nextBestIndex[stack[len(stack)-1]] = getMax(height, stack[len(stack)-1]+1, lastIndex) lastIndex = stack[len(stack)-1] stack = stack[0 : len(stack)-1] } sum := 0 i := 0 for i < len(height) { nextBest := nextBestIndex[i] if nextBest == i { return sum } modifiedHeight := height[i] if height[i] > height[nextBest] { modifiedHeight = height[nextBest] } for j := i + 1; j < nextBest; j++ { sum = sum + modifiedHeight - height[j] } i = nextBest } return sum } <file_sep>package main import "sort" /* Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal. In one move, you can increment or decrement an element of the array by 1 Input: nums = [1,2,3] Output: 2 Explanation: Only two moves are needed (remember each move increments or decrements one element): [1,2,3] => [2,2,3] => [2,2,2] Input: nums = [1,10,2,9] Output: 16 */ func minMoves2(nums []int) int { sort.Ints(nums) var moves int if len(nums)%2 != 0 { midIndex := (len(nums) - 1) / 2 for i := 0; i < midIndex; i++ { moves += nums[midIndex] - nums[i] } for i := midIndex + 1; i < len(nums); i++ { moves += nums[i] - nums[midIndex] } } else { midElement := (nums[len(nums)/2] + nums[(len(nums)-2)/2]) / 2 var i int for nums[i] <= midElement { moves += midElement - nums[i] i++ } for i < len(nums) { moves += nums[i] - midElement i++ } } return moves } <file_sep>package main func linearSearch(nums []int, startIndex, endIndex, mid int) (min int) { for i := startIndex; i < endIndex; i++ { if nums[i] < mid { return nums[i] } } return mid } func findMin(nums []int) int { startIndex := 0 endIndex := len(nums) - 1 mid := (startIndex + endIndex) / 2 for { if mid == startIndex || mid == endIndex { if nums[startIndex] > nums[endIndex] { return nums[endIndex] } return nums[startIndex] } if nums[mid] < nums[mid-1] { return nums[mid] } if nums[mid] > nums[startIndex] && nums[mid] < nums[endIndex-1] { return nums[startIndex] } if nums[mid] > nums[endIndex] && nums[mid] < nums[startIndex] { startIndex = mid + 1 } else if nums[mid] < nums[endIndex] && nums[mid] > nums[startIndex] { endIndex = mid } else { /* In case there is a tie deciding which direction to move, we don't have any other choice than iterating through the entire slice. (Worst case will be O(n) */ rightMin := linearSearch(nums, mid+1, endIndex+1, nums[mid]) leftMin := linearSearch(nums, startIndex, mid, nums[mid]) if rightMin > leftMin { return leftMin } return rightMin } mid = (startIndex + endIndex) / 2 } return 0 }
f010712987fa5eaf2f784fb4c6f82f506549d4f7
[ "Markdown", "Go Module", "Go" ]
61
Go
mouryavenkat/go-dsa
596d2e1b73797f78b200efd209d064407f0c55fb
6c429ce5feffdb01f7cbe6d5793cfaf7aa0a5cd5
refs/heads/main
<repo_name>dorjear/webflux-mvc-comparison<file_sep>/README.md # Webflux vs Spring MVC Compaction between spring 5 servlet stack vs WebFlux reactive stack For testing, we have a rest endpoint POST /persons that accepts a json Person object and returns an object with UUID. Gatlin is used to run the tests and generate report. Start the app with In person-registration-slow-service: mvn spring-boot:run In sample-reactive-spring-boot-2 or sample-spring-boot-2 : mvn spring-boot:run Run tests in perf-test-with-gatling with ./gradlew loadTest -D SIM_USERS=5000 <file_sep>/sample-reactive-spring-boot-2/src/main/kotlin/com/dorjear/study/samplereactivespringboot2/services/PersonRegistrationService.kt package com.dorjear.study.samplereactivespringboot2.services import com.dorjear.study.samplereactivespringboot2.models.Person import org.springframework.beans.factory.annotation.Value import org.springframework.http.HttpHeaders.ACCEPT import org.springframework.http.HttpHeaders.CONTENT_TYPE import org.springframework.http.MediaType.* import org.springframework.stereotype.Service import org.springframework.web.reactive.function.BodyInserters.fromValue import org.springframework.web.reactive.function.client.WebClient import reactor.core.publisher.Mono @Service class PersonRegistrationService(@Value("\${registration.service}") private val registrationServiceBaseUrl: String) { private val webClient = WebClient.builder().baseUrl(registrationServiceBaseUrl).build() fun addPerson(person: Person): Mono<Person> { return webClient.post() .uri("/register") .header(CONTENT_TYPE, APPLICATION_JSON_VALUE) .header(ACCEPT, APPLICATION_JSON_VALUE) .body(fromValue(person)) .exchangeToMono { it.bodyToMono(Person::class.java) } } } <file_sep>/person-registration-slow-service/src/test/kotlin/com/dorjear/study/reactive/slowservice/PersonRegistrationSlowServiceApplicationTests.kt package com.dorjear.study.reactive.slowservice import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class PersonRegistrationSlowServiceApplicationTests { @Test fun contextLoads() { } }
02f9b647ca75d2b54a7d3b51b332524d2a9a8b40
[ "Markdown", "Kotlin" ]
3
Markdown
dorjear/webflux-mvc-comparison
a460475ba09c0f62f43796120cba7a0e34db1a7a
d3af80aa37b8a838121f80570fa60f9ac374d931
refs/heads/master
<file_sep>// Global Vars. var buttonEl = document.getElementById("btn"); var newPW = document.getElementById("generatedPassword"); //when the button is clicked it will run the "generatePW" function buttonEl.addEventListener("click", generatePW); function generatePW() { var uppercase = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; var lowercase = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]; var numbers = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; var symbols = ["!", "#", "$", "&", "%", "'", "(", ")", "*", "+", "-", "/", ":", ";", "<", "=", ">", "?", "@", "^", "_", "~", "`", "{", "|", "}", "."]; //Open array to push user selection of what characters they pick var userPickArray = []; //prompts user to decide on password characters between 8 and 128 var pwLength = Number(prompt("Please input (betwwen 8 and 128) how many characters to include in your generated password.")); if (pwLength < 8 || pwLength > 128 || pwLength ==! Number) { alert("Please try again. Enter number between 8 abd 128"); return; } else { alert("You chose a password length of " + pwLength + " characters. "); } var confirmLowercase = confirm("Would you like your password to contain Lowercase letters? ( Click OK for Yes and Cancel for No") ; var confirmUppercase = confirm("Would you like your password to contain Uppercase letters? ( Click OK for Yes and Cancel for No") ; var confirmSymbols = confirm("Would you like your password to contain Symbols? ( Click OK for Yes and Cancel for No") ; var confirmNumbers = confirm("Would you like your password to contain Numbers? ( Click OK for Yes and Cancel for No") ; if (confirmLowercase === true) { userPickArray.push(...lowercase); } if (confirmNumbers === true) { userPickArray.push(...numbers); } if (confirmUppercase === true) { userPickArray.push(...uppercase); } if (confirmSymbols === true) { userPickArray.push(...symbols); } if (confirmLowercase === false && confirmSymbols === false && confirmNumbers === false && confirmUppercase === false) { alert("You must chose at least one of the following characters: lowercase, uppercase, numbers, or symbols"); return; } var userPW = ""; for (var i = 0; i < pwLength; i++) { var randomCharacter = userPickArray[Math.floor(Math.random() * userPickArray.length)]; userPW += randomCharacter; //Makes the PW show up. Concatentation of random characters that chosen in the password variable console.log(userPW) } newPW.innerHTML = userPW; } <file_sep># Password-Generator- Focusing on JavaScript I have created an application that will generate a random password. The password is generated by critera that is selected from the user. The application is web based and will run in the browser, the pages are dynamic, and the interface is responsive. The HTML and CSS are powered by JavaScript. The password is between 8 and 128 characters including lowercase, uppercase, numeric, and special characters. Prompts and alerts were a huge factor in this project.
6047e07fab976d2c4fbe21dce083eb400081d283
[ "JavaScript", "Markdown" ]
2
JavaScript
Devante-Andrew-Johns21/Password-Generator-
0119218a194b65f8f228a3d217f46753ddadb6ac
e2e10ff240b800744c8a5a2aa6096cef8560225d
refs/heads/main
<file_sep>import sys def main(argc: int, argv: []) -> int: cells: [] = [0] cell_index = 0 loop_cell_index = 0 loop_ref = [] loop_count = 0 input_index = 0 input = "" ret = 0 if (argc == 1): print("bfi: usage: python3 main.py [FILE] [INPUT: OPTIONAL]") return 0 elif (argc >= 2): program = open(argv[1], "r").read() if (argc >= 3): input = argv[2] i = 0 while (i < len(program)): char = program[i] if (char == ">"): cell_index += 1 if (not cells[cell_index:cell_index+1]): cells.insert(cell_index, 0) elif (char == "<"): cell_index -= 1 if (cell_index < 0): cell_index = len(cells)-1 elif (char == "+"): cells[cell_index] += 1 if (cells[cell_index] >= 256): cells[cell_index] = 0 elif (char == "-"): cells[cell_index] -= 1 if (cells[cell_index] < 0): cells[cell_index] = 255 elif (char == "."): sys.stdout.write(chr(cells[cell_index])) elif (char == ","): if (not input): print("\nERROR: trying to read from input, but no input was given") ret = 1 break elif (not input[input_index:input_index+1]): print("\nERROR: insufficient input given") ret = 1 break cells[cell_index] = ord(input[input_index]) input_index += 1 elif (char == "["): if (not loop_ref[loop_count: loop_count+1]): loop_ref.insert(loop_count, 0) loop_ref[loop_count] = i loop_count += 1 elif (char == "]"): loop_count -= 1 if (cells[cell_index] != 0): i = loop_ref[loop_count] loop_count += 1 i += 1 print(f"\n[{ret}]") return ret argv: [] = sys.argv main(len(argv), argv) <file_sep>CC=clang main: *c $(CC) main.c -o bfi --std=c99<file_sep># bfi simple brainfuck interpreter (in python with a lot of semicolons just to piss people off) it might work depends on what you try to do with it at least the hello world test works:) USAGE: python3 main.py [FILENAME] [INPUT: OPTIONAL] for the C version just compile it and run bfi [FILENAME] [INPUT: OPTIONAL] e.g. bfi test.bf TEST <file_sep>#include <stdlib.h> #include <stdio.h> #include <stdbool.h> // #include <malloc.h> #include <string.h> #define byte unsigned char #define ulong unsigned int typedef enum { NO_ERROR, NO_INPUT, INSUFFICIENT_INPUT } ERRORS; char* program; ulong program_len; byte* cells; ulong cell_len; ulong loop_index; ulong loop_count; ulong* loop_ref; ulong loop_ref_len; char* input; ulong input_len; ulong input_index; int ret; char* read_file(const char* filename, ulong* len) { FILE* file = fopen(filename, "r"); fseek(file, 0, SEEK_END); *len = ftell(file)+1; fseek(file, 0, SEEK_SET); char* buff = (char*)malloc(*len); char c; for (int i = 0; (c = fgetc(file)) != EOF; i++) { buff[i] = c; } fclose(file); return buff; } int main(int argc, char** argv) { program_len = 0; cells = malloc(sizeof(byte)); cell_len = 1; ulong index = 0; loop_index = 0; loop_count = 0; loop_ref = malloc(sizeof(ulong)); loop_ref_len = 1; input = ""; input_len = 0; input_index = 0; ret = NO_ERROR; if (argc == 1) { printf("bfi: usage: bfi [FILENAME] [INPUT: OPTIONAL]"); return 1; } else if (argc >= 2) { printf("filename: %s\n", argv[1]); program = read_file(argv[1], &program_len); printf("program: length %lu\n", program_len); printf("program: %s\n", program); if (argc >= 3) { input_len = strlen(argv[2]); input = malloc(sizeof(char)*input_len); input = argv[2]; } } bool run = true; int i = 0; char c = 0; while (run) { if (i >= program_len) { run = false; break; } c = program[i]; switch (c) { case '>': index++; if (index >= cell_len) { cell_len++; cells = realloc(cells, sizeof(byte)*cell_len); } break; case '<': index--; if (index < 0) { index = cell_len; } break; case '+': cells[index]++; if (cells[index] >= 255) cells[index] = 0; break; case '-': cells[index]--; if (cells[index] < 0) cells[index] = 255; break; case '.': printf("%c", cells[index]); break; case ',': if (argc <= 2) { printf("\nERROR: trying to read from input, but no input was given"); ret = NO_INPUT; run = false; } else if (input_index >= input_len) { printf("\nERROR: insufficient input given"); ret = INSUFFICIENT_INPUT; run = false; } cells[index] = input[input_index++]; break; case '[': if (loop_count >= loop_ref_len) { loop_ref_len++; loop_ref = realloc(loop_ref, sizeof(ulong)*loop_ref_len); loop_ref[loop_ref_len] = 0; } loop_ref[loop_count] = i; loop_count++; break; case ']': loop_count--; if (cells[index] != 0) { i = loop_ref[loop_count]; loop_count++; } break; default: break; } i++; } free(cells); free(program); free(loop_ref); // free(input); // why the fuck does this throw a segfault printf("\n[%d]\n", ret); return ret; } <file_sep><?php function interpret($text, $input=null) { $text = str_split($text); if (!empty($input)) { $input = str_split($input); } $cells = [0]; $ptr = 0; $input_ptr = 0; $loops = []; $loop_ptr = 0; $i = 0; while ($i < count($text)-1) { $c = $text[$i]; switch ($c) { case "+": $cells[$ptr]++; if ($cells[$ptr] > 255) { $cells[$ptr] = 0; } break; case "-": $cells[$ptr]--; if ($cells[$ptr] < 0) { $cells[$ptr] = 255; } break; case ">": $ptr++; if (!isset($cells[$ptr])) { $cells[$ptr] = 0; } break; case "<": $ptr--; if ($ptr < 0) { echo "error"; } break; case ".": echo chr($cells[$ptr]); break; case ",": echo $input[$input_ptr++]; break; case "[": if (!isset($loops[$loop_ptr])) { $loops[$loop_ptr] = 0; } $loops[$loop_ptr] = $i; $loop_ptr++; break; case "]": $loop_ptr--; if ($cells[$ptr] !== 0) { $i = $loops[$loop_ptr]; $loop_ptr++; } break; } $i++; } } ?> <!DOCTYPE HTML> <html lang="en"> </head> <title> placeholder </title> <link rel="stylesheet" href="main.css"> <head> <body> <form method="POST"> <textarea name="text"></textarea> <textarea name="input"></textarea> <button name="submit"> run </button> </form> <?php if (isset($_POST["submit"])) { interpret($_POST["text"], $_POST["input"]); } ?> </body> </html>
af81b01d5c513db4bfc17e066c255d03ed51e335
[ "Markdown", "Makefile", "Python", "PHP", "C" ]
5
Python
Bugyna/bfi
704d9a5580d7e513961928a6e2cd75275e9a2beb
67e1d3c932712cf168b0bd6f710e2e5ca6b04190
refs/heads/master
<file_sep>""" A simple demonstration of a serial port monitor that plots live data using PyQwt. The monitor expects to receive single-byte data packets on the serial port. Each received byte is understood as a biofeedback reading and is shown on a live chart. <NAME> (<EMAIL>) License: this code is in the public domain Last modified: 07.08.2009 """ import random, sys from PyQt4.QtCore import * from PyQt4.QtGui import * import PyQt4.Qwt5 as Qwt import Queue from scipy import signal, fft from numpy import arange from com_monitor import ComMonitorThread from eblib.serialutils import full_port_name, enumerate_serial_ports from eblib.utils import get_all_from_queue, get_item_from_queue from livedatafeed import LiveDataFeed class PlottingDataMonitor(QMainWindow): def __init__(self, parent=None): super(PlottingDataMonitor, self).__init__(parent) self.update_freq = 50 self.xaxis_min1 = 0 self.xaxis_max1 = 60 self.xaxis_step1 = 5 self.xaxis_min2 = 0 self.xaxis_max2 = 12 self.xaxis_step2 = 1 #Pulse self.yaxis_min_pulse = 0 self.yaxis_max_pulse = 2.5 self.yaxis_step_pulse = 0.5 #HR self.yaxis_min_hr = 0 self.yaxis_max_hr = 200 self.yaxis_step_hr = 20 #FFT self.yaxis_min_fft = 0 self.yaxis_max_fft = 1 self.yaxis_step_fft = 0.1 self.xaxis_max_it = 1 self.monitor_active = False self.com_monitor = None self.com_data_q = None self.com_error_q = None self.livefeed = LiveDataFeed() self.biofeedback_samples = [] self.timer = QTimer() self.create_menu() self.create_main_frame() self.create_status_bar() def make_data_box(self, name): label = QLabel(name) qle = QLineEdit() qle.setEnabled(False) qle.setFrame(False) return (label, qle) def create_plot_pulse1(self): plot = Qwt.QwtPlot(self) plot.setCanvasBackground(Qt.black) plot.setAxisTitle(Qwt.QwtPlot.xBottom, 'Time') plot.setAxisScale(Qwt.QwtPlot.xBottom, self.xaxis_min1, self.xaxis_max1, self.xaxis_step1) plot.setAxisTitle(Qwt.QwtPlot.yLeft, 'Voltage') plot.setAxisScale(Qwt.QwtPlot.yLeft, self.yaxis_min_pulse, self.yaxis_max_pulse, self.yaxis_step_pulse) plot.replot() curve = Qwt.QwtPlotCurve('') curve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) pen = QPen(QColor('limegreen')) pen.setWidth(2) curve.setPen(pen) curve.attach(plot) return plot, curve def create_plot_pulse2(self): plot = Qwt.QwtPlot(self) plot.setCanvasBackground(Qt.black) plot.setAxisTitle(Qwt.QwtPlot.xBottom, 'Time') plot.setAxisScale(Qwt.QwtPlot.xBottom, self.xaxis_min2, self.xaxis_max2, self.xaxis_step2) plot.setAxisTitle(Qwt.QwtPlot.yLeft, 'Voltage') plot.setAxisScale(Qwt.QwtPlot.yLeft, self.yaxis_min_pulse, self.yaxis_max_pulse, self.yaxis_step_pulse) plot.replot() curve = Qwt.QwtPlotCurve('') curve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) pen = QPen(QColor('limegreen')) pen.setWidth(2) curve.setPen(pen) curve.attach(plot) return plot, curve def create_plot_hr1(self): plot = Qwt.QwtPlot(self) plot.setCanvasBackground(Qt.black) plot.setAxisTitle(Qwt.QwtPlot.xBottom, 'Time') plot.setAxisScale(Qwt.QwtPlot.xBottom, self.xaxis_min1, self.xaxis_max1, self.xaxis_step1) plot.setAxisTitle(Qwt.QwtPlot.yLeft, 'BPM') plot.setAxisScale(Qwt.QwtPlot.yLeft, self.yaxis_min_hr, self.yaxis_max_hr, self.yaxis_step_hr) plot.replot() curve = Qwt.QwtPlotCurve('') curve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) pen = QPen(QColor('limegreen')) pen.setWidth(2) curve.setPen(pen) curve.attach(plot) return plot, curve def create_plot_hr2(self): plot = Qwt.QwtPlot(self) plot.setCanvasBackground(Qt.black) plot.setAxisTitle(Qwt.QwtPlot.xBottom, 'Time') plot.setAxisScale(Qwt.QwtPlot.xBottom, self.xaxis_min2, self.xaxis_max2, self.xaxis_step2) plot.setAxisTitle(Qwt.QwtPlot.yLeft, 'BPM') plot.setAxisScale(Qwt.QwtPlot.yLeft, self.yaxis_min_hr, self.yaxis_max_hr, self.yaxis_step_hr) plot.replot() curve = Qwt.QwtPlotCurve('') curve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) pen = QPen(QColor('limegreen')) pen.setWidth(2) curve.setPen(pen) curve.attach(plot) return plot, curve def create_plot_fft1(self): plot = Qwt.QwtPlot(self) plot.setCanvasBackground(Qt.black) plot.setAxisTitle(Qwt.QwtPlot.xBottom, 'Time') plot.setAxisScale(Qwt.QwtPlot.xBottom, self.xaxis_min1, self.xaxis_max1, self.xaxis_step1) plot.setAxisTitle(Qwt.QwtPlot.yLeft, 'Frequency') plot.setAxisScale(Qwt.QwtPlot.yLeft, self.yaxis_min_fft, self.yaxis_max_fft, self.yaxis_step_fft) plot.replot() curve = Qwt.QwtPlotCurve('') curve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) pen = QPen(QColor('limegreen')) pen.setWidth(2) curve.setPen(pen) curve.attach(plot) grid = Qwt.QwtPlotGrid() grid.attach(plot) return plot, curve def create_plot_fft2(self): plot = Qwt.QwtPlot(self) plot.setCanvasBackground(Qt.black) plot.setAxisTitle(Qwt.QwtPlot.xBottom, 'Time') plot.setAxisScale(Qwt.QwtPlot.xBottom, self.xaxis_min2, self.xaxis_max2, self.xaxis_step2) plot.setAxisTitle(Qwt.QwtPlot.yLeft, 'Frequency') plot.setAxisScale(Qwt.QwtPlot.yLeft, self.yaxis_min_fft, self.yaxis_max_fft, self.yaxis_step_fft) plot.replot() curve = Qwt.QwtPlotCurve('') curve.setRenderHint(Qwt.QwtPlotItem.RenderAntialiased) pen = QPen(QColor('limegreen')) pen.setWidth(2) curve.setPen(pen) curve.attach(plot) return plot, curve def create_status_bar(self): self.status_text = QLabel('Monitor idle') self.statusBar().addWidget(self.status_text, 1) def create_main_frame(self): # Port name # portname_l, self.portname = self.make_data_box('COM Port:') portname_layout = QHBoxLayout() portname_layout.addWidget(portname_l) portname_layout.addWidget(self.portname, 0) portname_layout.addStretch(1) portname_groupbox = QGroupBox('COM Port') portname_groupbox.setLayout(portname_layout) # Plot # self.plot_pulse1, self.curve_pulse1 = self.create_plot_pulse1() self.plot_pulse2, self.curve_pulse2 = self.create_plot_pulse2() self.plot_hr1, self.curve_hr1 = self.create_plot_hr1() self.plot_hr2, self.curve_hr2 = self.create_plot_hr2() self.plot_fft1, self.curve_fft1 = self.create_plot_fft1() self.plot_fft2, self.curve_fft2 = self.create_plot_fft2() plot_layout = QGridLayout() plot_layout.addWidget(self.plot_pulse1, 0, 0) plot_layout.addWidget(self.plot_pulse2, 0, 1) plot_layout.addWidget(self.plot_hr1, 1, 0) plot_layout.addWidget(self.plot_hr2, 1, 1) plot_layout.addWidget(self.plot_fft1, 2, 0) plot_layout.addWidget(self.plot_fft2, 2, 1) #self.timer.setInterval(1000.0 / 50) plot_groupbox = QGroupBox('Plot') plot_groupbox.setLayout(plot_layout) # Main frame and layout # self.main_frame = QWidget() main_layout = QVBoxLayout() main_layout.addWidget(portname_groupbox) main_layout.addWidget(plot_groupbox) main_layout.addStretch(1) self.main_frame.setLayout(main_layout) self.setCentralWidget(self.main_frame) self.set_actions_enable_state() def create_menu(self): self.file_menu = self.menuBar().addMenu("&File") selectport_action = self.create_action("Select COM &Port...", shortcut="Ctrl+P", slot=self.on_select_port, tip="Select a COM port") self.start_action = self.create_action("&Start monitor", shortcut="Ctrl+M", slot=self.on_start, tip="Start the data monitor") self.stop_action = self.create_action("&Stop monitor", shortcut="Ctrl+T", slot=self.on_stop, tip="Stop the data monitor") exit_action = self.create_action("E&xit", slot=self.close, shortcut="Ctrl+X", tip="Exit the application") self.start_action.setEnabled(False) self.stop_action.setEnabled(False) self.add_actions(self.file_menu, ( selectport_action, self.start_action, self.stop_action, None, exit_action)) self.help_menu = self.menuBar().addMenu("&Help") about_action = self.create_action("&About", shortcut='F1', slot=self.on_about, tip='About the monitor') self.add_actions(self.help_menu, (about_action,)) def set_actions_enable_state(self): if self.portname.text() == '': start_enable = stop_enable = False else: start_enable = not self.monitor_active stop_enable = self.monitor_active self.start_action.setEnabled(start_enable) self.stop_action.setEnabled(stop_enable) def on_about(self): msg = __doc__ QMessageBox.about(self, "About the demo", msg.strip()) def on_select_port(self): ports = list(enumerate_serial_ports()) if len(ports) == 0: QMessageBox.critical(self, 'No ports', 'No serial ports found') return item, ok = QInputDialog.getItem(self, 'Select a port', 'Serial port:', ports, 0, False) if ok and not item.isEmpty(): self.portname.setText(item) self.set_actions_enable_state() def on_stop(self): """ Stop the monitor """ if self.com_monitor is not None: self.com_monitor.join(0.01) self.com_monitor = None self.monitor_active = False self.timer.stop() self.set_actions_enable_state() self.status_text.setText('Monitor idle') def on_start(self): """ Start the monitor: com_monitor thread and the update timer """ if self.com_monitor is not None or self.portname.text() == '': return self.data_q = Queue.Queue() self.error_q = Queue.Queue() self.com_monitor = ComMonitorThread( self.data_q, self.error_q, full_port_name(str(self.portname.text())), 9600) self.com_monitor.start() com_error = get_item_from_queue(self.error_q) if com_error is not None: QMessageBox.critical(self, 'ComMonitorThread error', com_error) self.com_monitor = None self.monitor_active = True self.set_actions_enable_state() self.timer = QTimer() self.connect(self.timer, SIGNAL('timeout()'), self.on_timer) if self.update_freq > 0: self.timer.start(1000.0 / self.update_freq) self.status_text.setText('Monitor running') def on_timer(self): """ Executed periodically when the monitor update timer is fired. """ self.read_serial_data() self.update_monitor() def update_monitor(self): """ Updates the state of the monitor window with new data. The livefeed is used to find out whether new data was received since the last update. If not, nothing is updated. """ if self.livefeed.has_new_data: data = self.livefeed.read_data() self.biofeedback_samples.append( (data['timestamp'], data['biofeedback'])) xdata = [s[0] for s in self.biofeedback_samples] ydata = [s[1] for s in self.biofeedback_samples] if xdata[len(xdata)-1] > self.xaxis_max2*self.xaxis_max_it: #Window draw diff = xdata[len(xdata)-1] - self.xaxis_max2 self.plot_pulse2.setAxisScale(Qwt.QwtPlot.xBottom, self.xaxis_min2 + diff, self.xaxis_max2 + diff, 1) self.plot_hr2.setAxisScale(Qwt.QwtPlot.xBottom, self.xaxis_min2 + diff, self.xaxis_max2 + diff, 1) self.plot_fft2.setAxisScale(Qwt.QwtPlot.xBottom, self.xaxis_min2 + diff, self.xaxis_max2 + diff, 1) if xdata[len(xdata)-1] > self.xaxis_max1*self.xaxis_max_it: #Window draw diff = xdata[len(xdata)-1] - self.xaxis_max self.plot_pulse1.setAxisScale(Qwt.QwtPlot.xBottom, self.xaxis_min1 + diff, self.xaxis_max1 + diff, 1) self.plot_hr1.setAxisScale(Qwt.QwtPlot.xBottom, self.xaxis_min1 + diff, self.xaxis_max1 + diff, 1) self.plot_fft1.setAxisScale(Qwt.QwtPlot.xBottom, self.xaxis_min1 + diff, self.xaxis_max1 + diff, 1) #Clear and draw #self.plot.setAxisScale(Qwt.QwtPlot.xBottom, self.xaxis_max*self.xaxis_max_it, self.xaxis_max*(self.xaxis_max_it+1), 1) #Keep all #self.plot.setAxisScale(Qwt.QwtPlot.xBottom, 0, self.xaxis_max*(self.xaxis_max_it+1), 1) #self.xaxis_max_it += 1 #Pulse 1 & 2 self.curve_pulse1.setData(xdata, ydata) self.plot_pulse1.replot() self.curve_pulse2.setData(xdata, ydata) self.plot_pulse2.replot() #HR 1 & 2 peakind = signal.find_peaks_cwt(ydata, arange(1,50)) for i in range(1,len(peakind)): print peakind[i] ydata_hr[i-1] = 60 / (xdata[peakind[i]] - xdata[peakind[i-1]]) xdata_hr[i-1] = xdata[peakind[i]] self.curve_hr1.setData(xdata_hr,ydata_hr) self.plot_hr1.replot() self.curve_hr2.setData(xdata_hr,ydata_hr) self.plot_hr2.replot() #FFT 1 & 2 ydata_fft = fft(ydata_hr) self.curve_fft1.setData(xdata_hr,ydata_fft) self.plot_fft1.replot() self.curve_fft2.setData(xdata_hr,ydata_fft) self.plot_fft2.replot() def read_serial_data(self): """ Called periodically by the update timer to read data from the serial port. """ qdata = list(get_all_from_queue(self.data_q)) if len(qdata) > 0: print ("len: " + str(len(qdata))) for ind in range(0,len(qdata)): data = dict(timestamp=qdata[ind][1], biofeedback=qdata[ind][0]) print ("xd " + str(qdata[ind][1]) + " yd " + str(qdata[ind][0])) self.livefeed.add_data(data) # The following two methods are utilities for simpler creation # and assignment of actions # def add_actions(self, target, actions): for action in actions: if action is None: target.addSeparator() else: target.addAction(action) def create_action( self, text, slot=None, shortcut=None, icon=None, tip=None, checkable=False, signal="triggered()"): action = QAction(text, self) if icon is not None: action.setIcon(QIcon(":/%s.png" % icon)) if shortcut is not None: action.setShortcut(shortcut) if tip is not None: action.setToolTip(tip) action.setStatusTip(tip) if slot is not None: self.connect(action, SIGNAL(signal), slot) if checkable: action.setCheckable(True) return action def main(): app = QApplication(sys.argv) form = PlottingDataMonitor() form.show() app.exec_() if __name__ == "__main__": main()
2f6656c9db69d84e64a7105b8056261da3b111b8
[ "Python" ]
1
Python
mkjiang/code-for-blog
3469353d9fb846da677c0f3265855f1b95094c09
907461c2bc2dc35aab7bc9c3517170bb80d119f5
refs/heads/master
<file_sep># code-challenge-pop-up-modal Code Challenge - Recreate a popup modal based on Adobe XD specs <file_sep> // Event Listener #1 - When user clicks on the grey area (body) run 'closeModal' // document.body.addEventListener('click', closeModal, true); function closeModal(event) { if (event.target.id === "wrapper" || event.target.id === "body_id" || event.target.id === "cta-2" || event.target.id === "x_button") { var x = document.getElementById('sub-container'); x.style.display = 'none'; var y = document.getElementById('hidden-container'); y.style.display = 'block'; } } // Event Listener #2 - When hidden container button is clicked run function 'openModal' // document.getElementById("hidden-container").addEventListener("click", openModal); function openModal() { var y = document.getElementById('hidden-container'); y.style.display = 'none'; var x = document.getElementById('sub-container'); x.style.display = 'block'; }
33ede2c4de26fa9f72da17059352322bfcd3aaba
[ "Markdown", "JavaScript" ]
2
Markdown
The1987/code-challenge-pop-up-modal
57e5cf14f1ccf7cf12d68616f90655a6e4f418b9
e2770f7e3c62606c5c816349488416cbac37b542
refs/heads/master
<repo_name>gabrieldestro/ExerciciosPhp<file_sep>/src/TextWrap/Resolucao.php <?php namespace Galoa\ExerciciosPhp\TextWrap; /** * Implemente sua resolução aqui. */ class Resolucao implements TextWrapInterface { /** * {@inheritdoc} */ public function textWrap(string $text, int $length): array { $ret = array(); $retIndex = 0; $retLenght = 0; $tokenStart = 0; $tokenEnd = 0; $wordLength = 0; $toInsert = ""; $nextWord = ""; $insertBiggerWord = false; // Percorre todo o vetor de entrada while (isset($text[$tokenStart])) { // Pega a próxima palavra do texto, seu tamanho e avança a posição do token final $nextWord = $this->getNextWord($text, $tokenStart); $wordLength= strlen($nextWord); $tokenEnd += $wordLength; $tokenEnd++; // Se o comprimento da palavra foi maior que o comprimento permitido if ($wordLength >= $length) { // Caso ainda não esteja preparado para inserir a palavra if ($insertBiggerWord == false) { // Insere no vetor o que já estava guardado no buffer array_push($ret, $toInsert); $toInsert = ""; $retLenght = 0; $retIndex++; // Prepara para a inserção da palavra maior, fazendo com que ela seja relida $tokenEnd = $tokenStart; $insertBiggerWord = true; } // Caso a etapa de preparação acima já houver sido concluída else { // Insere o trecho da palavra no vetor $tokenEnd = $tokenEnd - ($wordLength-$length)-1; $toInsert .= $this->getSubstring($text, $tokenStart, $tokenEnd); array_push($ret, $toInsert); $toInsert = ""; $retLenght = 0; $retIndex++; $insertBiggerWord = false; } } // Caso a palavra caiba na linha atual do vetor elseif ($retLenght+$wordLength-1 < $length) { // Adiciona a palavra ao buffer de inserção $retLenght += $wordLength; $retLenght++; $toInsert .= $this->getSubstring ($text, $tokenStart, $tokenEnd); } // Caso não seja possível inserir a nova palavra naquela linha else { /* Insere no vetor o que estava no buffer e ajusta as variveis para que a leitura da palavra seja refeita */ array_push($ret, $toInsert); $toInsert = ""; $retLenght = 0; $retIndex++; $tokenEnd = $tokenStart; } // Inserção do trecho concluído, avança o token inicial $tokenStart = $tokenEnd; } // Insere no vetor o que restou no buffer array_push($ret, $toInsert); $retIndex++; // Remove as linhas que são vazias ou espaços em branco $ret = $this->removeBlankLine ($ret, $retIndex); $ret = array_values($ret); // Caso a string de entrada for vazia, o vetor retornado deve ser vazio if (empty($ret[0])) { return [""]; } return $ret; } /* Desc: Retorna uma substring, dada uma string pai e os indices inicial e final. Param: Texto, indice inicial para copiar, indice final para copiar. Retorno: Substring composta pelo texto entre os indices . */ private function getSubstring (string $txt, int $start, int $end) { $str = ""; for ($j = $start; isset($txt[$j]) && $j < $end; $j++) { $str .= $txt[$j]; } return $str; } /* Desc: Dado um texto e o índice inicial, retorna a próxima palavra. Param: Texto, indice inicial. Retorno: Substring composta pela próxima palavra do texto a partir do índice inicial. */ private function getNextWord (string $txt, int $start) { $end = $start; while(isset($txt[$end]) && $txt[$end] != " ") { $end++; } return $this->getSubstring ($txt, $start, $end); } /* Desc: Dado um vetor de Strings, remove todos elementos vazios. Param: Texto, tamanho do vetor. Retorno: Novo vetor sem os elementos vazios. */ private function removeBlankLine (array $vet, int $size):array { for ($i = 0; $i < $size; $i++) { if (empty($vet[$i]) || $vet[$i] == " ") { unset($vet[$i]); } else { $vet[$i] = trim($vet[$i]); } } return $vet; } }
202ba38b5879da4f28ccb8ee6b8cba3ab764209d
[ "PHP" ]
1
PHP
gabrieldestro/ExerciciosPhp
6bd1acf84d0786d630c85e079ef91babd2a7bbf6
d6f85d37ce6d553037ca17dfb71cad6625663050
refs/heads/master
<file_sep>import * as THREE from 'three'; import ThreeCss from '../class/ThreeCss'; import {CSS3DObject} from "three/examples/jsm/renderers/CSS3DRenderer"; import * as loadImage from 'blueimp-load-image'; import * as TimelineMax from "gsap/umd/TimelineMax"; import * as dat from 'dat.gui'; import {OrbitControls} from "three/examples/jsm/controls/OrbitControls"; // todo three.jsでの配置がmatrix3dなのに対し、gsapの3d表現がtranslate3dなので位置がずれてるかも const TC = new ThreeCss('webGL', true); // 最後の初期処理 TC.camera.position.set(0, 0, 4000); // TC.camera.lookAt(new THREE.Vector3(550, 0, 0)); // アロー関数にするとthisがglobalオブジェクトに束縛されてしまうのでfunction文を使う。 const guiCtrl = function () { this.Camera_x = 0; this.Camera_y = 0; this.Camera_z = 0; }; let gui = new dat.GUI(); let guiObj = new guiCtrl(); let folder = gui.addFolder('Folder'); const setCameraPosition = () => { TC.camera.position.set(guiObj.Camera_x, guiObj.Camera_y, guiObj.Camera_z); } folder.add(guiObj, 'Camera_x', 0, 5000).onChange(setCameraPosition); folder.add(guiObj, 'Camera_y', 0, 5000).onChange(setCameraPosition); folder.add(guiObj, 'Camera_z', 0, 5000).onChange(setCameraPosition); folder.open(); let counter: number = 0; // DOM生成 for (let i = 1; i <= 10; i++) { // position const initialPosition = { x: i % 3 * 1000, y: (Math.floor(i / 3) % 3) * -250, z: (Math.floor(i / 3) % 3) * 550 }; //DOM const el = $('<div class="element">'); const image = $('<img>'); image.attr('src', `../images/cat_0${i}.jpg`); // exif情報を元に回転 fetch(`http://localhost:3000/images/cat_0${i}.jpg`) .then((data) => { return data.blob(); }) .then((blob) => { loadImage.parseMetaData(blob, (allData) => { if (allData.exif) { switch (allData.exif.get('Orientation')) { case 6 : image.css({ transform: 'rotate(90deg)', }); break; default: break; } } }); }) ; el.append(image); let TLObj = TimelineMax({repeat: 0}); console.log(`../images/cat_0${i}.jpg`, initialPosition); $('.modal_close').on('click', () => { $('#modal').removeClass('active'); TLObj .to(el, { force3D: false, x: initialPosition.x, y: initialPosition.y, z: initialPosition.z, duration: 1, }); }); el.on('click', () => { TLObj .to(el, { force3D: false, x: 550, y: 0, z: 2500, duration: 1, }); $('#modal').addClass('active'); }); // jQueryObjectの場合インデックス0がHtmlElementらしい const tObj = new CSS3DObject(el[0]); tObj.position.set(initialPosition.x, initialPosition.y, initialPosition.z); TC.scene.add(tObj); }<file_sep>import * as THREE from 'three'; import {Color, Mesh, PerspectiveCamera, PointLight, Scene, SpotLight} from'three'; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"; import * as dat from 'dat.gui'; import { CSS3DRenderer } from "three/examples/jsm/renderers/CSS3DRenderer"; export default class ThreeUtils { constructor(){ } /** * @readme PlaneGeometry -> https://threejs.org/docs/#api/en/geometries/PlaneGeometry */ static createMeshPlane(width: number, height: number, color: any): Mesh { return new THREE.Mesh( new THREE.PlaneGeometry(width, height), new THREE.MeshBasicMaterial({color: color}), ) } /** * lightのT/FでBasicMaterialかLambertMaterialかを分ける * @readme BoxGeometry -> https://threejs.org/docs/#api/en/geometries/BoxGeometry */ static createMeshCube(width: number, height: number, depth: number, color: any, light :boolean = false): Mesh { return new THREE.Mesh( new THREE.BoxGeometry(width, height, depth), light === true ? new THREE.MeshLambertMaterial({color: color}) : new THREE.MeshBasicMaterial({color: color}), ); } /** * @readme https://threejs.org/docs/#api/en/geometries/SphereGeometry */ static createMeshSphere(radius: number, widthSegments: number, heightSegments: number, color: any, light :boolean = false): Mesh { return new THREE.Mesh( new THREE.SphereGeometry(radius, widthSegments, heightSegments), light === true ? new THREE.MeshLambertMaterial({color: color}) : new THREE.MeshBasicMaterial({color: color}), ); } /** * @readme https://threejs.org/docs/#api/en/lights/SpotLight */ static createSpotLight(x: number, y: number, z: number, color: any, shadow: boolean = false): SpotLight { const spotLight = new THREE.SpotLight(color); spotLight.position.set(x, y, z); spotLight.castShadow = shadow; return spotLight; } }<file_sep>import * as THREE from 'three'; import ThreeUtils from '../class/ThreeUtils'; import ThreeCanvas from '../class/ThreeCanvas'; const TC = new ThreeCanvas('webGL', true); const init = () => { // 最後の初期処理 TC.camera.position.set(20, 10, 100); TC.camera.lookAt(new THREE.Vector3(0, 0, 0)); // オブジェクトの配置 const axes = new THREE.AxesHelper(20); const planeMesh = ThreeUtils.createMeshPlane(60, 20, 0xcccccc); const cubeMesh = ThreeUtils.createMeshCube(4, 4, 4, 0x000000, true); const sphereMesh = ThreeUtils.createMeshSphere(4, 20, 20, 0x00ff00, true); planeMesh.rotation.set(-0.5 * Math.PI, 0, 0); cubeMesh.position.set(10, 10, 0); sphereMesh.position.set(0, 0, 0); // 光源追加 const spotLight = ThreeUtils.createSpotLight(50, 50, 50, 0xffffff, true); const spotLightHelper = new THREE.SpotLightHelper(spotLight); TC.scene.add(axes); TC.scene.add(planeMesh); TC.scene.add(cubeMesh); TC.scene.add(sphereMesh); TC.scene.add(spotLight); TC.scene.add(spotLightHelper); // レンダリング開始 TC.renderer.render(TC.scene, TC.camera); }; window.addEventListener('DOMContentLoaded', () => { init(); }); // ブラウザの幅が変更されたらレンダラーとカメラをwindowサイズにリサイズ window.addEventListener('resize', () => { TC.camera.aspect = window.innerWidth / window.innerHeight; TC.camera.updateProjectionMatrix(); TC.renderer.setSize(window.innerWidth, window.innerHeight); })<file_sep>import * as THREE from 'three'; import {Color, Mesh, PerspectiveCamera, PointLight, Scene, SpotLight, WebGLRenderer} from'three'; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; import * as dat from 'dat.gui'; export default class ThreeCanvas { w: number; h: number; renderer: WebGLRenderer; scene: Scene; camera: PerspectiveCamera; orbitControls: OrbitControls; datControls: any; constructor (id: string, orbit: boolean = false, ww = window.innerWidth, wh = window.innerHeight) { this.w = ww; this.h = wh; // レンダラーの初期化 this.renderer = new THREE.WebGLRenderer(); this.renderer.setSize(this.w, this.h); // 描画サイズ this.renderer.setPixelRatio(window.devicePixelRatio);// ピクセル比->多分2とか this.renderer.setClearColor(new THREE.Color(0xEEEEEE)); $(`#${id}`).append(this.renderer.domElement); // シーン初期化 this.scene = new THREE.Scene(); // カメラ初期化(視野角, アスペクト比, カメラの映る最短距離, カメラの映る最長距離) this.camera = new THREE.PerspectiveCamera(45, this.w / this.h, 1, 1000); // OrbitControls if (orbit) { this.orbitControls = new OrbitControls(this.camera, this.renderer.domElement); this.orbitControls.update(); // アロー関数であればthisのスコープがずれるのでthisが使える const animate = () => { requestAnimationFrame(animate); this.orbitControls.update(); this.renderer.render(this.scene, this.camera); }; animate(); } // dat init this.datControls = new dat.GUI(); } //[s: string]はジェネリクスでstringのどのキーがきても大丈夫 addDatControls(datControls: {[s: string]: string|number}[] ){ const controls = new function (){}; for(const dc of datControls) { controls[dc.controlName] = dc.initial; this.datControls.add(controls, dc.controlName, dc.from, dc.to); } } }<file_sep>import * as THREE from 'three'; import {Color, Mesh, PerspectiveCamera, PointLight, Scene, SpotLight} from'three'; import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"; import * as dat from 'dat.gui'; import { CSS3DRenderer } from "three/examples/jsm/renderers/CSS3DRenderer"; import {TrackballControls} from "three/examples/jsm/controls/TrackballControls"; export default class ThreeCss { w: number; h: number; renderer: CSS3DRenderer; scene: Scene; camera: PerspectiveCamera; orbitControls: OrbitControls; datControls: any; constructor (id: string, orbit: boolean = false, ww = window.innerWidth, wh = window.innerHeight) { this.w = ww; this.h = wh; // レンダラーの初期化 this.renderer = new CSS3DRenderer(); this.renderer.setSize(this.w, this.h); // 描画サイズ $(`#${id}`).append(this.renderer.domElement); // シーン初期化 this.scene = new THREE.Scene(); // カメラ初期化(視野角, アスペクト比, カメラの映る最短距離, カメラの映る最長距離) this.camera = new THREE.PerspectiveCamera(45, this.w / this.h, 1, 1000); // OrbitControls if (orbit) { // this.animation(); } const controls = new TrackballControls(this.camera, this.renderer.domElement); controls.minDistance = 500; controls.maxDistance = 6000; const animate = () => { requestAnimationFrame(animate); this.renderer.render(this.scene, this.camera); controls.update(); } animate(); // dat init this.datControls = new dat.GUI(); } animation() { this.orbitControls = new OrbitControls(this.camera, this.renderer.domElement); this.orbitControls.update(); // アロー関数であればthisのスコープがずれるのでthisが使える const animate = () => { requestAnimationFrame(animate); this.orbitControls.update(); this.renderer.render(this.scene, this.camera); } animate(); } }<file_sep>import * as THREE from 'three'; const init = () => { // サイズを指定 const width = 960; const height = 540; let rot = 0; // レンダラーを作成 const renderer = new THREE.WebGLRenderer({ canvas: <HTMLCanvasElement>document.querySelector('#webGL') }); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(width, height); // シーンを作成 const scene = new THREE.Scene(); // カメラを作成 const camera = new THREE.PerspectiveCamera(45, width / height); camera.position.set(50, 100, 500); camera.lookAt(new THREE.Vector3(0, 0, 0)); // 地面を作成 const plane2 = new THREE.GridHelper(600, 50); scene.add(plane2); const plane = new THREE.AxesHelper(300); scene.add(plane); // 直方体を作成 const material = new THREE.MeshNormalMaterial(); const geometry = new THREE.SphereGeometry(30, 30, 30); const mesh = new THREE.Mesh(geometry, material); scene.add(mesh); tick(); // 毎フレーム時に実行されるループイベントです function tick() { rot += 0.5; // 毎フレーム角度を0.5度ずつ足していく // ラジアンに変換する const radian = (rot * Math.PI) / 180; // 角度に応じてカメラの位置を設定 mesh.position.x = 200 * Math.sin(radian); mesh.position.y = 50; mesh.position.z = 200 * Math.cos(radian); // レンダリング renderer.render(scene, camera); // 球体のワールド座標を取得する const project = mesh.position.project(camera); const sx: any = (width / 2) * (+project.x + 1.0); const sy: any = (height / 2) * (-project.y + 1.0); const tf = document.getElementById('hud'); // テキストフィールドにスクリーン座標を表示 tf.innerHTML = `👆スクリーン座標(${Math.round(sx)}, ${Math.round(sy)})`; tf.style.transform = `translate(${sx}px, ${sy}px)`; // SVGでラインを描画 const line = document.getElementById('svgLine'); line.setAttribute('x2', sx); line.setAttribute('y2', sy); requestAnimationFrame(tick); } } window.addEventListener('load', init); <file_sep>const path = require('path'); const webpack = require('webpack'); module.exports = { mode: "development", entry: { "css3d": './src/js/modules/css3d.ts', "index": './src/js/modules/index.ts', "world": './src/js/modules/world.ts', "logo": './src/js/modules/logo.ts', "basic": './src/js/modules/basic.ts', }, // ファイルの出力設定 output: { // 出力ファイルのディレクトリ名 path: `${__dirname}/dist`, // 出力ファイル名 filename: '[name].js' }, module: { rules: [ { // 拡張子 .ts の場合 test: /\.ts$/, // TypeScript をコンパイルする use: "ts-loader" }, { // 画像もバンドルする 対象となるファイルの拡張子 test: /\.(gif|png|jpg)$/, // 画像をBase64として取り込む loader: 'url-loader' } ] }, // import 文で .ts ファイルを解決するため resolve: { extensions: [".ts", ".js"] }, plugins: [ new webpack.ProvidePlugin({ jQuery: "jquery", $: "jquery" }), ] };
c55942acc5e8e18ff6be1ccfa7a08160183b1425
[ "JavaScript", "TypeScript" ]
7
TypeScript
nakajima-cz/ThreeLearning
9d7bc6a7320ea57a35fe147c0768196061ae203e
743b2bd114564510b62004efdb482d34193b48e4
refs/heads/main
<file_sep>import { CourseModel } from '~/services/@types/course'; import { BaseService, BaseServiceConfig } from '../base-service'; import { CourseMaterialServiceConfig, CourseMaterialServiceRest } from '../course-material/course-material.service'; import { CourseModuleServiceConfig, CourseModuleServiceRest } from '../course-module/course-module.service'; import { CourseSkuServiceConfig, CourseSkuServiceRest } from '../course-sku/course-sku.service'; import { CourseSubscriptionServiceConfig, CourseSubscriptionServiceRest } from '../course-subscription/course-subscription.service'; import { CourseUserServiceConfig, CourseUserServiceRest } from '../course-user/course-user.service'; import { CourseVideoServiceConfig, CourseVideoServiceRest } from '../course-video/course-video.service'; import { CreateCourseDTO } from './dtos/create-course.dto'; import { UpdateCourseDTO } from './dtos/update-course.dto'; export interface CourseServiceConfig extends BaseServiceConfig {} export class CourseServiceRest extends BaseService { constructor(data: CourseServiceConfig) { super(data); } materials(config: CourseMaterialServiceConfig) { return new CourseMaterialServiceRest(config); } modules(config: CourseModuleServiceConfig) { return new CourseModuleServiceRest(config); } videos(config: CourseVideoServiceConfig) { return new CourseVideoServiceRest(config); } skus(config: CourseSkuServiceConfig) { return new CourseSkuServiceRest(config); } users(config: CourseUserServiceConfig) { return new CourseUserServiceRest(config); } subscriptions(config: CourseSubscriptionServiceConfig) { return new CourseSubscriptionServiceRest(config); } async create(data: CreateCourseDTO | FormData): Promise<CourseModel> { try { const response = await this.client.post<CourseModel>(`/courses`, data, { headers: { 'Content-Type': 'multipart/form-data' } }); if (response?.data) { return response.data; } } catch (error) {} return null; } async update( courseId: string, data: UpdateCourseDTO | FormData ): Promise<boolean> { try { const response = await this.client.patch<{ ok: boolean }>( `/courses/${courseId}`, data, { headers: { 'Content-Type': 'multipart/form-data' } } ); if (response?.data?.ok) { return true; } } catch (error) {} return false; } async findById(id: string): Promise<CourseModel> { try { const response = await this.client.get<CourseModel>(`/courses/${id}`); if (response?.data) { return response.data; } } catch (error) {} return null; } async findAll(): Promise<CourseModel[]> { try { const response = await this.client.get<CourseModel[]>(`/courses`); if (response?.data && response?.data.length > 0) { return response.data; } } catch (error) {} return null; } } <file_sep>import { ModuleModel } from '~/services/@types/module'; import { BaseService, BaseServiceConfig } from '../base-service'; import { CreateCourseModuleDTO } from './dtos/create-course-module.dto'; export interface CourseModuleServiceConfig extends BaseServiceConfig { readonly courseId: string; } export class CourseModuleServiceRest extends BaseService { readonly courseId: string; constructor(data: CourseModuleServiceConfig) { super(data); this.courseId = data.courseId; } async create(data: CreateCourseModuleDTO): Promise<ModuleModel> { try { const response = await this.client.post<ModuleModel>( `/courses/${this.courseId}/modules`, data ); if (response?.data) { return response.data; } } catch (error) {} return null; } async delete(moduleId: string): Promise<ModuleModel> { try { const response = await this.client.delete<ModuleModel>( `/modules/${moduleId}` ); if (response?.data) { return response.data; } } catch (error) {} return null; } async findAll(): Promise<ModuleModel[]> { try { const response = await this.client.get<ModuleModel[]>( `/courses/${this.courseId}/modules` ); if (response?.data && response?.data.length > 0) { return response.data; } } catch (error) {} return null; } } <file_sep>import { SubscriptionModel } from '~/services/@types/subscription'; import { FindAllPayload } from '~/services/interfaces/find-all.payload'; import { BaseService, BaseServiceConfig } from '../base-service'; export interface SubscriptionServiceConfig extends BaseServiceConfig {} export class SubscriptionServiceRest extends BaseService { constructor(data: SubscriptionServiceConfig) { super(data); } async cancel(id: string): Promise<boolean> { try { const response = await this.client.patch<{ ok: boolean }>( `/subscriptions/${id}/cancel` ); if (response?.data) { return true; } } catch (error) {} return false; } async start(id: string): Promise<boolean> { try { const response = await this.client.patch<{ ok: boolean }>( `/subscriptions/${id}/start` ); if (response?.data) { return true; } } catch (error) {} return false; } async findById(id: string): Promise<SubscriptionModel> { try { const response = await this.client.get<SubscriptionModel>( `/subscriptions/${id}` ); if (response?.data) { return response.data; } } catch (error) {} return null; } async findAll(data?: { status?: string; createdAt?: string; page?: string; limit?: string; }): Promise<FindAllPayload<SubscriptionModel>> { try { const requestData = Object.entries(data || {}); const params = requestData.length > 0 ? requestData.map(([key, value]) => `${key}=${value || ''}`).join('&') : ''; const response = await this.client.get<FindAllPayload<SubscriptionModel>>( `/subscriptions${requestData?.length ? '?' + params : ''}` ); if (response?.data) { return response.data; } } catch (error) {} return null; } } <file_sep>import { VideoModel } from '~/services/@types/video'; import { FindAllPayload } from '~/services/interfaces/find-all.payload'; import { BaseService, BaseServiceConfig } from '../base-service'; import { CreateCourseVideoDTO } from './dtos/create-course-video.dto'; import { UpdateCourseVideoDTO } from './dtos/update-course-video.dto'; export interface CourseVideoServiceConfig extends BaseServiceConfig { readonly moduleId: string; } export class CourseVideoServiceRest extends BaseService { readonly moduleId: string; constructor(data: CourseVideoServiceConfig) { super(data); this.moduleId = data.moduleId; } async create(data: CreateCourseVideoDTO | FormData): Promise<VideoModel> { try { const response = await this.client.post<VideoModel>( `/modules/${this.moduleId}/videos`, data, { headers: { 'Content-Type': 'multipart/form-data' } } ); if (response?.data) { return response.data; } } catch (error) {} return null; } async update( videoId: string, data: UpdateCourseVideoDTO | FormData ): Promise<VideoModel> { try { const response = await this.client.patch<VideoModel>( `/videos/${videoId}`, data, { headers: { 'Content-Type': 'multipart/form-data' } } ); if (response?.data) { return response.data; } } catch (error) {} return null; } async delete(videoId: string): Promise<VideoModel> { try { const response = await this.client.delete<VideoModel>( `/videos/${videoId}` ); if (response?.data) { return response.data; } } catch (error) {} return null; } async findAll(data?: { page?: string; limit?: string; title?: string; description?: string; position?: string; status?: string; updatedAt?: string; createdAt?: string; }): Promise<FindAllPayload<VideoModel>> { try { const requestData = Object.entries(data || {}); const params = requestData.length > 0 ? requestData.map(([key, value]) => `${key}=${value || ''}`).join('&') : ''; const response = await this.client.get<FindAllPayload<VideoModel>>( `/modules/${this.moduleId}/videos${ requestData?.length ? '?' + params : '' }` ); if (response?.data) { return response.data; } } catch (error) { console.log(error); } return null; } } <file_sep>NEXT_PUBLIC_BASE_API_SERVER_URL= NEXT_PUBLIC_AUTH_FRONTEND_URL= <file_sep>import { AddressModel } from '~/services/@types/address'; import { BaseService, BaseServiceConfig } from '../base-service'; export interface AddressServiceConfig extends BaseServiceConfig {} export class AddressServiceRest extends BaseService { constructor(data: AddressServiceConfig) { super(data); } async create(data: {}): Promise<AddressModel> { try { const response = await this.client.post<AddressModel>( `/me/addresses`, data ); if (response?.data) { return response.data; } } catch (error) {} return null; } } <file_sep>export interface CreateCourseVideoDTO { readonly name: string; readonly description: string; readonly video: any; readonly thumbnail: any; } <file_sep>export interface UpdateCourseVideoDTO { readonly name?: string; readonly description?: string; readonly thumbnail?: any; } <file_sep>import { SubscriptionModel } from '~/services/@types/subscription'; import { FindAllPayload } from '~/services/interfaces/find-all.payload'; import { BaseService, BaseServiceConfig } from '../base-service'; import { CreateCourseSubscriptionDTO } from './dtos/create-course-subscription.dto'; export interface CourseSubscriptionServiceConfig extends BaseServiceConfig { readonly courseId: string; } export class CourseSubscriptionServiceRest extends BaseService { readonly courseId: string; constructor(data: CourseSubscriptionServiceConfig) { super(data); this.courseId = data.courseId; } async create(data: CreateCourseSubscriptionDTO): Promise<SubscriptionModel> { try { const response = await this.client.post<SubscriptionModel>( `/courses/${this.courseId}/subscriptions`, data ); if (response?.data) { return response.data; } } catch (error) {} return null; } async start(data: { subscriptionId: string; userId: string; }): Promise<boolean> { try { const response = await this.client.patch<{ ok: boolean }>( `/courses/${this.courseId}/subscriptions/${data?.subscriptionId}/start`, data ); if (response?.data?.ok) { return response?.data?.ok; } } catch (error) {} return null; } async cancel(data: { subscriptionId: string; userId: string; }): Promise<boolean> { try { const response = await this.client.patch<{ ok: boolean }>( `/courses/${this.courseId}/subscriptions/${data?.subscriptionId}/cancel`, data ); if (response?.data?.ok) { return response?.data?.ok; } } catch (error) {} return null; } async findAll(data?: { limit?: string; page?: string; status?: string; type?: string; createdAt?: string; }): Promise<FindAllPayload<SubscriptionModel>> { try { const params = Object.entries(data || {}).map( ([key, value]) => `${key}=${value || ''}` ); const paramsString = params.join('&'); const response = await this.client.get<FindAllPayload<SubscriptionModel>>( `/courses/${this.courseId}/subscriptions${ params.length > 0 ? '?' + paramsString : '' }` ); if (response?.data) { return response.data; } } catch (error) {} return null; } } <file_sep>import { AddressServiceRest } from './services/address/address.service'; import { AppServiceRest } from './services/app/app.service'; import { BaseServiceConfig } from './services/base-service'; import { CategoryServiceRest } from './services/category/category.service'; import { CourseServiceRest } from './services/course/course.service'; import { MeServiceRest } from './services/me/me.service'; import { PriceServiceRest } from './services/price/price.service'; import { SkuServiceRest } from './services/sku/sku.service'; import { SubscriptionServiceRest } from './services/subscription/subscription.service'; import { UserServiceRest } from './services/user/user.service'; import { VideoServiceRest } from './services/video/video.service'; export interface ClientRestAPIInstance { readonly addresses: () => AddressServiceRest; readonly apps: () => AppServiceRest; readonly categories: () => CategoryServiceRest; readonly courses: () => CourseServiceRest; readonly me: () => MeServiceRest; readonly prices: () => PriceServiceRest; readonly skus: () => SkuServiceRest; readonly subscriptions: () => SubscriptionServiceRest; readonly users: () => UserServiceRest; readonly videos: () => VideoServiceRest; } export const clientRestApi = <T = BaseServiceConfig>( config?: T ): ClientRestAPIInstance => { const configData = config || {}; return { addresses: () => new AddressServiceRest(configData), apps: () => new AppServiceRest(configData), categories: () => new CategoryServiceRest(configData), courses: () => new CourseServiceRest(configData), me: () => new MeServiceRest(configData), prices: () => new PriceServiceRest(configData), skus: () => new SkuServiceRest(configData), subscriptions: () => new SubscriptionServiceRest(configData), users: () => new UserServiceRest(configData), videos: () => new VideoServiceRest(configData) }; }; <file_sep>export interface CreateCourseModuleDTO { readonly name: string; readonly description?: string; } <file_sep>import { UserModel } from '~/services/@types/user'; import { FindAllData } from '~/services/interfaces/find-all.data'; import { FindAllPayload } from '~/services/interfaces/find-all.payload'; import { BaseService, BaseServiceConfig } from '../base-service'; export interface CourseUserServiceConfig extends BaseServiceConfig { readonly courseId: string; } export class CourseUserServiceRest extends BaseService { readonly courseId: string; constructor(data: CourseUserServiceConfig) { super(data); this.courseId = data.courseId; } async findAll(data?: FindAllData): Promise<FindAllPayload<UserModel>> { try { const params = Object.entries({ ...data?.filter, ...data }).map( ([key, value]) => `${key}=${value || ''}` ); const paramsString = params.join('&'); const response = await this.client.get<FindAllPayload<UserModel>>( `/courses/${this.courseId}/users${ params.length > 0 ? '?' + paramsString : '' }` ); if (response?.data) { return response.data; } } catch (error) {} return null; } } <file_sep>import { MaterialModel } from '~/services/@types/material'; import { BaseService, BaseServiceConfig } from '../base-service'; import { CreateCourseMaterialDTO } from './dtos/create-course-material.dto'; export interface CourseMaterialServiceConfig extends BaseServiceConfig { readonly courseId: string; } export class CourseMaterialServiceRest extends BaseService { readonly courseId: string; constructor(data: CourseMaterialServiceConfig) { super(data); this.courseId = data.courseId; } async create( data: CreateCourseMaterialDTO | FormData ): Promise<MaterialModel> { try { const response = await this.client.post<MaterialModel>( `/courses/${this.courseId}/materials`, data, { headers: { 'Content-Type': 'multipart/form-data' } } ); if (response?.data) { return response.data; } } catch (error) {} return null; } async delete(materialId: string): Promise<MaterialModel> { try { const response = await this.client.delete<MaterialModel>( `/courses/${this.courseId}/materials/${materialId}` ); if (response?.data) { return response.data; } } catch (error) {} return null; } async findAll(): Promise<MaterialModel[]> { try { const response = await this.client.get<MaterialModel[]>( `/courses/${this.courseId}/materials` ); if (response?.data && response?.data.length > 0) { return response.data; } } catch (error) {} return null; } }
a43da88d4aaf8772ec55eb6b1d6f15add76fbf13
[ "TypeScript", "Shell" ]
13
TypeScript
stokei-enterprise/dashboard-frontend
039f1e1cae7c4b3a0d08e57c091f7ddabe7554c8
9560d96af07df1144be1ff44d794cf803ee8ace8
refs/heads/master
<repo_name>Jjwint1/muon-tomography<file_sep>/rho_3.6/1GeV_3.6/1GeV_3.6-source/src/PrimaryGeneratorAction.cpp // // PrimaryGeneratorAction.cpp // // // Created by <NAME>. // #include "PrimaryGeneratorAction.hh" #include "G4Event.hh" #include "G4ParticleGun.hh" #include "G4ParticleTable.hh" #include "G4ParticleDefinition.hh" #include "G4GenericMessenger.hh" #include "G4SystemOfUnits.hh" #include "Randomize.hh" PrimaryGeneratorAction::PrimaryGeneratorAction() : G4VUserPrimaryGeneratorAction(), mParticleGun(0), mMessenger(0), mMuon(0), mEnergy(2*GeV) { G4int n_particle = 1; mParticleGun = new G4ParticleGun(n_particle); G4ParticleTable* particleTable = G4ParticleTable::GetParticleTable(); G4String particleName; mMuon = particleTable->FindParticle(particleName="mu+"); mParticleGun->SetParticlePosition(G4ThreeVector(0.,0.,-1.*m)); mParticleGun->SetParticleDefinition(mMuon); // DefineCommands(); } PrimaryGeneratorAction::~PrimaryGeneratorAction() { delete mParticleGun; delete mMessenger; } void PrimaryGeneratorAction::GeneratePrimaries(G4Event* event) { mParticleGun->SetParticleMomentumDirection(G4ThreeVector(0, 0, 1)); // mParticleGun->SetParticleEnergy(mEnergy); mParticleGun->GeneratePrimaryVertex(event); } /*void PrimaryGeneratorAction::DefineCommands() { mMessenger = new G4GenericMessenger(this, "/muonTom/generator", "Primary generator control"); G4GenericMessenger::Command& energyCmd = mMessenger->DeclarePropertyWithUnit("energy", "GeV", mEnergy, "Energy of primary muons"); energyCmd.SetParameterName("E", true); energyCmd.SetRange("E>=0."); energyCmd.SetDefaultValue("1."); }*/ <file_sep>/concrete/500GeV-concrete/500GeV-concrete-source/include/SheetSD.hh // // SheetSD.hh // // // Created by <NAME>. // #ifndef SheetSD_h #define SheetSD_h #include "G4VSensitiveDetector.hh" #include "SheetHit.hh" class G4Step; class G4HCofThisEvent; class G4TouchableHistory; class SheetSD : public G4VSensitiveDetector { public: SheetSD(G4String name); virtual ~SheetSD(); virtual void Initialize(G4HCofThisEvent*HCE); virtual G4bool ProcessHits(G4Step*aStep,G4TouchableHistory*ROhist); private: SheetHitsCollection* mSheetHitsCollection; G4int mHCID; }; #endif <file_sep>/rho_3.6/500GeV_3.6/500GeV_3.6-source/src/EventAction.cpp // // EventAction.cpp // // // Created by <NAME>. // #include "EventAction.hh" #include "SheetHit.hh" #include "Analysis.hh" #include "G4Event.hh" #include "G4RunManager.hh" #include "G4EventManager.hh" #include "G4HCofThisEvent.hh" #include "G4VHitsCollection.hh" #include "G4SDManager.hh" #include "G4SystemOfUnits.hh" #include "G4ios.hh" #include "DetectorConstruction.hh" #include <iostream> #include <fstream> using namespace std; EventAction::EventAction() : G4UserEventAction(), mHCIDs(0) {} EventAction::~EventAction() {} void EventAction::BeginOfEventAction(const G4Event*) { if(mHCIDs.size() == 0) { G4SDManager* sdManager = G4SDManager::GetSDMpointer(); for(G4int i = 0; i < 101; i++) { string collectionName = "sheetSD" + to_string(i) + "/sheetColl"; mHCIDs.push_back(sdManager->GetCollectionID(collectionName)); } } } void EventAction::EndOfEventAction(const G4Event* event) { G4HCofThisEvent* hce = event->GetHCofThisEvent(); for(G4int i = 0; i < 101; i++) { SheetHitsCollection* sHC = static_cast<SheetHitsCollection*>(hce->GetHC(mHCIDs[i])); if (sHC->entries() != 0) { SheetHit* hit = (*sHC)[0]; G4ThreeVector localPos = hit->GetLocalPos(); G4ThreeVector momentum = hit->GetMomentum(); G4double angle = hit->GetAngle(); ofstream myFileX; string filename = "500GeV-wood-data/detectingSheet" + to_string(i*10) + "cm.txt"; myFileX.open(filename, ios::out | ios::app); myFileX << localPos.x()/cm << " " << localPos.y()/cm << " " << angle << endl; myFileX.close(); } else { ofstream myFileX; string filename = "500GeV-wood-data/detectingSheet" + to_string(i*10) + "cm.txt"; myFileX.open(filename, ios::out | ios::app); myFileX << "No" << endl; myFileX.close(); } } } <file_sep>/wood/100GeV-wood/100GeV-wood-source/include/Analysis.hh // // Analysis.hh // // // Created by <NAME>. // #ifndef Analysis_h #define Analysis_h #include "g4csv.hh" #endif <file_sep>/wood/500GeV-wood/500GeV-wood-source/include/PrimaryGeneratorAction.hh // // PrimaryGeneratorAction.hh // // // Created by <NAME>. // #ifndef PrimaryGeneratorAction_h #define PrimaryGeneratorAction_h #include "G4VUserPrimaryGeneratorAction.hh" #include "globals.hh" class G4ParticleGun; class G4GenericMessenger; class G4Event; class G4ParticleDefinition; class PrimaryGeneratorAction : public G4VUserPrimaryGeneratorAction { public: PrimaryGeneratorAction(); virtual ~PrimaryGeneratorAction(); virtual void GeneratePrimaries(G4Event*); void SetEnergy(G4double val) { mEnergy = val; } G4double GetEnergy() const { return mEnergy; } private: void DefineCommands(); G4ParticleGun* mParticleGun; G4GenericMessenger* mMessenger; G4ParticleDefinition* mMuon; G4double mEnergy; }; #endif <file_sep>/wood/20GeV-wood/20GeV-wood-source/src/SheetHit.cpp // // SheetHit.cpp // // // Created by <NAME>. // #include "SheetHit.hh" #include "G4VVisManager.hh" #include "G4VisAttributes.hh" #include "G4Circle.hh" #include "G4Colour.hh" #include "G4AttDefStore.hh" #include "G4AttDef.hh" #include "G4AttValue.hh" #include "G4UIcommand.hh" #include "G4UnitsTable.hh" #include "G4SystemOfUnits.hh" #include "G4ios.hh" G4ThreadLocal G4Allocator<SheetHit>* SheetHitAllocator; SheetHit::SheetHit() : G4VHit(), mLocalPos(0), mID(-1), mAngle(0) {} SheetHit::SheetHit(G4int i) : G4VHit(), mLocalPos(0), mID(i) {} SheetHit::~SheetHit() {} <file_sep>/rho_1.5/4GeV_1.5/4GeV_1.5-source/include/EventAction.hh // // EventAction.hh // // // Created by <NAME>. // #ifndef EventAction_h #define EventAction_h #include "G4UserEventAction.hh" #include "globals.hh" #include "G4THitsCollection.hh" #include "SheetHit.hh" #include <vector> class EventAction : public G4UserEventAction { public: EventAction(); virtual ~EventAction(); virtual void BeginOfEventAction(const G4Event*); virtual void EndOfEventAction(const G4Event*); private: std::vector<G4int> mHCIDs; std::vector<SheetHitsCollection*> mHitsCollections; }; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... #endif <file_sep>/rho_0.9/1GeV_0.9/1GeV_0.9-source/include/DetectorConstruction.hh // // DetectorConstruction.hh // // // Created by <NAME>. // #ifndef DetectorConstruction_h #define DetectorConstruction_h #include "globals.hh" #include "G4VUserDetectorConstruction.hh" #include <vector> class G4VPhysicalVolume; class G4Material; class G4VSensitiveDetector; class G4VisAttributes; class G4GenericMessenger; class DetectorConstruction : public G4VUserDetectorConstruction { public: DetectorConstruction(); virtual ~DetectorConstruction(); virtual G4VPhysicalVolume* Construct(); virtual void ConstructSDandField(); void ConstructMaterials(); private: G4GenericMessenger* mMessenger; std::vector<G4VisAttributes*> mVisAttributes; std::vector<G4LogicalVolume*> mDetectingSheets; std::vector<G4VSensitiveDetector*> mSensitiveDetectors; }; #endif <file_sep>/rho_1.5/4GeV_1.5/4GeV_1.5-source/src/RunAction.cpp // // RunAction.cpp // // // Created by <NAME>. // #include "RunAction.hh" #include "Analysis.hh" #include "G4UnitsTable.hh" #include "G4SystemOfUnits.hh" #include "Run.hh" #include <iostream> RunAction::RunAction() : G4UserRunAction(), runNumber(0) { } RunAction::~RunAction() { delete G4AnalysisManager::Instance(); } void RunAction::BeginOfRunAction(const G4Run*) { } void RunAction::EndOfRunAction(const G4Run* run) { runNumber++; G4cout << runNumber << G4endl; std::cout << runNumber << std::endl; } G4Run* RunAction::GenerateRun() { return new Run(); } <file_sep>/rho_1.5/20GeV_1.5/20GeV_1.5-source/include/RunAction.hh // // RunAction.hh // // // Created by <NAME>. // #ifndef RunAction_h #define RunAction_h #include "G4UserRunAction.hh" #include "globals.hh" class G4Run; class RunAction : public G4UserRunAction { public: RunAction(); virtual ~RunAction(); virtual void BeginOfRunAction(const G4Run*); virtual void EndOfRunAction(const G4Run*); virtual G4Run* GenerateRun(); G4int runNumber; }; #endif <file_sep>/concrete/500GeV-concrete/500GeV-concrete-source/include/SheetHit.hh // // SheetHit.hh // // // Created by <NAME> on 12/08/2019. // #ifndef SheetHit_h #define SheetHit_h #include "G4VHit.hh" #include "G4THitsCollection.hh" #include "G4Allocator.hh" #include "G4ThreeVector.hh" class SheetHit : public G4VHit { public: SheetHit(); SheetHit(G4int i); ~SheetHit(); void SetLocalPos(G4ThreeVector xyz) { mLocalPos = xyz; } G4ThreeVector GetLocalPos() const { return mLocalPos; } void SetMomentum(G4ThreeVector xyz) {mMomentum = xyz;} G4ThreeVector GetMomentum() {return mMomentum;} void SetAngle(G4double a) {mAngle = a;} G4double GetAngle() {return mAngle;} inline void *operator new(size_t); inline void operator delete(void*aHit); private: G4ThreeVector mLocalPos; G4ThreeVector mMomentum; G4double mAngle; G4int mID; }; typedef G4THitsCollection<SheetHit> SheetHitsCollection; extern G4ThreadLocal G4Allocator<SheetHit>* SheetHitAllocator; inline void* SheetHit::operator new(size_t) { if(!SheetHitAllocator) { SheetHitAllocator = new G4Allocator<SheetHit>; } return (void*)SheetHitAllocator->MallocSingle(); } inline void SheetHit::operator delete(void*aHit) { SheetHitAllocator->FreeSingle((SheetHit*) aHit); } #endif <file_sep>/concrete/20GeV-concrete/20GeV-concrete-source/include/Run.hh #ifndef RUN_HH #define RUN_HH #include "G4Run.hh" class Run : public G4Run { public: Run(); virtual ~Run() {}; virtual void RecordEvent(const G4Event*); }; #endif <file_sep>/concrete/1GeV-concrete/1GeV-concrete-source/src/DetectorConstruction.cpp // // DetectorConstruction.cpp // // // Created by <NAME>. // #include "DetectorConstruction.hh" #include "G4TransportationManager.hh" #include "G4SDParticleFilter.hh" #include "SheetSD.hh" #include "G4Material.hh" #include "G4Element.hh" #include "G4MaterialTable.hh" #include "G4NistManager.hh" #include "G4VSolid.hh" #include "G4Box.hh" #include "G4Tubs.hh" #include "G4LogicalVolume.hh" #include "G4VPhysicalVolume.hh" #include "G4PVPlacement.hh" #include "G4PVReplica.hh" #include "G4UserLimits.hh" #include "G4SDManager.hh" #include "G4VSensitiveDetector.hh" #include "G4RunManager.hh" #include "G4GenericMessenger.hh" #include "G4VisAttributes.hh" #include "G4Colour.hh" #include "G4ios.hh" #include "G4SystemOfUnits.hh" #include <vector> using namespace std; DetectorConstruction::DetectorConstruction() : G4VUserDetectorConstruction(), mMessenger(0), mVisAttributes(), mDetectingSheets(0), mSensitiveDetectors(0) { // DefineCommands(); } DetectorConstruction::~DetectorConstruction() { delete mMessenger; for (G4int i = 0; i < G4int(mVisAttributes.size()); i++) { delete mVisAttributes[i]; } } G4VPhysicalVolume* DetectorConstruction::Construct() { //Construct Materials ConstructMaterials(); G4Material* air = G4Material::GetMaterial("G4_AIR"); G4Material* concrete = G4Material::GetMaterial("G4_CONCRETE"); //check volume overlap G4bool checkOverlaps = true; //Geometries------------------------------------------------------------------------------ //World volume G4VSolid* worldSolid = new G4Box("worldBox", 11.*m, 11.*m, 11.*m); G4LogicalVolume* worldLogical = new G4LogicalVolume(worldSolid, air, "worldLogical"); G4VPhysicalVolume* worldPhysical = new G4PVPlacement(0, G4ThreeVector(), worldLogical, "worldPhysical", 0, false, 0, checkOverlaps); //ConcreteCube G4VSolid* concreteCubeSolid = new G4Box("concreteCubeBox", 0.5*m, 0.5*m, 1*m); G4LogicalVolume* concreteCubeLogical = new G4LogicalVolume(concreteCubeSolid, concrete, "concreteCubeLogical"); new G4PVPlacement(0, G4ThreeVector(0., 0., 0.), concreteCubeLogical, "concreteCubePhysical", worldLogical, false, 0, checkOverlaps); //detectingSheets G4VSolid* detectingSheetSolid = new G4Box("detectingSheetBox", 0.5*m, 0.5*m, 0.00001*cm); for(G4int i = 0; i < 21; i++) { mDetectingSheets.push_back(new G4LogicalVolume(detectingSheetSolid, concrete, "detectingSheetLogical")); G4double z = (-100.*cm + i * 10.*cm); new G4PVPlacement(0, G4ThreeVector(0., 0., z), mDetectingSheets[i], "detectingSheetPhysical", concreteCubeLogical, false, 0, false); } G4VisAttributes* visAttributes = new G4VisAttributes(G4Colour(1.0,1.0,1.0)); visAttributes->SetVisibility(false); worldLogical->SetVisAttributes(visAttributes); mVisAttributes.push_back(visAttributes); /* visAttributes = new G4VisAttributes(G4Colour(0.0, 0.0, 0.9)); mDetectingSheets[0]->SetVisAttributes(visAttributes); mVisAttributes.push_back(visAttributes); visAttributes = new G4VisAttributes(G4Colour(0.0, 0.0, 0.9)); mDetectingSheets[100]->SetVisAttributes(visAttributes); mVisAttributes.push_back(visAttributes);*/ return worldPhysical; } void DetectorConstruction::ConstructSDandField() { G4String filterName, particleName; G4SDParticleFilter* muonFilter = new G4SDParticleFilter(filterName="muonFilter", particleName="mu+"); G4SDManager* SDman = G4SDManager::GetSDMpointer(); G4String SDname; for(G4int i = 0; i < 21; i++) { string name = "sheetSD" + to_string(i); mSensitiveDetectors.push_back(new SheetSD(SDname=name)); mSensitiveDetectors[i]->SetFilter(muonFilter); SDman->AddNewDetector(mSensitiveDetectors[i]); mDetectingSheets[i]->SetSensitiveDetector(mSensitiveDetectors[i]); } } void DetectorConstruction::ConstructMaterials() { G4NistManager* nistManager = G4NistManager::Instance(); //air nistManager->FindOrBuildMaterial("G4_AIR"); //concrete nistManager->FindOrBuildMaterial("G4_CONCRETE"); } <file_sep>/concrete/4GeV-concrete/4GeV-concrete-source/singleRunGenerator.py for i in range(500000): file = open("singleRunMacro.mac", "a"); file.write("/run/beamOn 1\n"); file.close(); <file_sep>/rho_0.9/4GeV_0.9/4GeV_0.9-source/src/SheetSD.cpp // // SheetSD.cpp // // // Created by <NAME>. // #include "SheetSD.hh" #include "SheetHit.hh" #include "G4HCofThisEvent.hh" #include "G4TouchableHistory.hh" #include "G4Track.hh" #include "G4Step.hh" #include "G4SDManager.hh" #include "G4ios.hh" SheetSD::SheetSD(G4String name) : G4VSensitiveDetector(name), mSheetHitsCollection(0), mHCID(-1) { G4String HCname = "sheetColl"; collectionName.insert(HCname); } SheetSD::~SheetSD() {} void SheetSD::Initialize(G4HCofThisEvent* hce) { mSheetHitsCollection = new SheetHitsCollection(SensitiveDetectorName,collectionName[0]); if (mHCID<0) { mHCID = G4SDManager::GetSDMpointer()->GetCollectionID(mSheetHitsCollection); } hce->AddHitsCollection(mHCID,mSheetHitsCollection); } G4bool SheetSD::ProcessHits(G4Step* step, G4TouchableHistory*) { G4StepPoint* preStepPoint = step->GetPreStepPoint(); G4TouchableHistory* touchable = (G4TouchableHistory*)(step->GetPreStepPoint()->GetTouchable()); G4ThreeVector localPos = preStepPoint->GetPosition(); G4ThreeVector momentumDir = preStepPoint->GetMomentumDirection(); G4ThreeVector* normal = new G4ThreeVector(0., 0., 1.); G4double angle = acos(normal->dot(momentumDir)); SheetHit* hit = new SheetHit(); hit->SetLocalPos(localPos); hit->SetMomentum(momentumDir); hit->SetAngle(angle); mSheetHitsCollection->insert(hit); return true; } <file_sep>/rho_1.5/500GeV_1.5/500GeV_1.5-source/src/Run.cpp #include "Run.hh" Run::Run() : G4Run() { } void Run::RecordEvent(const G4Event* evt) { G4Run::RecordEvent(evt); }
d0ccbb5cfda24785f9685bc0b183c266cb0c5a67
[ "Python", "C++" ]
16
C++
Jjwint1/muon-tomography
a0cd771603e5ec666eb90051b3cd9f5561f39125
88358367eca403f5ac62b53f9c1a89373021af77
refs/heads/master
<file_sep><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Javascript Events 6</title> <link rel="stylesheet" href="../css/style.css"> <script defer type="text/javascript" src="../js/6.app.js"></script> </head> <body> <h1>Using querySelector and querySelectorAll</h1> <div class="bullets"> <ul> <li class="b">Select Dom elements using Css Selectors.</li> <li class="b">compatible with all new browsers.</li> <li class="b">available on the document object and element nodes.</li> <li class="b">returns a static collection instead of a live collection</li> </ul> </div> <footer> <a href="http://www.allthingsjavascript.com">www.allthingsjavascript.com</a> </footer> </body> </html><file_sep>//the onclick event manipulator is the wrong way to do it. //document.querySelector("input").onclick = function(){alert("Hello World")}; //addEventListener is the right way to do it. document.querySelector("input").addEventListener("click", function(){ alert("Hello World"); }); //addEventListeners are faster and lighter than the onclick event manipulator.<file_sep>let form = document.getElementById("myForm"); function average(e) { e.preventDefault(); let value1 = Number(document.getElementById("n1").value); let value2 = Number(document.getElementById("n2").value); let value3 = Number(document.getElementById("n3").value); let avGrade = (value1 + value2 + value3) / 3; document.getElementById("resultado").innerHTML = avGrade.toFixed(2); console.log("form has been submitted"); } form.addEventListener("submit", average);<file_sep>let count = 0; document.querySelector("input").addEventListener("click", message); document.querySelector("input").addEventListener("click", aMessage); document.querySelector("input").addEventListener("click", function () { count++ document.querySelector("p").innerHTML = `The Result is ${count}`; }); function message() { alert("Hello World"); }; function aMessage () { alert("Hello Second"); }; //You can´t remove a eventListener if the function was defined inside the addEventListener method. document.querySelector("input").removeEventListener("click", aMessage); document.querySelector("input").removeEventListener("click", message);<file_sep>let menuBtn = document.querySelector(".menu-btn"); let menu = document.querySelector(".side"); let menuStatus = false; menu.style.display = "none"; function menuToggle() { if (menuStatus == false) { menu.style.display = "block"; menuBtn.style.width = "40%"; menuStatus = true; } else if (menuStatus == true) { menu.style.display = "none"; menuBtn.style.width = "20%"; menuStatus = false; } } menuBtn.addEventListener("click", menuToggle);<file_sep>let count = 0; document.querySelector("input").addEventListener("click", function () { alert("Hello World"); }); document.querySelector("input").addEventListener("click", function () { alert("Hello Second"); }); document.querySelector("input").addEventListener("click", function () { count++ document.querySelector("p").innerHTML = `The Result is ${count}`; }); //.innerHTML changes de inner HTML of the selected element class or id.
34cd3254a9bcb1b0c2fdefa64c6452db27ee541c
[ "JavaScript", "HTML" ]
6
HTML
Demouraa/js_events
f2d135d79d13f48729bced92815a38a5da82bbad
d11eb0ca660422bcf4f586d49e70cf82f11243df
refs/heads/master
<repo_name>jyd1122/ExaminationQ<file_sep>/PHP笔试真题/德思昂拉.md 有笔试,都是一些简单的问题,有一题要注意是要写冒泡排序法的,然后公司做的是国外的批发商城,用的是国外开源项目Magento2<file_sep>/PHP笔试真题/广州鸟窝科技/phpExam .php <?php /* 一.按照给定菜单(menu)和订单(order),计算订单价格总和 */ $menu = '[ {"type_id":1,"name":"大菜","food":[ {"food_id":1,"name":"鱼香肉丝","price":"10"}, {"food_id":2,"name":"红烧肉","price":"11"}, {"food_id":3,"name":"香辣粉","price":"12"} ]}, {"type_id":2,"name":"中菜","food":[ {"food_id":4,"name":"小炒肉","price":"13"}, {"food_id":5,"name":"云吞","price":"14"} ]}, {"type_id":3,"name":"小菜","food":[ {"food_id":6,"name":"雪糕","price":"15"}, {"food_id":7,"name":"黄瓜","price":"16"} ]} ]'; /* */ //num系数量 $order = '[{"food_id":1,"num":2},{"food_id":3,"num":1},{"food_id":6,"num":2},{"food_id":7,"num":1}]'; /* 二.设计一个类Menu,实现以下功能: 1. 设定菜单,每个实例必须有且只有一个菜单(json字符串,结构如上题) 2. 方法calculate, 输入订单后(json字符串,结构如上题), 输出格价 3. 方法discount, 可设定折扣,输出格价时自动计算折扣 4. 静态方法counter。输出calculate方法被调用的次数 5. 将结果发送到<EMAIL>,邮件标题写上姓名,谢谢! */ <file_sep>/PHP笔试真题/面试题1/question.php <?php header( 'Content-Type:text/html;charset=utf-8 '); //1.用函数打印出后天的日期,输出格式为(Y-M-D); echo date('Y-m-d',strtotime('+2 days')); echo '<hr/>'; //2.$f=2.1,用函数格式华为保留两位小数2.10;$d=10000000,用函数输出格式化整数,10,000,000 $f=2.1; $d=10000000; echo number_format($f,2); echo '<br/>'; echo number_format($d); //echo number_format($d,2,'.',',');保留小数点后两位,小数点已'.',千位分隔符已',' echo '<hr/>'; //3.语句include和require的区别是什么?为了避免多次包含同一文件,应该如何处理?可用什么函数代替他们! // 答: include有条件包含,如果文件不存在会给出一个warning,但脚本会继续执行;require无条件包含,如果文件不存在会报致命错误,脚本停止执行。可用require_once或者include_once。可以检测文件是否重复包含。 //4.简单描述echo,print,print_r()之间的区别 //答:echo 不是函数,是一个语言结构。print输入字符串,print_r 可以打印变量值本身。给出的是 array,将会按照一定格式显示键和元素。object 与数组类似。 //5.用PHP写出显示客户端IP和服务器IP? echo $_SERVER['REMOTE_ADDR']."<BR/>"; echo getenv('REMOTE_ADDR')."<HR/>"; //::1说明你的电脑开启了ipv6支持,这是ipv6下的本地回环地址的表示。因为你访问的时候用的是localhost访问的,是正常情况。使用ip地址访问或者关闭ipv6支持都可以不显示这个。 //6.用函数获取http://www.baidu.com/网页内容标签<title></title> //$content=file_get_contents("http://www.qilong.com/"); //$postb=strpos($content,'<title>')+7; //$poste=strpos($content,'</title>'); //$length=$poste-$postb; //echo substr($content,$postb,$length); $c = curl_init(); $url = 'http://www.baidu.com/'; curl_setopt($c, CURLOPT_URL, $url); curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); $data = curl_exec($c); curl_close($c); $pos = strpos($data,'utf-8'); if($pos===false){$data = iconv("gbk","utf-8",$data);} preg_match("/<title>(.*)<\/title>/i",$data, $title); echo $title[1]."<hr/>"; //7.你用什么工具来进行版本控制的。请写出的用过、熟悉的PHP开源系统有哪些?模板?框架 //答:svn,git; phpcms,ddcms,ecshop; smarty,template; ci,tp,yii,yaf //8.写一个正则表达式,过滤网页上所有的JS脚本(即把script标记及其内容都去掉) preg_match("/<script.*?>.*?<\/script>/ig"); $script="以下内容不显示:"; echo preg_replace("/].*?>.*?/si", "替换内容", $script); <file_sep>/PHP笔试真题/本汀渔具.md 有笔试题,而且都不容易,但是其他人就在你旁边,拍不了试题,填完笔试题后会有技术跟你聊,不止简历上的内容,会扩展,对数据结构这块问的比较多,对缓存也挺感兴趣,做的是商城项目,已经做了6年了,现在想把重心转到线上<file_sep>/PHP笔试真题/潜行者.md 没有笔试,一个前端的跟你聊,然后是经理跟你聊,因为公司只有一个php正在办理离职,使用的是Laravel框架,要求能快速接手项目,做的是APP<file_sep>/README.md # ExaminationQ ### 部分企业笔试真题 <file_sep>/PHP笔试真题/七锦宫.md 会问你PHP运行模式有哪些, PHP是什么类型,CLI什么的,还有LINUX/LAMP/LNMP这一类相关常见的操作. 比如查看进程,杀死进程什么的.<file_sep>/PHP笔试真题/闻喜科技.md 有笔试题,但是都很简单,看过就业老师发的笔试题的都能答出来,只有最后一题加分题很难,然后有两个人面试,一个问完另外一个问,会当场查看你的项目(如已上线),顺便问你的一些功能的具体实现步骤,是外包公司,基本一个人负责一个项目,大小周休息<file_sep>/PHP笔试真题/广州微电互动面试.md 广州微电互动面试: 1.看简历负责什么项目,问是否一人开发,团队几人,有没有做好前端 2.什么样的项目适合PHP开发,项目基于什么框架开发,有原生开发过没 3.不同域名间怎么共享SESSION,主要应用单点登录系统,授权登录方面的知识 4.主要开HTML5游戏,HTML5游戏微信公众号开发 比如: 腾讯游戏频道(微信号:txgames) 4399小游戏(微信号:ixyx4399) 5秒轻游戏(微信号:qyx5miao) 5.问PHP的发展趋势,个人职业发展<file_sep>/PHP笔试真题/投一/投一.md echo(),print(),print_r()的区别 用PHP写出显示客户端IP与服务器IP的代码 语句include和require的区别是什么?为避免多次包含同一文件,可用(?)语句代替它们? 有一个网页地址, 比如PHP开发资源网主页: http://www.phpres.com/index.html,如何得到它的内容? 写出发贴数最多的十个人名字的SQL,利用下表:members(id,username,posts,pass,email)<file_sep>/PHP笔试真题/赛百威.md 赛百威面试提问: 1,linux中查找文件的命令?修改权限的命令?777是什么意思? 2,查找数据时有索引和没索引的区别,分别查找多少次? 3,高并发时数据库怎么优化? 4,抢购时怎么防止多线程同时写入? 5,memcache和redis的区别,他们的单个key值分别是多大? 6,laravel的路由跟tp的区别?有接触过yii和ci框架吗? 7,说说支付宝支付具体流程? 8,购物车模块中的cookie数据什么时候存进数据库? 9,大数据时session怎么存储? 10,抢购时需要几台服务器?分别处理什么逻辑?<file_sep>/PHP笔试真题/广州台大喜信息科技有限公司.md # 广州台大喜信息科技有限公司 ## 基本情况 公司地址:广州白云区永泰丛云路818号柏丰商务大厦A702 特点:公司规模不大,做集成系统开发,需要自己买社保 流程:没有笔试,填写登记表,人事面试---技术经理面试 ## 面试题(不分次序): ### 人事 1.介绍一下建网站的流程 2.根据登记表上你填的职业规划进行发问 3.过往的经历,然后根据你回答的内容去细问 ### 技术经理 1.你做过哪些项目 2.在项目过程中有遇到什么比较困难的难题,怎么解决 3.商城项目中哪张表的数据最多 4.你使用过哪些数据库 5.如果给你一个项目(社区类)的项目,使用你熟悉的框架,大概需要多久能独立完成 6.怎样在商品表中不用商品分类id字段找出相同分类的数据 PS:最后技术经理给我看了下他们准备做的项目,一个交互文档,是一个类似社区论坛的项目,包含注册登录功能,发帖子等等 <file_sep>/PHP笔试真题/广州鸟窝科技/phpExam(1).php <?php /*一.按照给定菜单(menu)和订单(order),计算订单价格总和*/ $menu = '[ {"type_id":1,"name":"大菜","food":[ {"food_id":1,"name":"鱼香肉丝","price":"10"}, {"food_id":2,"name":"红烧肉","price":"11"}, {"food_id":3,"name":"香辣粉","price":"12"} ]}, {"type_id":2,"name":"中菜","food":[ {"food_id":4,"name":"小炒肉","price":"13"}, {"food_id":5,"name":"云吞","price":"14"} ]}, {"type_id":3,"name":"小菜","food":[ {"food_id":6,"name":"雪糕","price":"15"}, {"food_id":7,"name":"黄瓜","price":"16"} ]} ]'; $order = '[{"food_id":1,"num":2},{"food_id":3,"num":1},{"food_id":6,"num":2},{"food_id":7,"num":1}]'; $menu = array_column( json_decode( $menu, true ), 'food' ); $menu_data = []; foreach ($menu as $item) { $menu_data = array_merge( $menu_data, $item ); } $price = 0; $order = json_decode( $order, true ); foreach ( $order as $detail ) { foreach ( $menu_data as $menu ) { if ( $menu['food_id'] == $detail['food_id'] ) { $price += $menu['price'] * $detail['num']; } } } echo '一:<br>本次应付金额为:' . $price; echo '<hr>'; /****************************************分割线************************************************/ /* 二.设计一个类Menu,实现以下功能: 1. 设定菜单,每个实例必须有且只有一个菜单(json字符串,结构如上题) 2. 方法calculate, 输入订单后(json字符串,结构如上题), 输出格价 3. 方法discount, 可设定折扣,输出格价时自动计算折扣 4. 静态方法counter。输出calculate方法被调用的次数 5. 将结果发送到<EMAIL>,邮件标题写上姓名,谢谢! */ class Menu { public $menu; public static $count; public function __construct( $menu = null ) { $this->menu = $menu; } /** * @param $order type:json 订单 * @param $discount type:int 折扣 * @return $price type:int 最终价格 */ public function calculate( $order, $discount = 0 ) { $menu = array_column( json_decode($this->menu, true), 'food' ); $order = json_decode( $order, true ); $menu_data = []; foreach ( $menu as $v ) { $menu_data = array_merge( $menu_data, $v ); } $price = 0; foreach ( $order as $item ) { foreach ($menu_data as $info) { if ($info['food_id'] == $item['food_id']) { $price += $info['price'] * $item['num']; } } } self::$count += 1; if ( $discount != 0 ) { $price = $this->discount( $discount, $price ); return $price; } return $price; } /** * @param $discount type:int 折扣 * @param $price type:int 总价 * @return type:int 打完折后的价格 */ public function discount( $discount, $price ) { return $price * ( $discount / 10 ); } /** * @return $count type:int 下单次数 * 本来是应该是存储为持久化数据在数据库或者redis中 */ public static function counter() { return self::$count; } } $menu = !empty( $_GET['menu'] ) ? $_GET['menu'] : '[ {"type_id":1,"name":"大菜","food":[ {"food_id":1,"name":"鱼香肉丝","price":"10"}, {"food_id":2,"name":"红烧肉","price":"11"}, {"food_id":3,"name":"香辣粉","price":"12"} ]}, {"type_id":2,"name":"中菜","food":[ {"food_id":4,"name":"小炒肉","price":"13"}, {"food_id":5,"name":"云吞","price":"14"} ]}, {"type_id":3,"name":"小菜","food":[ {"food_id":6,"name":"雪糕","price":"15"}, {"food_id":7,"name":"黄瓜","price":"16"} ]} ]'; $order = !empty( $_GET['order'] ) ? $_GET['order'] : '[{"food_id":1,"num":2},{"food_id":3,"num":1},{"food_id":6,"num":2},{"food_id":7,"num":1}]'; $Menu = new Menu( $menu ); $price1 = $Menu -> calculate( $order, 5 ); $price2 = $Menu -> calculate( $order, 6 ); $price3 = $Menu -> calculate( $order, 7 ); echo '二:<br>'; echo '订单1打完5折后的价格是' . $price1 . '<br>'; echo '订单2打完6折后的价格是' . $price2 . '<br>'; echo '订单3打完7折后的价格是' . $price3 . '<br>'; echo '今天总共有:' . Menu::counter() . '张订单';
6ffd4f3322cb7e4367006ef370905191baaf031e
[ "Markdown", "PHP" ]
13
Markdown
jyd1122/ExaminationQ
7165f1385b455c2e0e053ff9e5437757e420425b
29c5279522dcd8b18065ffe66c4ecc4991d11dbc
refs/heads/master
<repo_name>99property/dashboard<file_sep>/src/components/rightsection.js import React, { Component } from 'react' export default class rightsection extends Component { render() { return ( <div className="space-left5 col12"> <div className=""> <div className="clearfix"> <div data-title="Our API" className="keyline-top section contain clearfix "> <h2 id="our-api">Lorem Ipsum</h2> <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry standard dummy text ever since the 150 when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </p> </div> </div> </div> </div> ) } }
ce35c7128731246ea4250f8de1e16a3cd3b13709
[ "JavaScript" ]
1
JavaScript
99property/dashboard
16368b2e65711a45b8bfb4bf290cdd1047508103
ac2671f324085d785cccb68dc150fb0160652bf4
refs/heads/master
<repo_name>Blockchain-Mexico/0x-launch-kit-backend<file_sep>/ts/src/middleware/url_params_parsing.ts import * as express from 'express'; import * as _ from 'lodash'; import { CHAIN_ID } from '../config'; import { ValidationError } from '../errors'; /** * Parses URL params and stores them on the request object */ export function urlParamsParsing(req: express.Request, _res: express.Response, next: express.NextFunction): void { const chainId = parseChainId(req.query.chainId); // HACK: This is the recommended way to pass data from middlewares on. It's not beautiful nor fully type-safe. (req as any).chainId = chainId; next(); } function parseChainId(chainIdStrIfExists?: string): number { if (chainIdStrIfExists === undefined) { return CHAIN_ID; } else { const chainId = _.parseInt(chainIdStrIfExists); if (chainId !== CHAIN_ID) { const validationErrorItem = { field: 'chainId', code: 1004, reason: `Incorrect Chain ID: ${chainIdStrIfExists}`, }; throw new ValidationError([validationErrorItem]); } return chainId; } } <file_sep>/ts/src/runners/order_watcher_service_runner.ts import { WSClient } from '@0x/mesh-rpc-client'; import 'reflect-metadata'; import * as config from '../config'; import { initDBConnectionAsync } from '../db_connection'; import { OrderWatcherService } from '../services/order_watcher_service'; import { utils } from '../utils'; /** * This service is a simple writer from the Mesh events. On order discovery * or an order update it will be persisted to the database. It also is responsible * for syncing the database with Mesh on start or after a disconnect. */ (async () => { await initDBConnectionAsync(); utils.log(`Order Watching Service started!\nConfig: ${JSON.stringify(config, null, 2)}`); const meshClient = new WSClient(config.MESH_ENDPOINT); const orderWatcherService = new OrderWatcherService(meshClient); await orderWatcherService.syncOrderbookAsync(); })().catch(utils.log); <file_sep>/ts/src/runners/http_service_runner.ts import { WSClient } from '@0x/mesh-rpc-client'; import * as express from 'express'; import 'reflect-metadata'; import * as config from '../config'; import { initDBConnectionAsync } from '../db_connection'; import { HttpService } from '../services/http_service'; import { OrderBookService } from '../services/orderbook_service'; import { utils } from '../utils'; /** * This service handles the HTTP requests. This involves fetching from the database * as well as adding orders to mesh. */ (async () => { await initDBConnectionAsync(); const app = express(); app.listen(config.HTTP_PORT, () => { utils.log( `Standard relayer API (HTTP) listening on port ${config.HTTP_PORT}!\nConfig: ${JSON.stringify( config, null, 2, )}`, ); }); const meshClient = new WSClient(config.MESH_ENDPOINT); const orderBookService = new OrderBookService(meshClient); // tslint:disable-next-line:no-unused-expression new HttpService(app, orderBookService); })().catch(utils.log); <file_sep>/ts/src/config.ts // tslint:disable:custom-no-magic-numbers import { assert } from '@0x/assert'; import { BigNumber } from '@0x/utils'; import * as crypto from 'crypto'; import * as fs from 'fs'; import * as _ from 'lodash'; import * as path from 'path'; import { NULL_BYTES } from './constants'; const metadataPath = path.join(__dirname, '../../metadata.json'); enum EnvVarType { Port, ChainId, FeeRecipient, UnitAmount, Url, WhitelistAllTokens, Boolean, FeeAssetData, } // Whitelisted token addresses. Set to a '*' instead of an array to allow all tokens. export const WHITELISTED_TOKENS: string[] | '*' = _.isEmpty(process.env.WHITELIST_ALL_TOKENS) ? [ '0x2002d3812f58e35f0ea1ffbf80a75a38c32175fa', // ZRX on Kovan '0xd0a1e359811322d97991e03f863a0c30c2cf029c', // WETH on Kovan ] : assertEnvVarType('WHITELIST_ALL_TOKENS', process.env.WHITELIST_ALL_TOKENS, EnvVarType.WhitelistAllTokens); // Network port to listen on export const HTTP_PORT = _.isEmpty(process.env.HTTP_PORT) ? 3000 : assertEnvVarType('HTTP_PORT', process.env.HTTP_PORT, EnvVarType.Port); // Default chain id to use when not specified export const CHAIN_ID = _.isEmpty(process.env.CHAIN_ID) ? 42 : assertEnvVarType('CHAIN_ID', process.env.CHAIN_ID, EnvVarType.ChainId); // Mesh Endpoint export const MESH_ENDPOINT = _.isEmpty(process.env.MESH_ENDPOINT) ? 'ws://localhost:60557' : assertEnvVarType('MESH_ENDPOINT', process.env.MESH_ENDPOINT, EnvVarType.Url); // The fee recipient for orders export const FEE_RECIPIENT = _.isEmpty(process.env.FEE_RECIPIENT) ? getDefaultFeeRecipient() : assertEnvVarType('FEE_RECIPIENT', process.env.FEE_RECIPIENT, EnvVarType.FeeRecipient); // A flat fee that should be charged to the order maker export const MAKER_FEE_UNIT_AMOUNT = _.isEmpty(process.env.MAKER_FEE_UNIT_AMOUNT) ? new BigNumber(0) : assertEnvVarType('MAKER_FEE_UNIT_AMOUNT', process.env.MAKER_FEE_UNIT_AMOUNT, EnvVarType.UnitAmount); // A flat fee that should be charged to the order taker export const TAKER_FEE_UNIT_AMOUNT = _.isEmpty(process.env.TAKER_FEE_UNIT_AMOUNT) ? new BigNumber(0) : assertEnvVarType('TAKER_FEE_UNIT_AMOUNT', process.env.TAKER_FEE_UNIT_AMOUNT, EnvVarType.UnitAmount); // The maker fee token encoded as asset data export const MAKER_FEE_ASSET_DATA = _.isEmpty(process.env.MAKER_FEE_ASSET_DATA) ? NULL_BYTES : assertEnvVarType('MAKER_FEE_ASSET_DATA', process.env.MAKER_FEE_ASSET_DATA, EnvVarType.FeeAssetData); // The taker fee token encoded as asset data export const TAKER_FEE_ASSET_DATA = _.isEmpty(process.env.TAKER_FEE_ASSET_DATA) ? NULL_BYTES : assertEnvVarType('TAKER_FEE_ASSET_DATA', process.env.TAKER_FEE_ASSET_DATA, EnvVarType.FeeAssetData); // Max number of entities per page export const MAX_PER_PAGE = 1000; // Default ERC20 token precision export const DEFAULT_ERC20_TOKEN_PRECISION = 18; // Address used when simulating transfers from the maker as part of 0x order validation export const DEFAULT_TAKER_SIMULATION_ADDRESS = '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; function assertEnvVarType(name: string, value: any, expectedType: EnvVarType): any { let returnValue; switch (expectedType) { case EnvVarType.Port: try { returnValue = parseInt(value, 10); const isWithinRange = returnValue >= 0 && returnValue <= 65535; if (!isWithinRange) { throw new Error(); } } catch (err) { throw new Error(`${name} must be between 0 to 65535, found ${value}.`); } return returnValue; case EnvVarType.ChainId: try { returnValue = parseInt(value, 10); } catch (err) { throw new Error(`${name} must be a valid integer, found ${value}.`); } return returnValue; case EnvVarType.FeeRecipient: assert.isETHAddressHex(name, value); return value; case EnvVarType.Url: assert.isUri(name, value); return value; case EnvVarType.Boolean: return value === 'true'; case EnvVarType.UnitAmount: try { returnValue = new BigNumber(parseFloat(value)); if (returnValue.isNegative()) { throw new Error(); } } catch (err) { throw new Error(`${name} must be valid number greater than 0.`); } return returnValue; case EnvVarType.WhitelistAllTokens: return '*'; case EnvVarType.FeeAssetData: assert.isString(name, value); return value; default: throw new Error(`Unrecognised EnvVarType: ${expectedType} encountered for variable ${name}.`); } } function getDefaultFeeRecipient(): string { const metadata = JSON.parse(fs.readFileSync(metadataPath).toString()); const existingDefault: string = metadata.DEFAULT_FEE_RECIPIENT; const newDefault: string = existingDefault || `0xabcabc${crypto.randomBytes(17).toString('hex')}`; if (_.isEmpty(existingDefault)) { const metadataCopy = JSON.parse(JSON.stringify(metadata)); metadataCopy.DEFAULT_FEE_RECIPIENT = newDefault; fs.writeFileSync(metadataPath, JSON.stringify(metadataCopy)); } return newDefault; } <file_sep>/ts/src/runners/websocket_service_runner.ts import { WSClient } from '@0x/mesh-rpc-client'; import * as express from 'express'; import 'reflect-metadata'; import * as config from '../config'; import { initDBConnectionAsync } from '../db_connection'; import { WebsocketService } from '../services/websocket_service'; import { utils } from '../utils'; /** * This service handles websocket updates using a subscription from Mesh. */ (async () => { await initDBConnectionAsync(); const app = express(); const server = app.listen(config.HTTP_PORT, () => { utils.log( `Standard relayer API (WS) listening on port ${config.HTTP_PORT}!\nConfig: ${JSON.stringify( config, null, 2, )}`, ); }); const meshClient = new WSClient(config.MESH_ENDPOINT); // tslint:disable-next-line:no-unused-expression new WebsocketService(server, meshClient); })().catch(utils.log); <file_sep>/js/constants.js 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var utils_1 = require('@0x/utils'); exports.NULL_ADDRESS = '0x0000000000000000000000000000000000000000'; exports.NULL_BYTES = '0x'; exports.ZRX_DECIMALS = 18; exports.DEFAULT_PAGE = 1; exports.DEFAULT_PER_PAGE = 20; exports.ZERO = new utils_1.BigNumber(0); exports.MAX_TOKEN_SUPPLY_POSSIBLE = new utils_1.BigNumber(2).pow(256); // tslint:disable-line custom-no-magic-numbers <file_sep>/ts/src/types.ts import { AcceptedOrderInfo, RejectedOrderInfo } from '@0x/mesh-rpc-client'; import { APIOrder, OrdersChannelSubscriptionOpts, UpdateOrdersChannelMessage } from '@0x/types'; import { BigNumber } from '@0x/utils'; export enum OrderWatcherLifeCycleEvents { Added, Removed, Updated, } export type onOrdersUpdateCallback = (orders: APIOrderWithMetaData[]) => void; export interface AcceptedRejectedResults { accepted: AcceptedOrderInfo[]; rejected: RejectedOrderInfo[]; } export interface APIOrderMetaData { orderHash: string; remainingFillableTakerAssetAmount: BigNumber; } export interface APIOrderWithMetaData extends APIOrder { metaData: APIOrderMetaData; } export interface WebsocketSRAOpts { pongInterval?: number; } export interface OrderChannelRequest { type: string; channel: MessageChannels; requestId: string; payload?: OrdersChannelSubscriptionOpts; } export enum MessageTypes { Subscribe = 'subscribe', } export enum MessageChannels { Orders = 'orders', } export interface UpdateOrdersChannelMessageWithChannel extends UpdateOrdersChannelMessage { channel: MessageChannels; } <file_sep>/ts/src/services/orderbook_service.ts import { APIOrder, OrderbookResponse, PaginatedCollection } from '@0x/connect'; import { WSClient } from '@0x/mesh-rpc-client'; import { assetDataUtils } from '@0x/order-utils'; import { AssetPairsItem, OrdersRequestOpts, SignedOrder } from '@0x/types'; import * as _ from 'lodash'; import { getDBConnection } from '../db_connection'; import { ValidationError } from '../errors'; import { MeshUtils } from '../mesh_utils'; import { SignedOrderModel } from '../models/SignedOrderModel'; import { paginate } from '../paginator'; import { compareAskOrder, compareBidOrder, deserializeOrder, deserializeOrderToAPIOrder, includesTokenAddress, signedOrderToAssetPair, } from './orderbook_utils'; export class OrderBookService { private readonly _meshClient: WSClient; public static async getOrderByHashIfExistsAsync(orderHash: string): Promise<APIOrder | undefined> { const connection = getDBConnection(); const signedOrderModelIfExists = await connection.manager.findOne(SignedOrderModel, orderHash); if (signedOrderModelIfExists === undefined) { return undefined; } else { const deserializedOrder = deserializeOrderToAPIOrder(signedOrderModelIfExists as Required< SignedOrderModel >); return deserializedOrder; } } public static async getAssetPairsAsync( page: number, perPage: number, assetDataA: string, assetDataB: string, ): Promise<PaginatedCollection<AssetPairsItem>> { const connection = getDBConnection(); const signedOrderModels = (await connection.manager.find(SignedOrderModel)) as Array< Required<SignedOrderModel> >; const assetPairsItems: AssetPairsItem[] = signedOrderModels.map(deserializeOrder).map(signedOrderToAssetPair); let nonPaginatedFilteredAssetPairs: AssetPairsItem[]; if (assetDataA === undefined && assetDataB === undefined) { nonPaginatedFilteredAssetPairs = assetPairsItems; } else if (assetDataA !== undefined && assetDataB !== undefined) { const containsAssetDataAAndAssetDataB = (assetPair: AssetPairsItem) => (assetPair.assetDataA.assetData === assetDataA && assetPair.assetDataB.assetData === assetDataB) || (assetPair.assetDataA.assetData === assetDataB && assetPair.assetDataB.assetData === assetDataA); nonPaginatedFilteredAssetPairs = assetPairsItems.filter(containsAssetDataAAndAssetDataB); } else { const assetData = assetDataA || assetDataB; const containsAssetData = (assetPair: AssetPairsItem) => assetPair.assetDataA.assetData === assetData || assetPair.assetDataB.assetData === assetData; nonPaginatedFilteredAssetPairs = assetPairsItems.filter(containsAssetData); } const uniqueNonPaginatedFilteredAssetPairs = _.uniqWith(nonPaginatedFilteredAssetPairs, _.isEqual.bind(_)); const paginatedFilteredAssetPairs = paginate(uniqueNonPaginatedFilteredAssetPairs, page, perPage); return paginatedFilteredAssetPairs; } // tslint:disable-next-line:prefer-function-over-method public async getOrderBookAsync( page: number, perPage: number, baseAssetData: string, quoteAssetData: string, ): Promise<OrderbookResponse> { const connection = getDBConnection(); const bidSignedOrderModels = (await connection.manager.find(SignedOrderModel, { where: { takerAssetData: baseAssetData, makerAssetData: quoteAssetData }, })) as Array<Required<SignedOrderModel>>; const askSignedOrderModels = (await connection.manager.find(SignedOrderModel, { where: { takerAssetData: quoteAssetData, makerAssetData: baseAssetData }, })) as Array<Required<SignedOrderModel>>; const bidApiOrders: APIOrder[] = bidSignedOrderModels .map(deserializeOrderToAPIOrder) .sort((orderA, orderB) => compareBidOrder(orderA.order, orderB.order)); const askApiOrders: APIOrder[] = askSignedOrderModels .map(deserializeOrderToAPIOrder) .sort((orderA, orderB) => compareAskOrder(orderA.order, orderB.order)); const paginatedBidApiOrders = paginate(bidApiOrders, page, perPage); const paginatedAskApiOrders = paginate(askApiOrders, page, perPage); return { bids: paginatedBidApiOrders, asks: paginatedAskApiOrders, }; } // TODO:(leo) Do all filtering and pagination in a DB (requires stored procedures or redundant fields) // tslint:disable-next-line:prefer-function-over-method public async getOrdersAsync( page: number, perPage: number, ordersFilterParams: OrdersRequestOpts, ): Promise<PaginatedCollection<APIOrder>> { const connection = getDBConnection(); // Pre-filters const filterObjectWithValuesIfExist: Partial<SignedOrder> = { exchangeAddress: ordersFilterParams.exchangeAddress, senderAddress: ordersFilterParams.senderAddress, makerAssetData: ordersFilterParams.makerAssetData, takerAssetData: ordersFilterParams.takerAssetData, makerAddress: ordersFilterParams.makerAddress, takerAddress: ordersFilterParams.takerAddress, feeRecipientAddress: ordersFilterParams.feeRecipientAddress, makerFeeAssetData: ordersFilterParams.makerFeeAssetData, takerFeeAssetData: ordersFilterParams.takerFeeAssetData, }; const filterObject = _.pickBy(filterObjectWithValuesIfExist, _.identity.bind(_)); const signedOrderModels = (await connection.manager.find(SignedOrderModel, { where: filterObject })) as Array< Required<SignedOrderModel> >; let apiOrders = _.map(signedOrderModels, deserializeOrderToAPIOrder); // Post-filters apiOrders = apiOrders .filter( // traderAddress apiOrder => ordersFilterParams.traderAddress === undefined || apiOrder.order.makerAddress === ordersFilterParams.traderAddress || apiOrder.order.takerAddress === ordersFilterParams.traderAddress, ) .filter( // makerAssetAddress apiOrder => ordersFilterParams.makerAssetAddress === undefined || includesTokenAddress(apiOrder.order.makerAssetData, ordersFilterParams.makerAssetAddress), ) .filter( // takerAssetAddress apiOrder => ordersFilterParams.takerAssetAddress === undefined || includesTokenAddress(apiOrder.order.takerAssetData, ordersFilterParams.takerAssetAddress), ) .filter( // makerAssetProxyId apiOrder => ordersFilterParams.makerAssetProxyId === undefined || assetDataUtils.decodeAssetDataOrThrow(apiOrder.order.makerAssetData).assetProxyId === ordersFilterParams.makerAssetProxyId, ) .filter( // takerAssetProxyId apiOrder => ordersFilterParams.takerAssetProxyId === undefined || assetDataUtils.decodeAssetDataOrThrow(apiOrder.order.takerAssetData).assetProxyId === ordersFilterParams.takerAssetProxyId, ); const paginatedApiOrders = paginate(apiOrders, page, perPage); return paginatedApiOrders; } constructor(meshClient: WSClient) { this._meshClient = meshClient; } public async addOrderAsync(signedOrder: SignedOrder): Promise<void> { const { rejected } = await this._meshClient.addOrdersAsync([signedOrder], true); if (rejected.length !== 0) { throw new ValidationError([ { field: 'signedOrder', code: MeshUtils.rejectedCodeToSRACode(rejected[0].status.code), reason: `${rejected[0].status.code}: ${rejected[0].status.message}`, }, ]); } // Order Watcher Service will handle persistence } } <file_sep>/js/fee_strategy.js 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var config_1 = require('./config'); var constants_1 = require('./constants'); exports.fixedFeeStrategy = { getOrderConfig: function(_order) { var normalizedFeeRecipient = config_1.FEE_RECIPIENT.toLowerCase(); var orderConfigResponse = { senderAddress: constants_1.NULL_ADDRESS, feeRecipientAddress: normalizedFeeRecipient, makerFee: config_1.MAKER_FEE_UNIT_AMOUNT, takerFee: config_1.TAKER_FEE_UNIT_AMOUNT, makerFeeAssetData: config_1.MAKER_FEE_ASSET_DATA, takerFeeAssetData: config_1.TAKER_FEE_ASSET_DATA, }; return orderConfigResponse; }, }; <file_sep>/js/services/http_service.js 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var bodyParser = require('body-parser'); var cors = require('cors'); var asyncHandler = require('express-async-handler'); require('reflect-metadata'); var handlers_1 = require('../handlers'); var error_handling_1 = require('../middleware/error_handling'); var url_params_parsing_1 = require('../middleware/url_params_parsing'); // tslint:disable-next-line:no-unnecessary-class var HttpService = /** @class */ (function() { function HttpService(app, orderBook) { var handlers = new handlers_1.Handlers(orderBook); app.use(cors()); app.use(bodyParser.json()); app.use(url_params_parsing_1.urlParamsParsing); /** * GET AssetPairs endpoint retrieves a list of available asset pairs and the information required to trade them. * http://sra-spec.s3-website-us-east-1.amazonaws.com/#operation/getAssetPairs */ app.get('/v3/asset_pairs', asyncHandler(handlers_1.Handlers.assetPairsAsync.bind(handlers_1.Handlers))); /** * GET Orders endpoint retrieves a list of orders given query parameters. * http://sra-spec.s3-website-us-east-1.amazonaws.com/#operation/getOrders */ app.get('/v3/orders', asyncHandler(handlers.ordersAsync.bind(handlers))); /** * GET Orderbook endpoint retrieves the orderbook for a given asset pair. * http://sra-spec.s3-website-us-east-1.amazonaws.com/#operation/getOrderbook */ app.get('/v3/orderbook', asyncHandler(handlers.orderbookAsync.bind(handlers))); /** * GET FeeRecepients endpoint retrieves a collection of all fee recipient addresses for a relayer. * http://sra-spec.s3-website-us-east-1.amazonaws.com/v3/fee_recipients */ app.get('/v3/fee_recipients', handlers_1.Handlers.feeRecipients.bind(handlers_1.Handlers)); /** * POST Order config endpoint retrives the values for order fields that the relayer requires. * http://sra-spec.s3-website-us-east-1.amazonaws.com/#operation/getOrderConfig */ app.post('/v3/order_config', handlers_1.Handlers.orderConfig.bind(handlers_1.Handlers)); /** * POST Order endpoint submits an order to the Relayer. * http://sra-spec.s3-website-us-east-1.amazonaws.com/#operation/postOrder */ app.post('/v3/order', asyncHandler(handlers.postOrderAsync.bind(handlers))); /** * GET Order endpoint retrieves the order by order hash. * http://sra-spec.s3-website-us-east-1.amazonaws.com/#operation/getOrder */ app.get( '/v3/order/:orderHash', asyncHandler(handlers_1.Handlers.getOrderByHashAsync.bind(handlers_1.Handlers)), ); app.use(error_handling_1.errorHandler); } return HttpService; })(); exports.HttpService = HttpService; <file_sep>/ts/src/services/http_service.ts import * as bodyParser from 'body-parser'; import * as cors from 'cors'; import * as asyncHandler from 'express-async-handler'; // tslint:disable-next-line:no-implicit-dependencies import * as core from 'express-serve-static-core'; import 'reflect-metadata'; import { Handlers } from '../handlers'; import { errorHandler } from '../middleware/error_handling'; import { urlParamsParsing } from '../middleware/url_params_parsing'; import { OrderBookService } from '../services/orderbook_service'; // tslint:disable-next-line:no-unnecessary-class export class HttpService { constructor(app: core.Express, orderBook: OrderBookService) { const handlers = new Handlers(orderBook); app.use(cors()); app.use(bodyParser.json()); app.use(urlParamsParsing); /** * GET AssetPairs endpoint retrieves a list of available asset pairs and the information required to trade them. * http://sra-spec.s3-website-us-east-1.amazonaws.com/#operation/getAssetPairs */ app.get('/v3/asset_pairs', asyncHandler(Handlers.assetPairsAsync.bind(Handlers))); /** * GET Orders endpoint retrieves a list of orders given query parameters. * http://sra-spec.s3-website-us-east-1.amazonaws.com/#operation/getOrders */ app.get('/v3/orders', asyncHandler(handlers.ordersAsync.bind(handlers))); /** * GET Orderbook endpoint retrieves the orderbook for a given asset pair. * http://sra-spec.s3-website-us-east-1.amazonaws.com/#operation/getOrderbook */ app.get('/v3/orderbook', asyncHandler(handlers.orderbookAsync.bind(handlers))); /** * GET FeeRecepients endpoint retrieves a collection of all fee recipient addresses for a relayer. * http://sra-spec.s3-website-us-east-1.amazonaws.com/v3/fee_recipients */ app.get('/v3/fee_recipients', Handlers.feeRecipients.bind(Handlers)); /** * POST Order config endpoint retrives the values for order fields that the relayer requires. * http://sra-spec.s3-website-us-east-1.amazonaws.com/#operation/getOrderConfig */ app.post('/v3/order_config', Handlers.orderConfig.bind(Handlers)); /** * POST Order endpoint submits an order to the Relayer. * http://sra-spec.s3-website-us-east-1.amazonaws.com/#operation/postOrder */ app.post('/v3/order', asyncHandler(handlers.postOrderAsync.bind(handlers))); /** * GET Order endpoint retrieves the order by order hash. * http://sra-spec.s3-website-us-east-1.amazonaws.com/#operation/getOrder */ app.get('/v3/order/:orderHash', asyncHandler(Handlers.getOrderByHashAsync.bind(Handlers))); app.use(errorHandler); } } <file_sep>/js/middleware/url_params_parsing.js 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _ = require('lodash'); var config_1 = require('../config'); var errors_1 = require('../errors'); /** * Parses URL params and stores them on the request object */ function urlParamsParsing(req, _res, next) { var chainId = parseChainId(req.query.chainId); // HACK: This is the recommended way to pass data from middlewares on. It's not beautiful nor fully type-safe. req.chainId = chainId; next(); } exports.urlParamsParsing = urlParamsParsing; function parseChainId(chainIdStrIfExists) { if (chainIdStrIfExists === undefined) { return config_1.CHAIN_ID; } else { var chainId = _.parseInt(chainIdStrIfExists); if (chainId !== config_1.CHAIN_ID) { var validationErrorItem = { field: 'chainId', code: 1004, reason: 'Incorrect Chain ID: ' + chainIdStrIfExists, }; throw new errors_1.ValidationError([validationErrorItem]); } return chainId; } } <file_sep>/ts/src/index.ts import { WSClient } from '@0x/mesh-rpc-client'; import * as express from 'express'; import 'reflect-metadata'; import * as config from './config'; import { initDBConnectionAsync } from './db_connection'; import { HttpService } from './services/http_service'; import { OrderWatcherService } from './services/order_watcher_service'; import { OrderBookService } from './services/orderbook_service'; import { WebsocketService } from './services/websocket_service'; import { utils } from './utils'; (async () => { await initDBConnectionAsync(); const app = express(); const server = app.listen(config.HTTP_PORT, () => { utils.log( `Standard relayer API (HTTP) listening on port ${config.HTTP_PORT}!\nConfig: ${JSON.stringify( config, null, 2, )}`, ); }); let meshClient; await utils.attemptAsync( async () => { meshClient = new WSClient(config.MESH_ENDPOINT); await meshClient.getStatsAsync(); }, { interval: 3000, maxRetries: 10 }, ); if (!meshClient) { throw new Error('Unable to establish connection to Mesh'); } utils.log('Connected to Mesh'); const orderWatcherService = new OrderWatcherService(meshClient); await orderWatcherService.syncOrderbookAsync(); // tslint:disable-next-line:no-unused-expression new WebsocketService(server, meshClient); const orderBookService = new OrderBookService(meshClient); // tslint:disable-next-line:no-unused-expression new HttpService(app, orderBookService); })().catch(utils.log); <file_sep>/ts/src/services/order_watcher_service.ts import { WSClient } from '@0x/mesh-rpc-client'; import * as _ from 'lodash'; import { getDBConnection } from '../db_connection'; import { MeshUtils } from '../mesh_utils'; import { SignedOrderModel } from '../models/SignedOrderModel'; import { APIOrderWithMetaData, OrderWatcherLifeCycleEvents } from '../types'; import { deserializeOrder, serializeOrder } from './orderbook_utils'; // tslint:disable-next-line:no-var-requires const d = require('debug')('orderbook'); export class OrderWatcherService { private readonly _meshClient: WSClient; private static async _onOrderLifeCycleEventAsync( lifecycleEvent: OrderWatcherLifeCycleEvents, orders: APIOrderWithMetaData[], ): Promise<void> { if (orders.length <= 0) { return; } const connection = getDBConnection(); switch (lifecycleEvent) { case OrderWatcherLifeCycleEvents.Updated: case OrderWatcherLifeCycleEvents.Added: { const signedOrdersModel = orders.map(o => serializeOrder(o)); // MAX SQL variable size is 999. This limit is imposed via Sqlite. // The SELECT query is not entirely effecient and pulls in all attributes // so we need to leave space for the attributes on the model represented // as SQL variables in the "AS" syntax. We leave 99 free for the // signedOrders model await connection.manager.save(signedOrdersModel, { chunk: 900 }); break; } case OrderWatcherLifeCycleEvents.Removed: { const orderHashes = orders.map(o => o.metaData.orderHash); // MAX SQL variable size is 999. This limit is imposed via Sqlite // and other databases have higher limits (or no limits at all, eg postgresql) // tslint:disable-next-line:custom-no-magic-numbers const chunks = _.chunk(orderHashes, 999); for (const chunk of chunks) { await connection.manager.delete(SignedOrderModel, chunk); } break; } default: // Do Nothing } } constructor(meshClient: WSClient) { this._meshClient = meshClient; void this._meshClient.subscribeToOrdersAsync(async orders => { const { added, removed, updated } = MeshUtils.calculateAddedRemovedUpdated(orders); await OrderWatcherService._onOrderLifeCycleEventAsync(OrderWatcherLifeCycleEvents.Removed, removed); await OrderWatcherService._onOrderLifeCycleEventAsync(OrderWatcherLifeCycleEvents.Updated, updated); await OrderWatcherService._onOrderLifeCycleEventAsync(OrderWatcherLifeCycleEvents.Added, added); }); this._meshClient.onReconnected(async () => { d('Reconnecting to Mesh'); await this.syncOrderbookAsync(); }); } public async syncOrderbookAsync(): Promise<void> { d('SYNC orderbook with Mesh'); const connection = getDBConnection(); const signedOrderModels = (await connection.manager.find(SignedOrderModel)) as Array< Required<SignedOrderModel> >; const signedOrders = signedOrderModels.map(deserializeOrder); // Sync the order watching service state locally const orders = await this._meshClient.getOrdersAsync(); // TODO(dekz): Mesh can reject due to InternalError or EthRPCRequestFailed. // in the future we can attempt to retry these a few times. Ultimately if we // cannot validate the order we cannot keep the order around // Validate the local state and notify the order watcher of any missed orders const { accepted, rejected } = await MeshUtils.addOrdersToMeshAsync(this._meshClient, signedOrders); d(`SYNC ${rejected.length} rejected ${accepted.length} accepted ${signedOrders.length} sent`); // Remove all of the rejected orders if (rejected.length > 0) { await OrderWatcherService._onOrderLifeCycleEventAsync( OrderWatcherLifeCycleEvents.Removed, MeshUtils.orderInfosToApiOrders(rejected), ); } // Sync the order watching service state locally if (orders.length > 0) { await OrderWatcherService._onOrderLifeCycleEventAsync( OrderWatcherLifeCycleEvents.Added, MeshUtils.orderInfosToApiOrders(orders), ); } d('SYNC complete'); } } <file_sep>/js/utils.js 'use strict'; var __awaiter = (this && this.__awaiter) || function(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator['throw'](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function(resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [], }, f, y, t, g; return ( (g = { next: verb(0), throw: verb(1), return: verb(2) }), typeof Symbol === 'function' && (g[Symbol.iterator] = function() { return this; }), g ); function verb(n) { return function(v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError('Generator is already executing.'); while (_) try { if ( ((f = 1), y && (t = op[0] & 2 ? y['return'] : op[0] ? y['throw'] || ((t = y['return']) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) ) return t; if (((y = 0), t)) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if ( !((t = _.trys), (t = t.length > 0 && t[t.length - 1])) && (op[0] === 6 || op[0] === 2) ) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __read = (this && this.__read) || function(o, n) { var m = typeof Symbol === 'function' && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i['return'])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; var __spread = (this && this.__spread) || function() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; }; Object.defineProperty(exports, '__esModule', { value: true }); var json_schemas_1 = require('@0x/json-schemas'); var _ = require('lodash'); var errors_1 = require('./errors'); var schemaValidator = new json_schemas_1.SchemaValidator(); exports.utils = { log: function() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } // tslint:disable-next-line:no-console console.log.apply(console, __spread(args)); }, validateSchema: function(instance, schema) { var validationResult = schemaValidator.validate(instance, schema); if (_.isEmpty(validationResult.errors)) { return; } else { var validationErrorItems = _.map(validationResult.errors, function(schemaValidationError) { return schemaValidationErrorToValidationErrorItem(schemaValidationError); }); throw new errors_1.ValidationError(validationErrorItems); } }, delayAsync: function(ms) { return __awaiter(this, void 0, void 0, function() { return __generator(this, function(_a) { // tslint:disable:no-inferred-empty-object-type return [ 2 /*return*/, new Promise(function(resolve) { return setTimeout(resolve, ms); }), ]; }); }); }, attemptAsync: function(fn, opts) { if (opts === void 0) { opts = { interval: 1000, maxRetries: 10 }; } return __awaiter(this, void 0, void 0, function() { var result, attempt, error, isSuccess, err_1; return __generator(this, function(_a) { switch (_a.label) { case 0: attempt = 0; isSuccess = false; _a.label = 1; case 1: if (!(!result && attempt < opts.maxRetries)) return [3 /*break*/, 7]; attempt++; _a.label = 2; case 2: _a.trys.push([2, 4, , 6]); return [4 /*yield*/, fn()]; case 3: result = _a.sent(); isSuccess = true; error = undefined; return [3 /*break*/, 6]; case 4: err_1 = _a.sent(); error = err_1; return [4 /*yield*/, exports.utils.delayAsync(opts.interval)]; case 5: _a.sent(); return [3 /*break*/, 6]; case 6: return [3 /*break*/, 1]; case 7: if (!isSuccess) { throw error; } return [2 /*return*/, result]; } }); }); }, }; function schemaValidationErrorToValidationErrorItem(schemaValidationError) { if ( _.includes( [ 'type', 'anyOf', 'allOf', 'oneOf', 'additionalProperties', 'minProperties', 'maxProperties', 'pattern', 'format', 'uniqueItems', 'items', 'dependencies', ], schemaValidationError.name, ) ) { return { field: schemaValidationError.property, code: errors_1.ValidationErrorCodes.IncorrectFormat, reason: schemaValidationError.message, }; } else if ( _.includes( ['minimum', 'maximum', 'minLength', 'maxLength', 'minItems', 'maxItems', 'enum', 'const'], schemaValidationError.name, ) ) { return { field: schemaValidationError.property, code: errors_1.ValidationErrorCodes.ValueOutOfRange, reason: schemaValidationError.message, }; } else if (schemaValidationError.name === 'required') { return { field: schemaValidationError.argument, code: errors_1.ValidationErrorCodes.RequiredField, reason: schemaValidationError.message, }; } else if (schemaValidationError.name === 'not') { return { field: schemaValidationError.property, code: errors_1.ValidationErrorCodes.UnsupportedOption, reason: schemaValidationError.message, }; } else { throw new Error('Unknnown schema validation error name: ' + schemaValidationError.name); } } <file_sep>/js/mesh_utils.js 'use strict'; var __awaiter = (this && this.__awaiter) || function(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator['throw'](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function(resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [], }, f, y, t, g; return ( (g = { next: verb(0), throw: verb(1), return: verb(2) }), typeof Symbol === 'function' && (g[Symbol.iterator] = function() { return this; }), g ); function verb(n) { return function(v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError('Generator is already executing.'); while (_) try { if ( ((f = 1), y && (t = op[0] & 2 ? y['return'] : op[0] ? y['throw'] || ((t = y['return']) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) ) return t; if (((y = 0), t)) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if ( !((t = _.trys), (t = t.length > 0 && t[t.length - 1])) && (op[0] === 6 || op[0] === 2) ) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __values = (this && this.__values) || function(o) { var m = typeof Symbol === 'function' && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function() { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; }, }; }; var __read = (this && this.__read) || function(o, n) { var m = typeof Symbol === 'function' && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i['return'])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; var __spread = (this && this.__spread) || function() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; }; Object.defineProperty(exports, '__esModule', { value: true }); var mesh_rpc_client_1 = require('@0x/mesh-rpc-client'); var _ = require('lodash'); var constants_1 = require('./constants'); var errors_1 = require('./errors'); // tslint:disable-next-line:no-var-requires var d = require('debug')('MESH'); // tslint:disable-next-line:no-unnecessary-class var MeshUtils = /** @class */ (function() { function MeshUtils() {} MeshUtils.addOrdersToMeshAsync = function(meshClient, orders, batchSize) { if (batchSize === void 0) { batchSize = 100; } return __awaiter(this, void 0, void 0, function() { var e_1, _a, validationResults, chunks, chunks_1, chunks_1_1, chunk, results, e_1_1; return __generator(this, function(_b) { switch (_b.label) { case 0: validationResults = { accepted: [], rejected: [] }; chunks = _.chunk(orders, batchSize); _b.label = 1; case 1: _b.trys.push([1, 6, 7, 8]); (chunks_1 = __values(chunks)), (chunks_1_1 = chunks_1.next()); _b.label = 2; case 2: if (!!chunks_1_1.done) return [3 /*break*/, 5]; chunk = chunks_1_1.value; return [4 /*yield*/, meshClient.addOrdersAsync(chunk, true)]; case 3: results = _b.sent(); validationResults.accepted = __spread(validationResults.accepted, results.accepted); validationResults.rejected = __spread(validationResults.rejected, results.rejected); _b.label = 4; case 4: chunks_1_1 = chunks_1.next(); return [3 /*break*/, 2]; case 5: return [3 /*break*/, 8]; case 6: e_1_1 = _b.sent(); e_1 = { error: e_1_1 }; return [3 /*break*/, 8]; case 7: try { if (chunks_1_1 && !chunks_1_1.done && (_a = chunks_1.return)) _a.call(chunks_1); } finally { if (e_1) throw e_1.error; } return [7 /*endfinally*/]; case 8: return [2 /*return*/, validationResults]; } }); }); }; MeshUtils.orderInfosToApiOrders = function(orderEvent) { return orderEvent.map(function(e) { return MeshUtils.orderInfoToAPIOrder(e); }); }; MeshUtils.orderInfoToAPIOrder = function(orderEvent) { var remainingFillableTakerAssetAmount = orderEvent.fillableTakerAssetAmount ? orderEvent.fillableTakerAssetAmount : constants_1.ZERO; return { order: orderEvent.signedOrder, metaData: { orderHash: orderEvent.orderHash, remainingFillableTakerAssetAmount: remainingFillableTakerAssetAmount, }, }; }; MeshUtils.rejectedCodeToSRACode = function(code) { switch (code) { case mesh_rpc_client_1.RejectedCode.OrderCancelled: case mesh_rpc_client_1.RejectedCode.OrderExpired: case mesh_rpc_client_1.RejectedCode.OrderUnfunded: case mesh_rpc_client_1.RejectedCode.OrderHasInvalidMakerAssetAmount: case mesh_rpc_client_1.RejectedCode.OrderHasInvalidMakerAssetData: case mesh_rpc_client_1.RejectedCode.OrderHasInvalidTakerAssetAmount: case mesh_rpc_client_1.RejectedCode.OrderHasInvalidTakerAssetData: case mesh_rpc_client_1.RejectedCode.OrderFullyFilled: { return errors_1.ValidationErrorCodes.InvalidOrder; } case mesh_rpc_client_1.RejectedCode.OrderHasInvalidSignature: { return errors_1.ValidationErrorCodes.InvalidSignatureOrHash; } case mesh_rpc_client_1.RejectedCode.OrderForIncorrectChain: { return errors_1.ValidationErrorCodes.InvalidAddress; } default: return errors_1.ValidationErrorCodes.InternalError; } }; MeshUtils.calculateAddedRemovedUpdated = function(orderEvents) { var e_2, _a; var added = []; var removed = []; var updated = []; try { for ( var orderEvents_1 = __values(orderEvents), orderEvents_1_1 = orderEvents_1.next(); !orderEvents_1_1.done; orderEvents_1_1 = orderEvents_1.next() ) { var event_1 = orderEvents_1_1.value; var apiOrder = MeshUtils.orderInfoToAPIOrder(event_1); switch (event_1.endState) { case mesh_rpc_client_1.OrderEventEndState.Added: { added.push(apiOrder); break; } case mesh_rpc_client_1.OrderEventEndState.Cancelled: case mesh_rpc_client_1.OrderEventEndState.Expired: case mesh_rpc_client_1.OrderEventEndState.FullyFilled: case mesh_rpc_client_1.OrderEventEndState.Unfunded: { removed.push(apiOrder); break; } case mesh_rpc_client_1.OrderEventEndState.FillabilityIncreased: case mesh_rpc_client_1.OrderEventEndState.Filled: { updated.push(apiOrder); break; } default: d('Unknown Event', event_1.endState, event_1); break; } } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (orderEvents_1_1 && !orderEvents_1_1.done && (_a = orderEvents_1.return)) _a.call(orderEvents_1); } finally { if (e_2) throw e_2.error; } } return { added: added, removed: removed, updated: updated }; }; return MeshUtils; })(); exports.MeshUtils = MeshUtils; <file_sep>/ts/src/fee_strategy.ts import { OrderConfigRequest, OrderConfigResponse } from '@0x/connect'; import { FEE_RECIPIENT, MAKER_FEE_ASSET_DATA, MAKER_FEE_UNIT_AMOUNT, TAKER_FEE_ASSET_DATA, TAKER_FEE_UNIT_AMOUNT, } from './config'; import { NULL_ADDRESS } from './constants'; export const fixedFeeStrategy = { getOrderConfig: (_order: Partial<OrderConfigRequest>): OrderConfigResponse => { const normalizedFeeRecipient = FEE_RECIPIENT.toLowerCase(); const orderConfigResponse: OrderConfigResponse = { senderAddress: NULL_ADDRESS, feeRecipientAddress: normalizedFeeRecipient, makerFee: MAKER_FEE_UNIT_AMOUNT, takerFee: TAKER_FEE_UNIT_AMOUNT, makerFeeAssetData: MAKER_FEE_ASSET_DATA, takerFeeAssetData: TAKER_FEE_ASSET_DATA, }; return orderConfigResponse; }, };
b01d9b3d7c480b928ca76cf53c3c9c3347564d3f
[ "JavaScript", "TypeScript" ]
17
TypeScript
Blockchain-Mexico/0x-launch-kit-backend
ca95592bb78c63b1fb07ca70643c179c4e324c4e
379cb633cf1bb70abcb1edf81769c727ae35d718
refs/heads/master
<repo_name>lingraj438/php-books<file_sep>/action.php <?php if(isset($_POST["action"])) { if($_POST["action"] =="fetch"){ $folders = glob('uploads/*'); $output = ' <table class="table table-borderless table-hover"> <tr> <th>Subjects or Branch</th> <th>Type</th> </tr> '; if(count($folders) >0 ){ foreach($folders as $path_name_folder){ $namearr = explode('/',$path_name_folder); $name = end($namearr); $output .= ' <tr> <td style="width:70%;">'.$name.'</td>'; if(is_dir($path_name_folder)){ $output .=' <td>Folder</td> <td><button style="width:120px;" type="button" name="open" data-adr="'.$path_name_folder.'" class="open btn btn-success btn-xs">Open</button></td> </tr> '; } else{ $data = mime_content_type($path_name_folder); $ar = explode('/',$data); $type = end($ar); $output .=' <td>'.$type.'</td> <td><button style="width:120px;" type="button" name="file" data-adr="'.$path_name_folder.'" class="file btn btn-primary btn-xs">View file</button></td> </tr> '; } } } else{ $output .= ' <tr> <td colspan="2">No Folder Found</td> </tr> '; } $output .= '</table>'; $out = $output; echo $output; } if($_POST["action"] == "open"){ $folders = glob($_POST["folder_name"].'/*'); $linkname = $_POST["folder_name"]; $arr1 = explode('/',$linkname); $tmp = ""; foreach($arr1 as $tmpname){ if($tmpname == "uploads"){ $tmp .= 'Subject or Branch'.'/'; } else{ $tmp .= $tmpname.'/'; } } $head = $tmp; $arr2 = explode('/',$linkname); $length = count($arr2); \array_splice($arr2,$length-1,1); $lengthnew = count($arr2); $tmp2=''; for ($x = 0; $x <$lengthnew ; $x++) { if($x == $lengthnew-1){ $tmp2 .= $arr2[$x]; } else{ $tmp2 .= $arr2[$x].'/'; } } $back = $tmp2; $arr3 = explode('/',$back); $no = count($arr3); $output = ' <table class="table table-borderless table-hover"> <tr> <th>'.$head.'</th> <th>Type</th> <th><button style="width:120px;" type="button" name="back" data-adr="'.$back.','.$no.'" class="back btn btn-warning btn-xs">Back</button></th> </tr> '; if(count($folders) >0 ){ foreach($folders as $path_name_folder){ $namearr = explode('/',$path_name_folder); $name = end($namearr); $output .= ' <tr> <td style="width:70%;">'.$name.'</td>'; if(is_dir($path_name_folder)){ $output .=' <td>Folder</td> <td><button style="width:120px;" type="button" name="open" data-adr="'.$path_name_folder.'" class="open btn btn-success btn-xs">Open</button></td> </tr> '; } else{ $data = mime_content_type($path_name_folder); $ar = explode('/',$data); $type = end($ar); $output .=' <td>'.$type.'</td> <td><button style="width:120px;" type="button" name="file" data-adr="'.$path_name_folder.'" class="file btn btn-primary btn-xs">View file</button></td> </tr> '; } } } else{ $output .= ' <tr> <td colspan="2">No Folder Found</td> </tr> '; } $output .= '</table>'; echo $output; } if($_POST["action"] == "search"){ $string = $_POST["str"]; global $out; if(empty($string)){ $folders = glob('uploads/*'); $output = ' <table class="table table-borderless table-hover"> <tr> <th>Subjects or Branch</th> <th>Type</th> </tr> '; if(count($folders) >0 ){ foreach($folders as $path_name_folder){ $namearr = explode('/',$path_name_folder); $name = end($namearr); $output .= ' <tr> <td style="width:70%;">'.$name.'</td>'; if(is_dir($path_name_folder)){ $output .=' <td>Folder</td> <td><button style="width:120px;" type="button" name="open" data-adr="'.$path_name_folder.'" class="open btn btn-success btn-xs">Open</button></td> </tr> '; } else{ $data = mime_content_type($path_name_folder); $ar = explode('/',$data); $type = end($ar); $output .=' <td>'.$type.'</td> <td><button style="width:120px;" type="button" name="file" data-adr="'.$path_name_folder.'" class="file btn btn-primary btn-xs">View file</button></td> </tr> '; } } } else{ $output .= ' <tr> <td colspan="2">No Folder Found</td> </tr> '; } $output .= '</table>'; } else{ $output = ' <table class="table table-borderless table-hover"> <tr> <th>Subjects or Branch</th> <th>Type</th> </tr> '; function recur($folder){ $folders = glob($folder.'/*'); if(count($folders) >0 ){ foreach($folders as $file){ if(is_file($file)){ global $output, $string; if(strstr($file , $string)){ $namearr = explode('/',$file); $name = end($namearr); $output .= ' <tr> <td style="width:70%;">'.$name.'</td>'; $data = mime_content_type($file); $ar = explode('/',$data); $type = end($ar); $output .=' <td>'.$type.'</td> <td><button style="width:120px;" type="button" name="file" data-adr="'.$file.'" class="file btn btn-primary btn-xs">View file</button></td> </tr> '; } } else{ recur($file); } } } } $folder = 'uploads'; recur($folder); $output .= '</table>'; } echo $output; } } ?>
fc63843609e3f82674237e91ad8579d2adc526cc
[ "PHP" ]
1
PHP
lingraj438/php-books
0dbb9fbaa98627bbeefbb990d6b40c6761384850
3b3652da189e05879d7204d515a0b58f483cf8c9
refs/heads/master
<repo_name>matozog/TrashManagementApp-frontend<file_sep>/src/components/login/LogForm/LogForm.js import React, { Component } from 'react'; import { withStyles } from '@material-ui/core/styles'; import PropTypes from 'prop-types'; import { Card, Button, InputGroup, FormControl } from 'react-bootstrap'; import './LogForm.css' const styles = theme => ({ container: { display: 'flex-end', // margin: 20, margin: theme.spacing.unit, spacing: 15, color: "white", borderColor: "black", borderWidth:"2px", }, textField: { // width: 300, margin: 20, align:'right', borderColor:"black", }, typography:{ align: 'left', color:"primary", borderColor:"black", borderWidth:"3px", // margin: 20, // height: 60, }, button: { margin: theme.spacing.unit, }, margin:{ margin: theme.spacing.unit, display: 'flex', alignItems: 'center', width:300, left:'50%', top:'50%', marginLeft:'85px', }, card: { minWidth: 275, maxWidth: 400, margin: theme.spacing.unit, align: 'center' }, bullet: { display: 'inline-block', margin: '0 2px', transform: 'scale(0.8)', }, title: { fontSize: 20, }, pos: { marginBottom: 12, }, }); class LogForm extends Component{ render(){ return ( <Card className="loginCard"> <Card.Body className="loginCardBody"> <Card.Title>Log in to the system</Card.Title> <InputGroup className="mb-3"> <FormControl className="inputStyle" placeholder="Username" aria-label="Username" aria-describedby="basic-addon1" /> </InputGroup> <InputGroup className="mb-3"> <FormControl className="inputStyle" placeholder="<PASSWORD>" aria-label="<PASSWORD>" type="<PASSWORD>" aria-describedby="basic-addon1" /> </InputGroup> <Button variant="primary">Enter!</Button> </Card.Body> <Card.Footer> <Card.Link href="#">Any problems with password?</Card.Link> <br></br> <Card.Link href="#">No account?</Card.Link> </Card.Footer> </Card> ); } } LogForm.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(LogForm);<file_sep>/src/components/pages/LoginPage/LoginPage.js import React, { Component } from 'react'; import LoginHeader from '../../login/LoginHeader/LoginHeader' import LogForm from '../../login/LogForm/LogForm'; import '../../pictures/index.js'; import './LoginPage.css' class LoginPage extends Component{ render(){ return ( <div className="loginPage" align='center'> <LoginHeader/> <LogForm /> </div> ); } } export default LoginPage;<file_sep>/src/App.js import React, { Component } from 'react'; import { Route, Switch } from 'react-router-dom'; import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles'; import './App.css'; import LoginPage from './components/pages/LoginPage/LoginPage'; import HomePage from './components/pages/HomePage/HomePage'; const theme = createMuiTheme({ palette: { primary: { main: '#455A64' }, secondary: { main: '#0044ff' }, background: { default: '#eeeeee' } } }); class App extends Component { render() { return ( <MuiThemeProvider theme={theme}> <Switch> <Route exact path="/" component={LoginPage} /> <Route exact path="/home" component={HomePage} /> </Switch> </MuiThemeProvider> ); } } export default App; <file_sep>/src/components/login/Image.js import React, { Component } from 'react'; import Card from '@material-ui/core/Card'; import CardMedia from '@material-ui/core/CardMedia'; class Image extends Component{ render(){ return( <Card> {/* <img src={this.props.source} height={300} style={{transform: `rotate(${this.props.rotation}deg)`, borderWidth: '2px', borderColor: 'white'}} alt={this.props.alt}/> */} <CardMedia // className={classes.media} image={this.props.source} title="Paella dish" /> </Card> ); } } export default Image;<file_sep>/src/components/login/LoginHeader/LoginHeader.js import React, { Component } from 'react'; import './LoginHeader.css' class LoginHeader extends Component{ render(){ return( <h1> Trash Management System </h1> ); } } export default LoginHeader;<file_sep>/src/actions/index.js import { ADD_ARTICLE, REMOVE_ARTICLE, FOUND_BAD_WORD } from "../constans/action-types"; export const addArticle = payload => { return {type: ADD_ARTICLE, payload} }; export const removeArticle = payload => { return {type: REMOVE_ARTICLE, payload} } export const foundedBadWords = () => { return {type: FOUND_BAD_WORD} }
57c4ed6374c7d05c0686256274e9a8c0607ba5ab
[ "JavaScript" ]
6
JavaScript
matozog/TrashManagementApp-frontend
79aa67cb60a8ff7f2dd329423b43846bbaab0c09
d80af31cfe95856bca8ae37b5a5cd9cd03f6f263
refs/heads/master
<file_sep>package com.org.tradeplatform.testing; import com.org.tradeplatform.conf.Context; public class Test { public static void main(String arg[]) { Context context=new Context(); context.getObject(""); } } <file_sep>package org.com.tradplatform.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.org.tradeplatform.dao.impl.BaseDaoImpl; import com.org.tradeplatform.model.User; @RestController public class UserService { @Autowired BaseDaoImpl<User> baseDao; @RequestMapping("/save2") public String saveUser(@RequestParam String name) { User user=new User(); user.setUserName(name); baseDao.save(user); return "success"; } } <file_sep>package com.org.tradeplatform.dao; import java.util.List; import java.util.Map; public interface BaseDao<T> { public void save(T object); public List<T> findByProperties(Map<String,String> properties,String objectName); public List<T> getAllOjects(); public void update(T object); } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tradeplatform.base</groupId> <artifactId>TradePlatform</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> --> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc14 </artifactId> <version>10.2.0.4.0</version> <scope>System</scope> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- install:install-file -Dfile=D:\Software\jar\ojdbc14.jar -DgroupId=com.oracle -DartifactId=ojdbc14 -Dversion=10.2.0.4.0 -Dpackaging=jar -DgeneratePom=true --> </dependencies> <properties> <java-version>1.8</java-version> </properties> <modules> <module>DataLayer</module> <module>Web</module> <module>Service</module> </modules> </project><file_sep>package com.org.tradeplatform.dao.impl; import java.util.List; import java.util.Map; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import com.org.tradeplatform.dao.BaseDao; public abstract class BaseDaoImpl<T> implements BaseDao<T> { @Autowired protected SessionFactory sessionFactory; public void save(T object) { Session session=sessionFactory.openSession(); session.beginTransaction(); session.saveOrUpdate(object); session.getTransaction().commit(); session.flush(); session.close(); } @Override public List<T> findByProperties(Map<String,String> properties,String objectName) { String query="from "+objectName; if(properties != null && properties.size()>0) { query=query+" where "; for(Map.Entry<String, String> entry:properties.entrySet()) { query=query+" "+entry.getKey()+"="; if(entry.getValue() instanceof String) { query=query+"'"+entry.getValue()+"'"; } } System.out.println("Query:=> "+query); Session session=sessionFactory.openSession(); return session.createQuery(query).list(); } return null; } public List<Object> loadAllEntities(T object) { if(object instanceof Object) { Session session=sessionFactory.openSession(); List<Object> users=(List<Object>) session.createQuery("from User").list(); return users; } return null; } public List<Object> loadAllRecord() { Session session=sessionFactory.openSession(); List<Object> records=(List<Object>) session.createQuery("from Entry").list(); session.close(); return records; } @Override public List<T> getAllOjects() { Session session=sessionFactory.openSession(); List<T> objects=(List<T>) session.createQuery("from Entry").list(); session.close(); return objects; } @Override public void update(T object) { Session session=sessionFactory.openSession(); session.beginTransaction(); session.merge(object); session.getTransaction().commit(); session.flush(); session.close(); } } <file_sep>package org.com.tradplatform.services; public class EntityService<T> { public void update() { } } <file_sep>package com.org.tradeplatform.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Product { @GeneratedValue(strategy=GenerationType.AUTO) @Id private Integer productId; private String productName; @ManyToOne @JoinColumn(name="user_id") private User user; public Product() { } public Product(String productName) { this.productName=productName; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public Integer getProductId() { return productId; } public void setProductId(Integer productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } } <file_sep> public class TestDbPart { }
9cc4ac4b24a9c439489495faae094d58763cc123
[ "Java", "Maven POM" ]
8
Java
chhatarshal/tradeplatform
7a132f4383d47ed170ea789670a58fa1efd8e009
3450f05a6839bb5191283f731b0279f477f60d86
refs/heads/master
<file_sep>echo "Pushing service docker images to docker hub ...." docker login -u $DOCKER_USERNAME -p $DOCKER_PASSWORD docker push cherubini/tmx-authentication-service:$BUILD_NAME docker push cherubini/tmx-licensing-service:$BUILD_NAME docker push cherubini/tmx-organization-service:$BUILD_NAME docker push cherubini/tmx-confsvr:$BUILD_NAME docker push cherubini/tmx-eurekasvr:$BUILD_NAME docker push cherubini/tmx-zuulsvr:$BUILD_NAME
27488bf78c5ecea03024b9fec6366db2356f9b59
[ "Shell" ]
1
Shell
qruba/spmia-chapter10
8787485e1444156a7d37c8db050aa81f1d94d7f5
b46bc7a64c7f11221d85a99de4cd298629022890
refs/heads/main
<file_sep># utils List of utilities <file_sep>FROM python:slim WORKDIR /app RUN python3 -m venv venv RUN . venv/bin/activate RUN pip install requests COPY costco.py . # Install the say command RUN apt-get update RUN apt-get install gnustep-gui-runtime -y CMD [ "python", "costco.py"] <file_sep>import os import sys import logging import requests from time import sleep from sys import platform # from bs4 import BeautifulSoup logging.basicConfig(format="%(asctime)-15s %(name)s %(levelname)s> %(message)s", level=logging.INFO, stream=sys.stdout) logging.getLogger('comtypes').setLevel(logging.WARN) URL_COSTCO_NRXC29 = r'https://www.costco.ca/northrock-xc29-73.6-cm-(29-in.)-mountain-bike.product.100674055.html' URL_COSTCO_NRXC29_2 = r'https://www.costco.ca/northrock-xc29-73.6-cm-(29-in.)-mountain-bike-.product.1465328.html' URL_COSTCO_NRTanden = r'https://www.costco.ca/northwood-dualdrive-tandem-bicycle.product.100043708.html' headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36" } def check_stock(url): availabile = False response = requests.get(url, timeout=5, headers=headers) status_code = response.status_code logging.info(status_code) if status_code == 200 and 'IN_STOCK' in response.text : availabile = True return availabile def notify_mac(message): os.system('say ' + message) def notify_win(message): import pyttsx3 engine = pyttsx3.init() engine.say(message) engine.runAndWait() engine.stop() def notify(): logging.warning("Product is in stock!!!") message = "The bike is in stock, place order right now!!" for i in range(3): if platform == "win32": notify_win(message) elif platform == "linux": logging.warning(message) elif platform == "darwin": # os.system(f'say, {message}') notify_mac(message) sleep(5) i += 1 if __name__ == "__main__": logging.info("Begins") url = URL_COSTCO_NRXC29 #URL_COSTCO_NRTanden # while True: # logging.info("Checking inventory") if check_stock(url): notify() # break sleep(60) <file_sep>## Executing the script ### Native OS 1. `pip install requests` 2. `python costco.py` ### Container 1. [Install Docker](https://docs.docker.com/get-docker/) 2. Build the image `docker build -t maysunfaisal/costco .` 3. Run the container (detach) `docker run -idt maysunfaisal/costco` 4. Check the container log `docker logs -f <Container ID>`. (Get the Container ID by executing `docker ps` to list the running containers) TODO: expose the host sound device to the container, so that the `say` command works in a container as well
93ef0ca7311a4b0b577ebea0fa1cbee6659b23c6
[ "Markdown", "Python", "Dockerfile" ]
4
Markdown
maysunfaisal/utils
55ecdb43af1d5e9d5e416eab3504805e3deaffb0
381f570490cd595ddfb847b40d44ca658a62097f
refs/heads/master
<file_sep><?php /** * Created by PhpStorm. * User: dor * Date: 2/21/15 * Time: 7:14 PM */ ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> <meta name="description" content="" /> <meta name="author" content="" /> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <![endif]--> <title>Evento Registration Page</title> <!-- BOOTSTRAP CORE STYLE CSS --> <link href="assets/css/bootstrap.css" rel="stylesheet" /> <!-- FONTAWESOME STYLE CSS --> <link href="assets/css/font-awesome.min.css" rel="stylesheet" /> <!-- CUSTOM STYLE CSS --> <link href="assets/css/style.css" rel="stylesheet" /> <!-- GOOGLE FONT --> <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' /> <script src="static/js/jquery-1.11.2.min.js"></script> </head> <body> <div class="container"> <div class="row text-center pad-top "> <div class="col-md-12"> <h2>Evento User Registration Page</h2> </div> </div> <div class="row pad-top"> <div class="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1"> <div class="panel panel-default"> <div class="panel-heading"> <strong> Register Yourself </strong> </div> <div class="panel-body"> <form role="form" method="post" action="index.php"> <br/> <div class="form-group input-group"> <span class="input-group-addon"><i class="fa fa-circle-o-notch" ></i></span> <input id="fname" name="fname" type="text" class="form-control" placeholder="First Name" /> </div> <div class="form-group input-group"> <span class="input-group-addon"><i class="fa fa-circle-o-notch" ></i></span> <input id="lname" name="lname" type="text" class="form-control" placeholder="Last Name" /> </div> <div class="form-group input-group"> <span class="input-group-addon"><i class="fa fa-circle-o-notch" ></i></span> <input id="bdate" name="bdate" type="text" class="form-control" placeholder="Birth Date" /> </div> <div class="form-group input-group"> <span class="input-group-addon"><i class="fa fa-tag" ></i></span> <input id="username" name="username" type="text" class="form-control" placeholder="Desired Username" /> </div> <div class="form-group input-group"> <span class="input-group-addon">@</span> <input id="email" name="email" type="text" class="form-control" placeholder="Your Email" /> </div> <div class="form-group input-group"> <span class="input-group-addon"><i class="fa fa-lock" ></i></span> <input id="password" name="password" type="<PASSWORD>" class="form-control" placeholder="Enter Password" /> </div> <div class="form-group input-group"> <span class="input-group-addon"><i class="fa fa-lock" ></i></span> <input id="repassword" name="repassword" type="<PASSWORD>" class="form-control" placeholder="Retype Password" /> </div> <input id="submit" style="background-color: forestgreen;color: #ffffff" type="submit" value="Register Me" name="submit"> <hr /> Already Registered ? <a href="#" >Login here</a> </form> </div> </div> </div> </div> </div> <script> $('#submit').on('submit', function () { var password = $('<PASSWORD>'); var repassword= $('<PASSWORD>'); if (password!=repassword) alert("Password Not Match"); }); </script> <!-- JAVASCRIPT FILES PLACED AT THE BOTTOM TO REDUCE THE LOADING TIME --> <!-- CORE JQUERY --> <script src="assets/plugins/jquery-1.10.2.js"></script> <!-- BOOTSTRAP SCRIPTS --> <script src="assets/plugins/bootstrap.js"></script> </body> </html> <file_sep><?php /** * Created by PhpStorm. * User: dor * Date: 2/21/15 * Time: 6:03 PM */ class Model { private $controller; private $db_host ; private $username; private $password; private $db_name; // Database name public function __construct($controller){ $this->controller=$controller; $this->db_name="evento"; $this->db_host= "localhost"; $this->username = "root"; $this->password = "<PASSWORD>"; } public function register($username,$password,$email,$fname,$lname,$bdate){ // Create connection $conn = new mysqli($this->db_host, $this->username, $this->password, $this->db_name); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "INSERT INTO users (username,password,firstName, lastName, email,bDate) VALUES (\"$username\",\"$password\",\"$fname\",\"$lname\",\"$email\",\"$bdate\")"; if (mysqli_query($conn, $sql)) { mysqli_close($conn); return "OK"; } else { mysqli_close($conn); return "Error: " . $sql . "<br>" . mysqli_error($conn); } } public function hashtag($tag){ $conn = new mysqli($this->db_host, $this->username, $this->password, $this->db_name); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $result = mysql_query("SELECT id FROM tags WHERE tag = \'.$tag.\'"); if(mysql_num_rows($result) == 0) { // row not found, do stuff... $sql = "INSERT INTO tags (tag) VALUE (\".$tag.\")"; if (mysqli_query($conn, $sql)) { mysqli_close($conn); return"OK"; } else { mysqli_close($conn); return "Error: " . $sql . "<br>" . mysqli_error($conn); } } } /** * @param $tag * @param $username * @return string */ public function user2Hash($tag,$username){ $conn = new mysqli($this->db_host, $this->username, $this->password, $this->db_name); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $tagQ = "SELECT id FROM tags WHERE tag = '.$tag.'"; $userQ = "SELECT id FROM users WHERE username = '$username'"; $result=mysqli_query($conn,$tagQ); // Fetch one and one row while ($Trow=mysqli_fetch_row($result)) { $resultU = mysqli_query($conn, $userQ) ; // Fetch one and one row while ($Urow = mysqli_fetch_row($resultU)) { $sql = "INSERT INTO users_tags (userID,tagID) VALUE ($Urow[0],$Trow[0])"; if (mysqli_query($conn, $sql)) { mysqli_close($conn); return"OK"; } else { mysqli_close($conn); return "Error: " . $sql . "<br>" . mysqli_error($conn); } } } } }<file_sep><?php /** * Created by PhpStorm. * User: dor * Date: 2/21/15 * Time: 6:03 PM */ class View { private $controller; private $username; public function __construct($controller) { $this->controller = $controller; } public function register(){ $username=$_POST['username']; $password=$_POST['<PASSWORD>']; $repassword=$_POST['repassword']; if ($repassword!=$password){ echo "<script>alert(\"no match password\")</script>"; header("location:register.php"); } $fname=$_POST['fname']; $lname=$_POST['lname']; $email=$_POST['email']; $bdate=$_POST['bdate']; $this->controller->register($username,$password,$email,$fname,$lname,$bdate); } public function hashTag(){ $tags=$_POST['Hash']; $username=$_POST['Username']; $this->controller->hashtag($tags,$username); } } <file_sep><?php /** * Created by PhpStorm. * User: dor * Date: 2/21/15 * Time: 6:04 PM */ class Controller { private $model; private $view; public function __construct() { } public function register($username,$password,$email,$fname,$lname,$bdate){ $this->model->register($username,$password,$email,$fname,$lname,$bdate); } public function setControl($model,$view){ $this->model = $model; $this->view = $view; } public function hashtag($tags,$username){ $parts = explode(',', $tags); foreach ($parts as $tag){ $this->model->hashtag($tag); $this->model->user2Hash($tag,$username); } } }<file_sep><?php /** * Created by PhpStorm. * User: dor * Date: 2/21/15 * Time: 7:33 PM */ require 'Controller.php'; require 'Model.php'; require 'View.php'; $controller = new Controller(); $view = new View($controller); $model = new Model($controller); $controller->setControl($model,$view); if(isset($_POST['submit'])) { $view->register(); $username=$_POST['username']; header("location:tag.php?username=$username"); } if (is_ajax()) { if (isset($_POST["Hash"]) && !empty($_POST["Hash"])) { //Checks if action value exists $view->hashTag(); echo json_encode("{'result':'OK'}"); header("location: success.php"); } } //Function to check if the request is an AJAX request function is_ajax() { return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'; } <file_sep><?php /** * Created by PhpStorm. * User: dor * Date: 2/22/15 * Time: 9:32 AM */ ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> <meta name="description" content="" /> <meta name="author" content="" /> <!--[if IE]> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <![endif]--> <title>Evento Registration Page</title> <!-- BOOTSTRAP CORE STYLE CSS --> <link href="assets/css/bootstrap.css" rel="stylesheet" /> <!-- FONTAWESOME STYLE CSS --> <link href="assets/css/font-awesome.min.css" rel="stylesheet" /> <!-- CUSTOM STYLE CSS --> <link href="assets/css/style.css" rel="stylesheet" /> <!-- GOOGLE FONT --> <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' /> <script src="static/js/jquery-1.11.2.min.js"></script> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> </head> <body> <div class="container"> <div class="row text-center pad-top "> <div class="col-md-12"> <h2>Evento User Registration Page</h2> </div> </div> <div class="row pad-top"> <div class="col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1"> <div class="panel panel-default"> <div class="panel-heading"> <strong> Thank You for Register </strong> </div> </div> </div> </div>
75f7a575840c0be293de129fc1ee8fa534255ec3
[ "PHP" ]
6
PHP
amirdor/MVC_evento
beb2a650f52802e76755f2f8003c8a310fb1ec9d
ca78c0ff91849ae784d9c87487525b6c3d58a038
refs/heads/v2
<file_sep>// Package validator implements value validations // // Copyright 2014 <NAME> <<EMAIL>> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package validator_test import ( "fmt" "reflect" "sort" "strings" "testing" . "gopkg.in/check.v1" "gopkg.in/validator.v2" ) func Test(t *testing.T) { TestingT(t) } type MySuite struct{} var _ = Suite(&MySuite{}) type Simple struct { A int `validate:"min=10"` } type I interface { Foo() string } type Impl struct { F string `validate:"len=3"` } func (i *Impl) Foo() string { return i.F } type Impl2 struct { F string `validate:"len=3"` } func (i Impl2) Foo() string { return i.F } type NestedStruct struct { A string `validate:"nonzero" json:"a"` } type TestStruct struct { A int `validate:"nonzero" json:"a"` B string `validate:"len=8,min=6,max=4"` Sub struct { A int `validate:"nonzero" json:"sub_a"` B string C float64 `validate:"nonzero,min=1" json:"c_is_a_float"` D *string `validate:"nonzero"` } D *Simple `validate:"nonzero"` E I `validate:nonzero` } type TestCompositedStruct struct { NestedStruct `json:""` OtherNested NestedStruct `json:"otherNested"` Items []NestedStruct `json:"nestedItems"` } func (ms *MySuite) TestValidate(c *C) { t := TestStruct{ A: 0, B: "12345", } t.Sub.A = 1 t.Sub.B = "" t.Sub.C = 0.0 t.D = &Simple{10} t.E = &Impl{"hello"} err := validator.Validate(t) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["A"], HasError, validator.ErrZeroValue) c.Assert(errs["B"], HasError, validator.ErrLen) c.Assert(errs["B"], HasError, validator.ErrMin) c.Assert(errs["B"], HasError, validator.ErrMax) c.Assert(errs["Sub.A"], HasLen, 0) c.Assert(errs["Sub.B"], HasLen, 0) c.Assert(errs["Sub.C"], HasLen, 2) c.Assert(errs["Sub.D"], HasError, validator.ErrZeroValue) c.Assert(errs["E.F"], HasError, validator.ErrLen) } func (ms *MySuite) TestValidSlice(c *C) { s := make([]int, 0, 10) err := validator.Valid(s, "nonzero") c.Assert(err, NotNil) errs, ok := err.(validator.ErrorArray) c.Assert(ok, Equals, true) c.Assert(errs, HasError, validator.ErrZeroValue) for i := 0; i < 10; i++ { s = append(s, i) } err = validator.Valid(s, "min=11,max=5,len=9,nonzero") c.Assert(err, NotNil) errs, ok = err.(validator.ErrorArray) c.Assert(ok, Equals, true) c.Assert(errs, HasError, validator.ErrMin) c.Assert(errs, HasError, validator.ErrMax) c.Assert(errs, HasError, validator.ErrLen) c.Assert(errs, Not(HasError), validator.ErrZeroValue) } func (ms *MySuite) TestValidMap(c *C) { m := make(map[string]string) err := validator.Valid(m, "nonzero") c.Assert(err, NotNil) errs, ok := err.(validator.ErrorArray) c.Assert(ok, Equals, true) c.Assert(errs, HasError, validator.ErrZeroValue) err = validator.Valid(m, "min=1") c.Assert(err, NotNil) errs, ok = err.(validator.ErrorArray) c.Assert(ok, Equals, true) c.Assert(errs, HasError, validator.ErrMin) m = map[string]string{"A": "a", "B": "a"} err = validator.Valid(m, "max=1") c.Assert(err, NotNil) errs, ok = err.(validator.ErrorArray) c.Assert(ok, Equals, true) c.Assert(errs, HasError, validator.ErrMax) err = validator.Valid(m, "min=2, max=5") c.Assert(err, IsNil) m = map[string]string{ "1": "a", "2": "b", "3": "c", "4": "d", "5": "e", } err = validator.Valid(m, "len=4,min=6,max=1,nonzero") c.Assert(err, NotNil) errs, ok = err.(validator.ErrorArray) c.Assert(ok, Equals, true) c.Assert(errs, HasError, validator.ErrLen) c.Assert(errs, HasError, validator.ErrMin) c.Assert(errs, HasError, validator.ErrMax) c.Assert(errs, Not(HasError), validator.ErrZeroValue) } func (ms *MySuite) TestValidFloat(c *C) { err := validator.Valid(12.34, "nonzero") c.Assert(err, IsNil) err = validator.Valid(0.0, "nonzero") c.Assert(err, NotNil) errs, ok := err.(validator.ErrorArray) c.Assert(ok, Equals, true) c.Assert(errs, HasError, validator.ErrZeroValue) } func (ms *MySuite) TestValidInt(c *C) { i := 123 err := validator.Valid(i, "nonzero") c.Assert(err, IsNil) err = validator.Valid(i, "min=1") c.Assert(err, IsNil) err = validator.Valid(i, "min=124, max=122") c.Assert(err, NotNil) errs, ok := err.(validator.ErrorArray) c.Assert(ok, Equals, true) c.Assert(errs, HasError, validator.ErrMin) c.Assert(errs, HasError, validator.ErrMax) err = validator.Valid(i, "max=10") c.Assert(err, NotNil) errs, ok = err.(validator.ErrorArray) c.Assert(ok, Equals, true) c.Assert(errs, HasError, validator.ErrMax) } func (ms *MySuite) TestValidString(c *C) { s := "test1234" err := validator.Valid(s, "len=8") c.Assert(err, IsNil) err = validator.Valid(s, "len=0") c.Assert(err, NotNil) errs, ok := err.(validator.ErrorArray) c.Assert(ok, Equals, true) c.Assert(errs, HasError, validator.ErrLen) err = validator.Valid(s, "regexp=^[tes]{4}.*") c.Assert(err, IsNil) err = validator.Valid(s, "regexp=^.*[0-9]{5}$") c.Assert(err, NotNil) err = validator.Valid("", "nonzero,len=3,max=1") c.Assert(err, NotNil) errs, ok = err.(validator.ErrorArray) c.Assert(ok, Equals, true) c.Assert(errs, HasLen, 2) c.Assert(errs, HasError, validator.ErrZeroValue) c.Assert(errs, HasError, validator.ErrLen) c.Assert(errs, Not(HasError), validator.ErrMax) } func (ms *MySuite) TestValidateStructVar(c *C) { // just verifies that a the given val is a struct validator.SetValidationFunc("struct", func(val interface{}, _ string) error { v := reflect.ValueOf(val) if v.Kind() == reflect.Struct { return nil } return validator.ErrUnsupported }) type test struct { A int } err := validator.Valid(test{}, "struct") c.Assert(err, IsNil) type test2 struct { B int } type test1 struct { A test2 `validate:"struct"` } err = validator.Validate(test1{}) c.Assert(err, IsNil) type test4 struct { B int `validate:"foo"` } type test3 struct { A test4 } err = validator.Validate(test3{}) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["A.B"], HasError, validator.ErrUnknownTag) } func (ms *MySuite) TestValidatePointerVar(c *C) { // just verifies that a the given val is a struct validator.SetValidationFunc("struct", func(val interface{}, _ string) error { v := reflect.ValueOf(val) if v.Kind() == reflect.Struct { return nil } return validator.ErrUnsupported }) validator.SetValidationFunc("nil", func(val interface{}, _ string) error { v := reflect.ValueOf(val) if v.IsNil() { return nil } return validator.ErrUnsupported }) type test struct { A int } err := validator.Valid(&test{}, "struct") c.Assert(err, IsNil) type test2 struct { B int } type test1 struct { A *test2 `validate:"struct"` } err = validator.Validate(&test1{&test2{}}) c.Assert(err, IsNil) type test4 struct { B int `validate:"foo"` } type test3 struct { A test4 } err = validator.Validate(&test3{}) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["A.B"], HasError, validator.ErrUnknownTag) err = validator.Valid((*test)(nil), "nil") c.Assert(err, IsNil) type test5 struct { A *test2 `validate:"nil"` } err = validator.Validate(&test5{}) c.Assert(err, IsNil) type test6 struct { A *test2 `validate:"nonzero"` } err = validator.Validate(&test6{}) errs, ok = err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["A"], HasError, validator.ErrZeroValue) err = validator.Validate(&test6{&test2{}}) c.Assert(err, IsNil) type test7 struct { A *string `validate:"min=6"` B *int `validate:"len=7"` C *int `validate:"min=12"` D *int `validate:"nonzero"` E *int `validate:"nonzero"` F *int `validate:"nonnil"` G *int `validate:"nonnil"` } s := "aaa" b := 8 e := 0 err = validator.Validate(&test7{&s, &b, nil, nil, &e, &e, nil}) errs, ok = err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["A"], HasError, validator.ErrMin) c.Assert(errs["B"], HasError, validator.ErrLen) c.Assert(errs["C"], IsNil) c.Assert(errs["D"], HasError, validator.ErrZeroValue) c.Assert(errs["E"], HasError, validator.ErrZeroValue) c.Assert(errs["F"], IsNil) c.Assert(errs["G"], HasError, validator.ErrZeroValue) } func (ms *MySuite) TestValidateOmittedStructVar(c *C) { type test2 struct { B int `validate:"min=1"` } type test1 struct { A test2 `validate:"-"` } t := test1{} err := validator.Validate(t) c.Assert(err, IsNil) errs := validator.Valid(test2{}, "-") c.Assert(errs, IsNil) } func (ms *MySuite) TestUnknownTag(c *C) { type test struct { A int `validate:"foo"` } t := test{} err := validator.Validate(t) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs, HasLen, 1) c.Assert(errs["A"], HasError, validator.ErrUnknownTag) } func (ms *MySuite) TestValidateStructWithSlice(c *C) { type test2 struct { Num int `validate:"max=2"` String string `validate:"nonzero"` } type test struct { Slices []test2 `validate:"len=1"` } t := test{ Slices: []test2{{ Num: 6, String: "foo", }}, } err := validator.Validate(t) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["Slices[0].Num"], HasError, validator.ErrMax) c.Assert(errs["Slices[0].String"], IsNil) // sanity check } func (ms *MySuite) TestValidateStructWithNestedSlice(c *C) { type test2 struct { Num int `validate:"max=2"` } type test struct { Slices [][]test2 } t := test{ Slices: [][]test2{{{Num: 6}}}, } err := validator.Validate(t) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["Slices[0][0].Num"], HasError, validator.ErrMax) } func (ms *MySuite) TestValidateStructWithMap(c *C) { type test2 struct { Num int `validate:"max=2"` } type test struct { Map map[string]test2 StructKeyMap map[test2]test2 } t := test{ Map: map[string]test2{ "hello": {Num: 6}, }, StructKeyMap: map[test2]test2{ {Num: 3}: {Num: 1}, }, } err := validator.Validate(t) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["Map[hello](value).Num"], HasError, validator.ErrMax) c.Assert(errs["StructKeyMap[{Num:3}](key).Num"], HasError, validator.ErrMax) } func (ms *MySuite) TestUnsupported(c *C) { type test struct { A int `validate:"regexp=a.*b"` B float64 `validate:"regexp=.*"` } t := test{} err := validator.Validate(t) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs, HasLen, 2) c.Assert(errs["A"], HasError, validator.ErrUnsupported) c.Assert(errs["B"], HasError, validator.ErrUnsupported) } func (ms *MySuite) TestBadParameter(c *C) { type test struct { A string `validate:"min="` B string `validate:"len=="` C string `validate:"max=foo"` } t := test{} err := validator.Validate(t) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs, HasLen, 3) c.Assert(errs["A"], HasError, validator.ErrBadParameter) c.Assert(errs["B"], HasError, validator.ErrBadParameter) c.Assert(errs["C"], HasError, validator.ErrBadParameter) } func (ms *MySuite) TestCopy(c *C) { v := validator.NewValidator() // WithTag calls copy, so we just copy the validator with the same tag v2 := v.WithTag("validate") // now we add a custom func only to the second one, it shouldn't get added // to the first v2.SetValidationFunc("custom", func(_ interface{}, _ string) error { return nil }) type test struct { A string `validate:"custom"` } err := v2.Validate(test{}) c.Assert(err, IsNil) err = v.Validate(test{}) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs, HasLen, 1) c.Assert(errs["A"], HasError, validator.ErrUnknownTag) } func (ms *MySuite) TestTagEscape(c *C) { type test struct { A string `validate:"min=0,regexp=^a{3\\,10}"` } t := test{"aaaa"} err := validator.Validate(t) c.Assert(err, IsNil) t2 := test{"aa"} err = validator.Validate(t2) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["A"], HasError, validator.ErrRegexp) } func (ms *MySuite) TestEmbeddedFields(c *C) { type baseTest struct { A string `validate:"min=1"` } type test struct { baseTest B string `validate:"min=1"` } err := validator.Validate(test{}) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs, HasLen, 2) c.Assert(errs["baseTest.A"], HasError, validator.ErrMin) c.Assert(errs["B"], HasError, validator.ErrMin) type test2 struct { baseTest `validate:"-"` } err = validator.Validate(test2{}) c.Assert(err, IsNil) } func (ms *MySuite) TestEmbeddedPointerFields(c *C) { type baseTest struct { A string `validate:"min=1"` } type test struct { *baseTest B string `validate:"min=1"` } err := validator.Validate(test{baseTest: &baseTest{}}) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs, HasLen, 2) c.Assert(errs["baseTest.A"], HasError, validator.ErrMin) c.Assert(errs["B"], HasError, validator.ErrMin) } func (ms *MySuite) TestEmbeddedNilPointerFields(c *C) { type baseTest struct { A string `validate:"min=1"` } type test struct { *baseTest } err := validator.Validate(test{}) c.Assert(err, IsNil) } func (ms *MySuite) TestPrivateFields(c *C) { type test struct { b string `validate:"min=1"` } err := validator.Validate(test{ b: "", }) c.Assert(err, IsNil) } func (ms *MySuite) TestEmbeddedUnexported(c *C) { type baseTest struct { A string `validate:"min=1"` } type test struct { baseTest `validate:"nonnil"` } err := validator.Validate(test{}) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs, HasLen, 2) c.Assert(errs["baseTest"], HasError, validator.ErrCannotValidate) c.Assert(errs["baseTest.A"], HasError, validator.ErrMin) } func (ms *MySuite) TestValidateStructWithByteSliceSlice(c *C) { type test struct { Slices [][]byte `validate:"len=1"` } t := test{ Slices: [][]byte{[]byte(``)}, } err := validator.Validate(t) c.Assert(err, IsNil) } func (ms *MySuite) TestEmbeddedInterface(c *C) { type test struct { I } err := validator.Validate(test{Impl2{"hello"}}) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs, HasLen, 1) c.Assert(errs["I.F"], HasError, validator.ErrLen) err = validator.Validate(test{&Impl{"hello"}}) c.Assert(err, NotNil) errs, ok = err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs, HasLen, 1) c.Assert(errs["I.F"], HasError, validator.ErrLen) err = validator.Validate(test{}) c.Assert(err, IsNil) type test2 struct { I `validate:"nonnil"` } err = validator.Validate(test2{}) c.Assert(err, NotNil) errs, ok = err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs, HasLen, 1) c.Assert(errs["I"], HasError, validator.ErrZeroValue) } func (ms *MySuite) TestErrors(c *C) { err := validator.ErrorMap{ "foo": validator.ErrorArray{ fmt.Errorf("bar"), }, "baz": validator.ErrorArray{ fmt.Errorf("qux"), }, } sep := ", " expected := "foo: bar, baz: qux" expectedParts := strings.Split(expected, sep) sort.Strings(expectedParts) errString := err.Error() errStringParts := strings.Split(errString, sep) sort.Strings(errStringParts) c.Assert(expectedParts, DeepEquals, errStringParts) } func (ms *MySuite) TestJSONPrint(c *C) { t := TestStruct{ A: 0, } err := validator.WithPrintJSON(true).Validate(t) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["A"], IsNil) c.Assert(errs["a"], HasError, validator.ErrZeroValue) } func (ms *MySuite) TestPrintNestedJson(c *C) { t := TestCompositedStruct{ Items: []NestedStruct{{}}, } err := validator.WithPrintJSON(true).Validate(t) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["a"], HasError, validator.ErrZeroValue) c.Assert(errs["otherNested.a"], HasError, validator.ErrZeroValue) c.Assert(errs["nestedItems[0].a"], HasError, validator.ErrZeroValue) } func (ms *MySuite) TestJSONPrintOff(c *C) { t := TestStruct{ A: 0, } err := validator.WithPrintJSON(false).Validate(t) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["A"], HasError, validator.ErrZeroValue) c.Assert(errs["a"], IsNil) } func (ms *MySuite) TestJSONPrintNoTag(c *C) { t := TestStruct{ B: "te", } err := validator.WithPrintJSON(true).Validate(t) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["B"], HasError, validator.ErrLen) } func (ms *MySuite) TestValidateSlice(c *C) { type test2 struct { Num int `validate:"max=2"` String string `validate:"nonzero"` } err := validator.Validate([]test2{ { Num: 6, String: "foo", }, { Num: 1, String: "foo", }, }) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["[0].Num"], HasError, validator.ErrMax) c.Assert(errs["[0].String"], IsNil) // sanity check c.Assert(errs["[1].Num"], IsNil) // sanity check c.Assert(errs["[1].String"], IsNil) // sanity check } func (ms *MySuite) TestValidateMap(c *C) { type test2 struct { Num int `validate:"max=2"` String string `validate:"nonzero"` } err := validator.Validate(map[string]test2{ "first": { Num: 6, String: "foo", }, "second": { Num: 1, String: "foo", }, }) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["[first](value).Num"], HasError, validator.ErrMax) c.Assert(errs["[first](value).String"], IsNil) // sanity check c.Assert(errs["[second](value).Num"], IsNil) // sanity check c.Assert(errs["[second](value).String"], IsNil) // sanity check err = validator.Validate(map[test2]string{ { Num: 6, String: "foo", }: "first", { Num: 1, String: "foo", }: "second", }) c.Assert(err, NotNil) errs, ok = err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs["[{Num:6 String:foo}](key).Num"], HasError, validator.ErrMax) c.Assert(errs["[{Num:6 String:foo}](key).String"], IsNil) // sanity check c.Assert(errs["[{Num:1 String:foo}](key).Num"], IsNil) // sanity check c.Assert(errs["[{Num:1 String:foo}](key).String"], IsNil) // sanity check } func (ms *MySuite) TestNonNilFunction(c *C) { type test struct { A func() `validate:"nonnil"` } err := validator.Validate(test{}) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs, HasLen, 1) c.Assert(errs["A"], HasError, validator.ErrZeroValue) err = validator.Validate(test{ A: func() {}, }) c.Assert(err, IsNil) } func (ms *MySuite) TestTypeAliases(c *C) { type A string type B int64 type test struct { A1 A `validate:"regexp=^[0-9]+$"` A2 *A `validate:"regexp=^[0-9]+$"` B1 B `validate:"min=10"` B2 B `validate:"max=10"` } a123 := A("123") err := validator.Validate(test{ A1: a123, A2: &a123, B1: B(11), B2: B(9), }) c.Assert(err, IsNil) abc := A("abc") err = validator.Validate(test{ A1: abc, A2: &abc, B2: B(11), }) c.Assert(err, NotNil) errs, ok := err.(validator.ErrorMap) c.Assert(ok, Equals, true) c.Assert(errs, HasLen, 4) c.Assert(errs["A1"], HasError, validator.ErrRegexp) c.Assert(errs["A2"], HasError, validator.ErrRegexp) c.Assert(errs["B1"], HasError, validator.ErrMin) c.Assert(errs["B2"], HasError, validator.ErrMax) } type hasErrorChecker struct { *CheckerInfo } func (c *hasErrorChecker) Check(params []interface{}, names []string) (bool, string) { var ( ok bool slice []error value error ) slice, ok = params[0].(validator.ErrorArray) if !ok { return false, "First parameter is not an Errorarray" } value, ok = params[1].(error) if !ok { return false, "Second parameter is not an error" } for _, v := range slice { if v == value { return true, "" } } return false, "" } func (c *hasErrorChecker) Info() *CheckerInfo { return c.CheckerInfo } var HasError = &hasErrorChecker{&CheckerInfo{Name: "HasError", Params: []string{"HasError", "expected to contain"}}} <file_sep>// Package validator implements value validations // // Copyright 2014 <NAME> <<EMAIL>> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package validator_test import ( "fmt" "sort" "gopkg.in/validator.v2" ) // This example demonstrates a custom function to process template text. // It installs the strings.Title function and uses it to // Make Title Text Look Good In Our Template's Output. func ExampleValidate() { // First create a struct to be validated // according to the validator tags. type ValidateExample struct { Name string `validate:"nonzero"` Description string Age int `validate:"min=18"` Email string `validate:"regexp=^[0-9a-z]+@[0-9a-z]+(\\.[0-9a-z]+)+$"` Address struct { Street string `validate:"nonzero"` City string `validate:"nonzero"` } } // Fill in some values ve := ValidateExample{ Name: "<NAME>", // valid as it's nonzero Description: "", // valid no validation tag exists Age: 17, // invalid as age is less than required 18 } // invalid as Email won't match the regular expression ve.Email = "@not.a.valid.email" ve.Address.City = "Some City" // valid ve.Address.Street = "" // invalid err := validator.Validate(ve) if err == nil { fmt.Println("Values are valid.") } else { errs := err.(validator.ErrorMap) // See if Address was empty if errs["Address.Street"][0] == validator.ErrZeroValue { fmt.Println("Street cannot be empty.") } // Iterate through the list of fields and respective errors fmt.Println("Invalid due to fields:") // Here we have to sort the arrays to ensure map ordering does not // fail our example, typically it's ok to just range through the err // list when order is not important. var errOuts []string for f, e := range errs { errOuts = append(errOuts, fmt.Sprintf("\t - %s (%v)\n", f, e)) } // Again this part is extraneous and you should not need this in real // code. sort.Strings(errOuts) for _, str := range errOuts { fmt.Print(str) } } // Output: // Street cannot be empty. // Invalid due to fields: // - Address.Street (zero value) // - Age (less than min) // - Email (regular expression mismatch) } // This example shows how to use the Valid helper // function to validator any number of values func ExampleValid() { err := validator.Valid(42, "min=10,max=100,nonzero") fmt.Printf("42: valid=%v, errs=%v\n", err == nil, err) var ptr *int if err := validator.Valid(ptr, "nonzero"); err != nil { fmt.Println("ptr: Invalid nil pointer.") } err = validator.Valid("ABBA", "regexp=[ABC]*") fmt.Printf("ABBA: valid=%v\n", err == nil) // Output: // 42: valid=true, errs=<nil> // ptr: Invalid nil pointer. // ABBA: valid=true } // This example shows you how to change the tag name func ExampleSetTag() { type T struct { A int `foo:"nonzero" bar:"min=10"` } t := T{5} v := validator.NewValidator() v.SetTag("foo") err := v.Validate(t) fmt.Printf("foo --> valid: %v, errs: %v\n", err == nil, err) v.SetTag("bar") err = v.Validate(t) errs := err.(validator.ErrorMap) fmt.Printf("bar --> valid: %v, errs: %v\n", err == nil, errs) // Output: // foo --> valid: true, errs: <nil> // bar --> valid: false, errs: A: less than min } // This example shows you how to change the tag name func ExampleWithTag() { type T struct { A int `foo:"nonzero" bar:"min=10"` } t := T{5} err := validator.WithTag("foo").Validate(t) fmt.Printf("foo --> valid: %v, errs: %v\n", err == nil, err) err = validator.WithTag("bar").Validate(t) fmt.Printf("bar --> valid: %v, errs: %v\n", err == nil, err) // Output: // foo --> valid: true, errs: <nil> // bar --> valid: false, errs: A: less than min } <file_sep>module gopkg.in/validator.v2 go 1.18 require gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c require ( github.com/kr/pretty v0.2.1 // indirect github.com/kr/text v0.1.0 // indirect ) <file_sep>// Package validator implements value validations // // Copyright 2014 <NAME> <<EMAIL>> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package validator import ( "bytes" "errors" "fmt" "reflect" "regexp" "strings" ) // TextErr is an error that also implements the TextMarshaller interface for // serializing out to various plain text encodings. Packages creating their // own custom errors should use TextErr if they're intending to use serializing // formats like json, msgpack etc. type TextErr struct { Err error } // Error implements the error interface. func (t TextErr) Error() string { return t.Err.Error() } // MarshalText implements the TextMarshaller func (t TextErr) MarshalText() ([]byte, error) { return []byte(t.Err.Error()), nil } var ( // ErrZeroValue is the error returned when variable has zero value // and nonzero or nonnil was specified ErrZeroValue = TextErr{errors.New("zero value")} // ErrMin is the error returned when variable is less than mininum // value specified ErrMin = TextErr{errors.New("less than min")} // ErrMax is the error returned when variable is more than // maximum specified ErrMax = TextErr{errors.New("greater than max")} // ErrLen is the error returned when length is not equal to // param specified ErrLen = TextErr{errors.New("invalid length")} // ErrRegexp is the error returned when the value does not // match the provided regular expression parameter ErrRegexp = TextErr{errors.New("regular expression mismatch")} // ErrUnsupported is the error error returned when a validation rule // is used with an unsupported variable type ErrUnsupported = TextErr{errors.New("unsupported type")} // ErrBadParameter is the error returned when an invalid parameter // is provided to a validation rule (e.g. a string where an int was // expected (max=foo,len=bar) or missing a parameter when one is required (len=)) ErrBadParameter = TextErr{errors.New("bad parameter")} // ErrUnknownTag is the error returned when an unknown tag is found ErrUnknownTag = TextErr{errors.New("unknown tag")} // ErrInvalid is the error returned when variable is invalid // (normally a nil pointer) ErrInvalid = TextErr{errors.New("invalid value")} // ErrCannotValidate is the error returned when a struct is unexported ErrCannotValidate = TextErr{errors.New("cannot validate unexported struct")} ) // ErrorMap is a map which contains all errors from validating a struct. type ErrorMap map[string]ErrorArray // ErrorMap implements the Error interface so we can check error against nil. // The returned error is all existing errors with the map. func (err ErrorMap) Error() string { var b bytes.Buffer for k, errs := range err { if len(errs) > 0 { b.WriteString(fmt.Sprintf("%s: %s, ", k, errs.Error())) } } return strings.TrimSuffix(b.String(), ", ") } // ErrorArray is a slice of errors returned by the Validate function. type ErrorArray []error // ErrorArray implements the Error interface and returns all the errors comma seprated // if errors exist. func (err ErrorArray) Error() string { var b bytes.Buffer for _, errs := range err { b.WriteString(fmt.Sprintf("%s, ", errs.Error())) } errs := b.String() return strings.TrimSuffix(errs, ", ") } // ValidationFunc is a function that receives the value of a // field and a parameter used for the respective validation tag. type ValidationFunc func(v interface{}, param string) error // Validator implements a validator type Validator struct { // validationFuncs is a map of ValidationFuncs indexed // by their name. validationFuncs map[string]ValidationFunc // Tag name being used. tagName string // printJSON set to true will make errors print with the // name of their json field instead of their struct tag. // If no json tag is present the name of the struct field is used. printJSON bool } // Helper validator so users can use the // functions directly from the package var defaultValidator = NewValidator() // NewValidator creates a new Validator func NewValidator() *Validator { return &Validator{ tagName: "validate", validationFuncs: map[string]ValidationFunc{ "nonzero": nonzero, "len": length, "min": min, "max": max, "regexp": regex, "nonnil": nonnil, }, printJSON: false, } } // SetTag allows you to change the tag name used in structs func SetTag(tag string) { defaultValidator.SetTag(tag) } // SetTag allows you to change the tag name used in structs func (mv *Validator) SetTag(tag string) { mv.tagName = tag } // WithTag creates a new Validator with the new tag name. It is // useful to chain-call with Validate so we don't change the tag // name permanently: validator.WithTag("foo").Validate(t) func WithTag(tag string) *Validator { return defaultValidator.WithTag(tag) } // WithTag creates a new Validator with the new tag name. It is // useful to chain-call with Validate so we don't change the tag // name permanently: validator.WithTag("foo").Validate(t) func (mv *Validator) WithTag(tag string) *Validator { v := mv.copy() v.SetTag(tag) return v } // SetPrintJSON allows you to print errors with json tag names present in struct tags func SetPrintJSON(printJSON bool) { defaultValidator.SetPrintJSON(printJSON) } // SetPrintJSON allows you to print errors with json tag names present in struct tags func (mv *Validator) SetPrintJSON(printJSON bool) { mv.printJSON = printJSON } // WithPrintJSON creates a new Validator with printJSON set to new value. It is // useful to chain-call with Validate so we don't change the print option // permanently: validator.WithPrintJSON(true).Validate(t) func WithPrintJSON(printJSON bool) *Validator { return defaultValidator.WithPrintJSON(printJSON) } // WithPrintJSON creates a new Validator with printJSON set to new value. It is // useful to chain-call with Validate so we don't change the print option // permanently: validator.WithTag("foo").WithPrintJSON(true).Validate(t) func (mv *Validator) WithPrintJSON(printJSON bool) *Validator { v := mv.copy() v.SetPrintJSON(printJSON) return v } // Copy a validator func (mv *Validator) copy() *Validator { newFuncs := map[string]ValidationFunc{} for k, f := range mv.validationFuncs { newFuncs[k] = f } return &Validator{ tagName: mv.tagName, validationFuncs: newFuncs, printJSON: mv.printJSON, } } // SetValidationFunc sets the function to be used for a given // validation constraint. Calling this function with nil vf // is the same as removing the constraint function from the list. func SetValidationFunc(name string, vf ValidationFunc) error { return defaultValidator.SetValidationFunc(name, vf) } // SetValidationFunc sets the function to be used for a given // validation constraint. Calling this function with nil vf // is the same as removing the constraint function from the list. func (mv *Validator) SetValidationFunc(name string, vf ValidationFunc) error { if name == "" { return errors.New("name cannot be empty") } if vf == nil { delete(mv.validationFuncs, name) return nil } mv.validationFuncs[name] = vf return nil } // Validate calls the Validate method on the default validator. func Validate(v interface{}) error { return defaultValidator.Validate(v) } // Validate validates the fields of structs (included embedded structs) based on // 'validator' tags and returns errors found indexed by the field name. func (mv *Validator) Validate(v interface{}) error { m := make(ErrorMap) mv.deepValidateCollection(reflect.ValueOf(v), m, func() string { return "" }) if len(m) > 0 { return m } return nil } func (mv *Validator) validateStruct(sv reflect.Value, m ErrorMap) error { kind := sv.Kind() if (kind == reflect.Ptr || kind == reflect.Interface) && !sv.IsNil() { return mv.validateStruct(sv.Elem(), m) } if kind != reflect.Struct && kind != reflect.Interface { return ErrUnsupported } st := sv.Type() nfields := st.NumField() for i := 0; i < nfields; i++ { if err := mv.validateField(st.Field(i), sv.Field(i), m); err != nil { return err } } return nil } // validateField validates the field of fieldVal referred to by fieldDef. // If fieldDef refers to an anonymous/embedded field, // validateField will walk all of the embedded type's fields and validate them on sv. func (mv *Validator) validateField(fieldDef reflect.StructField, fieldVal reflect.Value, m ErrorMap) error { tag := fieldDef.Tag.Get(mv.tagName) if tag == "-" { return nil } // deal with pointers for (fieldVal.Kind() == reflect.Ptr || fieldVal.Kind() == reflect.Interface) && !fieldVal.IsNil() { fieldVal = fieldVal.Elem() } // ignore private structs unless Anonymous if !fieldDef.Anonymous && fieldDef.PkgPath != "" { return nil } var errs ErrorArray if tag != "" { var err error if fieldDef.PkgPath != "" { err = ErrCannotValidate } else { err = mv.validValue(fieldVal, tag) } if errarr, ok := err.(ErrorArray); ok { errs = errarr } else if err != nil { errs = ErrorArray{err} } } // no-op if field is not a struct, interface, array, slice or map fn := mv.fieldName(fieldDef) mv.deepValidateCollection(fieldVal, m, func() string { return fn }) if len(errs) > 0 { m[fn] = errs } return nil } func (mv *Validator) fieldName(fieldDef reflect.StructField) string { if mv.printJSON { if jsonTagValue, ok := fieldDef.Tag.Lookup("json"); ok { return parseName(jsonTagValue) } } return fieldDef.Name } func (mv *Validator) deepValidateCollection(f reflect.Value, m ErrorMap, fnameFn func() string) { switch f.Kind() { case reflect.Interface, reflect.Ptr: if f.IsNil() { return } mv.deepValidateCollection(f.Elem(), m, fnameFn) case reflect.Struct: subm := make(ErrorMap) err := mv.validateStruct(f, subm) parentName := fnameFn() if err != nil { m[parentName] = ErrorArray{err} } for j, k := range subm { keyName := j if parentName != "" { keyName = parentName + "." + keyName } m[keyName] = k } case reflect.Array, reflect.Slice: // we don't need to loop over every byte in a byte slice so we only end up // looping when the kind is something we care about switch f.Type().Elem().Kind() { case reflect.Struct, reflect.Interface, reflect.Ptr, reflect.Map, reflect.Array, reflect.Slice: for i := 0; i < f.Len(); i++ { mv.deepValidateCollection(f.Index(i), m, func() string { return fmt.Sprintf("%s[%d]", fnameFn(), i) }) } } case reflect.Map: for _, key := range f.MapKeys() { mv.deepValidateCollection(key, m, func() string { return fmt.Sprintf("%s[%+v](key)", fnameFn(), key.Interface()) }) // validate the map key value := f.MapIndex(key) mv.deepValidateCollection(value, m, func() string { return fmt.Sprintf("%s[%+v](value)", fnameFn(), key.Interface()) }) } } } // Valid validates a value based on the provided // tags and returns errors found or nil. func Valid(val interface{}, tags string) error { return defaultValidator.Valid(val, tags) } // Valid validates a value based on the provided // tags and returns errors found or nil. func (mv *Validator) Valid(val interface{}, tags string) error { if tags == "-" { return nil } v := reflect.ValueOf(val) if (v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface) && !v.IsNil() { return mv.validValue(v.Elem(), tags) } if v.Kind() == reflect.Invalid { return mv.validateVar(nil, tags) } return mv.validateVar(val, tags) } // validValue is like Valid but takes a Value instead of an interface func (mv *Validator) validValue(v reflect.Value, tags string) error { if v.Kind() == reflect.Invalid { return mv.validateVar(nil, tags) } return mv.validateVar(v.Interface(), tags) } // validateVar validates one single variable func (mv *Validator) validateVar(v interface{}, tag string) error { tags, err := mv.parseTags(tag) if err != nil { // unknown tag found, give up. return err } errs := make(ErrorArray, 0, len(tags)) for _, t := range tags { if err := t.Fn(v, t.Param); err != nil { errs = append(errs, err) } } if len(errs) > 0 { return errs } return nil } // tag represents one of the tag items type tag struct { Name string // name of the tag Fn ValidationFunc // validation function to call Param string // parameter to send to the validation function } // separate by no escaped commas var sepPattern *regexp.Regexp = regexp.MustCompile(`((?:^|[^\\])(?:\\\\)*),`) func splitUnescapedComma(str string) []string { ret := []string{} indexes := sepPattern.FindAllStringIndex(str, -1) last := 0 for _, is := range indexes { ret = append(ret, str[last:is[1]-1]) last = is[1] } ret = append(ret, str[last:]) return ret } // parseTags parses all individual tags found within a struct tag. func (mv *Validator) parseTags(t string) ([]tag, error) { tl := splitUnescapedComma(t) tags := make([]tag, 0, len(tl)) for _, i := range tl { i = strings.Replace(i, `\,`, ",", -1) tg := tag{} v := strings.SplitN(i, "=", 2) tg.Name = strings.Trim(v[0], " ") if tg.Name == "" { return []tag{}, ErrUnknownTag } if len(v) > 1 { tg.Param = strings.Trim(v[1], " ") } var found bool if tg.Fn, found = mv.validationFuncs[tg.Name]; !found { return []tag{}, ErrUnknownTag } tags = append(tags, tg) } return tags, nil } func parseName(tag string) string { if tag == "" { return "" } name := strings.SplitN(tag, ",", 2)[0] // if the field as be skipped in json, just return an empty string if name == "-" { return "" } return name } <file_sep>// Package validator implements value validations // // Copyright 2014 <NAME> <<EMAIL>> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package validator import ( "reflect" "regexp" "strconv" "unicode/utf8" ) // nonzero tests whether a variable value non-zero // as defined by the golang spec. func nonzero(v interface{}, param string) error { st := reflect.ValueOf(v) var valid bool switch st.Kind() { case reflect.String: valid = utf8.RuneCountInString(st.String()) != 0 case reflect.Ptr, reflect.Interface: valid = !st.IsNil() case reflect.Slice, reflect.Map, reflect.Array: valid = st.Len() != 0 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: valid = st.Int() != 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: valid = st.Uint() != 0 case reflect.Float32, reflect.Float64: valid = st.Float() != 0 case reflect.Bool: valid = st.Bool() case reflect.Invalid: valid = false // always invalid case reflect.Struct: valid = true // always valid since only nil pointers are empty default: return ErrUnsupported } if !valid { return ErrZeroValue } return nil } // length tests whether a variable's length is equal to a given // value. For strings it tests the number of characters whereas // for maps and slices it tests the number of items. func length(v interface{}, param string) error { st := reflect.ValueOf(v) var valid bool if st.Kind() == reflect.Ptr { if st.IsNil() { return nil } st = st.Elem() } switch st.Kind() { case reflect.String: p, err := asInt(param) if err != nil { return ErrBadParameter } valid = int64(utf8.RuneCountInString(st.String())) == p case reflect.Slice, reflect.Map, reflect.Array: p, err := asInt(param) if err != nil { return ErrBadParameter } valid = int64(st.Len()) == p case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: p, err := asInt(param) if err != nil { return ErrBadParameter } valid = st.Int() == p case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: p, err := asUint(param) if err != nil { return ErrBadParameter } valid = st.Uint() == p case reflect.Float32, reflect.Float64: p, err := asFloat(param) if err != nil { return ErrBadParameter } valid = st.Float() == p default: return ErrUnsupported } if !valid { return ErrLen } return nil } // min tests whether a variable value is larger or equal to a given // number. For number types, it's a simple lesser-than test; for // strings it tests the number of characters whereas for maps // and slices it tests the number of items. func min(v interface{}, param string) error { st := reflect.ValueOf(v) invalid := false if st.Kind() == reflect.Ptr { if st.IsNil() { return nil } st = st.Elem() } switch st.Kind() { case reflect.String: p, err := asInt(param) if err != nil { return ErrBadParameter } invalid = int64(utf8.RuneCountInString(st.String())) < p case reflect.Slice, reflect.Map, reflect.Array: p, err := asInt(param) if err != nil { return ErrBadParameter } invalid = int64(st.Len()) < p case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: p, err := asInt(param) if err != nil { return ErrBadParameter } invalid = st.Int() < p case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: p, err := asUint(param) if err != nil { return ErrBadParameter } invalid = st.Uint() < p case reflect.Float32, reflect.Float64: p, err := asFloat(param) if err != nil { return ErrBadParameter } invalid = st.Float() < p default: return ErrUnsupported } if invalid { return ErrMin } return nil } // max tests whether a variable value is lesser than a given // value. For numbers, it's a simple lesser-than test; for // strings it tests the number of characters whereas for maps // and slices it tests the number of items. func max(v interface{}, param string) error { st := reflect.ValueOf(v) var invalid bool if st.Kind() == reflect.Ptr { if st.IsNil() { return nil } st = st.Elem() } switch st.Kind() { case reflect.String: p, err := asInt(param) if err != nil { return ErrBadParameter } invalid = int64(utf8.RuneCountInString(st.String())) > p case reflect.Slice, reflect.Map, reflect.Array: p, err := asInt(param) if err != nil { return ErrBadParameter } invalid = int64(st.Len()) > p case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: p, err := asInt(param) if err != nil { return ErrBadParameter } invalid = st.Int() > p case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: p, err := asUint(param) if err != nil { return ErrBadParameter } invalid = st.Uint() > p case reflect.Float32, reflect.Float64: p, err := asFloat(param) if err != nil { return ErrBadParameter } invalid = st.Float() > p default: return ErrUnsupported } if invalid { return ErrMax } return nil } // regex is the builtin validation function that checks // whether the string variable matches a regular expression func regex(v interface{}, param string) error { rv := reflect.ValueOf(v) if rv.Kind() == reflect.Ptr { if rv.IsNil() { return nil } rv = rv.Elem() } if rv.Kind() != reflect.String { return ErrUnsupported } s := rv.String() re, err := regexp.Compile(param) if err != nil { return ErrBadParameter } if !re.MatchString(s) { return ErrRegexp } return nil } // asInt returns the parameter as a int64 // or panics if it can't convert func asInt(param string) (int64, error) { i, err := strconv.ParseInt(param, 0, 64) if err != nil { return 0, ErrBadParameter } return i, nil } // asUint returns the parameter as a uint64 // or panics if it can't convert func asUint(param string) (uint64, error) { i, err := strconv.ParseUint(param, 0, 64) if err != nil { return 0, ErrBadParameter } return i, nil } // asFloat returns the parameter as a float64 // or panics if it can't convert func asFloat(param string) (float64, error) { i, err := strconv.ParseFloat(param, 64) if err != nil { return 0.0, ErrBadParameter } return i, nil } // nonnil validates that the given pointer is not nil func nonnil(v interface{}, param string) error { st := reflect.ValueOf(v) // if we got a non-pointer then we most likely got // the value for a pointer field, either way, its not // nil switch st.Kind() { case reflect.Ptr, reflect.Interface, reflect.Func: if st.IsNil() { return ErrZeroValue } case reflect.Invalid: // the only way its invalid is if its an interface that's nil return ErrZeroValue } return nil } <file_sep>// Package validator implements value validations // // Copyright 2014 <NAME> <<EMAIL>> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /* Package validator implements value validations based on struct tags. In code it is often necessary to validate that a given value is valid before using it for something. A typical example might be something like this. if age < 18 { return error.New("age cannot be under 18") } This is a simple enough example, but it can get significantly more complex, especially when dealing with structs. l := len(strings.Trim(s.Username)) if l < 3 || l > 40 || !regexp.MatchString("^[a-zA-Z]$", s.Username) || s.Age < 18 || s.Password { return errors.New("Invalid request") } You get the idea. Package validator allows one to define valid values as struct tags when defining a new struct type. type NewUserRequest struct { Username string `validate:"min=3,max=40,regexp=^[a-zA-Z]*$"` Name string `validate:"nonzero"` Age int `validate:"min=18"` Password string `validate:"min=8"` } Then validating a variable of type NewUserRequest becomes trivial. nur := NewUserRequest{Username: "something", ...} if errs := validator.Validate(nur); errs != nil { // do something } Builtin validator functions Here is the list of validator functions builtin in the package. len For numeric numbers, len will simply make sure that the value is equal to the parameter given. For strings, it checks that the string length is exactly that number of characters. For slices, arrays, and maps, validates the number of items. (Usage: len=10) max For numeric numbers, max will simply make sure that the value is lesser or equal to the parameter given. For strings, it checks that the string length is at most that number of characters. For slices, arrays, and maps, validates the number of items. (Usage: max=10) min For numeric numbers, min will simply make sure that the value is greater or equal to the parameter given. For strings, it checks that the string length is at least that number of characters. For slices, arrays, and maps, validates the number of items. (Usage: min=10) nonzero This validates that the value is not zero. The appropriate zero value is given by the Go spec (e.g. for int it's 0, for string it's "", for pointers is nil, etc.). For pointers, the pointer's value is used to test for nonzero in addition to the pointer itself not being nil. To just check for not being nil, use nonnil. Usage: nonzero regexp Only valid for string types, it will validate that the value matches the regular expression provided as parameter. (Usage: regexp=^a.*b$) nonnil Validates that the given value is not nil. Usage: nonnil Note that there are no tests to prevent conflicting validator parameters. For instance, these fields will never be valid. ... A int `validate:"max=0,min=1"` B string `validate:"len=10,regexp=^$" ... Custom validation functions It is possible to define custom validation functions by using SetValidationFunc. First, one needs to create a validation function. // Very simple validation func func notZZ(v interface{}, param string) error { st := reflect.ValueOf(v) if st.Kind() != reflect.String { return validate.ErrUnsupported } if st.String() == "ZZ" { return errors.New("value cannot be ZZ") } return nil } Then one needs to add it to the list of validation funcs and give it a "tag" name. validate.SetValidationFunc("notzz", notZZ) Then it is possible to use the notzz validation tag. This will print "Field A error: value cannot be ZZ" type T struct { A string `validate:"nonzero,notzz"` } t := T{"ZZ"} if errs := validator.Validate(t); errs != nil { fmt.Printf("Field A error: %s\n", errs["A"][0]) } To use parameters, it is very similar. // Very simple validator with parameter func notSomething(v interface{}, param string) error { st := reflect.ValueOf(v) if st.Kind() != reflect.String { return validate.ErrUnsupported } if st.String() == param { return errors.New("value cannot be " + param) } return nil } And then the code below should print "Field A error: value cannot be ABC". validator.SetValidationFunc("notsomething", notSomething) type T struct { A string `validate:"notsomething=ABC"` } t := T{"ABC"} if errs := validator.Validate(t); errs != nil { fmt.Printf("Field A error: %s\n", errs["A"][0]) } As well, it is possible to overwrite builtin validation functions. validate.SetValidationFunc("min", myMinFunc) And you can delete a validation function by setting it to nil. validate.SetValidationFunc("notzz", nil) validate.SetValidationFunc("nonzero", nil) Using a non-existing validation func in a field tag will always return false and with error validate.ErrUnknownTag. Finally, package validator also provides a helper function that can be used to validate simple variables/values. // errs: nil errs = validator.Valid(42, "min=10, max=50") // errs: [validate.ErrZeroValue] errs = validator.Valid(nil, "nonzero") // errs: [validate.ErrMin,validate.ErrMax] errs = validator.Valid("hi", "nonzero,min=3,max=2") Custom tag name In case there is a reason why one would not wish to use tag 'validate' (maybe due to a conflict with a different package), it is possible to tell the package to use a different tag. validator.SetTag("valid") Then. Type T struct { A int `valid:"min=8, max=10"` B string `valid:"nonzero"` } SetTag is permanent. The new tag name will be used until it is again changed with a new call to SetTag. A way to temporarily use a different tag exists. validator.WithTag("foo").Validate(t) validator.WithTag("bar").Validate(t) // But this will go back to using 'validate' validator.Validate(t) Multiple validators You may often need to have a different set of validation rules for different situations. In all the examples above, we only used the default validator but you could create a new one and set specific rules for it. For instance, you might use the same struct to decode incoming JSON for a REST API but your needs will change when you're using it to, say, create a new instance in storage vs. when you need to change something. type User struct { Username string `validate:"nonzero"` Name string `validate:"nonzero"` Age int `validate:"nonzero"` Password string `validate:"nonzero"` } Maybe when creating a new user, you need to make sure all values in the struct are filled, but then you use the same struct to handle incoming requests to, say, change the password, in which case you only need the Username and the Password and don't care for the others. You might use two different validators. type User struct { Username string `creating:"nonzero" chgpw:"nonzero"` Name string `creating:"nonzero"` Age int `creating:"nonzero"` Password string `creating:"nonzero" chgpw:"nonzero"` } var ( creationValidator = validator.NewValidator() chgPwValidator = validator.NewValidator() ) func init() { creationValidator.SetTag("creating") chgPwValidator.SetTag("chgpw") } ... func CreateUserHandler(w http.ResponseWriter, r *http.Request) { var u User json.NewDecoder(r.Body).Decode(&user) if errs := creationValidator.Validate(user); errs != nil { // the request did not include all of the User // struct fields, so send a http.StatusBadRequest // back or something } // create the new user } func SetNewUserPasswordHandler(w http.ResponseWriter, r *http.Request) { var u User json.NewDecoder(r.Body).Decode(&user) if errs := chgPwValidator.Validate(user); errs != nil { // the request did not Username and Password, // so send a http.StatusBadRequest // back or something } // save the new password } It is also possible to do all of that using only the default validator as long as SetTag is always called before calling validator.Validate() or you chain the with WithTag(). */ package validator <file_sep># Package validator Package validator implements variable validations # Installation Just use go get. ```bash go get gopkg.in/validator.v2 ``` And then just import the package into your own code. ```go import ( "gopkg.in/validator.v2" ) ``` # Usage Please see http://godoc.org/gopkg.in/validator.v2 for detailed usage docs. A simple example would be. ```go type NewUserRequest struct { Username string `validate:"min=3,max=40,regexp=^[a-zA-Z]*$"` Name string `validate:"nonzero"` Age int `validate:"min=21"` Password string `validate:"min=8"` } nur := NewUserRequest{Username: "something", Age: 20} if errs := validator.Validate(nur); errs != nil { // values not valid, deal with errors here } ``` Builtin validators Here is the list of validators buildin in the package. Validators buildin will check the element pointed to if the value to check is a pointer. The `nil` pointer is treated as a valid value by validators buildin other than `nonzero`, so you should to use `nonzero` if you don't want to accept a `nil` pointer. ``` len For numeric numbers, len will simply make sure that the value is equal to the parameter given. For strings, it checks that the string length is exactly that number of characters. For slices, arrays, and maps, validates the number of items. (Usage: len=10) max For numeric numbers, max will simply make sure that the value is lesser or equal to the parameter given. For strings, it checks that the string length is at most that number of characters. For slices, arrays, and maps, validates the number of items. (Usage: max=10) min For numeric numbers, min will simply make sure that the value is greater or equal to the parameter given. For strings, it checks that the string length is at least that number of characters. For slices, arrays, and maps, validates the number of items. (Usage: min=10) nonzero This validates that the value is not zero. The appropriate zero value is given by the Go spec (e.g. for int it's 0, for string it's "", for pointers is nil, etc.) For structs, it will not check to see if the struct itself has all zero values, instead use a pointer or put nonzero on the struct's keys that you care about. For pointers, the pointer's value is used to test for nonzero in addition to the pointer itself not being nil. To just check for not being nil, use `nonnil`. (Usage: nonzero) regexp Only valid for string types, it will validate that the value matches the regular expression provided as parameter. Commas need to be escaped with 2 backslashes `\\`. (Usage: regexp=^a.*b$) nonnil Validates that the given value is not nil. (Usage: nonnil) ``` Custom validators It is possible to define custom validators by using SetValidationFunc. First, one needs to create a validation function. ```go // Very simple validator func notZZ(v interface{}, param string) error { st := reflect.ValueOf(v) if st.Kind() != reflect.String { return errors.New("notZZ only validates strings") } if st.String() == "ZZ" { return errors.New("value cannot be ZZ") } return nil } ``` Then one needs to add it to the list of validators and give it a "tag" name. ```go validator.SetValidationFunc("notzz", notZZ) ``` Then it is possible to use the notzz validation tag. This will print "Field A error: value cannot be ZZ" ```go type T struct { A string `validate:"nonzero,notzz"` } t := T{"ZZ"} if errs := validator.Validate(t); errs != nil { fmt.Printf("Field A error: %s\n", errs["A"][0]) } ``` You can also have multiple sets of validator rules with SetTag(). ```go type T struct { A int `foo:"nonzero" bar:"min=10"` } t := T{5} SetTag("foo") validator.Validate(t) // valid as it's nonzero SetTag("bar") validator.Validate(t) // invalid as it's less than 10 ``` SetTag is probably better used with multiple validators. ```go fooValidator := validator.NewValidator() fooValidator.SetTag("foo") barValidator := validator.NewValidator() barValidator.SetTag("bar") fooValidator.Validate(t) barValidator.Validate(t) ``` This keeps the default validator's tag clean. Again, please refer to godocs for a lot of more examples and different uses. # Pull requests policy tl;dr. Contributions are welcome. The repository is organized in version branches. Pull requests to, say, the `v2` branch that break API compatibility will not be accepted. It is okay to break the API in master, _not in the branches_. As for validation functions, the preference is to keep the main code simple and add most new functions to the validator-contrib repository. https://github.com/go-validator/validator-contrib For improvements and/or fixes to the builtin validation functions, please make sure the behaviour will not break existing functionality in the branches. If you see a case where the functionality of the builtin will change significantly, please send a pull request against `master`. We can discuss then whether the changes should be incorporated in the version branches as well. # License Copyright 2014 <NAME> <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
c53fe40514d4e271a96248d9e105b29acd6aca66
[ "Markdown", "Go Module", "Go" ]
7
Go
go-validator/validator
849d4e5cae3c79d0347839097329d70c7d3f4b2e
ebea6c965cef16afbd1986a920824f3651a480ae
refs/heads/master
<file_sep>#![feature(fnbox)] #![feature(generators)] #![feature(proc_macro)] #![feature(never_type)] extern crate bytes; extern crate futures_await as futures; extern crate msgio; #[macro_use] extern crate slog; extern crate tokio_io; mod negotiator; mod propose; mod accept; pub use negotiator::Negotiator; <file_sep>[package] authors = ["<NAME> <<EMAIL>>"] name = "multistream" version = "0.1.0" [dependencies] bytes = "0.4.4" futures-await = "0.1.1" msgio = { path = "../msgio-rs" } slog = "2.0.12" tokio-io = "0.1.2" <file_sep>use std::boxed::FnBox; use std::io; use std::str; use bytes::Bytes; use futures::{future, Future, Stream, Sink}; use msgio::{LengthPrefixed, Prefix, Suffix}; use slog::Logger; use tokio_io::codec::{Framed, FramedParts}; use tokio_io::{AsyncRead, AsyncWrite}; use accept::accept; use propose::propose_all; const PROTOCOL_ID: &'static str = "/multistream/1.0.0"; pub struct Negotiator<P: AsRef<str> + 'static, S: AsyncRead + AsyncWrite + 'static, R: 'static> { logger: Logger, initiator: bool, transport: Framed<S, LengthPrefixed>, protocols: Vec<(P, Box<FnBox(FramedParts<S>) -> R>)>, } fn send_header<S: AsyncRead + AsyncWrite + 'static>(logger: Logger, transport: Framed<S, LengthPrefixed>) -> impl Future<Item=Framed<S, LengthPrefixed>, Error=io::Error> { transport.send(Bytes::from(PROTOCOL_ID)) .and_then(|transport| transport.into_future().map_err(|(error, _stream)| error)) .and_then(move |(response, transport)| { let response = response.as_ref().map(|b| str::from_utf8(b)); trace!(logger, "multistream header received: {:?}", response); match response { Some(Ok(response)) => if response == PROTOCOL_ID { Ok(transport) } else { Err(io::Error::new(io::ErrorKind::Other, format!("Server requested unknown multistream protocol {:?}", response))) }, Some(Err(e)) => Err(io::Error::new(io::ErrorKind::InvalidData, e)), None => Err(io::Error::new(io::ErrorKind::Other, "Server unexpectedly closed the connection")), } }) } impl<P: AsRef<str> + 'static, S: AsyncRead + AsyncWrite + 'static, R: 'static> Negotiator<P, S, R> { pub fn start(logger: Logger, transport: S, initiator: bool) -> Negotiator<P, S, R> { let protocols = Vec::new(); let transport = transport.framed(LengthPrefixed(Prefix::VarInt, Suffix::NewLine)); Negotiator { logger, initiator, transport, protocols } } pub fn negotiate<F>(mut self, protocol: P, callback: F) -> Self where F: FnBox(FramedParts<S>) -> R + 'static { self.protocols.push((protocol, Box::new(callback))); self } pub fn finish(self) -> impl Future<Item=R, Error=io::Error> + 'static { let Negotiator { logger, initiator, transport, protocols } = self; send_header(logger.clone(), transport) .and_then(move |transport| { if initiator { debug!(logger, "Attempting to negotiate multistream"); future::Either::A(propose_all(logger, transport, protocols)) } else { debug!(logger, "Attempting to accept multistream"); future::Either::B(accept(logger, transport, protocols)) } }) } } <file_sep>use std::boxed::FnBox; use std::io; use std::str; use bytes::Bytes; use futures::{Stream, Sink}; use futures::prelude::{async, await}; use msgio::LengthPrefixed; use slog::Logger; use tokio_io::codec::{Framed, FramedParts}; use tokio_io::{AsyncRead, AsyncWrite}; #[async] pub fn accept<P, S, R>( logger: Logger, mut transport: Framed<S, LengthPrefixed>, mut protocols: Vec<(P, Box<FnBox(FramedParts<S>) -> R>)>) -> Result<R, io::Error> where P: AsRef<str> + 'static, S: AsyncRead + AsyncWrite + 'static, R: 'static { while let (Some(message), t) = await!(transport.into_future()).map_err(|(e, _)| e)? { transport = t; let message = {let logger = logger.clone(); String::from_utf8(message.to_vec()).map_err(move |e| { debug!(logger, "Server requested non-utf8 protocol"); io::Error::new(io::ErrorKind::InvalidData, e) })?}; if message == "ls" { debug!(logger, "TODO: Server requested ls"); return Err(io::Error::new(io::ErrorKind::Other, "TODO: Server requested ls")); } let index = protocols.iter().position(|&(ref p, _)| p.as_ref() == message); if let Some(i) = index { let (protocol, callback) = protocols.swap_remove(i); debug!(logger, "Negotiated multistream protocol {}", protocol.as_ref()); transport = await!(transport.send(Bytes::from(protocol.as_ref())))?; return Ok(callback(transport.into_parts())); } else { debug!(logger, "Server asked for unknown protocol {}", message); transport = await!(transport.send(Bytes::from(&b"na"[..])))?; } } return Err(io::Error::new(io::ErrorKind::Other, "Peer gave up on negotiation")); } <file_sep>use std::boxed::FnBox; use std::io; use std::str; use bytes::Bytes; use futures::{Future, Stream, Sink}; use futures::prelude::{async, await}; use msgio::LengthPrefixed; use slog::Logger; use tokio_io::codec::{Framed, FramedParts}; use tokio_io::{AsyncRead, AsyncWrite}; #[async] fn propose<P, S>(logger: Logger, transport: Framed<S, LengthPrefixed>, protocol: P) -> Result<(bool, Framed<S, LengthPrefixed>), io::Error> where P: AsRef<str> + 'static, S: AsyncRead + AsyncWrite + 'static { debug!(logger, "Attempting to propose multistream protocol"); let sending = transport.send(Bytes::from(protocol.as_ref())); let transport = await!(sending)?; let receiving = transport.into_future().map_err(|(error, _stream)| error); let (response, transport) = await!(receiving)?; match response.map(|b| String::from_utf8(b.to_vec())) { Some(Ok(response)) => if response == protocol.as_ref() { debug!(logger, "Negotiated multistream protocol"); Ok((true, transport)) } else if response == "na" { debug!(logger, "Server denied multistream protocol"); Ok((false, transport)) } else { debug!(logger, "Server returned unexpected response {}", response); Err(io::Error::new(io::ErrorKind::Other, "Unexpected response while negotiating multistream")) }, Some(Err(e)) => { debug!(logger, "Server sent non-utf8 message"); Err(io::Error::new(io::ErrorKind::InvalidData, e)) } None => { debug!(logger, "Server unexpectedly closed the connection"); Err(io::Error::new(io::ErrorKind::Other, "Server unexpectedly closed the connection")) } } } #[async] pub fn propose_all<P, S, R>(logger: Logger, mut transport: Framed<S, LengthPrefixed>, protocols: Vec<(P, Box<FnBox(FramedParts<S>) -> R + 'static>)>) -> Result<R, io::Error> where P: AsRef<str> + 'static, S: AsyncRead + AsyncWrite + 'static, R: 'static { for (protocol, callback) in protocols { let proposal = propose(logger.new(o!("protocol" => protocol.as_ref().to_owned())), transport, protocol); let (success, t) = await!(proposal)?; if success { return Ok(callback(t.into_parts())); } else { transport = t; } } Err(io::Error::new(io::ErrorKind::Other, "No protocol was negotiated")) }
7d0edaed7689826b88dfa7bfb027ad076507cb80
[ "TOML", "Rust" ]
5
Rust
Nemo157/multistream-rs
f04654b88f99f6fd527977d965330a7e2dce7bb7
d37830c351d2b970e84daa5831963aae4f873e81
refs/heads/master
<repo_name>DeepanshuJha/WebTechnologyAssignment<file_sep>/A7/src/java/com/myapp/struts/loginform.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.myapp.struts; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; /** * * @author d_silent */ public class loginform extends org.apache.struts.action.Action { /* forward name="success" path="" */ private static final String SUCCESS = "success"; private static final String FAILURE = "failure"; /** * This is the action called from the Struts framework. * * @param mapping The ActionMapping used to select this instance. * @param form The optional ActionForm bean for this request. * @param request The HTTP Request we are processing. * @param response The HTTP Response we are processing. * @throws java.lang.Exception * @return */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { PrintWriter out = response.getWriter(); loginbean lb = (loginbean)form; int rollno = Integer.valueOf(lb.getRollno()); String name = lb.getName(); Class.forName("com.mysql.jdbc.Driver"); Connection con; try{ con = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", ""); Statement st; st = con.createStatement(); ResultSet resu; resu = st.executeQuery("Select * from login"); while(resu.next()){ if((int)resu.getObject(1) == rollno && resu.getObject(2).equals(name)){ return mapping.findForward(SUCCESS); } } return mapping.findForward(FAILURE); }catch(Exception e){ out.println(e); } return mapping.findForward(FAILURE); } } <file_sep>/A5/display.php <!DOCTYPE html> <html lang="en"> <head> <title>Display</title> <link rel="stylesheet" href="bootstrap.min.css"> <script src="jquery-3.2.1.min.js"></script> </head> <body> <div class="container"> <h1 class="text-center text-primary my-3">DISPLAY OPERATION</h1> <div class="my-4"> <table class="table table-bordered table-striped"> <tr> <th>No.</th> <th>Roll No</th> <th>Name</th> </tr> <?php include_once("config.php"); $query = "Select * from login"; $result = mysqli_query($con, $query); if(mysqli_num_rows($result) > 0){ $number = 1; while($row = mysqli_fetch_array($result)){ echo "<tr>"; echo "<td>".$number."</td>"; echo "<td>".$row['rollno']."</td>"; echo "<td>".$row['name']."</td>"; echo "</tr>"; $number++; } } ?> </table> </div> <a href="index.php" role="button" class="btn btn-primary">Go Back</a> </div> <script src="bootstrap.min.js"></script> </body> </html><file_sep>/A5/update.php <!DOCTYPE html> <html lang="en"> <head> <title>Update</title> <link rel="stylesheet" href="bootstrap.min.css"> </head> <body> <div class="container"> <h1 class="text-primary text-center my-3">UPDATE OPERTION</h1> <div class="my-4" style="width:500px; margin: auto; position:relative; top:75px;"> <?php include_once('config.php'); if(isset($_POST['rollno']) && isset($_POST['name'])){ $rollno = $_POST['rollno']; $name = $_POST['name']; $query = "UPDATE `login` SET `name`= '$name' WHERE `rollno` = '$rollno'"; $res = mysqli_query($con, $query); if($res){ echo "<h4 class='text-success'>Success</h4>"; } } ?> <form action="update.php" method="POST"> <div class="form-group"> <label for="rollno">Roll No</label> <input type="text" class="form-control" name="rollno"> </div> <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" name="name"> </div> <input type="submit" class="btn btn-warning px-4" name="submit"> <a href="index.php" role="button" class="btn btn-primary">Go Back</a> </form> </div> </div> <script src="bootstrap.min.js"></script> </body> </html><file_sep>/A5/add.php <!DOCTYPE html> <html lang="en"> <head> <title>CRUD</title> <link rel="stylesheet" href="bootstrap.min.css"> <script src="jquery-3.2.1.min.js"></script> </head> <body> <div class="container"> <h1 class="text-center text-primary my-3">INSERT OPERATION</h1> <div style="width:500px; margin: auto; position:relative; top:75px;"> <?php include_once('config.php'); if(isset($_POST['submit'])){ $rollno = $_POST['rollno']; $name = $_POST['name']; $query = "insert into login values('$rollno', '$name')"; $res = mysqli_query($con, $query); if($res){ echo "<h4 class='text-success'>Success</h4>"; } } ?> <form action="add.php" method="POST"> <div class="form-group"> <label for="rollno">Roll No</label> <input type="text" name="rollno" class="form-control"> </div> <div class="form-group"> <label for="name">Name</label> <input type="text" name="name" class="form-control"> </div> <input type="submit" class="btn btn-success px-4" name="submit"> <a href="index.php" role="button" class="btn btn-primary">Go Back</a> </form> </div> </div> <script src="bootstrap.min.js"></script> </body> </html><file_sep>/A4/src/java/deepanshu/loginServer.java package deepanshu; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/login") public class loginServer extends HttpServlet{ public void service(HttpServletRequest req, HttpServletResponse res) throws IOException,ServletException { PrintWriter out = res.getWriter(); int rollno = Integer.valueOf(req.getParameter("rollno")); String name = req.getParameter("name"); try{ Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", ""); Statement st; st = con.createStatement(); ResultSet result = st.executeQuery("Select * from login"); while(result.next()){ if((int)result.getObject(1) == rollno && result.getObject(2).equals(name)){ res.sendRedirect("success.jsp"); } } res.sendRedirect("failure.jsp"); }catch(Exception e){ out.println(e); } } } <file_sep>/README.md # WebTechnologyAssignment All WTL asssignments * A1 - HTML Pages * A2 - XML & XLST * A3 - Validation * A4 - JSP Servlet * A5 - PHP & MYSQL * A6 - PHP, AJAX & MYSQL * A7 - Struts * A8 - Angular and Bootstrap * A9 - Bootstrap Calculator (alternative for EJB) # Table Structure Used This is the db and table used for all the assignments above. ```sql -> Create database user; -> Create table login (rollno int, name varchar(30)); ``` <file_sep>/A7/nbproject/private/private.properties deploy.ant.properties.file=/Users/d_silent/Library/Application Support/NetBeans/8.2/tomcat90.properties j2ee.server.home=/Library/Tomcat j2ee.server.instance=tomcat90:home=/Library/Tomcat user.properties.file=/Users/d_silent/Library/Application Support/NetBeans/8.2/build.properties <file_sep>/A6/backend.php <?php $con = mysqli_connect("localhost", "root", "", "user"); extract($_POST); if(isset($_POST['readRecords'])){ $data = '<table class="table table-bordered table-striped"> <tr> <th>No.</th> <th>Roll No</th> <th>Name</th> <th>Delete Action</th> </tr>'; $query = "Select * from login"; $result = mysqli_query($con, $query); if(mysqli_num_rows($result) > 0){ $number = 1; while($row = mysqli_fetch_array($result)){ $data .= '<tr> <td>'.$number.'</td> <td>'.$row['rollno'].'</td> <td>'.$row['name'].'</td> <td><button type="button" class="btn btn-danger" onclick="deleteUser('.$row['rollno'].')">Delete</button></td> </tr>'; $number++; } } $data .= "</table>"; echo $data; } if(isset($_POST['rollno']) && isset($_POST['name'])){ $query = "insert into login values('$rollno', '$name')"; mysqli_query($con, $query); } if(isset($_POST['deleteId'])){ $query = "delete from login where rollno = '$deleteId'"; mysqli_query($con, $query); } ?>
004e6262ca298305cf9d46db29c8412c224fd449
[ "Markdown", "Java", "PHP", "INI" ]
8
Java
DeepanshuJha/WebTechnologyAssignment
6eaef4285e475396932a6ea969c49918a74fdecd
add45075fa7efab73c178648eb436d3c23e06a89
refs/heads/master
<file_sep>#include <stdio.h> int fib_recursivo(int x); int main() { int result; result = fib_recursivo(1); printf("Resultado: %d\n", result); return 0; } int fib_recursivo(int x) { if(x == 0 || x == 1) { return 1; } return fib_recursivo(x-1) + fib_recursivo(x-2); } <file_sep>/** * Programa para arvore binaria de busca (Cria arvore, Insere no e Percorre arvore Em Ordem, Pre-Ordem e Pos-Ordem) * * Autor: <NAME> * GitHub: https://github.com/SantosAdan/C-C- * Data: 01/03/2017 */ #include <stdlib.h> #include <stdio.h> // Definindo constantes para representar os caminhos #define PRE_ORDER 1 #define IN_ORDER 2 #define POST_ORDER 3 // Estrutura para representacao do no struct node { int value; struct node *left, *right; }; typedef struct node NODE; // Criando alias para a estrutura // Cabecalho de Funcoes void makeTree(NODE ** root, int value); void insertNode(NODE ** root, int value); void deleteNode(NODE ** root, int value); void traverseTree(NODE * root, int option); void printInOrder(NODE * root); void printPreOrder(NODE * root); void printPostOrder(NODE * root); /** * Limpa a tela Windows/Linux */ void clrscr() { system("@cls||clear"); } void main() { int option, value; NODE *root = NULL; while(1) { printf("\n------------------------- MENU ------------------------\n"); printf("\t\t1 - Criar arvore binaria\n"); printf("\t\t2 - Inserir elemento na arvore\n"); printf("\t\t3 - Remover elemento da arvore\n"); printf("\t\t4 - Imprime arvore EM ORDEM\n"); printf("\t\t5 - Imprime arvore PRE ORDEM\n"); printf("\t\t6 - Imprime arvore POS ORDEM\n"); printf("\t\t7 - Sair\n"); printf("\n-------------------------------------------------------"); printf("\nEscolha uma opcao: "); scanf("%d", &option); clrscr(); switch (option) { case 1: printf("\nEntre com o valor para o no: "); scanf("%d", &value); makeTree(&root, value); break; case 2: printf("\nEntre com o valor para o no: "); scanf("%d", &value); insertNode(&root, value); break; case 3: printf("\nEntre com o valor para remover: "); scanf("%d", &value); deleteNode(&root, value); break; case 4: printf("\n----------- EM ORDEM -------------\n"); traverseTree(root, IN_ORDER); printf("\n-----------------------------------\n"); break; case 5: printf("\n----------- PRE-ORDEM -------------\n"); traverseTree(root, PRE_ORDER); printf("\n-----------------------------------\n"); break; case 6: printf("\n----------- POS-ORDEM -------------\n"); traverseTree(root, POST_ORDER); printf("\n-----------------------------------\n"); break; case 7: exit(0); default : printf("Escolha errada. Por favor escolha uma opcao valida... "); break; } } } /** * Cria arvore binaria com valor passado pelo usuario. * * @param root Ponteiro para no raiz da arvore * @param value Valor a inserir no no raiz */ void makeTree(NODE ** root, int value) { NODE *temp = NULL; temp = (NODE *)malloc(sizeof(NODE)); temp->left = temp->right = NULL; temp->value = value; *root = temp; return; } /** * Insere valor na árvore. * * @param root Ponteiro para no raiz da arvore * @param value Valor a inserir no no raiz */ void insertNode(NODE ** root, int value) { NODE *temp = NULL; // Se árvore vazia, cria árvore inserindo o valor no nó raiz if(!(*root)) { makeTree(&(*root), value); } // se o valor for menor que o armazenado no nó da iteracao if(value < (*root)->value) { insertNode(&(*root)->left, value); // Insere no a esquerda } // se o valor for maior que o armazenado no nó da iteracao else if(value > (*root)->value) { insertNode(&(*root)->right, value); // Insere no a direita } } /** * Remove nó com o valor passado pelo usuário. * * @param root Ponteiro para no raiz da arvore * @param value Valor a inserir no no raiz */ void deleteNode(NODE ** root, int value) { printf("\nNao implementado...\n"); } /** * Caminha na árvore utilizando o método selecionado pelo usuário. * * @param root Ponteiro para no raiz da arvore * @param optiob Valor a inserir no no raiz */ void traverseTree(NODE * root, int option) { switch(option) { case 1: printPreOrder(root); break; case 2: printInOrder(root); break; case 3: printPostOrder(root); break; } } /** * Percorre árvore EM ORDEM * * @param root Ponteiro para no raiz da arvore */ void printInOrder(NODE * root) { if(root == NULL) { printf("Árvore Vazia!"); return; } if(root) { printInOrder(root->left); printf("%d - ", root->value); printInOrder(root->right); } } /** * Percorre árvore PRÉ-ORDEM * * @param root Ponteiro para no raiz da arvore */ void printPreOrder(NODE * root) { if(root == NULL) { printf("Árvore Vazia!"); return; } if(root) { printf("%d - ", root->value); printPreOrder(root->left); printPreOrder(root->right); } } /** * Percorre árvore PÓS-ORDEM * * @param root Ponteiro para no raiz da arvore */ void printPostOrder(NODE * root) { if(root == NULL) { printf("Árvore Vazia!"); return; } if(root) { printPostOrder(root->left); printPostOrder(root->right); printf("%d - ", root->value); } } <file_sep># Estudos de Estruturas de Dados em C e C++ ## Fibonacci Recursivo * fib_recursivo.c ## Função Mínimo e Máximo * MinMax.c ## Árvore Binária de Busca * binaryTree.c<file_sep>/** * Programa para encontrar valor minimo e valor maximo dos elementos de um vetor. * * Autor: <NAME> * GitHub: https://github.com/SantosAdan/C-C- * Data: 01/03/2017 */ #include <stdio.h> #define MAX 65536 // Declaracao de Funcoes void findMinMax(int * min, int * max, int vetor[], int posicao); int main() { int min, max; int posicao, valor; int vetor[MAX]; printf("Entre com os valores do vetor: \n"); printf("Entre com valor -1 para parar de inserir dados no vetor.\n"); // Inicializa o contador da posicao/tamanho do vetor posicao = 0; // Enquanto o valor digitado for diferente de -1 while(valor != -1) { printf("\nVetor[%d] = ", posicao); scanf("%d", &valor); // Se o valor digitado for -1, finaliza a entrada de dados if(valor == -1) break; vetor[posicao] = valor; posicao++; } // Se o vetor possui mais de um elemento, encontra MIM e MAX e imprime na tela if(posicao != 0) { findMinMax(&min, &max, vetor, posicao); printf("Minimo = %d\nMaximo = %d\n", min, max); } // Senao exibe mensagem de vetor vazio e encerra programa else { printf("\nVetor nao possui elementos.\n"); } return 0; } /** * Função para encontrar o valor máximo e mínimo de um conjunto de dados * @param min Ponteiro para a variável minimo * @param max Ponteiro para a variável maximo * @param vetor Vetor contendo o conjunto de dados * @param tamanho Numero de elementos do vetor */ void findMinMax(int * min, int * max, int vetor[], int tamanho) { int contador = 0; *min = vetor[0]; *max = vetor[0]; for (contador = 0; contador < tamanho; contador++) { if(*min > vetor[contador]) { *min = vetor[contador]; } if(*max < vetor[contador]) { *max = vetor[contador]; } } }
d258d2c3d46cc5af952afff4a172309ea7732725
[ "Markdown", "C" ]
4
C
SantosAdan/C-C-
5b56e6cf89ba5bf3c5a981af3c59423feed69cca
767e87ee4e3394e3bf4e05fd7f4bf1d733f615ae
refs/heads/master
<file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CadSiglaComponent } from './cad-sigla/cad-sigla.component'; import { ListaSiglaComponent } from './lista-sigla/lista-sigla.component'; @NgModule({ declarations: [CadSiglaComponent, ListaSiglaComponent], imports: [ CommonModule ] }) export class SiglasModule { } <file_sep>import { ImagemService } from './../../zservice/imagem.service'; import { ProcedimentoatendimentoService } from './../../zservice/procedimentoatendimento.service'; import { SelectItem } from 'primeng/api'; import { Imagem, PaginaDeImagens, LAYOUT_IMG, ImagemImpressa, Estudo } from './../../core/model'; import { Component, Input, OnInit } from '@angular/core'; import { Location } from '@angular/common'; @Component({ selector: 'app-paginaimagens', templateUrl: './paginaimagens.component.html', styleUrls: ['./paginaimagens.component.css'] }) export class PaginaimagensComponent implements OnInit { @Input() paginadeimagens: Array<PaginaDeImagens>; @Input('listaimagem') listaimagem: Array<Imagem>; pagina = new PaginaDeImagens(); listaimagemsbase = new Array<Imagem>(); qtdimagems: SelectItem[]; qtdimagemselecionada = 1; paginaselecionada = 0; valorspinner: number = 1; valorselecionado: number = 0; constructor(private location: Location, private serviceproc: ProcedimentoatendimentoService) {} ngOnInit() { this.OpcoesQtdImagens(); this.ConfigurarVariavel(); if (this.paginadeimagens.length === 0) { this.AdicionarPagina(); } this.VerificaQualLayout(0); this.PegaAltura(); } PegaAltura() { const painel = document.getElementById('painelgerallaudo').clientHeight; const editor = document.getElementById('geral'); editor.setAttribute('style' , 'height: ' + painel + 'px;'); } OpcoesQtdImagens() { this.qtdimagems = [ {label: '1 Imagem Grande', value: 1}, {label: '1 Imagem Média', value: 2}, {label: '2 Imagem Grandes', value: 3}, {label: '2 Imagem Médias', value: 4}, {label: '3 Imagem Médias', value: 5}, {label: '4 Imagem Grandes', value: 6}, {label: '4 Imagem Médias', value: 7}, {label: '4 Imagem Pequenas', value: 8}, {label: '6 Imagem Grandes', value: 9}, {label: '6 Imagem Médias', value: 10}, {label: '8 Imagem Grandes', value: 11}, {label: '8 Imagem Pequenas', value: 12}, {label: '9 Imagem Pequenas', value: 13}, {label: '12 Imagem Pequenas', value: 14}, {label: '15 Imagem Pequenas', value: 15} ]; } AdicionarPagina() { this.pagina = new PaginaDeImagens(); this.pagina.layout = this.EscolhendoLayout(); this.pagina.procedimentoatendimento = this.listaimagem[0].procedimentoatendimento; this.paginadeimagens.push(this.pagina); } RemoverPagina() { this.paginadeimagens.splice(this.paginaselecionada, 1); } EscolherPagina(index) { this.paginaselecionada = index; this.VerificaQualLayout(index); } PermiteArrastar(ev) { ev.preventDefault(); } Arrastar(ev) { ev.dataTransfer.setData('text', ev.target.id); } Dropar(ev, valor: number) { ev.preventDefault(); const data = ev.dataTransfer.getData('text'); for (let i = 0; i < this.listaimagem.length; i++) { if (this.listaimagem[i].nomeimagem === data) { if (this.listaimagemsbase[valor] === undefined) { this.listaimagemsbase[valor] = this.listaimagem[i]; this.listaimagem.splice(i, 1); const imagemimpressa = new ImagemImpressa(); imagemimpressa.indice = valor; imagemimpressa.imagem = this.listaimagemsbase[valor]; this.pagina.layout = this.EscolhendoLayout(); this.pagina.imagemimpressa.push(imagemimpressa); } else { this.listaimagem.push(this.listaimagemsbase[valor]); this.listaimagemsbase[valor] = this.listaimagem[i]; this.listaimagem.splice(i, 1); this.pagina.layout = this.EscolhendoLayout(); this.paginadeimagens[this.paginaselecionada].imagemimpressa[valor].imagem = this.listaimagemsbase[valor]; this.pagina.imagemimpressa.push(this.paginadeimagens[this.paginaselecionada].imagemimpressa[i]); } } } } DropRetorno(ev) { let confere = true as boolean; ev.preventDefault(); const data = ev.dataTransfer.getData('text'); this.listaimagem.forEach(elo => { if (elo.nomeimagem === data) { confere = false; } }); if (confere) { this.listaimagem.push(this.listaimagemsbase[data]); this.listaimagemsbase[data] = undefined; } } ConfigurarVariavel() { const lista = new Array<number>(); this.paginadeimagens.forEach(elo => { elo.imagemimpressa.forEach(alo => { lista.push(alo.imagem.codigo); }); }); lista.forEach(elo => { this.listaimagem.forEach(alo => { if (elo === alo.codigo) { this.listaimagem.splice(this.listaimagem.indexOf(alo), 1); } }); }); this.ConfigurarDimensoes(); } VerificaQualLayout(posicao) { if (this.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_1_GRANDE) { this.qtdimagemselecionada = 1; } if (this.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_1_MEDIA) { this.qtdimagemselecionada = 2; } if (this.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_2_GRANDE) { this.qtdimagemselecionada = 3; } if (this.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_2_MEDIA) { this.qtdimagemselecionada = 4; } if (this.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_3_MEDIA) { this.qtdimagemselecionada = 5; } if (this.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_4_GRANDE) { this.qtdimagemselecionada = 6; } if (this.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_4_MEDIA) { this.qtdimagemselecionada = 7; } if (this.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_4_PEQUENA) { this.qtdimagemselecionada = 8; } if (this.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_6_GRANDE) { this.qtdimagemselecionada = 9; } if (this.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_6_MEDIA) { this.qtdimagemselecionada = 10; } if (this.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_8_GRANDE) { this.qtdimagemselecionada = 11; } if (this.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_8_PEQUENA) { this.qtdimagemselecionada = 12; } if (this.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_9_PEQUENA) { this.qtdimagemselecionada = 13; } if (this.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_12_PEQUENA) { this.qtdimagemselecionada = 14; } if (this.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_15_PEQUENA) { this.qtdimagemselecionada = 15; } this.ConfigurarDimensoes(); this.RoteandoImagens(posicao); } RoteandoImagens(numero: number) { this.listaimagemsbase = new Array<Imagem>(); this.paginadeimagens[numero].imagemimpressa.forEach(alo => { this.serviceproc.PegarImagemString(alo.imagem.codigo).subscribe(data => { alo.imagem.imagem = data; this.listaimagemsbase.push(alo.imagem); }, error => { console.log(error); }); }); } EscolhendoLayout() { if (this.qtdimagemselecionada === 1) { return LAYOUT_IMG.LAYOUT_1_GRANDE; } if (this.qtdimagemselecionada === 2) { return LAYOUT_IMG.LAYOUT_1_MEDIA; } if (this.qtdimagemselecionada === 3) { return LAYOUT_IMG.LAYOUT_2_GRANDE; } if (this.qtdimagemselecionada === 4) { return LAYOUT_IMG.LAYOUT_2_MEDIA; } if (this.qtdimagemselecionada === 5) { return LAYOUT_IMG.LAYOUT_3_MEDIA; } if (this.qtdimagemselecionada === 6) { return LAYOUT_IMG.LAYOUT_4_GRANDE; } if (this.qtdimagemselecionada === 7) { return LAYOUT_IMG.LAYOUT_4_MEDIA; } if (this.qtdimagemselecionada === 8) { return LAYOUT_IMG.LAYOUT_4_PEQUENA; } if (this.qtdimagemselecionada === 9) { return LAYOUT_IMG.LAYOUT_6_GRANDE; } if (this.qtdimagemselecionada === 10) { return LAYOUT_IMG.LAYOUT_6_MEDIA; } if (this.qtdimagemselecionada === 11) { return LAYOUT_IMG.LAYOUT_8_GRANDE; } if (this.qtdimagemselecionada === 12) { return LAYOUT_IMG.LAYOUT_8_PEQUENA; } if (this.qtdimagemselecionada === 13) { return LAYOUT_IMG.LAYOUT_9_PEQUENA; } if (this.qtdimagemselecionada === 14) { return LAYOUT_IMG.LAYOUT_12_PEQUENA; } if (this.qtdimagemselecionada === 15) { return LAYOUT_IMG.LAYOUT_15_PEQUENA; } } ConfigurarDimensoes() { for (let i = 1; i <= 15; i++) { const lab = document.getElementById('lab' + i); lab.setAttribute('style', 'display: none'); const gradeimg = document.getElementById('gradeimg'); gradeimg.children[i - 1].setAttribute('style', 'display: none'); } if (this.qtdimagemselecionada === 1) { const gradeimg = document.getElementById('gradeimg'); gradeimg.setAttribute('style', 'margin: 0 auto; position: relative; text-align: center; margin-top: 61mm;'); gradeimg.children[0].setAttribute('style', 'display:block; padding: 2mm;'); const lab = document.getElementById('lab1'); lab.setAttribute('style', 'display: block'); lab.setAttribute('class', 'foto1grande'); } if (this.qtdimagemselecionada === 2) { const gradeimg = document.getElementById('gradeimg'); gradeimg.setAttribute('style', 'margin: 0 auto; position: relative; text-align: center; margin-top: 61mm;'); gradeimg.children[0].setAttribute('style', 'display:block; padding: 2mm;'); const lab = document.getElementById('lab1'); lab.setAttribute('style', 'display: block'); lab.setAttribute('class', 'foto1media'); } if (this.qtdimagemselecionada === 3) { const gradeimg = document.getElementById('gradeimg'); gradeimg.setAttribute('style', 'margin: 0 auto; position: relative; text-align: center; margin-top: 20mm;'); for (let i = 1; i <= 2; i++) { const lab = document.getElementById('lab' + i); lab.setAttribute('style', 'display: block'); lab.setAttribute('class', 'foto2grande'); gradeimg.children[i - 1].setAttribute('style', 'display:block; padding: 2mm;'); } } if (this.qtdimagemselecionada === 4) { const gradeimg = document.getElementById('gradeimg'); gradeimg.setAttribute('style', 'margin: 0 auto; position: relative; text-align: center; margin-top: 61mm;'); for (let i = 1; i <= 2; i++) { const lab = document.getElementById('lab' + i); lab.setAttribute('style', 'display: block'); lab.setAttribute('class', 'foto2media'); gradeimg.children[i - 1].setAttribute('style', 'display:block; padding: 2mm;'); } } if (this.qtdimagemselecionada === 5) { const gradeimg = document.getElementById('gradeimg'); gradeimg.setAttribute('style', 'margin: 0 auto; position: relative; text-align: center; margin-top: 61mm;'); for (let i = 1; i <= 3; i++) { const lab = document.getElementById('lab' + i); lab.setAttribute('style', 'display: block'); lab.setAttribute('class', 'foto3media'); gradeimg.children[i - 1].setAttribute('style', 'display:block; padding: 2mm;'); } } if (this.qtdimagemselecionada === 6) { const gradeimg = document.getElementById('gradeimg'); gradeimg.setAttribute('style', 'margin: 0 auto; position: relative; text-align: center; margin-top: 61mm; width: 190mm; height: auto; display: block;'); for (let i = 1; i <= 4; i++) { const lab = document.getElementById('lab' + i); lab.setAttribute('style', 'display: block'); lab.setAttribute('class', 'foto4grande'); gradeimg.children[i - 1].setAttribute('style', 'display:block; padding: 2mm; float: left;'); } } if (this.qtdimagemselecionada === 7) { const gradeimg = document.getElementById('gradeimg'); gradeimg.setAttribute('style', 'margin: 0 auto; position: relative; text-align: center; margin-top: 20mm; width: 170mm; height: auto; display: block;'); for (let i = 1; i <= 4; i++) { const lab = document.getElementById('lab' + i); lab.setAttribute('style', 'display: block'); lab.setAttribute('class', 'foto4media'); gradeimg.children[i - 1].setAttribute('style', 'display:block; padding: 2mm; float: left;'); } } if (this.qtdimagemselecionada === 8) { const gradeimg = document.getElementById('gradeimg'); gradeimg.setAttribute('style', 'margin: 0 auto; position: relative; text-align: center; margin-top: 61mm; width: 140mm; height: auto; display: block;'); for (let i = 1; i <= 4; i++) { const lab = document.getElementById('lab' + i); lab.setAttribute('style', 'display: block'); lab.setAttribute('class', 'foto4pequena'); gradeimg.children[i - 1].setAttribute('style', 'display:block; padding: 2mm; float: left;'); } } if (this.qtdimagemselecionada === 9) { const gradeimg = document.getElementById('gradeimg'); gradeimg.setAttribute('style', 'margin: 0 auto; position: relative; text-align: center; margin-top: 30mm; width: 190mm; height: auto; display: block;'); for (let i = 1; i <= 6; i++) { const lab = document.getElementById('lab' + i); lab.setAttribute('style', 'display: block'); lab.setAttribute('class', 'foto6grande'); gradeimg.children[i - 1].setAttribute('style', 'display:block; padding: 2mm; float: left;'); } } if (this.qtdimagemselecionada === 10) { const gradeimg = document.getElementById('gradeimg'); gradeimg.setAttribute('style', 'margin: 0 auto; position: relative; text-align: center; margin-top: 30mm; width: 170mm; height: auto; display: block;'); for (let i = 1; i <= 6; i++) { const lab = document.getElementById('lab' + i); lab.setAttribute('style', 'display: block'); lab.setAttribute('class', 'foto6media grade1'); gradeimg.children[i - 1].setAttribute('style', 'display:block; padding: 2mm; float: left;'); } } if (this.qtdimagemselecionada === 11) { const gradeimg = document.getElementById('gradeimg'); gradeimg.setAttribute('style', 'margin: 0 auto; position: relative; text-align: center; margin-top: 20mm; width: 190mm; height: auto; display: block;'); for (let i = 1; i <= 8; i++) { const lab = document.getElementById('lab' + i); lab.setAttribute('style', 'display: block'); lab.setAttribute('class', 'foto8grande'); gradeimg.children[i - 1].setAttribute('style', 'display:block; padding: 2mm; float: left;'); } } if (this.qtdimagemselecionada === 12) { const gradeimg = document.getElementById('gradeimg'); gradeimg.setAttribute('style', 'margin: 0 auto; position: relative; text-align: center; margin-top: 30mm; width: 140mm; height: auto; display: block;'); for (let i = 1; i <= 8; i++) { const lab = document.getElementById('lab' + i); lab.setAttribute('style', 'display: block'); lab.setAttribute('class', 'foto8pequena'); gradeimg.children[i - 1].setAttribute('style', 'display:block; padding: 2mm; float: left;'); } } if (this.qtdimagemselecionada === 13) { const gradeimg = document.getElementById('gradeimg'); gradeimg.setAttribute('style', 'margin: 0 auto; position: relative; text-align: center; margin-top: 61mm; width: 180mm; height: auto; display: block;'); for (let i = 1; i <= 9; i++) { const lab = document.getElementById('lab' + i); lab.setAttribute('style', 'display: block'); lab.setAttribute('class', 'foto9pequena'); gradeimg.children[i - 1].setAttribute('style', 'display:block; padding: 2mm; float: left;'); } } if (this.qtdimagemselecionada === 14) { const gradeimg = document.getElementById('gradeimg'); gradeimg.setAttribute('style', 'margin: 0 auto; position: relative; text-align: center; margin-top: 61mm; width: 180mm; height: auto; display: block;'); for (let i = 1; i <= 12; i++) { const lab = document.getElementById('lab' + i); lab.setAttribute('style', 'display: block'); lab.setAttribute('class', 'foto12pequena'); gradeimg.children[i - 1].setAttribute('style', 'display:block; padding: 2mm; float: left;'); } } if (this.qtdimagemselecionada === 15) { const gradeimg = document.getElementById('gradeimg'); gradeimg.setAttribute('style', 'margin: 0 auto; position: relative; text-align: center; margin-top: 20mm; width: 180mm; height: auto; display: block;'); for (let i = 1; i <= 15; i++) { const lab = document.getElementById('lab' + i); lab.setAttribute('style', 'display: block'); lab.setAttribute('class', 'foto15pequena'); gradeimg.children[i - 1].setAttribute('style', 'display:block; padding: 2mm; float: left;'); } } } PegarPosicao(event) { this.valorselecionado = event + 1; } Voltar() { this.location.back(); } } <file_sep>import { Subcategoriacid10Service } from './../../zservice/subcategoriacid10.service'; import { Router } from '@angular/router'; import { SubcategoriaCid10 } from './../../core/model'; import { Component, OnInit } from '@angular/core'; import { LazyLoadEvent } from 'primeng/api'; import {Location} from '@angular/common'; import { SubcategoriascidFiltro } from '../../zservice/subcategoriacid10.service'; @Component({ selector: 'app-lista-subcategoriacid', templateUrl: './lista-subcategoriacid.component.html', styleUrls: ['./lista-subcategoriacid.component.css'] }) export class ListaSubcategoriacidComponent implements OnInit { subcategorias = []; subcategoria: SubcategoriaCid10; totalRegistros = 0; filtro = new SubcategoriascidFiltro(); camposbusca: any[]; display = true; exclusao = false; constructor(private service: Subcategoriacid10Service, private route: Router, private location: Location) { } ngOnInit() { this.camposbusca = [ {label: 'Nome'}, {label: 'Codigo'}, {label: 'Categoria'}, {label: 'Grupo'}, {label: 'Assunto/capitulo'} ]; setTimeout (() => document.querySelector('.ui-dialog-titlebar-close').addEventListener('click', () => this.Fechar()), 0); } onRowSelect(event) { this.subcategoria = event.data; } Alterar() { if (this.subcategoria?.codigo != null) { this.route.navigate(['/subcategoriacid', this.subcategoria.codigo]); } } PrimeiraSelecao() { this.subcategoria = this.subcategorias[0]; } UltimaSelecao() { this.subcategoria = this.subcategorias[this.subcategorias.length - 1]; } ProximaSelecao() { const valor = this.subcategorias.indexOf(this.subcategoria); this.subcategoria = this.subcategorias[valor + 1]; } AnteriorSelecao() { const valor = this.subcategorias.indexOf(this.subcategoria); this.subcategoria = this.subcategorias[valor - 1]; } Consultar(pagina = 0): Promise<any> { this.filtro.pagina = pagina; return this.service.Consultar(this.filtro) .then(response => { this.totalRegistros = response.total; this.subcategorias = response.subcategorias.content; }).catch(erro => console.log(erro)); } BuscaDinamica() { const drop = $('#codigodrop :selected').text(); const texto = document.getElementById('buscando') as HTMLInputElement; setTimeout (() => { if ((drop === 'Nome')) { this.filtro.codigotexto = undefined; this.filtro.nome = texto.value; this.Consultar(); } if ((drop === 'Categoria') && (texto.value !== '')) { return this.service.BuscarListaPorNomeCategoria(texto.value) .then(response => { this.subcategorias = response; }).catch(erro => console.log(erro)); } if ((drop === 'Codigo')) { this.filtro.nome = undefined; this.filtro.codigotexto = texto.value; this.Consultar(); } }, 1000); } AtivarExcluir() { if (this.subcategoria.codigo != null) { this.exclusao = true; } } Excluir() { this.service.Remover(this.subcategoria.codigo).then(() => {}).catch(erro => erro); this.exclusao = false; setTimeout (() => this.Consultar(), 100); } aoMudarPagina(event: LazyLoadEvent) { const pagina = event.first / event.rows; this.Consultar(pagina); } Voltar() { this.location.back(); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { TextolivreComponent } from './modelosdetexto/textolivre/textolivre.component'; import { ProcedimentoCadApendComponent } from './atendimentos/procedimento-cad-apend/procedimento-cad-apend.component'; import { ListaGrupoexameComponent } from './grupoexames/lista-grupoexame/lista-grupoexame.component'; import { ListaSiglaComponent } from './siglas/lista-sigla/lista-sigla.component'; import { ListaLicenciadoComponent } from './licenciados/lista-licenciado/lista-licenciado.component'; import { ListaEstadoComponent } from './estados/lista-estado/lista-estado.component'; import { CadSiglaComponent } from './siglas/cad-sigla/cad-sigla.component'; import {ToastModule} from 'primeng/toast'; import { HashLocationStrategy, LocationStrategy } from '@angular/common'; import { CadEstadoComponent } from './estados/cad-estado/cad-estado.component'; import { CadLicenciadoComponent } from './licenciados/cad-licenciado/cad-licenciado.component'; import { CadPacientesComponent } from './pacientes/cad-pacientes/cad-pacientes.component'; import { ListaPacientesComponent } from './pacientes/lista-pacientes/lista-pacientes.component'; import { CadTextopessoalComponent } from './textopessoal/cad-textopessoal/cad-textopessoal.component'; import { ListaTextopessoalComponent } from './textopessoal/lista-textopessoal/lista-textopessoal.component'; import { CadSolicitanteComponent } from './solicitantes/cad-solicitante/cad-solicitante.component'; import { ListaSolicitanteComponent } from './solicitantes/lista-solicitante/lista-solicitante.component'; import { ListaExecutanteComponent } from './executantes/lista-executante/lista-executante.component'; import { CadExecutanteComponent } from './executantes/cad-executante/cad-executante.component'; import { CadProcmedicoComponent } from './procmedicos/cad-procmedico/cad-procmedico.component'; import { ListaProcmedicoComponent } from './procmedicos/lista-procmedico/lista-procmedico.component'; import { CadGrupoexameComponent } from './grupoexames/cad-grupoexame/cad-grupoexame.component'; import { CadConvenioComponent } from './convenios/cad-convenio/cad-convenio.component'; import { ListaConvenioComponent } from './convenios/lista-convenio/lista-convenio.component'; import { TelaAtendimentoComponent } from './atendimentos/tela-atendimento/tela-atendimento.component'; import { ListaAtendimentoComponent } from './atendimentos/lista-atendimento/lista-atendimento.component'; import { CapturaComponent } from './capturas/captura/captura.component'; import { PaginaimagensComponent } from './laudos/paginaimagens/paginaimagens.component'; import { LaudoComponent } from './laudos/laudo/laudo.component'; import { EdicaoimagemComponent } from './capturas/edicaoimagem/edicaoimagem.component'; import { CadSubcategoriacidComponent } from './cid/cad-subcategoriacid/cad-subcategoriacid.component'; import { ListaSubcategoriacidComponent } from './cid/lista-subcategoriacid/lista-subcategoriacid.component'; import { ViewerComponent } from './servidor/viewer/viewer.component'; import { PrevisualizacaoComponent } from './servidor/previsualizacao/previsualizacao.component'; import { ListaServidorComponent } from './servidor/lista-servidor/lista-servidor.component'; import { MenubarModule } from 'primeng/menubar'; import { HttpClientModule } from '@angular/common/http'; import { AppRoutingModule } from './app-routing.module'; import { PaginainicioComponent } from './paginainicio/paginainicio.component'; import { FooterComponent } from './core/footer/footer.component'; import { NavbarComponent } from './core/navbar/navbar.component'; import { AppComponent } from './app.component'; import {SplitButtonModule} from 'primeng/splitbutton'; import { DataViewModule } from 'primeng/dataview'; import { PanelModule } from 'primeng/panel'; import {ScrollPanelModule} from 'primeng/scrollpanel'; import {RatingModule } from 'primeng/rating'; import {CardModule} from 'primeng/card'; import { TableModule } from 'primeng/table'; import { DialogModule } from 'primeng/dialog'; import {CarouselModule} from 'primeng/carousel'; import { CoreModule } from './core/core.module'; import {RadioButtonModule} from 'primeng/radiobutton'; import {WebcamModule} from 'ngx-webcam'; import {AccordionModule} from 'primeng/accordion'; import {TabViewModule} from 'primeng/tabview'; import * as $ from 'jquery'; import { DragDropModule } from '@angular/cdk/drag-drop'; import {FileUploadModule} from 'primeng/fileupload'; import { BrowserModule } from '@angular/platform-browser'; import { CalendarModule } from 'primeng/calendar'; import {ToolbarModule} from 'primeng/toolbar'; import { CheckboxModule } from 'primeng/checkbox'; import { DropdownModule } from 'primeng/dropdown'; import {TreeTableModule} from 'primeng/treetable'; import {SpinnerModule} from 'primeng/spinner'; import {EditorModule} from 'primeng/editor'; import {InputMaskModule} from 'primeng/inputmask'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { FieldsetModule } from 'primeng/fieldset'; import { FormsModule } from '@angular/forms'; import {ConfirmDialogModule} from 'primeng/confirmdialog'; import { ReactiveFormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent, NavbarComponent, FooterComponent, PaginainicioComponent, ListaServidorComponent, PrevisualizacaoComponent, ViewerComponent, ListaSubcategoriacidComponent, CadSubcategoriacidComponent, EdicaoimagemComponent, LaudoComponent, PaginaimagensComponent, CapturaComponent, ListaAtendimentoComponent, TelaAtendimentoComponent, ListaConvenioComponent, CadConvenioComponent, CadGrupoexameComponent, ListaProcmedicoComponent, CadProcmedicoComponent, CadExecutanteComponent, ListaExecutanteComponent, ListaSolicitanteComponent, CadSolicitanteComponent, ListaTextopessoalComponent, CadTextopessoalComponent, ListaPacientesComponent, CadPacientesComponent, CadLicenciadoComponent, CadEstadoComponent, CadSiglaComponent, ListaEstadoComponent, ListaLicenciadoComponent, ListaSiglaComponent, ListaGrupoexameComponent, ProcedimentoCadApendComponent, TextolivreComponent ], imports: [ BrowserModule, BrowserAnimationsModule, AppRoutingModule, HttpClientModule, FieldsetModule, FormsModule, ReactiveFormsModule, CalendarModule, InputMaskModule, ToolbarModule, CheckboxModule, DropdownModule, CoreModule, DataViewModule, PanelModule, RatingModule, CardModule, TableModule, DialogModule, ConfirmDialogModule, CarouselModule, WebcamModule, DialogModule, TreeTableModule, FileUploadModule, TabViewModule, ReactiveFormsModule, EditorModule, ScrollPanelModule, DragDropModule, EditorModule, RadioButtonModule, SpinnerModule, AccordionModule, MenubarModule, FormsModule, SplitButtonModule, ToastModule ], providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { CamposDoLaudo } from './../../core/model'; import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-textolivre', templateUrl: './textolivre.component.html', styleUrls: ['./textolivre.component.css'] }) export class TextolivreComponent implements OnInit { @Input() camposdolaudo: CamposDoLaudo; constructor() { } ngOnInit(): void { this.PegaAltura(); } PegaAltura() { const painel = document.getElementById('paineltexto').clientHeight; const editor = document.querySelector('div.p-editor-content'); editor.setAttribute('style' , 'height: ' + painel + 'px;'); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CadEstadoComponent } from './cad-estado/cad-estado.component'; import { ListaEstadoComponent } from './lista-estado/lista-estado.component'; @NgModule({ declarations: [CadEstadoComponent, ListaEstadoComponent], imports: [ CommonModule ] }) export class EstadosModule { } <file_sep>import { Router } from '@angular/router'; import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'DoorLayout'; constructor(private router: Router) {} ExibindoNavbar() { return this.router.url.indexOf('/operacoes/laudos') && this.router.url.indexOf('/operacoes/captura') && this.router.url.indexOf('/viewer'); } ExibindoFundo() { return this.router.url.indexOf('/servidor') && this.router.url.indexOf('/previsualizar') && this.router.url.indexOf('/viewer'); } ExibirRodape() { return this.router.url.indexOf('/operacoes/laudos') && this.router.url.indexOf('/operacoes/captura') && this.router.url.indexOf('/viewer'); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CapturaComponent } from './captura/captura.component'; import { EdicaoimagemComponent } from './edicaoimagem/edicaoimagem.component'; @NgModule({ declarations: [CapturaComponent, EdicaoimagemComponent], imports: [ CommonModule ] }) export class CapturasModule { } <file_sep>import { FormGroup } from '@angular/forms'; import { Atendimento } from './../../core/model'; import { LazyLoadEvent } from 'primeng/api'; import { Router } from '@angular/router'; import { AtendimentoFilter, AtendimentoService } from './../../zservice/atendimento.service'; import { Component, OnInit } from '@angular/core'; import {Location} from '@angular/common'; @Component({ selector: 'app-lista-atendimento', templateUrl: './lista-atendimento.component.html', styleUrls: ['./lista-atendimento.component.css'] }) export class ListaAtendimentoComponent implements OnInit { atendimentos = []; atendimento: Atendimento; totalRegistros = 0; filtro = new AtendimentoFilter(); dropbusca: any[]; dropperiodo: any[]; laudoperiodo: any[]; formulario: FormGroup; display: boolean = true; exclusao: boolean = false; periodoselecionado: string; camposelecionado: string; campotextobuscar: string; laudoselecionado: string; constructor(private service: AtendimentoService, private route: Router, private location: Location) { } ngOnInit() { this.IniciarDrops(); this.IniciarParametroBasico(); this.BuscaDinamica(); } private IniciarParametroBasico(){ this.periodoselecionado = 'hoje'; this.camposelecionado = 'codigo'; this.laudoselecionado = 'indiferente'; } private IniciarDrops(){ this.dropbusca = [ {label: 'Codigo', value: 'codigo'}, {label: 'Paciente', value: 'paciente'}, {label: 'Prof. Exec', value: 'profexecutante'} ]; this.dropperiodo = [ {label: 'Personalizado(todos)', value: 'todos'}, {label: 'Hoje', value: 'hoje'}, {label: 'Ultima Semana', value: 'semana'}, {label: 'Ultimo mês', value: 'mes'} ]; this.laudoperiodo = [ {label: 'Indiferente', value: 'indiferente'}, {label: 'Pendente', value: 'pendente'}, {label: 'Pronto', value: 'pronto'} ]; } Alterar() { if (this.atendimento?.codigo != null) { this.route.navigate(['/operacoes/atendimento', this.atendimento.codigo]); } } PrimeiraSelecao() { this.atendimento = this.atendimentos[0]; } UltimaSelecao() { this.atendimento = this.atendimentos[this.atendimentos.length - 1]; } ProximaSelecao() { const valor = this.atendimentos.indexOf(this.atendimento); this.atendimento = this.atendimentos[valor + 1]; } AnteriorSelecao() { const valor = this.atendimentos.indexOf(this.atendimento); this.atendimento = this.atendimentos[valor - 1]; } Consultar(pagina = 0): Promise<any> { this.filtro.pagina = pagina; return this.service.Consultar(this.filtro) .then(response => { this.totalRegistros = response.total; this.atendimentos = response.atendimentos.content; }).catch(erro => console.log(erro)); } BuscaDinamica() { setTimeout(() => { if ((this.camposelecionado === 'codigo') && (this.campotextobuscar !== undefined) && (this.campotextobuscar !== '')) { const numero = +this.campotextobuscar; return this.service.BuscarListaPorId(numero) .then(response => { this.atendimentos = response; }).catch(erro => console.log(erro)); } else { if (this.camposelecionado === 'paciente') { this.filtro.pacientenome = this.campotextobuscar; } if (this.camposelecionado === 'profexecutante') { this.filtro.solicitantenome = this.campotextobuscar; } if (this.periodoselecionado === 'todos') { this.filtro.datafinal = null; this.filtro.datainicial = null; this.Consultar(); } if (this.periodoselecionado === 'hoje') { const final = new Date(); this.filtro.datafinal = final; this.filtro.datainicial = final; } if (this.periodoselecionado === 'semana') { const final = new Date(); const inicial = new Date(); inicial.setDate(new Date().getDate() - 7); this.filtro.datainicial = inicial; this.filtro.datafinal = final; } if (this.periodoselecionado === 'mes') { const final = new Date(); const inicial = new Date(); inicial.setDate(new Date().getDate() - 30); this.filtro.datainicial = inicial; this.filtro.datafinal = final; } this.Consultar(); } }, 10); } AtivarExcluir() { if (this.atendimento.codigo != null) { this.exclusao = true; } } Excluir() { this.service.Remover(this.atendimento.codigo).then(() => {}).catch(erro => erro); this.exclusao = false; setTimeout (() => this.Consultar(), 100); } aoMudarPagina(event: LazyLoadEvent) { const pagina = event.first / event.rows; this.Consultar(pagina); } Voltar() { this.location.back(); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ListaServidorComponent } from './lista-servidor/lista-servidor.component'; import { PrevisualizacaoComponent } from './previsualizacao/previsualizacao.component'; import { ViewerComponent } from './viewer/viewer.component'; @NgModule({ declarations: [ListaServidorComponent, PrevisualizacaoComponent, ViewerComponent], imports: [ CommonModule ] }) export class ServidorModule { } <file_sep>import { isEmptyObject } from 'jquery'; import { ProcedimentoCadApendComponent } from './../procedimento-cad-apend/procedimento-cad-apend.component'; import { ConvenioService, ConvenioFiltro } from './../../zservice/convenio.service'; import { Atendimento } from './../../core/model'; import { ActivatedRoute, Router } from '@angular/router'; import { AtendimentoService, AtendimentoFilter } from './../../zservice/atendimento.service'; import { FormArray, FormControl } from '@angular/forms'; import { Component, OnInit, ViewChild } from '@angular/core'; import {Location} from '@angular/common'; import * as moment from 'moment'; import {MessageService} from 'primeng/api'; import {ConfirmationService} from 'primeng/api'; @Component({ selector: 'app-tela-atendimento', templateUrl: './tela-atendimento.component.html', styleUrls: ['./tela-atendimento.component.css'], providers: [MessageService, ConfirmationService] }) export class TelaAtendimentoComponent implements OnInit { @ViewChild(ProcedimentoCadApendComponent) appendchild: ProcedimentoCadApendComponent; atendimento = new Atendimento(); filtro = new AtendimentoFilter(); items: FormArray; filtroconvenio = new ConvenioFiltro(); display = true; exibiratestado = false; pacientes: any[]; convenios: any[]; conselhos: any[]; subcategoriacids: any[]; estados: any[]; executantes: any[]; solicitantes: any[]; codigodecid: number; codigoprofexecutante: number; constructor(private service: AtendimentoService, private serviceconv: ConvenioService, private rota: ActivatedRoute, private route: Router, private location: Location, private messageService: MessageService, private confirmService: ConfirmationService) { } ngOnInit() { const codatendimento = this.rota.snapshot.params.cod; this.CarregarConvenios(); this.CarregarPacientes(); this.CarregarSolicitantes(); this.CarregarConselhos(); this.CarregarEstados(); this.CarregarCids(); this.CarregarExecutantes(); if (codatendimento) { this.CarregaAtendimento(codatendimento); } else { this.VerificarData(); } if (this.atendimento.datacadastro === undefined) { this.atendimento.datacadastro = new Date(); } } AbrirDialogo() { this.exibiratestado = true; } get editando() { return this.atendimento.codigo === null ? false : Boolean(this.atendimento.codigo); } VerificarData() { const data = moment(); this.atendimento.dataatendimento = moment(data, 'YYYY-MM-DD').toDate(); } CarregaAtendimento(codigo: number) { this.service.BuscarPorId(codigo).then(atendimento => {this.atendimento = atendimento;}).catch(erro => erro); } Salvar() { this.atendimento.procedimentos.forEach(elo => { delete elo.listaimagem; delete elo.paginadeimagens; }); if(this.ValidaCampoVazio()){ return; } if(this.editando){ this.Atualizar(); return; } this.Adicionar(); } private ValidaCampoVazio() { if (this.atendimento.convenio.codigo == null){ this.CamposErro('Convênio'); const editor = document.querySelector('#convenio .p-inputtext') as HTMLElement; editor.setAttribute('style' , 'background-color: #fcd5d5;'); return true; } if (this.atendimento.paciente.nome == null){ this.CamposErro('Nome Paciente'); const editor = document.querySelector('#paciente .p-inputtext') as HTMLElement; editor.setAttribute('style' , 'background-color: #fcd5d5;'); return true; } if (this.atendimento.paciente.nome == null){ this.CamposErro('Data Nascimento'); const editor = document.querySelector('#datanasc .p-inputtext') as HTMLElement; editor.setAttribute('style' , 'background-color: #fcd5d5; text-transform: uppercase;'); return true; } if (isEmptyObject(this.atendimento.procedimentos)){ this.CamposErro('Procedimentos'); const editor = document.querySelector('#tabelaproc .corpotabela .tabelas') as HTMLElement; editor.setAttribute('style' , 'background-color: #fcd5d5; border: 1px solid #cc0000'); return true; } return false; } private VerificaDuplicidade(){ this.filtro.pacientenome = this.atendimento.paciente.nome; this.filtro.datainicial = this.atendimento.datacadastro; this.filtro.datafinal = this.atendimento.datacadastro; this.filtro.datanascpaciente = this.atendimento.paciente.datanasc; this.service.VerificarSeNomeExiste(this.filtro) .then( valor => { if(valor){ this.CamposAviso(this.atendimento.paciente.nome); const editor = document.getElementById('paciente'); editor.setAttribute('style' , 'background-color: #fcf6a1; text-transform: uppercase;'); this.confirmService.confirm({ message: 'Alerta: já existe um atendimento cadastrado para esse paciente com a data de hoje!' }); } } ); } private CamposErro(campo: string) { this.messageService.add({severity:'error', summary: 'Erro', detail:'Preencher campo ' + campo.toUpperCase(), life:6000}); } private CamposAviso(campo: string) { this.messageService.add({severity:'warn', summary: 'Aviso', detail:'Valor ' + campo.toUpperCase() + ' já existe no banco de dados', life:10000}); } Adicionar() { this.service.Adicionar(this.atendimento) .then(() => { this.route.navigate(['/operacoes/atendimento']); }) .catch(erro => erro); } Atualizar() { this.service.Atualizar(this.atendimento) .then(() => { this.route.navigate(['/operacoes/atendimento']); }) .catch(erro => erro); } private Teste(){ this.atendimento.procedimentos.forEach(elo => { elo.listaimagem.forEach(alo => {}); }); } Nova(form: FormControl) { form.reset(); setTimeout(function() { this.atendimento = new Atendimento(); }.bind(this), 1); this.route.navigate(['/operacoes/atendimento/novo']); } CarregarConselhos() { this.service.ListarSigla().then(lista => { this.conselhos = lista.map(sigla => ({label: sigla.descricao, value: sigla.codigo})); }).catch(erro => erro); } CarregarEstados() { this.service.ListarEstados().then(lista => { this.estados = lista.map(estado => ({label: estado.uf, value: estado.codigo})); }).catch(erro => erro); } CarregarPacientes() { this.service.ListarPacientes().then(lista => { this.pacientes = lista.map(paciente => ({label: paciente.nome, value: paciente.codigo})); }).catch(erro => erro); } InserirPacientes() { this.service.BuscarPorIdPaciente(this.atendimento.paciente.codigo) .then( response => { this.atendimento.paciente = response; }); setTimeout(() => { this.VerificaDuplicidade(); }, 500); } InserirProfSolicitante() { this.service.BuscarPorIdProf(this.atendimento.solicitante.codigo) .then(response => { this.atendimento.solicitante = response; }); } CarregarConvenios() { this.filtroconvenio.ativo = true; return this.serviceconv.Consultar(this.filtroconvenio) .then(response => { this.convenios = response.convenios.content.map(conv => ({label: conv.nome, value: conv.codigo})); }).catch(erro => console.log(erro)); } CarregarSolicitantes() { this.service.ListarSolicitantes().then(lista => { this.solicitantes = lista.map(solicitante => ({label: solicitante.nome, value: solicitante})); }).catch(erro => erro); } CarregarExecutantes() { this.service.ListarExecutantes().then(lista => { this.executantes = lista.map(executante => ({label: executante.nome, value: executante.codigo})); }).catch(erro => erro); } CarregarCids() { this.service.ListarSubcategoriaCid().then(lista => { this.subcategoriacids = lista.map(cid => ({label: cid.nome, value: cid.codigo})); }).catch(erro => erro); } VaiParaLaudos() { if (this.appendchild.procedimento !== null && this.appendchild.procedimento !== undefined && this.appendchild.procedimento.codigo !== undefined) { this.route.navigate(['/operacoes/laudos', this.appendchild.procedimento.codigo]); } } VaiCaptura() { if (this.appendchild.procedimento !== null && this.appendchild.procedimento !== undefined && this.appendchild.procedimento.codigo !== undefined) { this.route.navigate(['/operacoes/captura', this.atendimento.codigo, this.appendchild.procedimento.codigo]); } } GerarAtendimento() { this.Salvar(); this.service.PorAtestado(1) .then(relatorio => { const url = window.URL.createObjectURL(relatorio); window.open(url); }); this.exibiratestado = false; } Fechar() { this.route.navigate(['/home']); } Voltar() { this.location.back(); } } <file_sep>import { element } from 'protractor'; import { ActivatedRoute } from '@angular/router'; import { Paciente, Series, Instancia } from './../../core/model'; import { ServidorService } from './../../zservice/servidor.service'; import { Component, OnInit } from '@angular/core'; export interface ArvoreDeDados { data?: any; children?: ArvoreDeDados[]; leaf?: boolean; expanded?: boolean; } @Component({ selector: 'app-previsualizacao', templateUrl: './previsualizacao.component.html', styleUrls: ['./previsualizacao.component.css'] }) export class PrevisualizacaoComponent implements OnInit { paciente: Paciente; lista: ArvoreDeDados[]; constructor(private service: ServidorService, private route: ActivatedRoute) { } ngOnInit() { const codigo = this.route.snapshot.params.cod; if (codigo) { this.CarregarDadosPaciente(1); } } CarregarDadosPaciente(codigo: number) { return this.service.BuscarPorId(codigo).then(response => { this.paciente = response; this.lista = this.CriarTabela().data; }); } CriarTabela() { return { 'data': this.CriarLinhaEstudo() }; } CriarLinhaEstudo() { const lista = []; console.log('lista aqui ' + this.paciente); this.paciente.estudos.forEach((el) => { const pega = { data: { 'codigo': el.codigo, 'descricao': el.studydescription, 'chave': el.accessionnumber, 'date': el.studydatetime }, children: this.CriarLinhaSeries(el.series) }; lista.push(pega); }); return lista; } CriarLinhaSeries(serie: Array<Series>) { const listadenovo = []; serie.forEach((el) => { const pegadenovo = { data: { 'codigo': el.codigo, 'descricao': el.seriesdescription, 'chave': el.seriesinstanceuid }, children: this.CriarLinhaInstancia(el.instancias) }; listadenovo.push(pegadenovo); }); return listadenovo; } CriarLinhaInstancia(instance: Array<Instancia>) { const otralista = []; instance.forEach((el) => { const otrapega = { data: { 'codigo': el.codigo, 'descricao': el.sopinstanceuid, 'chave': el.mediastoragesopinstanceuid, 'date': '', 'viewer': '' } }; otralista.push(otrapega); }); return otralista; } }<file_sep>import { FormGroup } from '@angular/forms'; import { Router } from '@angular/router'; import { TextopessoalService, TextoPessoalFiltro } from './../../zservice/textopessoal.service'; import { TextoPessoal } from './../../core/model'; import { Component, OnInit } from '@angular/core'; import { LazyLoadEvent } from 'primeng/api'; import {Location} from '@angular/common'; @Component({ selector: 'app-lista-textopessoal', templateUrl: './lista-textopessoal.component.html', styleUrls: ['./lista-textopessoal.component.css'] }) export class ListaTextopessoalComponent implements OnInit { textospessoais = []; texto: TextoPessoal; totalRegistros = 0; filtro = new TextoPessoalFiltro(); textodocampo: string; dropselecionado: string = 'abreviatura'; camposbusca: any[]; formulario: FormGroup; display = true; exclusao = false; constructor(private service: TextopessoalService, private route: Router, private location: Location) { } ngOnInit() { this.camposbusca = [ {label: 'Abreviatura', value: 'abreviatura'}, {label: 'Codigo', value: 'codigo'} ]; } onRowSelect(event) { this.texto = event.data; } Alterar() { if (this.texto?.codigo != null) { this.route.navigate(['/listatextopessoal', this.texto.codigo]); } } PrimeiraSelecao() { this.texto = this.textospessoais[0]; } UltimaSelecao() { this.texto = this.textospessoais[this.textospessoais.length - 1]; } ProximaSelecao() { const valor = this.textospessoais.indexOf(this.texto); this.texto = this.textospessoais[valor + 1]; } AnteriorSelecao() { const valor = this.textospessoais.indexOf(this.texto); this.texto = this.textospessoais[valor - 1]; } Consultar(pagina = 0): Promise<any> { this.filtro.pagina = pagina; return this.service.Consultar(this.filtro) .then(response => { this.totalRegistros = response.total; this.textospessoais = response.textopessoals.content; }).catch(erro => console.log(erro)); } BuscaDinamica() { setTimeout (() => { if (this.dropselecionado === 'abreviatura') { this.filtro.abreviatura = this.textodocampo; this.Consultar(); } if ((this.dropselecionado === 'codigo') && (this.textodocampo !== '')) { const numero = +this.textodocampo; return this.service.BuscarListaPorId(numero) .then(response => { this.textospessoais = response; }).catch(erro => console.log(erro)); } }, 1000); } AtivarExcluir() { if (this.texto.codigo != null) { this.exclusao = true; } } Excluir() { this.service.Remover(this.texto.codigo).then(() => {}).catch(erro => erro); this.exclusao = false; setTimeout (() => this.Consultar(), 100); } aoMudarPagina(event: LazyLoadEvent) { const pagina = event.first / event.rows; this.Consultar(pagina); } Voltar() { this.location.back(); } Fechar() { this.route.navigate(['/home']); } } <file_sep>export class Estudo { codigo: number; accessionnumber: string; studyid: string; studyinstanceuid: string; studydescription: string; studydatetime: Date; referringphysicianname: string; studypriorityid: string; studystatusid: string; additionalpatienthistory: string; admittingdiagnosesdescription: string; datacriacao: Date; datamodificacao: Date; paciente = new Paciente(); series = new Array<Series>(); } export class Series { codigo: number; seriesinstanceuid: string; seriesdescription: string; seriesnumber: number; patientposition: string; bodypartexamined: string; laterality: string; operatorsname: string; protocolname: string; seriesdatetime: Date; datacriacao: Date; datamodicifacao: Date; estudo = new Estudo(); instancias = new Array<Instancia>(); equipamento = new Equipamento(); } export class Paciente { codigo: number; pacienteid: string; nome: string; datanasc: Date; idade: string; sexo: EnumSexo; estudos = new Array<Estudo>(); endereco = new Endereco(); contato = new Contato(); datacriacao: Date; datamodificacao: Date; datamenstruacao: Date observacoes: string; tamanho: string; peso: string; atributoextra1: string; atributoextra2: string; atributoextra3: string; } export class Instancia { codigo: number; instancenumber: number; patientorientation: string; mediastoragesopinstanceuid: string; sopinstanceuid: string; sopclassuid: string; transfersyntaxuid: string; acquisitiondatetime: Date; imagetype: string; pixelspacing: number; imageorientation: string; xraytubecurrent: number; exposuretime: number; kvp: string; slicelocation: number; slicethickness: number; imageposition: string; windowcenter: string; windowwidth: string; contentdatetime: Date; datacriacao: Date; datamodificacao: Date; serie = new Series(); tagimagem = new Tagimagem(); } export class Equipamento { codigo: number; instituicao: string; endereco: string; departamento: string; nomemodality: string; conversiontype: string; fabricante: string; modelo: string; stationname: string; serial: string; softwareversion: string; datacriacao: Date; datamodificacao: Date; serie = new Series(); } export class Abreviatura { codigo: number; titulo: string; texto: string; } export class CID10 { codigo: number; sku: string; nome: string; } export class CBHPM { codigo: number; sku: string; procedimento: string; porte: string; valorporte: string; custooperacional: string; nauxiliares: number; porteanest: string; valortotal: string; filmes: number; incidencia: number; unidrdfarmaco: string; subgrupo = new SubgrupoCBHPM(); } export class SubgrupoCBHPM { codigo: number; sku: string; subgrupo: string; grupo = new GrupoCBHPM(); } export class GrupoCBHPM { codigo: number; sku: string; grupo: string; } export class CNES { codigo: number; sku: string; razaosocial: string; nomefantasia: string; cnpj: string; cpf: string; codmunicipio: string; municipio: string; } export class Contato { email: string; telefone: string; telefone2: string; celular: string; } export class Convenio { codigo: number; nome: string; nomedocontato: string; telefone: string; fax: string; ativo: boolean; email: string; observacoes: string; numcopiasdolaudo: number; endereco = new Endereco(); } export class Endereco { logradouro: string; complemento: string; numero: number; bairro: string; cidade: string; estado: string; cep: string; } export class Crm { codigo: number; crm: string; nome: string; especialidades = []; } export class EspecialidadeMedica { codigo: number; nome: string; } export class GrupoCID10 { codigo: number; codigotexto: string; nome: string; capitulocid10 = new CapituloCID10(); } export class CategoriaCID10 { codigo: number; codigotexto: string; nome: string; grupocid10 = new GrupoCID10(); } export class SubcategoriaCid10 { codigo: number; codigotexto: string; nome: string; nome50: string; restrsexo: string; classificacao: string; causaobito: string; referencia: string; excluidos: string; categoriacid10 = new CategoriaCID10(); } export class CapituloCID10 { codigo: number; codigotexto: string; nome: string; } export class GrupoProcedimento { codigo: number; nomegrupo: string; } export class ProcedimentoMedico { codigo: number; nome: string; diasparaentregadolaudo: string; margemtop: number; margembottom: number; restricaosexo: string; imagem1: string; imagem2: string; laudomodelo: boolean; grupo = new GrupoProcedimento(); } export class Imagem { codigo: number; caminho: string; nomeimagem: string; extensao: string; imagem: any; dicom: boolean; codigouid: string; procedimentoatendimento = new ProcedimentoAtendimento(); } export class ProfissionalExecutante { codigo: number; nome: string; titulo: EnumTitulo; contato = new Contato(); endereco = new Endereco(); conselho = new TissConselho(); frasepessoal: string; } export class TissConselho { codigo: number; sigla = new Sigla(); descricao: string; estado = new Estado(); } export class ProfissionalSolicitante { codigo: number; nome: string; conselho = new TissConselho(); } export class TabelaDeProcedimentos { codigo: number; convenio = new Convenio(); } export class TextoPessoal { codigo: number; abreviatura: string; texto: string; } export class Tagimagem { codigo: number; imagetype: string; sopclassuid: string; sopinstanceuid: string; studydate: string; seriesdate: string; acquisitiondate: string; contentdate: string; studytime: string; seriestime: string; acquisitiontime: string; contenttime: string; accessionnumber: string; modality: string; presentationintenttype: string; manufacturer: string; institutionname: string; institutionaddress: string; referringphysiciansname: string; stationname: string; studydescription: string; seriesdescription: string; institutionaldepartmentname: string; performingphysiciansname: string; operatorsname: string; manufacturersmodelname: string; referencedpatientsequence: string; anatomicregionsequence: string; primaryAnatomicstructuresequence: string; patientsname: string; patientid: string; softwareversions: string; imagerpixelspacing: string; positionertype: string; detectortype: string; detectordescription: string; detectormode: string; timeoflastdetectorcalibration: string; samplesperpixel: string; photometricinterpretation: string; rows: string; columns: string; } export class TagImagemGamb { tag: string; indentificacao: string; campo: string; } export class Atendimento { codigo: number; paciente = new Paciente(); convenio = new Convenio(); solicitante = new ProfissionalSolicitante(); procedimentos = new Array<ProcedimentoAtendimento>(); dataatendimento: Date; datacadastro: Date; observacoes: string; codigoprofexecutante: number; codigodecid: number; dataatestado: Date; } export class ProcedimentoAtendimento { codigo: number; profexecutante = new ProfissionalExecutante(); procedimentomedico = new ProcedimentoMedico(); procmedico: number; valorpaciente: string; valorconvenio: string; preventregalaudo: Date; dataexecucao: Date; paginadeimagens = new Array<PaginaDeImagens>(); atendimento = new Atendimento(); listaimagem = new Array<Imagem>(); laudo = new Laudo(); codigoatdteste: number; } export class Modality { codigo: number; name: string; description: string; ip: string; port: number; timeout: number; } export class ParametrosDoSistema { codigo: number; logomarcalaudo: any; } export class Licenciado { codigo: number; cnpj: string; cnes: string; cpf: string; licenciadopara: string; razaosocial: string; endereco = new Endereco(); telefone1: string; telefone2: string; email: string; site: string; serial: string; qtdeacessos: number; tipodelicenca: string; } export class Estado { codigo: number; uf: string; descricao: string; } export class Sigla { codigo: number; descricao: string; } export class ImagemImpressa { codigo: number; imagem = new Imagem(); indice: number; paginadeimagens = new PaginaDeImagens(); } export class ModeloDeLaudoDoProc { codigo: number; procedimentomedico = new ProcedimentoMedico(); modelodelaudo = new ModeloDeLaudo(); descricao: string; customstring: string; prioridade: number; } export class ModeloDeLaudo { codigo: number; nome: string; contexto: string; visao: string; } export class PaginaDeImagens { codigo: number; layout: LAYOUT_IMG; imagemimpressa = new Array<ImagemImpressa>(); procedimentoatendimento = new ProcedimentoAtendimento(); } export class Laudo { codigo: number; status: STATUS_LAUDO; camposdolaudo = new CamposDoLaudo(); modelodelaudo: ModeloDeLaudoDoProc; cidresultadodoexame: SubcategoriaCid10; } export class ParametroDoLaudo { codigo: number; index: number; valor: string; camposdolaudo: CamposDoLaudo; constructor(codigo?: number, index?: number, valor?: string, camposdolaudo?: CamposDoLaudo) { this.codigo = codigo; this.index = index; this.valor = valor; this.camposdolaudo = camposdolaudo; } } export enum LAYOUT_IMG { LAYOUT_1_GRANDE = 'LAYOUT_1_GRANDE', LAYOUT_1_MEDIA = 'LAYOUT_1_MEDIA', LAYOUT_2_GRANDE = 'LAYOUT_2_GRANDE', LAYOUT_2_MEDIA = 'LAYOUT_2_MEDIA', LAYOUT_3_MEDIA = 'LAYOUT_3_MEDIA', LAYOUT_4_GRANDE = 'LAYOUT_4_GRANDE', LAYOUT_4_MEDIA = 'LAYOUT_4_MEDIA', LAYOUT_4_PEQUENA = 'LAYOUT_4_PEQUENA', LAYOUT_6_GRANDE = 'LAYOUT_6_GRANDE', LAYOUT_6_MEDIA = 'LAYOUT_6_MEDIA', LAYOUT_8_GRANDE = 'LAYOUT_8_GRANDE', LAYOUT_8_PEQUENA = 'LAYOUT_8_PEQUENA', LAYOUT_9_PEQUENA = 'LAYOUT_9_PEQUENA', LAYOUT_12_PEQUENA = 'LAYOUT_12_PEQUENA', LAYOUT_15_PEQUENA = 'LAYOUT_15_PEQUENA', LAYOUT_LAUDO_E_4_IMG = 'LAYOUT_LAUDO_E_4_IMG', LAYOUT_LAUDO_E_5_IMG = 'LAYOUT_LAUDO_E_5_IMG' } export enum STATUS_LAUDO { pendente = 'PENDENTE', pronto = 'PRONTO' } export class CamposDoLaudo { codigo: number; campo1: string; } export enum EnumTitulo { DR = 'DR', DRA = 'DRA', Nenhum = 'Nenhum' } export enum EnumSexo { INDEFINIDO = 'INDEFINIDO', MASCULINO = 'MASCULINO', FEMININO = 'FEMININO' } <file_sep>import { Router } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { MenuItem } from 'primeng/api'; @Component({ selector: 'app-navbar', templateUrl: './navbar.component.html', styleUrls: ['./navbar.component.css'] }) export class NavbarComponent implements OnInit { items: MenuItem[]; constructor(private router: Router) { } ngOnInit() { this.items = [ { label: 'Dicom', routerLink: ['servidor/listagem'] }, { label: 'Cadastros', items: [ {label: 'Convênio', icon: 'fa fa-fw fa-cubes', routerLink: ['listaconvenio']}, {label: 'Proc. Médicos', icon: 'fa fa-fw fa-cubes', routerLink: ['listaexameprocmedico']}, {label: 'Pacientes', icon: 'fa fa-fw fa-cubes', routerLink: ['listapaciente']}, {label: 'Prof. Executantes', icon: 'fa fa-fw fa-cubes', routerLink: ['listaprofexecutante']}, {label: 'Prof. Solicitantes', icon: 'fa fa-fw fa-cubes', routerLink: ['listaprofsolicitante']}, {label: 'Textos Pessoal', icon: 'fa fa-fw fa-cubes', routerLink: ['listatextopessoal']} ] }, { label: 'Operações', items: [ {label: 'Atendimento', icon: 'fa fa-fw fa-clipboard', routerLink: ['operacoes/atendimento']}, {label: 'Laudo', icon: 'fa fa-fw fa-clipboard', routerLink: ['operacoes/laudos']}, {label: 'Captura', icon: 'fa fa-fw fa-clipboard', routerLink: ['operacoes/captura']} ] }, { label: 'Relatórios', items: [ {label: 'Convênio', icon: 'fa fa-fw fa-file-image-o', routerLink: ['laudos']}, {label: 'Prof. Executante', icon: 'fa fa-fw fa-file-image-o', routerLink: ['captura']} ] }, { label: 'Ferramentas', items: [ {label: 'Licenciados', icon: 'fa fa-fw fa-linode', routerLink: ['listalicenciado']}, {label: 'Estados', icon: 'fa fa-fw fa-linode', routerLink: ['listaestado']}, {label: 'Siglas', icon: 'fa fa-fw fa-linode', routerLink: ['listasigla']} ] } ]; } } <file_sep>import { FormGroup, FormBuilder } from '@angular/forms'; import { LicenciadoService } from './../../zservice/licenciado.service'; import { MessageService } from 'primeng/api'; import { Router, ActivatedRoute } from '@angular/router'; import {ConfirmationService} from 'primeng/api'; import { Licenciado } from './../../core/model'; import { Component, OnInit } from '@angular/core'; import {Location} from '@angular/common'; @Component({ selector: 'app-cad-licenciado', templateUrl: './cad-licenciado.component.html', styleUrls: ['./cad-licenciado.component.css'], providers: [ MessageService , ConfirmationService] }) export class CadLicenciadoComponent implements OnInit { formulario: FormGroup; constructor( private service: LicenciadoService, private rota: ActivatedRoute, private formbuilder: FormBuilder, private route: Router, private location: Location) { } ngOnInit() { this.CriarFormulario(new Licenciado()); const codlicenciado = this.rota.snapshot.params.cod; if (codlicenciado) { this.CarregarLicenciados(codlicenciado); } } get editando() { return Boolean(this.formulario.get('codigo').value); } CriarFormulario(licenciado: Licenciado) { this.formulario = this.formbuilder.group({ codigo: [null, licenciado.codigo], razaosocial: [null, licenciado.razaosocial], licenciadopara: [null, licenciado.licenciadopara], cnpj: [null, licenciado.cnpj], cnes: [null, licenciado.cnes], cpf: [null, licenciado.cpf], telefone2: [null, licenciado.telefone2], email: [null, licenciado.email], site: [null, licenciado.site], serial: [null, licenciado.serial], qtdeacessos: [null, licenciado.qtdeacessos], telefone1: [null, licenciado.telefone1], endereco: this.formbuilder.group({ logradouro: [null, licenciado.endereco.logradouro], complemento: [null, licenciado.endereco.complemento], numero: [null, licenciado.endereco.numero], bairro: [null, licenciado.endereco.bairro], cidade: [null, licenciado.endereco.cidade], estado: [null, licenciado.endereco.estado], cep: [null, licenciado.endereco.cep] }) }); } CarregarLicenciados(codigo: number) { this.service.BuscarPorId(codigo).then(licenciado => this.formulario.patchValue(licenciado)); } Salvar() { if (this.editando) { this.AtualizarLicenciado(); } else { this.formulario.patchValue(this.AdicionarLicenciado()); } this.CriarFormulario(new Licenciado()); } AdicionarLicenciado() { return this.service.Adicionar(this.formulario.value) .then(salvo => { this.route.navigate(['/ferramentas/listalicenciado']); }); } AtualizarLicenciado() { this.service.Atualizar(this.formulario.value) .then(licenciado => { this.formulario.patchValue(licenciado); this.route.navigate(['/ferramentas/listalicenciado']); }); } Voltar() { this.location.back(); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ListaSubcategoriacidComponent } from './lista-subcategoriacid/lista-subcategoriacid.component'; import { CadSubcategoriacidComponent } from './cad-subcategoriacid/cad-subcategoriacid.component'; @NgModule({ declarations: [ListaSubcategoriacidComponent, CadSubcategoriacidComponent], imports: [ CommonModule ] }) export class CidModule { } <file_sep>import { Instancia } from './../core/model'; import { environment } from './../../environments/environment.prod'; import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; export class ResumoInstancia { idinstance: number; mediastoragesopinstanceuid: string; tagimagem: number; } @Injectable({ providedIn: 'root' }) export class InstanceService { url: string; urltags: string; constructor(private http: HttpClient) { this.url = `${environment.apiUrl}/instances`; this.urltags = `${environment.apiUrl}/tagimagens`; } Listar(): Promise<any> { return this.http.get(`${this.url}`).toPromise().then(response => response); } Adicionar(instancia) { return this.http.post(`${this.url}`, instancia).subscribe(response => response); } BuscarPorId(codigo: number): Promise<any> { return this.http.get(`${this.url}/${codigo}`) .toPromise() .then(response => { const instancia = response as Instancia; return instancia; }); } ResumoProDicom(codigo: number): Promise<any> { return this.http.get(`${this.url}/${codigo}?resumo`) .toPromise() .then(response => { const instancia = response as ResumoInstancia; return instancia; }); } Atualizar(instancia: Instancia): Promise<any> { return this.http.put(`${this.url}/${instancia.codigo}`, instancia) .toPromise() .then(response => { const instanciaalterado = response as Instancia; return instanciaalterado; }); } Remover(codigo: number) { this.http.delete(`${this.url}/${codigo}`) .toPromise() .then(() => null); } BuscarTagImgGamb(codigo: number): Promise<any> { return this.http.get(`${this.urltags}/tab/${codigo}`) .toPromise() .then(response => response); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TextolivreComponent } from './textolivre/textolivre.component'; @NgModule({ declarations: [TextolivreComponent], imports: [ CommonModule ] }) export class ModelosdetextoModule { } <file_sep>import { ImagemService } from './../../zservice/imagem.service'; import { TextolivreComponent } from './../../modelosdetexto/textolivre/textolivre.component'; import { ModelodelaudodoprocService } from './../../zservice/modelodelaudodoproc.service'; import { ProcedimentoatendimentoService } from './../../zservice/procedimentoatendimento.service'; import { PaginaimagensComponent } from './../paginaimagens/paginaimagens.component'; import { ParametrodosistemaService } from './../../zservice/parametrodosistema.service'; import { isEmptyObject } from 'jquery'; import { ActivatedRoute, Router } from '@angular/router'; import { Atendimento, ProcedimentoAtendimento, ModeloDeLaudoDoProc, Laudo, Imagem, LAYOUT_IMG, Instancia } from './../../core/model'; import { AtendimentoService } from './../../zservice/atendimento.service'; import { Component, OnInit, ViewChild } from '@angular/core'; import {Location} from '@angular/common'; import { ConfirmationService } from 'primeng/api'; import { MessageService } from 'primeng/api'; import cornerstone from 'cornerstone-core'; import cornerstoneMath from 'cornerstone-math'; import cornerstoneTools from 'cornerstone-tools'; import Hammer from 'hammerjs'; import cornerstoneWADOImageLoader from 'cornerstone-wado-image-loader'; import * as dicomParser from 'dicom-parser'; @Component({ selector: 'app-laudo', templateUrl: './laudo.component.html', styleUrls: ['./laudo.component.css'], providers: [ MessageService , ConfirmationService] }) export class LaudoComponent implements OnInit { @ViewChild(TextolivreComponent) textolivrechild: TextolivreComponent; @ViewChild(PaginaimagensComponent) paginaimagenschild: PaginaimagensComponent; imagelogo: any; atendimentos: any[]; testeimagems: Array<Imagem>; procedimentosAtd: any[]; atendimento = new Atendimento(); procedimento = new ProcedimentoAtendimento(); modelodelaudodoproc = new Array<ModeloDeLaudoDoProc>(); modelodelaudo: any[]; prioridade: number; dropmodelo = false; conferindo = false; abrirpaginaimg = false; paginafoto = 1; instancia: Instancia; gosto: boolean = true; constructor(private service: AtendimentoService, private serviceproc: ProcedimentoatendimentoService, private servicemodelo: ModelodelaudodoprocService, private rota: ActivatedRoute, private route: Router, private servicoparametro: ParametrodosistemaService, private location: Location, private confirmation: ConfirmationService, private messageService: MessageService, private serviceimg: ImagemService) { } ngOnInit(): void { const codigo = this.rota.snapshot.params.cod; this.CarregarAtendimentos(); this.getImagemFromService(); if (codigo) { this.BuscarProcedimento(codigo); } //this.ConfigureCornerBase(); //this.BuscarInstanciaResumida(1); } ConfigureCornerBase() { cornerstoneWADOImageLoader.external.cornerstone = cornerstone; cornerstoneWADOImageLoader.external.dicomParser = dicomParser; cornerstoneTools.external.cornerstone = cornerstone; cornerstoneTools.external.Hammer = Hammer; cornerstoneTools.external.cornerstoneMath = cornerstoneMath; } BuscarInstanciaResumida(idinstance: number, ) { this.service.ResumoProDicom(idinstance) .then( instance => { this.instancia = instance; this.CriarTelaVisualizarDicom(instance.mediastoragesopinstanceuid); } ); } CriarTelaVisualizarDicom(instanceuid: string) { const element = document.querySelector('.image-canvas'); const DCMPath = this.service.BuscarUrlBuscaImagem(instanceuid); cornerstone.enable(element); cornerstone.loadAndCacheImage('wadouri:' + DCMPath).then(imageData => { cornerstone.displayImage(element, imageData); }).catch( error => { console.error(error); }); } FotoAnterior() { if(this.paginafoto > 1) this.paginafoto--; } FotoPosterior() { if (this.paginafoto < this.procedimento.listaimagem.length) this.paginafoto++; } BuscarProcedimento(codigo: number) { this.serviceproc.BuscarPorId(codigo) .then(procedimento => { this.procedimento = procedimento; this.BuscarAtendimento(procedimento.atendimento.codigo); this.RenderizarModeloLaudo(); this.AbrirLaudo(); this.RoteandoImagens(); this.BuscandoModelosLaudo(codigo); this.testeimagems = this.procedimento.listaimagem; }).catch(erro => erro); } BuscarAtendimento(codigo: number) { this.service.BuscarPorId(codigo) .then(atendimento => { this.atendimento = atendimento; this.CarregarProcedimentos(); this.serviceimg.ListarPorCodigouid(this.atendimento.paciente.estudos[0].series[0].instancias[0].mediastoragesopinstanceuid).then(response => response); }).catch(erro => erro); } CarregaAtendimento(codigo: number) { this.service.BuscarPorId(codigo) .then(atendimento => { this.atendimento = atendimento; this.CarregarProcedimentos(); }).catch(erro => erro); } AtivarModelo() { this.dropmodelo = true; } CarregarAtendimentos() { this.service.ListarAtendimentos().then(lista => { this.atendimentos = lista.map(atendimento => ({label: 'atend: ' + atendimento.codigo + ' ' + atendimento.paciente.nome, value: atendimento.codigo})); }).catch(erro => erro); } CarregarProcedimentos() { this.service.BuscarProcedimentosPorAt(this.atendimento.codigo) .then( response => { this.atendimento = response; this.procedimentosAtd = this.atendimento.procedimentos.map(procedimento => ({label: procedimento.procedimentomedico.nome, value: procedimento.codigo})); } ); // this.BuscarImagensDicom(); } BuscandoModelosLaudo(codigo) { this.servicemodelo.BuscarPelaIdProcedimento(codigo) .then( resp => { this.modelodelaudodoproc = resp; this.prioridade = this.modelodelaudodoproc[0].prioridade; this.modelodelaudo = resp.map(modelo => ({label: modelo.descricao, value: modelo.prioridade})); this.FiltrandoProcedimento(); this.RenderizarModeloLaudo(); this.RoteandoImagens(); } ); } RoteandoImagens() { this.procedimento.listaimagem.forEach(elo => { this.serviceproc.PegarImagemString(elo.codigo).subscribe(data => { elo.imagem = data; }, error => { console.log(error); }); }); } FiltrandoProcedimento() { this.atendimento.procedimentos.filter(elo => { if (elo.codigo === this.procedimento.codigo) { this.procedimento = elo; } }); } RenderizarModeloLaudo() { if (isEmptyObject(this.procedimento.laudo)) { this.procedimento.laudo = new Laudo(); this.conferindo = true; this.AbrirLaudo(); } else { this.conferindo = true; } } PegarPagina(event){ this.paginafoto = event + 1; } Salvar() { this.serviceproc.AtualizarComPaginas(this.procedimento); this.ImprimirDocumento(); } AbrirLaudo() { this.modelodelaudodoproc.filter(elo => { if (elo.prioridade === this.prioridade) { this.procedimento.laudo.camposdolaudo.campo1 = elo.customstring; } }); setTimeout(() => { this.dropmodelo = false; }, 5); } getImagemFromService() { this.servicoparametro.PegarImagem(1).subscribe(data => { this.createImageFromBlob(data); }, error => { console.log(error); }); } createImageFromBlob(image: Blob) { const reader = new FileReader(); reader.addEventListener('load', () => { this.imagelogo = reader.result; }, false); if (image) { reader.readAsDataURL(image); } } EscolherImagens() { if (this.atendimento?.codigo != null && !isEmptyObject(this.procedimento.listaimagem)) { this.conferindo = false; this.abrirpaginaimg = true; } } AbrirTelaCaptura() { this.route.navigate(['operacoes/captura', this.procedimento.codigo]); } EscolherLaudo() { this.procedimento.listaimagem = this.testeimagems; this.abrirpaginaimg = false; this.conferindo = true; } private BuscarImagensDicom() { this.atendimento.paciente.estudos.forEach(estudo => { estudo.series.forEach(serie => { serie.instancias.forEach(instancia => { this.serviceimg.ListarPorCodigouid(instancia.mediastoragesopinstanceuid).then(response => { this.serviceproc.PegarImagemString(response.codigo).subscribe(data => { response.imagem = data; }); this.procedimento.listaimagem.push(response); }); }); }); }); } ImprimirDocumento() { const win = window.open(); win.document.write(this.ConfigurarCabecalho()); win.document.write(this.ConfigurarLaudo()); this.PegarImagemPraImpressao(); setTimeout(() => { this.procedimento.paginadeimagens.forEach(elo => { win.document.write(this.ConfigurarPaginaImg(this.procedimento.paginadeimagens.indexOf(elo))); }); }, 25); setTimeout(() => { win.document.write(this.ConfigurarRodape()); win.document.close(); win.print(); }, 50); } PegarImagemPraImpressao() { this.procedimento.paginadeimagens.forEach(elo => { elo.imagemimpressa.forEach(alo => { this.serviceproc.PegarImagemString(alo.imagem.codigo).subscribe(data => { alo.imagem.imagem = data; }, error => { console.log(error); }); }); }); } private ConfigurarCabecalho() { return '<div class="page-header" style="text-align: center; margin: 0 auto; height: 230px; position: fixed; top: 0mm; width: 93%; background-color: white;">' + '<div style="width: 100%;" class="logotip">' + '<img id="imagemtopomenu" style="width: 150px; height: 100px;" src="' + this.imagelogo + '">' + '</div>' + '<div class="cabecalho" id="cabecalho" style="width: 100%; margin: 0 auto; text-align: center; border-top: 2px solid #000000; border-bottom: 2px solid #000000; margin-top: 10px; padding-top: 5px; padding-bottom: 5px;">' + '<div id="linha1" style="width: 98%; display: inline-flex;">' + '<span style="width: 50%; text-align: left; font-famitly: Tahoma; font-size: 12pt; font-weight: bold;">PACIENTE: ' + this.atendimento.paciente.nome.toUpperCase() + '</span>' + '<span style="width: 50%; text-align: right; font-famitly: Tahoma; font-size: 12pt; font-weight: bold;">ATENDIMENTO: ' + this.ConfereAtendimento() + '</span>' + '</div>' + '<div id="linha2" style="width: 98%; display: inline-flex;">' + '<span style="width: 50%; text-align: left; font-famitly: Tahoma; font-size: 12pt; font-weight: bold;">Data Atendimento: ' + this.atendimento.dataatendimento + '</span>' + '<span style="width: 50%; text-align: right; font-famitly: Tahoma; font-size: 12pt; font-weight: bold;">Data Nasc: ' + this.atendimento.paciente.datanasc + ' Idade: ' + this.atendimento.paciente.idade + '</span>' + '</div>' + '<div id="linha3" style="width: 98%; display: inline-flex;">' + '<span style="width: 50%; text-align: left; font-famitly: Tahoma; font-size: 12pt; font-weight: bold;">Dr. SOL.: ' + this.atendimento.solicitante.nome + '</span>' + '<span style="width: 50%; text-align: right; font-famitly: Tahoma; font-size: 12pt; font-weight: bold;">Convênio: ' + this.atendimento.convenio.nome + '</span>' + '</div>' + '</div>' + '<div class="labelprocedimento" id="labelprocedimento" style="width: 93%; margin: 0 auto; text-align: center; background-color: #cfcfcf; margin-top: 30px;">' + '<span id="labelproc" style="text-transform: uppercase; font-weight: bold; font-family: Arial, Helvetica, sans-serif;">' + this.ConfigurarLabelProcedimento() + '</span>' + '</div>' + '</div>'; } private ConfereAtendimento() { return ('0000000' + this.atendimento.codigo).slice(-7); } private ConfigurarLabelProcedimento() { let proc; this.procedimentosAtd.forEach(elo => { if (elo.value === this.procedimento.codigo) { proc = elo.label; } }); return proc; } private ConfigurarLaudo() { return '<table>' + '<thead>' + '<tr>' + '<td>' + '<div class="page-header-space" style="height: 230px;"></div>' + '</td>' + '</tr>' + '</thead>' + '<tbody>' + '<tr>' + '<td>' + '<div class="page" style="width: 93%; margin: 0 auto;">' + this.procedimento.laudo.camposdolaudo.campo1 + '</div>' + '</td>' + '</tr>' + '<tr>' + '<td>' + '<div style="width: 100%; padding-top: 20px;">' + '<div class="assinatura" id="assinatura" style="width: 40%; text-align: center; border-top: 1px solid; margin-top: 80px; margin: 0 auto;">' + '<span id="labelassinatura">' + this.ConfigurarAssinatura() + '</span>' + '</div>' + '</div>' + '</td>' + '</tr>' + '</tbody>' + '<tfoot>' + '<tr>' + '<td>' + '<div class="page-footer-space" style="height: 25px;"></div>' + '</td>' + '</tr>' + '</tfoot>' + '</table>'; } private ConfigurarPaginaImg(posicao: number) { return '<table style="page-break-after: always;">' + '<thead>' + '<tr>' + '<td style="page-break-after: always;">' + '<div class="page-header-space" style="height: 230px;"></div>' + '</td>' + '</tr>' + '</thead>' + '<tbody>' + '<tr>' + '<td>' + '<div class="page" style="width: 210mm; margin: 0 auto; margin-top: 2px; flex-direction: row; justify-content: center; align-items: center">' + this.SalvarPagina(posicao) + '</div>' + '</td>' + '</tr>' + '</tbody>' + '<tfoot>' + '<tr>' + '<td>' + '<div class="page-footer-space" style="height: 25px;"></div>' + '</td>' + '</tr>' + '</tfoot>' + '</table>'; } private ConfigurarAssinatura() { return 'MÉDICO EXECUTANTE <br>' + this.atendimento.solicitante.conselho.sigla.descricao + ' ' + this.atendimento.solicitante.conselho.estado.uf + ' ' + this.atendimento.solicitante.conselho.descricao; } ConfigurarRodape() { return '<div class="page-footer" style="height: 25px; position: fixed; bottom: 0; width: 93%; border-top: 1px solid black; text-align: center; border-top: 1px solid #000; background-color: white;">' + '<span id="labelrodape">Para adquirir este software acesse www.novaopcaomed.com.br (62)3643-6264</span>' + '</div>'; } SalvarPagina(posicao: number) { if (this.procedimento.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_1_GRANDE) { return '<div class="papela4" id="papela4">' + '<div id="gradeimg" style="margin: 0 auto; position: relative; text-align: center; margin-top: 61mm;">' + '<div style="display:block; padding: 2mm;">' + '<div id="lab1" style="display: block" class="foto1grande">' + '<img style="width: 140mm; height: 105mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[0].imagem.imagem + '">' + '</div>' + '</div>' + '</div>' + '</div>'; } if (this.procedimento.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_1_MEDIA) { return '<div class="papela4" id="papela4">' + '<div id="gradeimg" style="margin: 0 auto; position: relative; text-align: center; margin-top: 61mm;">' + '<div style="display:block; padding: 2mm;">' + '<div id="lab1" style="display: block" class="foto1media">' + '<img style="width:100mm; height: 73mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[0].imagem.imagem + '">' + '</div>' + '</div>' + '</div>' + '</div>'; } if (this.procedimento.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_2_GRANDE) { return '<div class="papela4" id="papela4">' + '<div id="gradeimg" style="margin: 0 auto; position: relative; text-align: center; margin-top: 10mm;">' + '<div style="display:block; padding: 2mm;">' + '<div id="lab1" style="display: block" class="foto2grande">' + '<img style="width: 140mm; height: 105mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[0].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm;">' + '<div id="lab1" style="display: block" class="foto2grande">' + '<img style="width: 140mm; height: 105mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[1].imagem.imagem + '">' + '</div>' + '</div>' + '</div>' + '</div>'; } if (this.procedimento.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_2_MEDIA) { return '<div class="papela4" id="papela4">' + '<div id="gradeimg" style="margin: 0 auto; position: relative; text-align: center; margin-top: 45mm;">' + '<div style="display:block; padding: 2mm;">' + '<div id="lab1" style="display: block" class="foto2media">' + '<img style="width: 100mm; height: 73mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[0].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm;">' + '<div id="lab2" style="display: block" class="foto2media">' + '<img style="width: 100mm; height: 73mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[1].imagem.imagem + '">' + '</div>' + '</div>' + '</div>' + '</div>'; } if (this.procedimento.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_3_MEDIA) { return '<div class="papela4" id="papela4">' + '<div id="gradeimg" style="margin: 0 auto; position: relative; text-align: center; margin-top: 15mm;">' + '<div style="display:block; padding: 2mm;">' + '<div id="lab1" style="display: block" class="foto3media">' + '<img style="width: 80mm; height: 66mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[0].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm;">' + '<div id="lab2" style="display: block" class="foto3media">' + '<img style="width: 80mm; height: 66mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[1].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm;">' + '<div id="lab3" style="display: block" class="foto3media">' + '<img style="width: 80mm; height: 66mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[2].imagem.imagem + '">' + '</div>' + '</div>' + '</div>' + '</div>'; } if (this.procedimento.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_4_GRANDE) { return '<div class="papela4" id="papela4">' + '<div id="gradeimg" style="margin: 0 auto; position: relative; text-align: center; margin-top: 50mm; width: 190mm; height: auto; display: block;">' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab1" style="display: block" class="foto4grande">' + '<img style="width: 90mm; height: 68mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[0].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab2" style="display: block" class="foto4grande">' + '<img style="width: 90mm; height: 68mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[1].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab3" style="display: block" class="foto4grande">' + '<img style="width: 90mm; height: 68mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[2].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab4" style="display: block" class="foto4grande">' + '<img style="width: 90mm; height: 68mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[3].imagem.imagem + '">' + '</div>' + '</div>' + '</div>' + '</div>'; } if (this.procedimento.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_4_MEDIA) { return '<div class="papela4" id="papela4">' + '<div id="gradeimg" style="margin: 0 auto; position: relative; text-align: center; margin-top: 55mm; width: 170mm; height: auto; display: block;">' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab1" style="display: block" class="foto4media">' + '<img style="width: 80mm; height: 66mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[0].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab2" style="display: block" class="foto4media">' + '<img style="width: 80mm; height: 66mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[1].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab3" style="display: block" class="foto4media">' + '<img style="width: 80mm; height: 66mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[2].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab4" style="display: block" class="foto4media">' + '<img style="width: 80mm; height: 66mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[3].imagem.imagem + '">' + '</div>' + '</div>' + '</div>' + '</div>'; } if (this.procedimento.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_4_PEQUENA) { return '<div class="papela4" id="papela4">' + '<div id="gradeimg" style="margin: 0 auto; position: relative; text-align: center; margin-top: 61mm; width: 140mm; height: auto; display: block;">' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab1" style="display: block" class="foto4pequena">' + '<img style="width: 65mm; height: 50mm" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[0].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab2" style="display: block" class="foto4pequena">' + '<img style="width: 65mm; height: 50mm" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[1].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab3" style="display: block" class="foto4pequena">' + '<img style="width: 65mm; height: 50mm" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[2].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab4" style="display: block" class="foto4pequena">' + '<img style="width: 65mm; height: 50mm" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[3].imagem.imagem + '">' + '</div>' + '</div>' + '</div>' + '</div>'; } if (this.procedimento.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_6_GRANDE) { return '<div class="papela4" id="papela4">' + '<div id="gradeimg" style="margin: 0 auto; position: relative; text-align: center; margin-top: 10mm; width: 190mm; height: auto; display: block;">' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab1" style="display: block" class="foto6grande">' + '<img style="width: 90mm; height: 68mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[0].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab2" style="display: block" class="foto6grande">' + '<img style="width: 90mm; height: 68mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[1].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab3" style="display: block" class="foto6grande">' + '<img style="width: 90mm; height: 68mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[2].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab4" style="display: block" class="foto6grande">' + '<img style="width: 90mm; height: 68mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[3].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab5" style="display: block" class="foto6grande">' + '<img style="width: 90mm; height: 68mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[4].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab6" style="display: block" class="foto6grande">' + '<img style="width: 90mm; height: 68mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[5].imagem.imagem + '">' + '</div>' + '</div>' + '</div>' + '</div>'; } if (this.procedimento.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_6_MEDIA) { return '<div class="papela4" id="papela4">' + '<div id="gradeimg" style="margin: 0 auto; position: relative; text-align: center; margin-top: 15mm; width: 170mm; height: auto; display: block;">' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab1" style="display: block" class="foto6media grade1">' + '<img style="width: 80mm; height: 66mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[0].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab2" style="display: block" class="foto6media grade1">' + '<img style="width: 80mm; height: 66mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[1].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab3" style="display: block" class="foto6media grade1">' + '<img style="width: 80mm; height: 66mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[2].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab4" style="display: block" class="foto6media grade1">' + '<img style="width: 80mm; height: 66mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[3].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab5" style="display: block" class="foto6media grade1">' + '<img style="width: 80mm; height: 66mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[4].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab6" style="display: block" class="foto6media grade1">' + '<img style="width: 80mm; height: 66mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[5].imagem.imagem + '">' + '</div>' + '</div>' + '</div>' + '</div>'; } if (this.procedimento.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_8_GRANDE) { return '<div>' + '<div id="gradeimg" style="margin: 0 auto; position: relative; text-align: center; width: 180mm; height: auto; display: block;">' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab1" style="display: block" class="foto8grande">' + '<img style="width: 80mm; height: 55mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[0].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab2" style="display: block" class="foto8grande">' + '<img style="width: 80mm; height: 55mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[1].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab3" style="display: block" class="foto8grande">' + '<img style="width: 80mm; height: 55mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[2].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab4" style="display: block" class="foto8grande">' + '<img style="width: 80mm; height: 55mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[3].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab5" style="display: block" class="foto8grande">' + '<img style="width: 80mm; height: 55mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[4].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab6" style="display: block" class="foto8grande">' + '<img style="width: 80mm; height: 55mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[5].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab7" style="display: block" class="foto8grande">' + '<img style="width: 80mm; height: 55mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[6].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab8" style="display: block" class="foto8grande">' + '<img style="width: 80mm; height: 55mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[7].imagem.imagem + '">' + '</div>' + '</div>' + '</div>' + '</div>'; } if (this.procedimento.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_8_PEQUENA) { return '<div class="papela4" id="papela4">' + '<div id="gradeimg" style="margin: 0 auto; position: relative; text-align: center; margin-top: 10mm; width: 140mm; height: auto; display: block;">' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab1" style="display: block" class="foto8pequena">' + '<img style="width: 65mm; height: 50mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[0].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab2" style="display: block" class="foto8pequena">' + '<img style="width: 65mm; height: 50mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[1].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab3" style="display: block" class="foto8pequena">' + '<img style="width: 65mm; height: 50mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[2].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab4" style="display: block" class="foto8pequena">' + '<img style="width: 65mm; height: 50mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[3].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab5" style="display: block" class="foto8pequena">' + '<img style="width: 65mm; height: 50mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[4].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab6" style="display: block" class="foto8pequena">' + '<img style="width: 65mm; height: 50mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[5].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab7" style="display: block" class="foto8pequena">' + '<img style="width: 65mm; height: 50mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[6].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab8" style="display: block" class="foto8pequena">' + '<img style="width: 65mm; height: 50mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[7].imagem.imagem + '">' + '</div>' + '</div>' + '</div>' + '</div>'; } if (this.procedimento.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_9_PEQUENA) { return '<div class="papela4" id="papela4">' + '<div id="gradeimg" style="margin: 0 auto; position: relative; text-align: center; margin-top: 61mm; width: 180mm; height: auto; display: block;">' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab1" style="display: block" class="foto9pequena">' + '<img style="width:55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[0].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab2" style="display: block" class="foto9pequena">' + '<img style="width:55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[1].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab3" style="display: block" class="foto9pequena">' + '<img style="width:55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[2].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab4" style="display: block" class="foto9pequena">' + '<img style="width:55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[3].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab5" style="display: block" class="foto9pequena">' + '<img style="width:55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[4].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab6" style="display: block" class="foto9pequena">' + '<img style="width:55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[5].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab7" style="display: block" class="foto9pequena">' + '<img style="width:55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[6].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab8" style="display: block" class="foto9pequena">' + '<img style="width:55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[7].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab9" style="display: block" class="foto9pequena">' + '<img style="width:55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[8].imagem.imagem + '">' + '</div>' + '</div>' + '</div>' + '</div>'; } if (this.procedimento.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_12_PEQUENA) { return '<div class="papela4" id="papela4">' + '<div id="gradeimg" style="margin: 0 auto; position: relative; text-align: center; margin-top: 30mm; width: 180mm; height: auto; display: block;">' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab1" style="display: block" class="foto12pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[0].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab2" style="display: block" class="foto12pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[1].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab3" style="display: block" class="foto12pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[2].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab4" style="display: block" class="foto12pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[3].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab5" style="display: block" class="foto12pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[4].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab6" style="display: block" class="foto12pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[5].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab7" style="display: block" class="foto12pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[6].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab8" style="display: block" class="foto12pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[7].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab9" style="display: block" class="foto12pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[8].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab10" style="display: block" class="foto12pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[9].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab11" style="display: block" class="foto12pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[10].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab12" style="display: block" class="foto12pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[11].imagem.imagem + '">' + '</div>' + '</div>' + '</div>' + '</div>'; } if (this.procedimento.paginadeimagens[posicao].layout === LAYOUT_IMG.LAYOUT_15_PEQUENA) { return '<div class="papela4" id="papela4">' + '<div id="gradeimg" style="margin: 0 auto; position: relative; text-align: center; margin-top: 5mm; width: 180mm; height: auto; display: block;">' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab1" style="display: block" class="foto15pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[0].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab2" style="display: block" class="foto15pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[1].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab3" style="display: block" class="foto15pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[2].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab4" style="display: block" class="foto15pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[3].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab5" style="display: block" class="foto15pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[4].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab6" style="display: block" class="foto15pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[5].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab7" style="display: block" class="foto15pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[6].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab8" style="display: block" class="foto15pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[7].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab9" style="display: block" class="foto15pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[8].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab10" style="display: block" class="foto15pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[9].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab11" style="display: block" class="foto15pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[10].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab12" style="display: block" class="foto15pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[11].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab13" style="display: block" class="foto15pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[12].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab14" style="display: block" class="foto15pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[13].imagem.imagem + '">' + '</div>' + '</div>' + '<div style="display:block; padding: 2mm; float: left;">' + '<div id="lab15" style="display: block" class="foto15pequena">' + '<img style="width: 55mm; height: 40mm;" class="imagem" src="' + this.procedimento.paginadeimagens[posicao].imagemimpressa[14].imagem.imagem + '">' + '</div>' + '</div>' + '</div>' + '</div>'; } } Voltar() { this.location.back(); } } <file_sep>import { Atendimento, Paciente, Convenio, ProfissionalSolicitante, Crm, Sigla, Estado, SubcategoriaCid10, ProfissionalExecutante } from './../core/model'; import { environment } from './../../environments/environment.prod'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import * as moment from 'moment'; import { ResumoInstancia } from './instance.service'; export class AtendimentoFilter { pagina = 0; itensPorPagina = 14; pacientenome: string; solicitantenome: string; datainicial: Date; datafinal: Date; datanascpaciente: Date; } export class PdfFiltroDados { procedimento: string; executante: string; codigoprocedimento: string; } @Injectable({ providedIn: 'root' }) export class AtendimentoService { url: string; conveniourl: string; pacienteurl: string; solicitanteurl: string; siglaurl: string; estadosurl: string; urlcids: string; executanteurl: string; urlinstancia: string; constructor(private http: HttpClient) { this.url = `${environment.apiUrl}/atendimentos`; this.conveniourl = `${environment.apiUrl}/convenios`; this.pacienteurl = `${environment.apiUrl}/servidor`; this.solicitanteurl = `${environment.apiUrl}/profissionaissolicitantes`; this.siglaurl = `${environment.apiUrl}/siglas`; this.urlcids = `${environment.apiUrl}/subcategoriacid`; this.estadosurl = `${environment.apiUrl}/estados`; this.executanteurl = `${environment.apiUrl}/profissionaisexecutantes`; this.urlinstancia = `${environment.apiUrl}/instances`; } Consultar(filtro: AtendimentoFilter): Promise<any> { let params = new HttpParams({ fromObject: { page: filtro.pagina.toString(), size: filtro.itensPorPagina.toString() } }); if (filtro.pacientenome) { params = params.append('pacientenome', filtro.pacientenome); } if (filtro.solicitantenome) { params = params.append('solicitantenome', filtro.solicitantenome); } if (filtro.datainicial) { params = params.append('datainicial', moment(filtro.datainicial).format('YYYY-MM-DD')); } if (filtro.datafinal) { params = params.append('datafinal', moment(filtro.datafinal).format('YYYY-MM-DD')); } return this.http.get<any>(`${this.url}?resumo`, { params }) .toPromise() .then(response => { const atendimentos = response; const resultado = { atendimentos, total: response.totalElements }; return resultado; }); } BuscarListaPorId(codigo: number): Promise<any> { return this.http.get(`${this.url}/lista/${codigo}`).toPromise().then(response => response); } BuscarListaPorNomePaciente(nome: string): Promise<any> { return this.http.get(`${this.url}/listapac/${nome}`).toPromise().then(response => response); } Adicionar(atendimento: Atendimento): Promise<Atendimento> { return this.http.post<Atendimento>(this.url, atendimento).toPromise(); } BuscarPorId(codigo: number): Promise<any> { return this.http.get(`${this.url}/${codigo}`) .toPromise() .then(response => { const atendimento = response as Atendimento; this.converterStringsParaDatas([atendimento]); return atendimento; }); } BuscarPorIdParaAtd(codigo: number): Promise<any> { return this.http.get(`${this.url}/atd/${codigo}`) .toPromise() .then(response => { const atendimento = response as Atendimento; this.converterStringsParaDatas([atendimento]); return atendimento; }); } BuscarProcedimentosPorAt(codigo: number): Promise<any> { return this.http.get(`${this.url}/${codigo}`) .toPromise() .then(response => { const atendimento = response as Atendimento; return atendimento; }); } Atualizar(atendimento: Atendimento): Promise<any> { return this.http.put(`${this.url}/${atendimento.codigo}`, atendimento) .toPromise() .then(response => { const atendimentoalterado = response as Atendimento; this.converterStringsParaDatas([atendimentoalterado]); return atendimentoalterado; }); } Remover(codigo: number): Promise<any> { return this.http.delete(`${this.url}/${codigo}`) .toPromise() .then(() => null); } ListarPacientes(): Promise<Paciente[]> { return this.http.get<Paciente[]>(this.pacienteurl).toPromise(); } ListarAtendimentos(): Promise<Atendimento[]> { return this.http.get<Atendimento[]>(this.url).toPromise(); } ListarConvenios(): Promise<Convenio[]> { return this.http.get<Convenio[]>(this.conveniourl).toPromise(); } ListarEstados(): Promise<Estado[]> { return this.http.get<Estado[]>(this.estadosurl).toPromise(); } ListarExecutantes(): Promise<ProfissionalExecutante[]> { return this.http.get<ProfissionalExecutante[]>(this.executanteurl).toPromise(); } ListarSolicitantes(): Promise<ProfissionalSolicitante[]> { return this.http.get<ProfissionalSolicitante[]>(this.solicitanteurl).toPromise(); } ListarSigla(): Promise<Sigla[]> { return this.http.get<Sigla[]>(this.siglaurl).toPromise(); } ListarSubcategoriaCid(): Promise<SubcategoriaCid10[]> { return this.http.get<SubcategoriaCid10[]>(this.urlcids).toPromise(); } BuscarPorIdPaciente(codigo: number): Promise<Paciente> { return this.http.get<Paciente>(`${this.pacienteurl}/${codigo}`) .toPromise() .then(response => { const paciente = response as Paciente; this.converterStringsParaDatasPat([paciente]); return paciente; }); } BuscarPorIdProf(codigo: number): Promise<any> { return this.http.get(`${this.solicitanteurl}/${codigo}`) .toPromise() .then(response => { const profissionalsolicitante = response as ProfissionalSolicitante; return profissionalsolicitante; }); } private converterStringsParaDatasPat(pacientes: Paciente[]) { for (const paciente of pacientes) { if (paciente.datanasc !== null) { paciente.datanasc = moment(paciente.datanasc, 'YYYY-MM-DD').toDate(); } paciente.datacriacao = moment(paciente.datacriacao, 'YYYY-MM-DD').toDate(); } } private converterStringsParaDatas(atendimentos: Atendimento[]) { for (const atendimento of atendimentos) { atendimento.dataatendimento = moment(atendimento.dataatendimento, 'YYYY-MM-DD').toDate(); atendimento.datacadastro = moment(atendimento.datacadastro, 'YYYY-MM-DD').toDate(); if (atendimento.paciente.datanasc != null) { atendimento.paciente.datanasc = moment(atendimento.paciente.datanasc, 'YYYY-MM-DD').toDate(); } for (const proc of atendimento.procedimentos) { if (proc.dataexecucao != null) { proc.dataexecucao = moment(proc.dataexecucao, 'YYYY-MM-DD').toDate(); } if (proc.preventregalaudo != null) { proc.preventregalaudo = moment(proc.dataexecucao, 'YYYY-MM-DD').toDate(); } } } } PorAtestado(codigo: number) { return this.http.get(`${this.url}/relatorios/atestado/${codigo}`,{ responseType: 'blob' }).toPromise(); } PdfLaudo(codigo: number, pdfdados: PdfFiltroDados) { let params = new HttpParams({ fromObject: { } }); if (pdfdados.executante) { params = params.append('executante', pdfdados.executante); } if (pdfdados.procedimento) { params = params.append('procedimento', pdfdados.procedimento); } if (pdfdados.codigoprocedimento) { params = params.append('codigoprocedimento', pdfdados.codigoprocedimento); } return this.http.get(`${this.url}/pdflaudo/${codigo}?pdff`, { params: params, responseType: 'blob' }).toPromise(); } VerificarSeNomeExiste(filtro: AtendimentoFilter): Promise<boolean> { let params = new HttpParams(); if (filtro.pacientenome) { params = params.append('pacientenome', filtro.pacientenome); } if (filtro.datafinal) { params = params.append('datafinal', moment(filtro.datafinal).format('YYYY-MM-DD')); } if (filtro.datainicial) { params = params.append('datainicial', moment(filtro.datainicial).format('YYYY-MM-DD')); } if (filtro.datanascpaciente) { params = params.append('datanascpaciente', moment(filtro.datanascpaciente).format('YYYY-MM-DD')); } return this.http.get<boolean>(`${this.url}?verificarexistencia`,{ params }) .toPromise() .then(response => { const valor = response as boolean; return valor; }); } BuscarUrlBuscaImagem(instanceuid: any) { return `${this.pacienteurl}/dicom/${instanceuid}`; } ResumoProDicom(codigo: number): Promise<any> { return this.http.get(`${this.urlinstancia}/${codigo}?resumo`) .toPromise() .then(response => { const instancia = response as ResumoInstancia; return instancia; }); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CadLicenciadoComponent } from './cad-licenciado/cad-licenciado.component'; import { ListaLicenciadoComponent } from './lista-licenciado/lista-licenciado.component'; @NgModule({ declarations: [CadLicenciadoComponent, ListaLicenciadoComponent], imports: [ CommonModule ] }) export class LicenciadosModule { } <file_sep>import { FormGroup } from '@angular/forms'; import { ProfissionalexecutanteService, ProfissionalExecutanteFiltro } from './../../zservice/profissionalexecutante.service'; import { Router } from '@angular/router'; import { ProfissionalExecutante } from './../../core/model'; import { Component, OnInit } from '@angular/core'; import { LazyLoadEvent } from 'primeng/api'; import {Location} from '@angular/common'; @Component({ selector: 'app-lista-executante', templateUrl: './lista-executante.component.html', styleUrls: ['./lista-executante.component.css'] }) export class ListaExecutanteComponent implements OnInit { profissionaisexec = []; profissional: ProfissionalExecutante; totalRegistros = 0; filtro = new ProfissionalExecutanteFiltro(); textodocampo: string; dropselecionado: string = 'nome'; camposbusca: any[]; formulario: FormGroup; display = true; exclusao = false; constructor(private service: ProfissionalexecutanteService, private route: Router, private location: Location) { } ngOnInit() { this.camposbusca = [ {label: 'Nome', value: 'nome'}, {label: 'Num Conselho', value: 'conselho'} ]; } onRowSelect(event) { this.profissional = event.data; } Alterar() { if (this.profissional?.codigo != null) { this.route.navigate(['/listaprofexecutante', this.profissional.codigo]); } } PrimeiraSelecao() { this.profissional = this.profissionaisexec[0]; } UltimaSelecao() { this.profissional = this.profissionaisexec[this.profissionaisexec.length - 1]; } ProximaSelecao() { const valor = this.profissionaisexec.indexOf(this.profissional); this.profissional = this.profissionaisexec[valor + 1]; } AnteriorSelecao() { const valor = this.profissionaisexec.indexOf(this.profissional); this.profissional = this.profissionaisexec[valor - 1]; } Consultar(pagina = 0): Promise<any> { this.filtro.pagina = pagina; return this.service.Consultar(this.filtro) .then(response => { this.totalRegistros = response.total; this.profissionaisexec = response.profissionalexecutantes.content; }).catch(erro => console.log(erro)); } BuscaDinamica() { setTimeout (() => { if (this.dropselecionado === 'nome') { this.filtro.nome = this.textodocampo; this.Consultar(); } if ((this.dropselecionado === 'conselho') && (this.textodocampo !== '')) { return this.service.BuscarListaPorId(this.textodocampo) .then(response => { this.profissionaisexec = response; }).catch(erro => console.log(erro)); } }, 1000); } AtivarExcluir() { if (this.profissional.codigo != null) { this.exclusao = true; } } Excluir() { this.service.Remover(this.profissional.codigo).then(() => {}).catch(erro => erro); this.exclusao = false; setTimeout (() => this.Consultar(), 100); } aoMudarPagina(event: LazyLoadEvent) { const pagina = event.first / event.rows; this.Consultar(pagina); } Voltar() { this.location.back(); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { isEmptyObject } from 'jquery'; import { ConvenioService } from './../../zservice/convenio.service'; import { Component, OnInit } from '@angular/core'; import { Convenio } from './../../core/model'; import { FormGroup, FormBuilder } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import {Location} from '@angular/common'; import {MessageService} from 'primeng/api'; @Component({ selector: 'app-cad-convenio', templateUrl: './cad-convenio.component.html', styleUrls: ['./cad-convenio.component.css'], providers: [MessageService] }) export class CadConvenioComponent implements OnInit { formulario: FormGroup; display = true; constructor(private service: ConvenioService, private rota: ActivatedRoute, private formbuilder: FormBuilder, private route: Router, private location: Location, private messageService: MessageService) { } ngOnInit() { this.CriarFormulario(new Convenio()); const codconvenio = this.rota.snapshot.params.cod; if (codconvenio) { this.CarregarConvenios(codconvenio); } else { this.formulario.controls['ativo'].setValue('true'); } } get editando() { return Boolean(this.formulario.get('codigo').value); } CriarFormulario(convenio: Convenio) { this.formulario = this.formbuilder.group({ codigo: [null, convenio.codigo], nome: [null, convenio.nome], nomedocontato: [null, convenio.nomedocontato], telefone: [null, convenio.telefone], fax: [null, convenio.fax], ativo: [null, convenio.ativo], email: [null, convenio.email], observacoes: [null, convenio.observacoes], numcopiasdolaudo: [null, convenio.numcopiasdolaudo], endereco: this.formbuilder.group({ logradouro: [null, convenio.endereco.logradouro], complemento: [null, convenio.endereco.complemento], numero: [null, convenio.endereco.numero], bairro: [null, convenio.endereco.bairro], cidade: [null, convenio.endereco.cidade], estado: [null, convenio.endereco.estado], cep: [null, convenio.endereco.cep] }) }); } CarregarConvenios(codigo: number) { this.service.BuscarPorId(codigo).then(convenio => this.formulario.patchValue(convenio)); } Salvar() { if(this.ValidaCampoVazio()){ return; } if(this.editando){ this.AtualizarConvenios(); return; } this.VerificaDuplicidade(); } ValidaCampoVazio() { if (isEmptyObject(this.formulario.controls['nome'].value)){ this.CamposErro('Nome'); const editor = document.getElementById('nome'); editor.setAttribute('style' , 'background-color: #f8b7be4d; text-transform: uppercase;'); return true; } return false; } VerificaDuplicidade(){ this.service.VerificarSeNomeExiste(this.formulario.controls['nome'].value) .then( valor => { if(valor){ this.CamposAviso(this.formulario.controls['nome'].value); const editor = document.getElementById('nome'); editor.setAttribute('style' , 'background-color: #ffe399; text-transform: uppercase;'); } else { this.formulario.patchValue(this.AdicionarConvenios()); } } ); } AdicionarConvenios() { return this.service.Adicionar(this.formulario.value) .then(() => { this.route.navigate(['/listaconvenio']); }); } AtualizarConvenios() { this.service.Atualizar(this.formulario.value) .then(() => { this.route.navigate(['/listaconvenio']); }); } private CamposErro(campo: string) { this.messageService.add({severity:'error', summary: 'Erro', detail:'Preencher campo ' + campo.toUpperCase(), life:6000}); } private CamposAviso(campo: string) { this.messageService.add({severity:'warn', summary: 'Aviso', detail:'Valor ' + campo.toUpperCase() + ' já existe no banco de dados', life:10000}); } Voltar() { this.location.back(); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { isEmptyObject } from 'jquery'; import { GrupoprocedimentoService } from './../../zservice/grupoprocedimento.service'; import { ProcedimentomedicoService } from './../../zservice/procedimentomedico.service'; import { Component, OnInit } from '@angular/core'; import { ProcedimentoMedico } from './../../core/model'; import { FormGroup, FormBuilder } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import {Location} from '@angular/common'; import {MessageService} from 'primeng/api'; @Component({ selector: 'app-cad-procmedico', templateUrl: './cad-procmedico.component.html', styleUrls: ['./cad-procmedico.component.css'], providers: [MessageService] }) export class CadProcmedicoComponent implements OnInit { formulario: FormGroup; grupos = []; display = true; constructor(private service: ProcedimentomedicoService, private rota: ActivatedRoute, private serviceGrupo: GrupoprocedimentoService, private formbuilder: FormBuilder, private route: Router, private location: Location, private messageService: MessageService) { } ngOnInit() { this.CriarFormulario(new ProcedimentoMedico()); const codprocedimentomedico = this.rota.snapshot.params.cod; if (codprocedimentomedico) { this.CarregarProcedimentoMedico(codprocedimentomedico); } this.BuscarGrupos(); } BuscarGrupos() { return this.serviceGrupo.Listar() .then(response => { this.grupos = response .map(g => ({ label: g.nomegrupo, value: g.codigo })); }); } get editando() { return Boolean(this.formulario.get('codigo').value); } CriarFormulario(procedimentomedico: ProcedimentoMedico) { this.formulario = this.formbuilder.group({ codigo: [null, procedimentomedico.codigo], nome: [null, procedimentomedico.nome], grupo: this.formbuilder.group({ codigo: [null, procedimentomedico.grupo.codigo] }) }); } CarregarProcedimentoMedico(codigo: number) { this.service.BuscarPorId(codigo).then(procedimento => this.formulario.patchValue(procedimento)); } Salvar() { if(this.ValidaCampoVazio()){ return; } if(this.editando){ this.AtualizarProcedimentoMedico(); return; } this.VerificaDuplicidade(); } ValidaCampoVazio() { if (isEmptyObject(this.formulario.controls['nome'].value)){ this.CamposErro('Nome'); const editor = document.getElementById('nome'); editor.setAttribute('style' , 'background-color: #fcd5d5; text-transform: uppercase;'); return true; } if (this.formulario.controls['grupo'].value.codigo == null){ this.CamposErro('Grupo'); const editor = document.querySelector('#grupo .ui-inputtext') as HTMLElement; editor.setAttribute('style' , 'background-color: #fcd5d5; text-transform: uppercase;'); return true; } return false; } VerificaDuplicidade(){ this.service.VerificarSeNomeExiste(this.formulario.controls['nome'].value) .then( valor => { if(valor){ this.CamposAviso(this.formulario.controls['nome'].value); const editor = document.getElementById('nome'); editor.setAttribute('style' , 'background-color: #fcf6a1; text-transform: uppercase;'); } else { this.formulario.patchValue(this.AdicionarProcedimentoMedico()); } } ); } private CamposErro(campo: string) { this.messageService.add({severity:'error', summary: 'Erro', detail:'Preencher campo ' + campo.toUpperCase(), life:6000}); } private CamposAviso(campo: string) { this.messageService.add({severity:'warn', summary: 'Aviso', detail:'Valor ' + campo.toUpperCase() + ' já existe no banco de dados', life:10000}); } AdicionarProcedimentoMedico() { return this.service.Adicionar(this.formulario.value) .then(() => { this.route.navigate(['/listaexameprocmedico']); }); } AtualizarProcedimentoMedico() { this.service.Atualizar(this.formulario.value) .then(() => { this.route.navigate(['/listaexameprocmedico']); }); } Voltar() { this.location.back(); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { environment } from './../../environments/environment.prod'; import { Injectable } from '@angular/core'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Paciente } from '../core/model'; export class PacienteFiltro { pacienteid: string; nome: string; datanasc: Date; idade: string; sexo: string; dicom: boolean; pagina = 0; itensPorPagina = 10; } @Injectable({ providedIn: 'root' }) export class ServidorService { url: string; constructor(private http: HttpClient) { this.url = `${environment.apiUrl}/servidor`; } Listar(): Promise<any> { return this.http.get(`${this.url}`).toPromise().then(response => response); } Consultar(filtro: PacienteFiltro): Promise<any> { let params = new HttpParams({ fromObject: { page: filtro.pagina.toString(), size: filtro.itensPorPagina.toString() } }); if (filtro.pacienteid) { params = params.append('pacienteid', filtro.pacienteid); } if (filtro.dicom) { params = params.append('dicom', 'true'); } return this.http.get<any>(`${this.url}?resumo`, { params }) .toPromise() .then(response => { const pacientes = response; const resultado = { pacientes, total: response.totalElements }; return resultado; }); } BuscarPorId(codigo: number): Promise<any> { return this.http.get(`${this.url}/${codigo}`) .toPromise() .then(response => { const paciente = response as Paciente; return paciente; }); } BuscarUrlBuscaImagem(instanceuid: any) { return `${this.url}/dicom/${instanceuid}`; } BuscarInstanciasDoPaciente(codigo: number): Promise<any> { return this.http.get<any>(`${this.url}/series/${codigo}`).toPromise().then(response => response); } urlUploadAnexo(valor) { return this.http.post(`${this.url}/teste`, valor).subscribe(resposta => console.log('Upload ok.')); } } <file_sep>import { MessageService, ConfirmationService } from 'primeng/api'; import { ProfissionalexecutanteService } from './../../zservice/profissionalexecutante.service'; import { ProcedimentomedicoService } from './../../zservice/procedimentomedico.service'; import { ProcedimentoAtendimento } from './../../core/model'; import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-procedimento-cad-apend', templateUrl: './procedimento-cad-apend.component.html', styleUrls: ['./procedimento-cad-apend.component.css'], providers: [MessageService, ConfirmationService] }) export class ProcedimentoCadApendComponent implements OnInit { @Input() procedimentos: Array<ProcedimentoAtendimento>; procedimento = new ProcedimentoAtendimento(); exbindoFormularioProcedimento = false; procedimentoIndex: number; profissionalexecutantes: any[]; procedimentomedicos: any[]; constructor(private serviceProc: ProcedimentomedicoService, private serviceProf: ProfissionalexecutanteService, private messageService: MessageService) { } ngOnInit() { this.CarregarProcedimentosMedico(); this.CarregaProfissionalExecutante(); } PrepararNovoProcedimento() { this.exbindoFormularioProcedimento = true; this.procedimento = new ProcedimentoAtendimento(); this.procedimentoIndex = this.procedimentos.length; } PrepararEdicaoProcedimento(procedimento: ProcedimentoAtendimento) { this.procedimento = procedimento; this.procedimentoIndex = this.procedimentos.indexOf(procedimento); this.exbindoFormularioProcedimento = true; } ConfirmarProcedimento() { if(this.ValidaCampoVazio()){ return; } this.ValidarProfExecutante(); this.procedimentos[this.procedimentoIndex] = this.procedimento; this.exbindoFormularioProcedimento = false; } private ValidarProfExecutante() { if(this.procedimento.profexecutante === null) { delete this.procedimento.profexecutante; } } private ValidaCampoVazio(){ if (this.procedimento.procedimentomedico.codigo == null){ this.CamposErro('Procedimento Médico'); const editor = document.querySelector('#procedimentomedico .p-inputtext') as HTMLElement; editor.setAttribute('style' , 'background-color: #fcd5d5;'); return true; } return false; } private CamposErro(campo: string) { this.messageService.add({severity:'error', summary: 'Erro', detail:'Preencher campo ' + campo.toUpperCase(), life:6000}); } RemoverProcedimento(index) { this.procedimentos.splice(index, 1); } CarregarProcedimentosMedico() { this.serviceProc.Listar().then(lista => { this.procedimentomedicos = lista.map(proc => ({label: proc.nome, value: proc})); }).catch(erro => erro); } CarregaProfissionalExecutante() { this.serviceProf.Listar().then(lista => { this.profissionalexecutantes = lista.map(prof => ({label: prof.nome, value: prof})); }).catch(erro => erro); } AdicionandoDias() { this.procedimento.preventregalaudo = new Date(); this.procedimento.dataexecucao = new Date(); } BotaoCancelar() { this.exbindoFormularioProcedimento = false; } get editando() { return this.procedimento && this.procedimento.codigo; } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ListaExecutanteComponent } from './lista-executante/lista-executante.component'; import { CadExecutanteComponent } from './cad-executante/cad-executante.component'; @NgModule({ declarations: [ListaExecutanteComponent, CadExecutanteComponent], imports: [ CommonModule ] }) export class ExecutantesModule { } <file_sep>import { Subcategoriacid10Service } from './../../zservice/subcategoriacid10.service'; import { Component, OnInit } from '@angular/core'; import { SubcategoriaCid10 } from './../../core/model'; import { FormGroup, FormBuilder } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import {Location} from '@angular/common'; @Component({ selector: 'app-cad-subcategoriacid', templateUrl: './cad-subcategoriacid.component.html', styleUrls: ['./cad-subcategoriacid.component.css'] }) export class CadSubcategoriacidComponent implements OnInit { formulario: FormGroup; display = true; constructor(private service: Subcategoriacid10Service, private rota: ActivatedRoute, private formbuilder: FormBuilder, private route: Router, private location: Location) { } ngOnInit() { this.CriarFormulario(new SubcategoriaCid10()); const codconvenio = this.rota.snapshot.params.cod; if (codconvenio) { this.CarregarSubcategoriaCid10(codconvenio); } setTimeout (() => document.querySelector('.ui-dialog-titlebar-close').addEventListener('click', () => this.Fechar()), 10); } get editando() { return Boolean(this.formulario.get('codigo').value); } CriarFormulario(subcategoria: SubcategoriaCid10) { this.formulario = this.formbuilder.group({ codigo: [null, subcategoria.codigo], nome: [null, subcategoria.nome], codigotexto: [null, subcategoria.codigotexto], nome50: [null, subcategoria.nome50], restrsexo: [null, subcategoria.restrsexo], classificacao: [null, subcategoria.classificacao], causaobito: [null, subcategoria.causaobito], referencia: [null, subcategoria.referencia], excluidos: [null, subcategoria.excluidos], categoriacid10: this.formbuilder.group({ codigo: [null, subcategoria.categoriacid10.codigo], nome: [null, subcategoria.categoriacid10.nome], codigotexto: [null, subcategoria.categoriacid10.codigotexto], grupocid10: this.formbuilder.group({ codigo: [null, subcategoria.categoriacid10.grupocid10.codigo], codigotexto: [null, subcategoria.categoriacid10.grupocid10.codigotexto], nome: [null, subcategoria.categoriacid10.grupocid10.nome], capitulocid: this.formbuilder.group({ codigo: [null, subcategoria.categoriacid10.grupocid10.capitulocid10.codigo], codigotexto: [null, subcategoria.categoriacid10.grupocid10.codigotexto], nome: [null, subcategoria.categoriacid10.grupocid10.nome] }) }) }) }); } CarregarSubcategoriaCid10(codigo: number) { this.service.BuscarPorId(codigo).then(convenio => this.formulario.patchValue(convenio)); } Voltar() { this.location.back(); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { isEmptyObject } from 'jquery'; import { TextopessoalService } from './../../zservice/textopessoal.service'; import { TextoPessoal } from './../../core/model'; import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import {Location} from '@angular/common'; import {MessageService} from 'primeng/api'; @Component({ selector: 'app-cad-textopessoal', templateUrl: './cad-textopessoal.component.html', styleUrls: ['./cad-textopessoal.component.css'], providers: [MessageService] }) export class CadTextopessoalComponent implements OnInit { formulario: FormGroup; display = true; constructor(private service: TextopessoalService, private rota: ActivatedRoute, private formbuilder: FormBuilder, private route: Router, private location: Location, private messageService: MessageService) { } ngOnInit() { this.CriarFormulario(new TextoPessoal()); const codtextopessoal = this.rota.snapshot.params.cod; if (codtextopessoal) { this.CarretarTextoPessoal(codtextopessoal); } } get editando() { return Boolean(this.formulario.get('codigo').value); } CriarFormulario(texto: TextoPessoal) { this.formulario = this.formbuilder.group({ codigo: [null, texto.codigo], abreviatura: [null, texto.abreviatura], texto: [null, texto.texto] }); } CarretarTextoPessoal(codigo: number) { this.service.BuscarPorId(codigo).then(texto => this.formulario.patchValue(texto)); } Salvar() { if(this.ValidaCampoVazio()){ return; } if(this.editando){ this.AtualizarTextoPessoal(); return; } this.VerificaDuplicidade(); } ValidaCampoVazio() { if (isEmptyObject(this.formulario.controls['abreviatura'].value)){ this.CamposErro('Abreviatura'); const editor = document.getElementById('nome'); editor.setAttribute('style' , 'background-color: #fcd5d5; text-transform: uppercase;'); return true; } return false; } VerificaDuplicidade(){ this.service.VerificarSeNomeExiste(this.formulario.controls['abreviatura'].value) .then( valor => { if(valor){ this.CamposAviso(this.formulario.controls['abreviatura'].value); const editor = document.getElementById('nome'); editor.setAttribute('style' , 'background-color: #fcf6a1; text-transform: uppercase;'); } else { this.formulario.patchValue(this.AdicionarTextoPessoal()); } } ); } private CamposErro(campo: string) { this.messageService.add({severity:'error', summary: 'Erro', detail:'Preencher campo ' + campo.toUpperCase(), life:6000}); } private CamposAviso(campo: string) { this.messageService.add({severity:'warn', summary: 'Aviso', detail:'Valor ' + campo.toUpperCase() + ' já existe no banco de dados', life:10000}); } AdicionarTextoPessoal() { return this.service.Adicionar(this.formulario.value) .then(salvo => { this.route.navigate(['/listatextopessoal']); }); } AtualizarTextoPessoal() { this.service.Atualizar(this.formulario.value) .then(texto => { this.formulario.patchValue(texto); this.route.navigate(['/listatextopessoal']); }); } Voltar() { this.location.back(); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { isEmptyObject } from 'jquery'; import { Estado } from './../../core/model'; import { EstadosService, EstadosFiltro } from './../../zservice/estados.service'; import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import {Location} from '@angular/common'; import {MessageService} from 'primeng/api'; @Component({ selector: 'app-cad-estado', templateUrl: './cad-estado.component.html', styleUrls: ['./cad-estado.component.css'], providers: [MessageService] }) export class CadEstadoComponent implements OnInit { formulario: FormGroup; display = true; filtro= new EstadosFiltro(); constructor(private service: EstadosService, private rota: ActivatedRoute, private formbuilder: FormBuilder, private route: Router, private location: Location, private messageService: MessageService) { } ngOnInit() { this.CriarFormulario(new Estado()); const codestado = this.rota.snapshot.params.cod; if (codestado) { this.CarregarEstado(codestado); } } get editando() { return Boolean(this.formulario.get('codigo').value); } CriarFormulario(estado: Estado) { this.formulario = this.formbuilder.group({ codigo: [null, estado.codigo], uf: [null, estado.uf], descricao: [null, estado.descricao] }); } CarregarEstado(codigo: number) { this.service.BuscarPorId(codigo).then(texto => this.formulario.patchValue(texto)); } Salvar() { if(this.ValidaCampoVazio()){ return; } if(this.editando){ this.AtualizarEstado(); return; } this.VerificaDuplicidade(); } ValidaCampoVazio() { if (isEmptyObject(this.formulario.controls['uf'].value)){ this.CamposErro('UF'); const editor = document.getElementById('uf'); editor.setAttribute('style' , 'background-color: #fcd5d5; text-transform: uppercase;'); return true; } return false; } VerificaDuplicidade(){ this.service.VerificarSeNomeExiste(this.formulario.controls['uf'].value) .then( valor => { if(valor){ this.CamposAviso(this.formulario.controls['uf'].value); const editor = document.getElementById('uf'); editor.setAttribute('style' , 'background-color: #fcf6a1; text-transform: uppercase;'); } else { this.AdicionarEstado(); } } ); } private CamposErro(campo: string) { this.messageService.add({severity:'error', summary: 'Erro', detail:'Preencher campo ' + campo.toUpperCase(), life:6000}); } private CamposAviso(campo: string) { this.messageService.add({severity:'warn', summary: 'Aviso', detail:'Valor ' + campo.toUpperCase() + ' já existe no banco de dados', life:10000}); } AdicionarEstado() { this.service.Adicionar(this.formulario.value) .then(() => { this.route.navigate(['/listaestado']); }); } AtualizarEstado() { this.service.Atualizar(this.formulario.value) .then(() => { this.route.navigate(['/listaestado']); }); } Voltar() { this.location.back(); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { Sigla } from './../core/model'; import { environment } from './../../environments/environment.prod'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; export class SiglaFiltro { pagina = 0; itensPorPagina = 50; descricao: string; } @Injectable({ providedIn: 'root' }) export class SiglaService { url: string; constructor(private http: HttpClient) { this.url = `${environment.apiUrl}/siglas`; } Listar(): Promise<any> { return this.http.get(`${this.url}`).toPromise().then(response => response); } Consultar(filtro: SiglaFiltro): Promise<any> { let params = new HttpParams({ fromObject: { page: filtro.pagina.toString(), size: filtro.itensPorPagina.toString() } }); if (filtro.descricao) { params = params.append('descricao', filtro.descricao); } return this.http.get<any>(`${this.url}?resumo`, { params }) .toPromise() .then(response => { const siglas = response; const resultado = { siglas, total: response.totalElements }; return resultado; }); } Adicionar(sigla): Promise<Sigla> { return this.http.post<Sigla>(`${this.url}`, sigla).toPromise(); } BuscarPorId(codigo: number): Promise<any> { return this.http.get(`${this.url}/${codigo}`) .toPromise() .then(response => { const sigla = response as Sigla; return sigla; }); } BuscarListaPorId(codigo: number): Promise<any> { return this.http.get(`${this.url}/lista/${codigo}`).toPromise().then(response => response); } Atualizar(sigla: Sigla): Promise<any> { return this.http.put(`${this.url}/${sigla.codigo}`, sigla) .toPromise() .then(response => { const siglaalterado = response as Sigla; return siglaalterado; }); } Remover(codigo: number): Promise<any> { return this.http.delete(`${this.url}/${codigo}`) .toPromise() .then(() => null); } VerificarSeNomeExiste(nome: string): Promise<any> { return this.http.get(`${this.url}/verificar/${nome}`) .toPromise() .then(response => response); } } <file_sep>import { PacienteFiltro } from './servidor.service'; import { Paciente } from './../core/model'; import { environment } from './../../environments/environment.prod'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import * as moment from 'moment'; @Injectable({ providedIn: 'root' }) export class PacienteService { url: string; constructor(private http: HttpClient) { this.url = `${environment.apiUrl}/servidor`; } Listar(): Promise<any> { return this.http.get(`${this.url}`).toPromise().then(response => response); } Consultar(filtro: PacienteFiltro): Promise<any> { let params = new HttpParams({ fromObject: { page: filtro.pagina.toString(), size: filtro.itensPorPagina.toString() } }); if (filtro.nome) { params = params.append('nome', filtro.nome); } if (filtro.idade) { params = params.append('idade', filtro.idade); } if (filtro.dicom) { params = params.append('dicom', 'true'); } if (filtro.datanasc) { params = params.append('datanasc', moment(filtro.datanasc).format('YYYY-MM-DD')); } if (filtro.sexo) { params = params.append('sexo', filtro.sexo); } return this.http.get<any>(`${this.url}?resumo`, { params }) .toPromise() .then(response => { const pacientes = response; const resultado = { pacientes, total: response.totalElements }; return resultado; }); } VerificarSeNomeExiste(filtro: PacienteFiltro): Promise<any> { let params = new HttpParams(); if (filtro.nome) { params = params.append('nome', filtro.nome); } if (filtro.datanasc) { params = params.append('datanasc', moment(filtro.datanasc).format('YYYY-MM-DD')); } return this.http.get<any>(`${this.url}?verificarexistencia`,{ params }) .toPromise() .then(response => { const valor = response as boolean; return valor; }); } Adicionar(paciente): Promise<Paciente> { return this.http.post<Paciente>(`${this.url}`, paciente).toPromise(); } BuscarPorId(codigo: number): Promise<Paciente> { return this.http.get<Paciente>(`${this.url}/${codigo}`) .toPromise() .then(response => { const paciente = response as Paciente; this.converterStringsParaDatas([paciente]); return paciente; }); } BuscarListaPorId(codigo: number): Promise<any> { return this.http.get(`${this.url}/lista/${codigo}`).toPromise().then(response => response); } Atualizar(paciente: Paciente): Promise<any> { return this.http.put(`${this.url}/${paciente.codigo}`, paciente) .toPromise() .then(response => { const pacientealterado = response as Paciente; this.converterStringsParaDatas([pacientealterado]); return pacientealterado; }); } Remover(codigo: number): Promise<any> { return this.http.delete(`${this.url}/${codigo}`).toPromise().then(() => null); } private converterStringsParaDatas(pacientes: Paciente[]) { for (const paciente of pacientes) { if (paciente.datanasc !== null) { paciente.datanasc = moment(paciente.datanasc, 'YYYY-MM-DD').toDate(); } if (paciente.datacriacao !== null) { paciente.datacriacao = moment(paciente.datacriacao, 'YYYY-MM-DD').toDate(); } } } } <file_sep>import { PacienteFiltro } from './../../zservice/servidor.service'; import { isEmptyObject } from 'jquery'; import { PacienteService } from './../../zservice/paciente.service'; import { Component, OnInit } from '@angular/core'; import { Paciente, EnumSexo } from './../../core/model'; import { ActivatedRoute, Router } from '@angular/router'; import {Location} from '@angular/common'; import {MessageService} from 'primeng/api'; @Component({ selector: 'app-cad-pacientes', templateUrl: './cad-pacientes.component.html', styleUrls: ['./cad-pacientes.component.css'], providers: [MessageService] }) export class CadPacientesComponent implements OnInit { paciente = new Paciente(); display = true; enumsexo: any[]; constructor(private service: PacienteService, private rota: ActivatedRoute, private route: Router, private location: Location, private messageService: MessageService) { } ngOnInit() { const codigo = this.rota.snapshot.params.cod; if (codigo) { this.CarregarPaciente(codigo); } this.enumsexo = [ {label: 'Indefinido', value: EnumSexo.INDEFINIDO}, {label: 'Masculino', value: EnumSexo.MASCULINO}, {label: 'Feminino', value: EnumSexo.FEMININO} ]; if (this.paciente.datacriacao === undefined) { this.paciente.datacriacao = new Date; } } get editando() { return Boolean(this.paciente.codigo) } CarregarPaciente(codigo: number) { this.service.BuscarPorId(codigo) .then(paciente => { this.paciente = paciente; }) .catch(erro => erro); } Salvar() { if(this.ValidaCampoVazio()){ return; } if(this.editando){ this.AtualizarPaciente(); return; } this.VerificaDuplicidade(); } ValidaCampoVazio() { if (isEmptyObject(this.paciente.nome)){ this.CamposErro('Nome'); const editor = document.getElementById('nome'); editor.setAttribute('style' , 'background-color: #fcd5d5; text-transform: uppercase;'); return true; } // if (isEmptyObject(this.paciente.sexo)){ // this.CamposErro('Sexo'); // const editor = document.querySelector('#sexo .ui-inputtext') as HTMLElement; // editor.setAttribute('style' , 'background-color: #fcd5d5;'); // return true; // } // if (this.paciente.datanasc == null){ // this.CamposErro('Data Nascimento'); // const editor = document.querySelector('#datanasc .ui-inputtext') as HTMLElement; // editor.setAttribute('style' , 'background-color: #fcd5d5; width: 127px; height: 25px;' + // 'border-radius:2px; border: 1px solid rgb(110, 110, 110);'); // return true; // } return false; } VerificaDuplicidade(){ let filtro = new PacienteFiltro(); filtro.nome = this.paciente.nome; filtro.datanasc = this.paciente.datanasc; this.service.VerificarSeNomeExiste(filtro) .then( valor => { if(valor){ this.CamposAviso(this.paciente.nome + ' e ' + 'Data Nasc'); const editor = document.getElementById('nome'); editor.setAttribute('style' , 'background-color: #fcf6a1; text-transform: uppercase;'); } else { this.AdicionarPaciente(); } } ); } private CamposErro(campo: string) { this.messageService.add({severity:'error', summary: 'Erro', detail:'Preencher campo ' + campo.toUpperCase(), life:6000}); } private CamposAviso(campo: string) { this.messageService.add({severity:'warn', summary: 'Aviso', detail:'Valor ' + campo.toUpperCase() + ' já existe no banco de dados', life:10000}); } AdicionarPaciente() { return this.service.Adicionar(this.paciente) .then(() => { this.route.navigate(['/listapaciente']); }); } AtualizarPaciente() { this.service.Atualizar(this.paciente) .then(() => { this.route.navigate(['/listapaciente']); }); } Voltar() { this.location.back(); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { isEmptyObject } from 'jquery'; import { GrupoprocedimentoService } from './../../zservice/grupoprocedimento.service'; import { Component, OnInit } from '@angular/core'; import { GrupoProcedimento } from './../../core/model'; import { FormGroup, FormBuilder } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import {Location} from '@angular/common'; import {MessageService} from 'primeng/api'; @Component({ selector: 'app-cad-grupoexame', templateUrl: './cad-grupoexame.component.html', styleUrls: ['./cad-grupoexame.component.css'], providers: [MessageService] }) export class CadGrupoexameComponent implements OnInit { formulario: FormGroup; display = true; constructor(private service: GrupoprocedimentoService, private rota: ActivatedRoute, private formbuilder: FormBuilder, private route: Router, private location: Location, private messageService: MessageService) { } ngOnInit() { this.CriarFormulario(new GrupoProcedimento()); const codigogrupo = this.rota.snapshot.params.cod; if (codigogrupo) { this.CarregarGrupoProcedimento(codigogrupo); } } get editando() { return Boolean(this.formulario.get('codigo').value); } CriarFormulario(grupo: GrupoProcedimento) { this.formulario = this.formbuilder.group({ codigo: [null, grupo.codigo], nomegrupo: [null, grupo.nomegrupo] }); } CarregarGrupoProcedimento(codigo: number) { this.service.BuscarPorId(codigo).then(texto => this.formulario.patchValue(texto)); } Salvar() { if(this.ValidaCampoVazio()){ return; } if(this.editando){ this.AtualizarGrupoProcedimento(); return; } this.VerificaDuplicidade(); } ValidaCampoVazio() { if (isEmptyObject(this.formulario.controls['nomegrupo'].value)){ this.CamposErro('Nome'); const editor = document.getElementById('nome'); editor.setAttribute('style' , 'background-color: #fcd5d5; text-transform: uppercase;'); return true; } return false; } VerificaDuplicidade(){ this.service.VerificarSeNomeExiste(this.formulario.controls['nomegrupo'].value) .then( valor => { if(valor){ this.CamposAviso(this.formulario.controls['nomegrupo'].value); const editor = document.getElementById('nome'); editor.setAttribute('style' , 'background-color: #fcf6a1; text-transform: uppercase;'); } else { this.formulario.patchValue(this.AdicionarGrupoProcedimento()); } } ); } private CamposErro(campo: string) { this.messageService.add({severity:'error', summary: 'Erro', detail:'Preencher campo ' + campo.toUpperCase(), life:6000}); } private CamposAviso(campo: string) { this.messageService.add({severity:'warn', summary: 'Aviso', detail:'Valor ' + campo.toUpperCase() + ' já existe no banco de dados', life:10000}); } AdicionarGrupoProcedimento() { return this.service.Adicionar(this.formulario.value) .then(() => { this.route.navigate(['/listagrupoexame']); }); } AtualizarGrupoProcedimento() { this.service.Atualizar(this.formulario.value) .then(() => { this.route.navigate(['/listagrupoexame']); }); } Voltar() { this.location.back(); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { Convenio } from './../../core/model'; import { Router } from '@angular/router'; import { ConvenioFiltro, ConvenioService } from './../../zservice/convenio.service'; import { Component, OnInit } from '@angular/core'; import { LazyLoadEvent } from 'primeng/api'; import {Location} from '@angular/common'; @Component({ selector: 'app-lista-convenio', templateUrl: './lista-convenio.component.html', styleUrls: ['./lista-convenio.component.css'] }) export class ListaConvenioComponent implements OnInit { convenios = []; convenio: Convenio; totalRegistros = 0; filtro = new ConvenioFiltro(); camposbusca: any[]; textodocampo: string; dropselecionado: string = 'nome'; display = true; exclusao = false; constructor(private service: ConvenioService, private route: Router, private location: Location) { } ngOnInit() { this.camposbusca = [ {label: 'Nome', value: 'nome'}, {label: 'Codigo', value: 'codigo'} ]; //setTimeout (() => document.querySelector('.ui-dialog-titlebar-close').addEventListener('click', () => this.Fechar()), 0); } Alterar() { if (this.convenio?.codigo != null) { this.route.navigate(['/listaconvenio', this.convenio.codigo]); } } PrimeiraSelecao() { this.convenio = this.convenios[0]; } UltimaSelecao() { this.convenio = this.convenios[this.convenios.length - 1]; } ProximaSelecao() { const valor = this.convenios.indexOf(this.convenio); this.convenio = this.convenios[valor + 1]; } AnteriorSelecao() { const valor = this.convenios.indexOf(this.convenio); this.convenio = this.convenios[valor - 1]; } Consultar(pagina = 0): Promise<any> { this.filtro.pagina = pagina; return this.service.Consultar(this.filtro) .then(response => { this.totalRegistros = response.total; this.convenios = response.convenios.content; }).catch(erro => console.log(erro)); } BuscaDinamica() { setTimeout (() => { if (this.dropselecionado === 'nome') { this.filtro.nome = this.textodocampo; this.Consultar(); } if ((this.dropselecionado === 'codigo') && (this.textodocampo !== '')) { const numero = +this.textodocampo; return this.service.BuscarListaPorId(numero) .then(response => { this.convenios = response; }).catch(erro => console.log(erro)); } }, 1000); } AtivarExcluir() { if (this.convenio.codigo != null) { this.exclusao = true; } } Excluir() { this.service.Remover(this.convenio.codigo).then(() => {}).catch(erro => erro); this.exclusao = false; setTimeout (() => this.Consultar(), 100); } aoMudarPagina(event: LazyLoadEvent) { const pagina = event.first / event.rows; this.Consultar(pagina); } Voltar() { this.location.back(); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { Observable } from 'rxjs'; import { environment } from './../../environments/environment.prod'; import { HttpClient, HttpParams } from '@angular/common/http'; import { ProcedimentoAtendimento, ImagemImpressa, PaginaDeImagens } from './../core/model'; import { Injectable } from '@angular/core'; import { stringify } from 'querystring'; export class ProcedimentoAtendimentoFiltro { pagina = 0; itensPorPagina = 7; } @Injectable({ providedIn: 'root' }) export class ProcedimentoatendimentoService { url: string; constructor(private http: HttpClient) { this.url = `${environment.apiUrl}/procedimentos`; } Listar(): Promise<any> { return this.http.get(`${this.url}`).toPromise().then(response => response); } Consultar(filtro: ProcedimentoAtendimentoFiltro): Promise<any> { const params = new HttpParams({ fromObject: { page: filtro.pagina.toString(), size: filtro.itensPorPagina.toString() } }); return this.http.get<any>(`${this.url}?resumo`, { params }) .toPromise() .then(response => { const procedimentos = response; const resultado = { procedimentos, total: response.totalElements }; return resultado; }); } Adicionar(procedimento): Promise<ProcedimentoAtendimento> { return this.http.post<ProcedimentoAtendimento>(`${this.url}`, procedimento).toPromise(); } BuscarPorId(codigo: number): Promise<any> { return this.http.get(`${this.url}/${codigo}`) .toPromise() .then(response => { const procedimento = response as ProcedimentoAtendimento; return procedimento; }); } BuscarPorIdComImgLista(codigo: number): Promise<any> { return this.http.get(`${this.url}/listaimg/${codigo}`) .toPromise() .then(response => { const procedimento = response as ProcedimentoAtendimento; return procedimento; }); } BuscarCodProcedimento(codigo: number): Promise<any> { return this.http.get(`${this.url}/codprocedimento/${codigo}`) .toPromise() .then(response => { const codprocedimento = response as number; return codprocedimento; }); } Atualizar(procedimento: ProcedimentoAtendimento): Promise<any> { console.log(procedimento); try { return this.http.put(`${this.url}/${procedimento.codigo}`, procedimento) .toPromise() .then(response => { const procedimentoalterado = response as ProcedimentoAtendimento; return procedimentoalterado; }); } catch (error) { console.log(error); } } AtualizarComImagens(procedimento: ProcedimentoAtendimento): Promise<any> { return this.http.put(`${this.url}/atualizarcomimagens/${procedimento.codigo}`, procedimento) .toPromise() .then(response => { const procedimentoalterado = response as ProcedimentoAtendimento; return procedimentoalterado; }); } AtualizarComPaginas(procedimento: ProcedimentoAtendimento): Promise<any> { procedimento.listaimagem = null; procedimento.paginadeimagens.forEach(elo => { elo.imagemimpressa.forEach(alo => { alo.imagem.imagem = null; }); }); return this.http.put(`${this.url}/atualizarcompaginas/teste/${procedimento.codigo}`, procedimento) .toPromise() .then(response => { const procedimentoalterado = response as ProcedimentoAtendimento; return procedimentoalterado; }); } Remover(codigo: number): Promise<any> { return this.http.delete(`${this.url}/${codigo}`) .toPromise() .then(() => null); } PegarImagem(codigo: number): Observable<Blob> { return this.http.get(`${this.url}/imagem/${codigo}`, { responseType: 'blob' }); } PegarImagems(codigo: number): Observable<string> { return this.http.get(`${this.url}/imagemstring/${codigo}`, { responseType: 'text' }); } PegarImagemString(codigo: number): Observable<string> { return this.http.get(`${this.url}/imagemstring/${codigo}`, { responseType: 'text' }); } } <file_sep>import { Estado } from './../core/model'; import { environment } from './../../environments/environment.prod'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; export class EstadosFiltro { pagina = 0; itensPorPagina = 28; uf: string; descricao: string; } @Injectable({ providedIn: 'root' }) export class EstadosService { url: string; constructor(private http: HttpClient) { this.url = `${environment.apiUrl}/estados`; } Listar(): Promise<any> { return this.http.get(`${this.url}`).toPromise().then(response => response); } Consultar(filtro: EstadosFiltro): Promise<any> { let params = new HttpParams({ fromObject: { page: filtro.pagina.toString(), size: filtro.itensPorPagina.toString() } }); if (filtro.uf) { params = params.append('uf', filtro.uf); } if (filtro.descricao) { params = params.append('descricao', filtro.descricao); } return this.http.get<any>(`${this.url}?resumo`, { params }) .toPromise() .then(response => { const estados = response; const resultado = { estados, total: response.totalElements }; return resultado; }); } Adicionar(estado): Promise<Estado> { return this.http.post<Estado>(`${this.url}`, estado).toPromise(); } BuscarPorId(codigo: number): Promise<any> { return this.http.get(`${this.url}/${codigo}`) .toPromise() .then(response => { const estado = response as Estado; return estado; }); } BuscarListaPorId(codigo: number): Promise<any> { return this.http.get(`${this.url}/lista/${codigo}`).toPromise().then(response => response); } Atualizar(estado: Estado): Promise<any> { return this.http.put(`${this.url}/${estado.codigo}`, estado) .toPromise() .then(response => { const estadoalterado = response as Estado; return estadoalterado; }); } Remover(codigo: number): Promise<any> { return this.http.delete(`${this.url}/${codigo}`) .toPromise() .then(() => null); } VerificarSeNomeExiste(nome: string): Promise<any> { return this.http.get(`${this.url}/verificar/${nome}`) .toPromise() .then(response => { const valor = response as boolean; return valor; }); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ListaTextopessoalComponent } from './lista-textopessoal/lista-textopessoal.component'; import { CadTextopessoalComponent } from './cad-textopessoal/cad-textopessoal.component'; @NgModule({ declarations: [ListaTextopessoalComponent, CadTextopessoalComponent], imports: [ CommonModule ] }) export class TextopessoalModule { } <file_sep>import { ActivatedRoute, Router } from '@angular/router'; import { ConfirmationService } from 'primeng/api'; import { MessageService } from 'primeng/api'; import { AtendimentoService } from './../../zservice/atendimento.service'; import { Atendimento, Imagem, ProcedimentoAtendimento } from './../../core/model'; import { Component, OnInit } from '@angular/core'; import { WebcamInitError, WebcamUtil, WebcamImage } from 'ngx-webcam'; import { Subject, Observable } from 'rxjs'; import { ProcedimentoatendimentoService } from '../../zservice/procedimentoatendimento.service'; import {Location} from '@angular/common'; @Component({ selector: 'app-captura', templateUrl: './captura.component.html', styleUrls: ['./captura.component.css'], providers: [ MessageService , ConfirmationService] }) export class CapturaComponent implements OnInit { atendimento = new Atendimento(); procedimento = new ProcedimentoAtendimento(); atendimentos: any[]; procedimentosAtd: any[]; showWebcam = true; allowCameraSwitch = true; multipleWebcamsAvailable = false; errors: WebcamInitError[] = []; webcamImage = new Array<Imagem>(); trigger: Subject<void> = new Subject<void>(); nextWebcam: Subject<boolean|string> = new Subject<boolean|string>(); videoOptions: MediaTrackConstraints = {}; deviceId: string; index: number; cont: number; imagemant: any; verifica = false; item = 0; videos: any[]; paginafoto = 1; constructor(private service: AtendimentoService, private rota: ActivatedRoute, private route: Router, private serviceproc: ProcedimentoatendimentoService, private confirmation: ConfirmationService, private location: Location) { } ngOnInit() { const codigoatendimento = this.rota.snapshot.params.codigoatendimento; const codigoprocedimento = this.rota.snapshot.params.codigoprocedimento; this.CarregarAtendimentos(); if (codigoatendimento) this.BuscarProcedimento(codigoatendimento); WebcamUtil.getAvailableVideoInputs() .then((mediaDevices: MediaDeviceInfo[]) => { this.multipleWebcamsAvailable = mediaDevices && mediaDevices.length > 1; }); } BuscarProcedimento(codigo: number) { this.serviceproc.BuscarPorId(codigo) .then(procedimento => { this.procedimento = procedimento; this.BuscarAtendimento(procedimento.atendimento.codigo); this.BuscarImagens(); }).catch(erro => erro); } BuscarAtendimento(codigo: number) { this.service.BuscarPorId(codigo) .then(atendimento => { this.atendimento = atendimento; this.CarregarProcedimentos(); }).catch(erro => erro); } CarregarAtendimentos() { this.service.ListarAtendimentos().then(lista => { this.atendimentos = lista.map(atendimento => ({label: atendimento.codigo + ' ' + atendimento.paciente.nome, value: atendimento})); }).catch(erro => erro); } CarregarProcedimentos() { this.procedimentosAtd = this.atendimento.procedimentos.map(procedimento => ({label: procedimento.procedimentomedico.nome, value: procedimento})); } GravandoImagens() { if(this.verifica === false) return; this.procedimento.listaimagem.forEach((el) => { el.imagem = el.imagem.imageAsBase64.replace('data:image/jpeg;base64,', ''); }); try { this.procedimento.codigoatdteste = this.atendimento.codigo; this.serviceproc.AtualizarComImagens(this.procedimento); this.route.navigate(['/home']); } catch (error) { console.log(error); } } PegarPagina(event){ this.paginafoto = event + 1; } FotoAnterior() { if(this.paginafoto > 1) this.paginafoto--; } FotoPosterior() { if (this.paginafoto < this.procedimento.listaimagem.length) this.paginafoto++; } ConfirmarExclusao() { this.confirmation.confirm({ message: 'Deseja Excluir esta Imagem?', accept: () => { this.Excluir(this.paginafoto - 1); } }); } Excluir(codigo: number) { this.procedimento.listaimagem.splice(codigo, 1); this.verifica = true; } BuscarImagens() { this.procedimento.listaimagem.forEach((el) => { if(el.imagem !== null) return; this.serviceproc.PegarImagemString(el.codigo).subscribe(data => { const web = new WebcamImage(data, data, null); el.imagem = web; }, error => { console.log(error); }); }); } PegaAltura() { const alturaAtual = document.getElementById('divisoria').clientHeight; return alturaAtual; } PegaLargura() { const larguraAtual = document.getElementById('divisoria').clientWidth; const final = (larguraAtual / 2) + 250; return final; } public TiraFoto(): void { this.trigger.next(); if (this.item === 0) { this.item = 1; } this.verifica = true; } public toggleWebcam(): void { this.showWebcam = !this.showWebcam; } public handleInitError(error: WebcamInitError): void { this.errors.push(error); } public showNextWebcam(directionOrDeviceId: boolean|string): void { // true => move forward through devices // false => move backwards through devices // string => move to device with given deviceId this.nextWebcam.next(directionOrDeviceId); } public handleImage(webcamImage: WebcamImage): void { this.cont = this.procedimento.listaimagem.length + 1; const imagem = new Imagem(); const nomeprocedimento = ('000' + this.procedimento.procedimentomedico.codigo).slice(-3); const contador = ('00' + this.cont).slice(-2); const extensao = '.jpeg'; imagem.procedimentoatendimento.codigo = this.procedimento.codigo; imagem.nomeimagem = nomeprocedimento + contador; imagem.extensao = extensao; imagem.dicom = false; imagem.imagem = webcamImage; this.procedimento.listaimagem.push(imagem); } public cameraWasSwitched(deviceId: string): void { console.log('active device: ' + deviceId); this.deviceId = deviceId; } public get triggerObservable(): Observable<void> { return this.trigger.asObservable(); } public get nextWebcamObservable(): Observable<boolean|string> { return this.nextWebcam.asObservable(); } MostrarLaudo() { this.route.navigate(['operacoes/laudos', this.procedimento.codigo]); } Voltar() { this.location.back(); } }<file_sep>import { isEmptyObject } from 'jquery'; import { EstadosService } from './../../zservice/estados.service'; import { SiglaService } from './../../zservice/sigla.service'; import { ProfissionalSolicitante } from './../../core/model'; import { ProfissionalsolicitanteService } from './../../zservice/profissionalsolicitante.service'; import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import {Location} from '@angular/common'; import {MessageService} from 'primeng/api'; @Component({ selector: 'app-cad-solicitante', templateUrl: './cad-solicitante.component.html', styleUrls: ['./cad-solicitante.component.css'], providers: [MessageService] }) export class CadSolicitanteComponent implements OnInit { formulario: FormGroup; display = true; siglas = []; estados = []; constructor(private service: ProfissionalsolicitanteService, private serviceSigla: SiglaService, private serviceEstado: EstadosService, private rota: ActivatedRoute, private formbuilder: FormBuilder, private route: Router, private location: Location, private messageService: MessageService) { } ngOnInit() { this.CriarFormulario(new ProfissionalSolicitante()); const codprofissionalsol = this.rota.snapshot.params.cod; if (codprofissionalsol) { this.CarregarProfissionalSolicitante(codprofissionalsol); } this.BuscarEstados(); this.BuscarSiglas(); } get editando() { return Boolean(this.formulario.get('codigo').value); } CriarFormulario(profissional: ProfissionalSolicitante) { this.formulario = this.formbuilder.group({ codigo: [null, profissional.codigo], nome: [null, profissional.nome], conselho: this.formbuilder.group({ codigo: [null, profissional.conselho.codigo], descricao: [profissional.conselho.descricao], sigla: this.formbuilder.group({ codigo: [null, profissional.conselho.sigla.codigo] }), estado: this.formbuilder.group({ codigo: [null, profissional.conselho.estado.codigo] }) }) }); } CarregarProfissionalSolicitante(codigo: number) { this.service.BuscarPorId(codigo).then(profissional => this.formulario.patchValue(profissional)); } Salvar() { if(this.ValidaCampoVazio()){ return; } if(this.editando){ this.AtualizarProfissionalSolicitante(); return; } this.VerificaDuplicidade(); } ValidaCampoVazio() { if (isEmptyObject(this.formulario.controls['nome'].value)){ this.CamposErro('Nome'); const editor = document.getElementById('nome'); editor.setAttribute('style' , 'background-color: #fcd5d5; text-transform: uppercase;'); return true; } if (this.formulario.controls['conselho'].value.sigla.codigo == null){ this.CamposErro('Sigla'); const editor = document.querySelector('#sigla .p-inputtext') as HTMLElement; editor.setAttribute('style' , 'background-color: #fcd5d5; text-transform: uppercase;'); return true; } if (this.formulario.controls['conselho'].value.estado.codigo == null){ this.CamposErro('Estado'); const editor = document.querySelector('#estado .p-inputtext') as HTMLElement; editor.setAttribute('style' , 'background-color: #fcd5d5; text-transform: uppercase;'); return true; } if (isEmptyObject(this.formulario.controls['conselho'].value.descricao)){ this.CamposErro('Num. do conselho'); const editor = document.getElementById('conselho'); editor.setAttribute('style' , 'background-color: #fcd5d5; text-transform: uppercase;'); return true; } return false; } VerificaDuplicidade(){ this.service.VerificarSeNomeExiste(this.formulario.controls['nome'].value) .then( valor => { if(valor){ this.CamposAviso(this.formulario.controls['nome'].value); const editor = document.getElementById('nome'); editor.setAttribute('style' , 'background-color: #fcf6a1; text-transform: uppercase;'); } else { this.formulario.patchValue(this.AdicionarProfissionalSolicitante()); } } ); } private CamposErro(campo: string) { this.messageService.add({severity:'error', summary: 'Erro', detail:'Preencher campo ' + campo.toUpperCase(), life:6000}); } private CamposAviso(campo: string) { this.messageService.add({severity:'warn', summary: 'Aviso', detail:'Valor ' + campo.toUpperCase() + ' já existe no banco de dados', life:10000}); } AdicionarProfissionalSolicitante() { return this.service.Adicionar(this.formulario.value) .then(salvo => { this.route.navigate(['/listaprofsolicitante']); }); } AtualizarProfissionalSolicitante() { this.service.Atualizar(this.formulario.value) .then(profissional => { this.formulario.patchValue(profissional); this.route.navigate(['/listaprofsolicitante']); }); } Voltar() { this.location.back(); } BuscarSiglas() { return this.serviceSigla.Listar() .then(siglas => { this.siglas = siglas .map(g => ({ label: g.descricao, value: g.codigo })); }); } BuscarEstados() { return this.serviceEstado.Listar() .then(estados => { this.estados = estados .map(g => ({ label: g.uf, value: g.codigo })); }); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { LaudoComponent } from './laudo/laudo.component'; import { PaginaimagensComponent } from './paginaimagens/paginaimagens.component'; @NgModule({ declarations: [LaudoComponent, PaginaimagensComponent], imports: [ CommonModule ] }) export class LaudosModule { } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ListaSolicitanteComponent } from './lista-solicitante/lista-solicitante.component'; import { CadSolicitanteComponent } from './cad-solicitante/cad-solicitante.component'; @NgModule({ declarations: [ListaSolicitanteComponent, CadSolicitanteComponent], imports: [ CommonModule ] }) export class SolicitantesModule { } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ListaProcmedicoComponent } from './lista-procmedico/lista-procmedico.component'; import { CadProcmedicoComponent } from './cad-procmedico/cad-procmedico.component'; @NgModule({ declarations: [ListaProcmedicoComponent, CadProcmedicoComponent], imports: [ CommonModule ] }) export class ProcmedicosModule { } <file_sep>export const environment = { production: true, // apiUrl: 'http://192.168.15.80:8087' apiUrl: 'http://localhost:8087' }; <file_sep>import { ServidorService, PacienteFiltro } from './../../zservice/servidor.service'; import { Paciente } from './../../core/model'; import { Component, OnInit } from '@angular/core'; import { LazyLoadEvent } from 'primeng/api'; @Component({ selector: 'app-lista-servidor', templateUrl: './lista-servidor.component.html', styleUrls: ['./lista-servidor.component.css'] }) export class ListaServidorComponent implements OnInit { pacientes = []; totalRegistros = 0; filtro = new PacienteFiltro(); constructor(private service: ServidorService) { } ngOnInit() {} Consultar(pagina = 0): Promise<any> { this.filtro.pagina = pagina; this.filtro.dicom = true; return this.service.Consultar(this.filtro) .then(response => { this.totalRegistros = response.total; this.pacientes = response.pacientes.content; }).catch(erro => console.log(erro)); } BuscarPeloId(paciente: Paciente) { this.service.BuscarPorId(paciente.codigo).then(response => this.pacientes = response); } aoMudarPagina(event: LazyLoadEvent) { const pagina = event.first / event.rows; this.Consultar(pagina); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ListaPacientesComponent } from './lista-pacientes/lista-pacientes.component'; import { CadPacientesComponent } from './cad-pacientes/cad-pacientes.component'; @NgModule({ declarations: [ListaPacientesComponent, CadPacientesComponent], imports: [ CommonModule ] }) export class PacientesModule { } <file_sep>import { LicenciadoFiltro, LicenciadoService } from './../../zservice/licenciado.service'; import { Licenciado } from './../../core/model'; import { Router } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { LazyLoadEvent } from 'primeng/api'; import {Location} from '@angular/common'; @Component({ selector: 'app-lista-licenciado', templateUrl: './lista-licenciado.component.html', styleUrls: ['./lista-licenciado.component.css'] }) export class ListaLicenciadoComponent implements OnInit { licenciados = []; licenciado: Licenciado; totalRegistros = 0; filtro = new LicenciadoFiltro(); camposbusca: any[]; display = true; exclusao = false; constructor(private service: LicenciadoService, private route: Router, private location: Location) { } ngOnInit() { this.camposbusca = [ {label: 'Licenciado'}, {label: 'Código'} ]; } Alterar() { if (this.licenciado?.codigo != null) { this.route.navigate(['/listalicenciado', this.licenciado.codigo]); } } PrimeiraSelecao() { this.licenciado = this.licenciados[0]; } UltimaSelecao() { this.licenciado = this.licenciados[this.licenciados.length - 1]; } ProximaSelecao() { const valor = this.licenciados.indexOf(this.licenciado); this.licenciado = this.licenciados[valor + 1]; } AnteriorSelecao() { const valor = this.licenciados.indexOf(this.licenciado); this.licenciado = this.licenciados[valor - 1]; } Consultar(pagina = 0): Promise<any> { this.filtro.pagina = pagina; return this.service.Consultar(this.filtro) .then(response => { this.totalRegistros = response.total; this.licenciados = response.licenciados.content; }).catch(erro => console.log(erro)); } BuscaDinamica() { const drop = $('#codigodrop :selected').text(); const texto = document.getElementById('buscando') as HTMLInputElement; setTimeout (() => { if (drop === 'Licenciado') { this.filtro.licenciadopara = texto.value; this.Consultar(); } if ((drop === 'Codigo') && (texto.value !== '')) { const numero = +texto.value; return this.service.BuscarListaPorId(numero) .then(response => { this.licenciados = response; }).catch(erro => console.log(erro)); } }, 1000); } AtivarExcluir() { if (this.licenciado.codigo != null) { this.exclusao = true; } } Excluir() { this.service.Remover(this.licenciado.codigo).then(() => {}).catch(erro => erro); this.exclusao = false; setTimeout (() => this.Consultar(), 100); } aoMudarPagina(event: LazyLoadEvent) { const pagina = event.first / event.rows; this.Consultar(pagina); } Voltar() { this.location.back(); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { SiglaFiltro, SiglaService } from './../../zservice/sigla.service'; import { Sigla } from './../../core/model'; import { Router } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { LazyLoadEvent } from 'primeng/api'; import {Location} from '@angular/common'; @Component({ selector: 'app-lista-sigla', templateUrl: './lista-sigla.component.html', styleUrls: ['./lista-sigla.component.css'] }) export class ListaSiglaComponent implements OnInit { siglas = []; sigla: Sigla; totalRegistros = 0; filtro = new SiglaFiltro(); textodocampo: string; dropselecionado: string = 'descricao'; camposbusca: any[]; display = true; exclusao = false; constructor(private service: SiglaService, private route: Router, private location: Location) { } ngOnInit() { this.camposbusca = [ {label: 'Descrição', value: 'descricao'}, {label: 'Codigo', value: 'codigo'} ]; } Alterar() { if (this.sigla?.codigo != null) { this.route.navigate(['/listasigla', this.sigla.codigo]); } } PrimeiraSelecao() { this.sigla = this.siglas[0]; } UltimaSelecao() { this.sigla = this.siglas[this.siglas.length - 1]; } ProximaSelecao() { const valor = this.siglas.indexOf(this.sigla); this.sigla = this.siglas[valor + 1]; } AnteriorSelecao() { const valor = this.siglas.indexOf(this.sigla); this.sigla = this.siglas[valor - 1]; } Consultar(pagina = 0): Promise<any> { this.filtro.pagina = pagina; return this.service.Consultar(this.filtro) .then(response => { this.totalRegistros = response.total; this.siglas = response.siglas.content; }).catch(erro => console.log(erro)); } BuscaDinamica() { setTimeout (() => { if (this.dropselecionado === 'descricao') { this.filtro.descricao = this.textodocampo; this.Consultar(); } if ((this.dropselecionado === 'codigo') && (this.textodocampo !== '')) { const numero = +this.textodocampo; return this.service.BuscarListaPorId(numero) .then(response => { this.siglas = response; }).catch(erro => console.log(erro)); } }, 1000); } AtivarExcluir() { if (this.sigla.codigo != null) { this.exclusao = true; } } Excluir() { this.service.Remover(this.sigla.codigo).then(() => {}).catch(erro => erro); this.exclusao = false; setTimeout (() => this.Consultar(), 100); } aoMudarPagina(event: LazyLoadEvent) { const pagina = event.first / event.rows; this.Consultar(pagina); } Voltar() { this.location.back(); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { EstadosService } from './../../zservice/estados.service'; import { SiglaService } from './../../zservice/sigla.service'; import { ProfissionalexecutanteService } from './../../zservice/profissionalexecutante.service'; import { Component, OnInit } from '@angular/core'; import { ProfissionalExecutante } from './../../core/model'; import { FormControl } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import {Location} from '@angular/common'; import {MessageService} from 'primeng/api'; import { isEmptyObject } from 'jquery'; @Component({ selector: 'app-cad-executante', templateUrl: './cad-executante.component.html', styleUrls: ['./cad-executante.component.css'], providers: [MessageService] }) export class CadExecutanteComponent implements OnInit { profissional = new ProfissionalExecutante(); siglas = []; estados = []; executanteselecionado: number; display = true; constructor(private service: ProfissionalexecutanteService, private serviceSigla: SiglaService, private serviceEstado: EstadosService, private rota: ActivatedRoute, private route: Router, private location: Location, private messageService: MessageService) { } ngOnInit() { const codprofissionalexec = this.rota.snapshot.params.cod; if (codprofissionalexec) { this.CarregarProfissionalExecutante(codprofissionalexec); } this.BuscarEstados(); this.BuscarSiglas(); } get editando() { return Boolean(this.profissional.codigo) } CarregarPessoa(codigo: number) { this.service.BuscarPorId(codigo) .then(profissional => { this.profissional = profissional; }) .catch(erro => erro); } Salvar(form: FormControl) { if(this.ValidaCampoVazio()){ return; } if(this.editando){ this.AtualizarProfissionalExecutante(); return; } this.VerificaDuplicidade(); } CarregarProfissionalExecutante(codigo: number) { this.service.BuscarPorId(codigo) .then(profissional => { this.profissional = profissional; }) .catch(erro => erro); } AdicionarProfissionalExecutante() { this.service.Adicionar(this.profissional) .then(() => { this.route.navigate(['/listaprofexecutante']); }) .catch(erro => erro); } AtualizarProfissionalExecutante() { this.service.Atualizar(this.profissional) .then(() => { this.route.navigate(['/listaprofexecutante']); }).catch(erro => erro); } ValidaCampoVazio() { if (isEmptyObject(this.profissional.nome)){ this.CamposErro('Nome'); const editor = document.getElementById('nome'); editor.setAttribute('style' , 'background-color: #fcd5d5; text-transform: uppercase;'); return true; } if (this.profissional.conselho.sigla.codigo == null){ this.CamposErro('Sigla'); const editor = document.querySelector('#sigla .p-inputtext') as HTMLElement; editor.setAttribute('style' , 'background-color: #fcd5d5; text-transform: uppercase;'); return true; } if (this.profissional.conselho.estado.codigo == null){ this.CamposErro('Estado'); const editor = document.querySelector('#estado .p-inputtext') as HTMLElement; editor.setAttribute('style' , 'background-color: #fcd5d5; text-transform: uppercase;'); return true; } if (isEmptyObject(this.profissional.conselho.descricao)){ this.CamposErro('Num. do Conselho'); const editor = document.getElementById('conselho'); editor.setAttribute('style' , 'background-color: #fcd5d5; text-transform: uppercase;'); return true; } return false; } VerificaDuplicidade(){ this.service.VerificarSeNomeExiste(this.profissional.nome) .then( valor => { if(valor){ this.CamposAviso(this.profissional.nome); const editor = document.getElementById('nome'); editor.setAttribute('style' , 'background-color: #fcf6a1; text-transform: uppercase;'); } else { this.AdicionarProfissionalExecutante(); } } ); } private CamposErro(campo: string) { this.messageService.add({severity:'error', summary: 'Erro', detail:'Preencher campo ' + campo.toUpperCase(), life:6000}); } private CamposAviso(campo: string) { this.messageService.add({severity:'warn', summary: 'Aviso', detail:'Valor ' + campo.toUpperCase() + ' já existe no banco de dados', life:10000}); } Voltar() { this.location.back(); } BuscarSiglas() { return this.serviceSigla.Listar() .then(siglas => { this.siglas = siglas .map(g => ({ label: g.descricao, value: g.codigo })); }); } BuscarEstados() { return this.serviceEstado.Listar() .then(estados => { this.estados = estados .map(g => ({ label: g.uf, value: g.codigo })); }); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { EstadosFiltro, EstadosService } from './../../zservice/estados.service'; import { Estado } from './../../core/model'; import { Router } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { LazyLoadEvent } from 'primeng/api'; import {Location} from '@angular/common'; @Component({ selector: 'app-lista-estado', templateUrl: './lista-estado.component.html', styleUrls: ['./lista-estado.component.css'] }) export class ListaEstadoComponent implements OnInit { estados = []; estado: Estado; totalRegistros = 0; filtro = new EstadosFiltro(); textodocampo: string; dropselecionado: string = 'uf'; camposbusca: any[]; display = true; exclusao = false; constructor(private service: EstadosService, private route: Router, private location: Location) { } ngOnInit() { this.camposbusca = [ {label: 'UF', value: 'uf'}, {label: 'Descrição', value: 'descricao'}, {label: 'Codigo', value: 'codigo'} ]; } Alterar() { if (this.estado?.codigo != null) { this.route.navigate(['/listaestado', this.estado.codigo]); } } PrimeiraSelecao() { this.estado = this.estados[0]; } UltimaSelecao() { this.estado = this.estados[this.estados.length - 1]; } ProximaSelecao() { const valor = this.estados.indexOf(this.estado); this.estado = this.estados[valor + 1]; } AnteriorSelecao() { const valor = this.estados.indexOf(this.estado); this.estado = this.estados[valor - 1]; } Consultar(pagina = 0): Promise<any> { this.filtro.pagina = pagina; return this.service.Consultar(this.filtro) .then(response => { this.totalRegistros = response.total; this.estados = response.estados.content; }).catch(erro => console.log(erro)); } BuscaDinamica() { setTimeout (() => { if (this.dropselecionado === 'uf') { this.filtro.uf = this.textodocampo; this.Consultar(); } if (this.dropselecionado === 'descricao') { this.filtro.descricao = this.textodocampo; this.Consultar(); } if ((this.dropselecionado === 'codigo') && (this.textodocampo !== '')) { const numero = +this.textodocampo; return this.service.BuscarListaPorId(numero) .then(response => { this.estados = response; }).catch(erro => console.log(erro)); } }, 1000); } AtivarExcluir() { if (this.estado.codigo != null) { this.exclusao = true; } } Excluir() { this.service.Remover(this.estado.codigo).then(() => {}).catch(erro => erro); this.exclusao = false; setTimeout (() => this.Consultar(), 100); } aoMudarPagina(event: LazyLoadEvent) { const pagina = event.first / event.rows; this.Consultar(pagina); } Voltar() { this.location.back(); } Fechar() { this.route.navigate(['/home']); } } <file_sep>import { ListaGrupoexameComponent } from './grupoexames/lista-grupoexame/lista-grupoexame.component'; import { ListaSiglaComponent } from './siglas/lista-sigla/lista-sigla.component'; import { ListaEstadoComponent } from './estados/lista-estado/lista-estado.component'; import { ListaLicenciadoComponent } from './licenciados/lista-licenciado/lista-licenciado.component'; import { PaginainicioComponent } from './paginainicio/paginainicio.component'; import { ListaTextopessoalComponent } from './textopessoal/lista-textopessoal/lista-textopessoal.component'; import { ListaSolicitanteComponent } from './solicitantes/lista-solicitante/lista-solicitante.component'; import { ListaExecutanteComponent } from './executantes/lista-executante/lista-executante.component'; import { ListaPacientesComponent } from './pacientes/lista-pacientes/lista-pacientes.component'; import { ListaProcmedicoComponent } from './procmedicos/lista-procmedico/lista-procmedico.component'; import { ListaConvenioComponent } from './convenios/lista-convenio/lista-convenio.component'; import { CadEstadoComponent } from './estados/cad-estado/cad-estado.component'; import { CadSiglaComponent } from './siglas/cad-sigla/cad-sigla.component'; import { CadLicenciadoComponent } from './licenciados/cad-licenciado/cad-licenciado.component'; import { CadPacientesComponent } from './pacientes/cad-pacientes/cad-pacientes.component'; import { CadTextopessoalComponent } from './textopessoal/cad-textopessoal/cad-textopessoal.component'; import { CadSolicitanteComponent } from './solicitantes/cad-solicitante/cad-solicitante.component'; import { CadExecutanteComponent } from './executantes/cad-executante/cad-executante.component'; import { CadProcmedicoComponent } from './procmedicos/cad-procmedico/cad-procmedico.component'; import { CadGrupoexameComponent } from './grupoexames/cad-grupoexame/cad-grupoexame.component'; import { CadConvenioComponent } from './convenios/cad-convenio/cad-convenio.component'; import { TelaAtendimentoComponent } from './atendimentos/tela-atendimento/tela-atendimento.component'; import { ListaAtendimentoComponent } from './atendimentos/lista-atendimento/lista-atendimento.component'; import { CapturaComponent } from './capturas/captura/captura.component'; import { PaginaimagensComponent } from './laudos/paginaimagens/paginaimagens.component'; import { LaudoComponent } from './laudos/laudo/laudo.component'; import { EdicaoimagemComponent } from './capturas/edicaoimagem/edicaoimagem.component'; import { CadSubcategoriacidComponent } from './cid/cad-subcategoriacid/cad-subcategoriacid.component'; import { ListaSubcategoriacidComponent } from './cid/lista-subcategoriacid/lista-subcategoriacid.component'; import { ViewerComponent } from './servidor/viewer/viewer.component'; import { PrevisualizacaoComponent } from './servidor/previsualizacao/previsualizacao.component'; import { ListaServidorComponent } from './servidor/lista-servidor/lista-servidor.component'; import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = [ { path: '', data: { title: 'Página Inicial' }, children: [ { path: 'home', component: PaginainicioComponent } ] }, { path: '', data: { title: 'Servidor' }, children: [ { path: 'servidor/listagem', component: ListaServidorComponent } ] }, { path: '', data: { title: 'PreVisualizar' }, children: [ { path: 'previsualizar/:cod', component: PrevisualizacaoComponent } ] }, { path: '', data: { title: 'Viewer' }, children: [ { path: 'viewer/:cod', component: ViewerComponent } ] }, { path: '', data: { title: 'Lista CID10' }, children: [ { path: 'listasubcategoriacid', component: ListaSubcategoriacidComponent } ] }, { path: '', data: { title: 'Lista CID10' }, children: [ { path: 'subcategoriacid/:cod', component: CadSubcategoriacidComponent } ] }, { path: '', data: { title: 'Editar Imagem' }, children: [ { path: 'operacoes/editarimagem', component: EdicaoimagemComponent } ] }, { path: '', data: { title: 'Laudos' }, children: [ { path: 'operacoes/laudos', component: LaudoComponent } ] }, { path: '', data: { title: 'Laudos' }, children: [ { path: 'operacoes/laudos/:cod', component: LaudoComponent } ] }, { path: '', data: { title: 'Laudos' }, children: [ { path: 'operacoes/laudos-teste', component: PaginaimagensComponent } ] }, { path: '', data: { title: 'Laudos' }, children: [ { path: 'operacoes/laudos-teste/:cod', component: PaginaimagensComponent } ] }, { path: '', data: { title: 'Captura' }, children: [ { path: 'operacoes/captura', component: CapturaComponent } ] }, { path: '', data: { title: 'Captura' }, children: [ { path: 'operacoes/captura/:atendimentocodigo/:procedimentocodigo', component: CapturaComponent } ] }, { path: '', data: { title: 'Atendimentos' }, children: [ { path: 'operacoes/atendimento', component: ListaAtendimentoComponent } ] }, { path: '', data: { title: 'Incluir Atendimento' }, children: [ { path: 'operacoes/atendimento/novo', component: TelaAtendimentoComponent } ] }, { path: '', data: { title: 'Incluir Atendimento' }, children: [ { path: 'operacoes/atendimento/:cod', component: TelaAtendimentoComponent } ] }, { path: '', data: { title: 'Cadastrar Convênio' }, children: [ { path: 'listaconvenio', component: ListaConvenioComponent } ] }, { path: '', data: { title: 'Cadastrar Convênio' }, children: [ { path: 'listaconvenio/novo', component: CadConvenioComponent } ] }, { path: '', data: { title: 'Editar Convênio' }, children: [ { path: 'listaconvenio/:cod', component: CadConvenioComponent } ] }, { path: '', data: { title: 'Cadastrar Grupos de Procedimento' }, children: [ { path: 'listagrupoexame/novo', component: CadGrupoexameComponent } ] }, { path: '', data: { title: 'Editar Grupos de Procedimento' }, children: [ { path: 'listagrupoexame/:cod', component: CadGrupoexameComponent } ] }, { path: '', data: { title: 'Grupos de Procedimento' }, children: [ { path: 'listagrupoexame', component: ListaGrupoexameComponent } ] }, { path: '', data: { title: 'Cadastrar Procedimento Médico' }, children: [ { path: 'listaexameprocmedico', component: ListaProcmedicoComponent } ] }, { path: '', data: { title: 'Cadastrar Procedimento Médico' }, children: [ { path: 'listaexameprocmedico/novo', component: CadProcmedicoComponent } ] }, { path: '', data: { title: 'Cadastrar Procedimento Médico' }, children: [ { path: 'listaexameprocmedico/:cod', component: CadProcmedicoComponent } ] }, { path: '', data: { title: 'Cadastrar Profissional Executante' }, children: [ { path: 'listaprofexecutante/novo', component: CadExecutanteComponent } ] }, { path: '', data: { title: 'Editar Profissional Executante' }, children: [ { path: 'listaprofexecutante', component: ListaExecutanteComponent } ] }, { path: '', data: { title: 'Editar Profissional Executante' }, children: [ { path: 'listaprofexecutante/:cod', component: CadExecutanteComponent } ] }, { path: '', data: { title: 'Cadastrar Profissional Solicitante' }, children: [ { path: 'listaprofsolicitante', component: ListaSolicitanteComponent } ] }, { path: '', data: { title: 'Cadastrar Profissional Solicitante' }, children: [ { path: 'listaprofsolicitante/novo', component: CadSolicitanteComponent } ] }, { path: '', data: { title: 'Editar Profissional Solicitante' }, children: [ { path: 'listaprofsolicitante/:cod', component: CadSolicitanteComponent } ] }, { path: '', data: { title: 'Cadastrar Texto Pessoal' }, children: [ { path: 'listatextopessoal', component: ListaTextopessoalComponent } ] }, { path: '', data: { title: 'Cadastrar Texto Pessoal' }, children: [ { path: 'listatextopessoal/novo', component: CadTextopessoalComponent } ] }, { path: '', data: { title: 'Cadastrar Texto Pessoal' }, children: [ { path: 'listatextopessoal/:cod', component: CadTextopessoalComponent } ] }, { path: '', data: { title: 'Cadastrar Paciente' }, children: [ { path: 'listapaciente', component: ListaPacientesComponent } ] }, { path: '', data: { title: 'Cadastrar Paciente' }, children: [ { path: 'listapaciente/novo', component: CadPacientesComponent } ] }, { path: '', data: { title: 'Cadastrar Paciente' }, children: [ { path: 'listapaciente/:cod', component: CadPacientesComponent } ] }, { path: '', data: { title: 'Cadastrar Licenciado' }, children: [ { path: 'listalicenciado/novo', component: CadLicenciadoComponent } ] }, { path: '', data: { title: 'Editar Licenciado' }, children: [ { path: 'listalicenciado/:cod', component: CadLicenciadoComponent } ] }, { path: '', data: { title: 'Lista Licenciado' }, children: [ { path: 'listalicenciado', component: ListaLicenciadoComponent } ] }, { path: '', data: { title: 'Cadastrar Estado' }, children: [ { path: 'listaestado/novo', component: CadEstadoComponent } ] }, { path: '', data: { title: 'Editar Estado' }, children: [ { path: 'listaestado/:cod', component: CadEstadoComponent } ] }, { path: '', data: { title: 'Lista Estado' }, children: [ { path: 'listaestado', component: ListaEstadoComponent } ] }, { path: '', data: { title: 'Cadastrar Sigla' }, children: [ { path: 'listasigla/novo', component: CadSiglaComponent } ] }, { path: '', data: { title: 'Editar Sigla' }, children: [ { path: 'listasigla/:cod', component: CadSiglaComponent } ] }, { path: '', data: { title: 'Lista Sigla' }, children: [ { path: 'listasigla', component: ListaSiglaComponent } ] } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>import { Observable } from 'rxjs'; import { Imagem } from './../core/model'; import { environment } from './../../environments/environment'; import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; export class ImagemFiltro { pagina = 0; itensPorPagina = 7; } @Injectable({ providedIn: 'root' }) export class ImagemService { url: string; constructor(private http: HttpClient) { this.url = `${environment.apiUrl}/imagens`; } Listar(): Promise<any> { return this.http.get(`${this.url}`).toPromise().then(response => response); } Consultar(filtro: ImagemFiltro): Promise<any> { const params = new HttpParams({ fromObject: { page: filtro.pagina.toString(), size: filtro.itensPorPagina.toString() } }); return this.http.get<any>(`${this.url}?resumo`, { params }) .toPromise() .then(response => { const imagens = response; const resultado = { imagens, total: response.totalElements }; return resultado; }); } Adicionar(imagem): Promise<Imagem> { return this.http.post<Imagem>(`${this.url}`, imagem).toPromise(); } BuscarPorId(codigo: number): Promise<any> { return this.http.get(`${this.url}/${codigo}`) .toPromise() .then(response => { const imagem = response as Imagem; return imagem; }); } Atualizar(imagem: Imagem): Promise<any> { return this.http.put(`${this.url}/${imagem.codigo}`, Imagem) .toPromise() .then(response => { const imagemalterado = response as Imagem; return imagemalterado; }); } Remover(codigo: number): Promise<any> { return this.http.delete(`${this.url}/${codigo}`) .toPromise() .then(() => null); } ListarPorCodigouid(codigouid: string): Promise<any> { return this.http.get(`${this.url}/listadicom/${codigouid}`).toPromise().then(response => response); } PegarImagem(codigo: number): Observable<Blob> { return this.http.get(`${this.url}/imagem/${codigo}`, { responseType: 'blob' }); } PegarImagems(codigo: number): Observable<string> { return this.http.get(`${this.url}/imagemstring/${codigo}`, { responseType: 'text' }); } PegarImagemString(codigo: number): Observable<string> { return this.http.get(`${this.url}/imagemstring/${codigo}`, { responseType: 'text' }); } } <file_sep>import { FormGroup } from '@angular/forms'; import { PacienteFiltro } from './../../zservice/servidor.service'; import { Router } from '@angular/router'; import { PacienteService } from './../../zservice/paciente.service'; import { Paciente } from './../../core/model'; import { Component, OnInit } from '@angular/core'; import { LazyLoadEvent } from 'primeng/api'; import {Location} from '@angular/common'; @Component({ selector: 'app-lista-pacientes', templateUrl: './lista-pacientes.component.html', styleUrls: ['./lista-pacientes.component.css'] }) export class ListaPacientesComponent implements OnInit { pacientes = []; paciente: Paciente; totalRegistros = 0; filtro = new PacienteFiltro(); textodocampo: string; dropselecionado: string = 'nome'; camposbusca: any[]; formulario: FormGroup; display = true; exclusao = false; constructor(private service: PacienteService, private route: Router, private location: Location) { } ngOnInit() { this.CriarCamposBusca(); } private CriarCamposBusca() { this.camposbusca = [ {label: 'Nome', value: 'nome'}, {label: 'Prontuario', value: 'prontuario'}, {label: 'Data Nasc', value: 'datanasc'}, {label: 'Data Cad', value: 'datacad'} ]; } onRowSelect(event) { this.paciente = event.data; } Alterar() { if (this.paciente.codigo != null) { this.route.navigate(['/listapaciente', this.paciente.codigo]); } } PrimeiraSelecao() { this.paciente = this.pacientes[0]; } UltimaSelecao() { this.paciente = this.pacientes[this.pacientes.length - 1]; } ProximaSelecao() { const valor = this.pacientes.indexOf(this.paciente); this.paciente = this.pacientes[valor + 1]; } AnteriorSelecao() { const valor = this.pacientes.indexOf(this.paciente); this.paciente = this.pacientes[valor - 1]; } Consultar(pagina = 0): Promise<any> { this.filtro.pagina = pagina; this.filtro.dicom = false; return this.service.Consultar(this.filtro) .then(response => { this.totalRegistros = response.total; this.pacientes = response.pacientes.content; }).catch(erro => console.log(erro)); } BuscaDinamica() { setTimeout (() => { if (this.dropselecionado === 'nome') { this.filtro.datanasc = null; this.filtro.nome = this.textodocampo; this.Consultar(); } if ((this.dropselecionado === 'prontuario') && (this.textodocampo !== '')) { const numero = +this.textodocampo; return this.service.BuscarListaPorId(numero) .then(response => { this.pacientes = response; }).catch(erro => console.log(erro)); } }, 1000); } AtivarExcluir() { if (this.paciente.codigo != null) { this.exclusao = true; } } Excluir() { this.service.Remover(this.paciente.codigo).then(() => {}).catch(erro => erro); this.exclusao = false; setTimeout (() => this.Consultar(), 100); } aoMudarPagina(event: LazyLoadEvent) { const pagina = event.first / event.rows; this.Consultar(pagina); } Fechar() { this.route.navigate(['/home']); } Voltar() { this.location.back(); } }
2a5a85eb8ef9543fc45ebcf23232cb959ac92281
[ "TypeScript" ]
54
TypeScript
alankaiko/DoorLayout
2de3f8209980451fa057db40fbf5d1d81a4d6685
d9a3f60406edaf94c51181d5abbba35e16253135
refs/heads/master
<file_sep>import pandas as pd import numpy as np import spacy import time from fuzzywuzzy import fuzz from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.preprocessing import StandardScaler #import xgboost as xgb from sklearn.metrics import confusion_matrix from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score from sklearn import svm from sklearn import linear_model from collections import defaultdict from tqdm import tqdm import matplotlib.pyplot as plt import seaborn as sns #__________________intermediary/helper_functions_______________________# def get_pos_tags(doc1,doc2,pos,as_vecs=False): ''' doc1,doc2 : Spacy Document Objects pos: string Part-of-speech tag (ie 'noun','verb') returns: tuple of token lists (pseudo-document) filtered by pos tag ''' if as_vecs: return [token.vector for token in doc1 if token.pos_ == pos.upper()],[token.vector for token in doc2 if token.pos_ == pos.upper()] return [token for token in doc1 if token.pos_ == pos.upper()],[token for token in doc2 if token.pos_ == pos.upper()] def get_ents(doc_pair, as_vecs=False): ''' doc_pair : tuple of lists of spacy tokens returns: filters both docs for tokens with entity tags ''' return [token for token in doc_pair[0] if token.ent_type],[token for token in doc_pair[1] if token.ent_type] def get_ent_types(doc_pair): ''' doc_pair : tuple of lists of spacy tokens returns: entity types for both docs as tup of lists ''' return [token.ent_type_ for token in doc_pair[0] if token.ent_type],[token.ent_type_ for token in doc_pair[1] if token.ent_type] def count_toks(doc_pair,unique=False,doc2=False): ''' doc_pair : tuple of lists of spacy tokens returns : total number of tokens in both docs. If unique, returns the number of unique tokens (as determined by lemma values) ''' flatten = lambda l: [item.lemma_ for sublist in l for item in sublist] flat=flatten(doc_pair) if unique: return len(set(flat)) return len(flat) def count_txt_toks(doc_pair,unique=False): ''' doc_pair : tuple of lists of spacy tokens Works the same as count_toks but for non-spacy tokens returns : total number of tokens in both docs. If unique, returns the number of unique tokens (as determined by lemma values) ''' flatten = lambda l: [item for sublist in l for item in sublist] flat=flatten(doc_pair) if unique: return len(set(flat)) return len(flat) def get_common_words(doc_pair,as_vecs=False,use_toks=True): ''' doc_pair : tuple of lists of spacy tokens returns: new list of common tokens, compared by lemma values if use_toks is true ''' if use_toks: return [token for token in doc_pair[0] if token.lemma_ in [token.lemma_ for token in doc_pair[1]]] return [token for token in doc_pair[0] if token in [token for token in doc_pair[1]]] def get_diff_words(doc_pair,as_vecs=False,use_toks=True): ''' doc_pair : tuple of lists of spacy tokens returns: new doc pair of different tokens, compared by lemma values if use_toks is true ''' if use_toks: in_1_not_2 = [token for token in doc_pair[0] if token.lemma not in [token.lemma for token in doc_pair[1]]] in_2_not_1 = [token for token in doc_pair[1] if token.lemma not in [token.lemma for token in doc_pair[0]]] else: in_1_not_2 = [token for token in doc_pair[0] if token not in [token for token in doc_pair[1]]] in_2_not_1 = [token for token in doc_pair[1] if token not in [token for token in doc_pair[0]]] if not as_vecs: return in_1_not_2,in_2_not_1 else: return [token.vector for token in in_1_not_2],[token.vector for token in in_2_not_1] def get_sims(doc_pair): ''' doc_pair : tuple of lists of spacy tokens averages word vecs in each doc returns: cosine similarity of two docs ''' if len(doc_pair[0])==0 or len(doc_pair[1])==0: return 0 mean_vecs = [] for each in doc_pair: if len(each)<=1: mean_vecs.append(each) else: mean_vecs.append(mean_vec(each)) return similarity(mean_vecs[0],mean_vecs[1]) def mean_vec(list_of_vecs,use_toks=False): '''extends functionality of spacy.doc.vector by averaging the vectors of component tokens''' if use_toks: return np.mean(np.array([x.vector for x in list_of_vecs]), axis=0) return np.mean(np.array([*list_of_vecs]), axis=0) ##__________________________________FEATURE_ENGINEERING_________________________________## #___________________________________statistical semantic features def ent_match_ratio(doc1,doc2,unique=False): '''Returns a basic fuzz.ratio of the entities in each document''' ents1,ents2=get_ents((doc1,doc2)) weight = 1 return .01*fuzz.ratio(ents1,ents2)*weight def ent_type_match_ratio(doc1,doc2): '''Returns a basic fuzz.ratio of entity types (ie USA=>GPE for geopolitical entity)''' enttypes1,enttypes2=get_ent_types((doc1,doc2)) return .01*fuzz.ratio(enttypes1,enttypes2) def pos_match_ratio(doc1,doc2,pos): '''Returns a basic fuzz.ratio of given part of speech (ie verb) in each document''' pos=get_pos_tags(doc1,doc2,pos) return .01*fuzz.ratio(*pos) #___________________________________purely semantic features def similarity(vec1, vec2): '''Mimics spacy similarity for general vectors. Returns cosine similarity of two vecs''' vec12 = np.squeeze(vec1) vec22 = np.squeeze(vec2) if vec12.all() and vec22.all(): return np.dot(vec12, vec22) / (np.linalg.norm(vec12) * np.linalg.norm(vec22)) else: return 0 def sim_by_pos(doc1,doc2,pos): return get_sims(get_pos_tags(doc1,doc2,pos,as_vecs=True)) def sim_of_diffs(doc1,doc2,pos=None): if pos: return get_sims(get_diff_words(get_pos_tags(doc1,doc2,pos),as_vecs=True)) return get_sims(get_diff_words((doc1,doc2),as_vecs=True)) lemmastr = lambda l: "".join([item.lemma_+" " for item in l]).strip() ##PREPARE PARSE PIPELINE: # def prepare(traindf): # q1 = traindf['question1'] # q2 = traindf['question2'] # # q1_it = iter(q1) # q2_it = iter(q2) # # q1_docs_ = nlp.pipe(q1_it) #nlp.pipe takes an iterator and returns a generator that preforms spacy pipeline # # q2_docs_ = nlp.pipe(q2_it) # return zip(q1_docs_,q2_docs_) def parse(doc_pairs,keep_docs=True,keep_text=False): feat_dict = defaultdict(list) pos_list = ['noun','verb','adj','adv'] for q1,q2 in tqdm(tup_of_docs): if keep_docs: feat_dict['q1_docs'].append(q1) feat_dict['q2_docs'].append(q2) if keep_text: feat_dict['q1_txt'].append(q1.text) feat_dict['q2_txt'].append(q2.text) feat_dict['sim'].append(q1.similarity(q2)) feat_dict['sim_of_diffs'].append(sim_of_diffs(q1,q2)) for pos in pos_list: feat_dict[f'sim_of_{pos}s'].append(sim_by_pos(q1,q2,pos)) feat_dict[f'sim_of_diffs_{pos}s'].append(sim_of_diffs(q1,q2,pos=pos)) feat_dict[f'{pos}_mratio'].append(pos_match_ratio(q1,q2,pos)) feat_dict['propn_mratio'].append(pos_match_ratio(q1,q2,'propn')) feat_dict['ent_ratio'].append(ent_match_ratio(q1,q2)) feat_dict['ent_type_match_ratio'].append(ent_type_match_ratio(q1,q2)) return pd.DataFrame(data=feat_dict) ##TESTING/CHECKING def feature_sampler(index,df=None,y=None): test1,test2 = (df.q1_docs.loc[index],df.q2_docs.loc[index]) pos_list = ['noun','verb','adj','adv'] print('question 1: ',test1) print('question 2: ',test2) print('is duplicate: ',y.loc[index]) print('\n') print('similarities: ', test1.similarity(test2)) print('similarity of differences: ',sim_of_diffs(test1,test2)) for pos in pos_list: print('\n _______%ss_______'%pos) print(get_pos_tags(test1,test2,pos)) print('%s_matchratio: '%pos,pos_match_ratio(test1,test2,pos)) print('sim: ',sim_by_pos(test1,test2,pos)) print('s.o.d.s: ',sim_of_diffs(test1,test2,pos=pos)) print('\n _______Proper_Nouns_______') print(get_pos_tags(test1,test2,'propn')) # print('has_propns: ',both_have_pos((test1,test2),'propn')) print('propn_matchratio:',pos_match_ratio(test1,test2,'propn')) print('sim: ',sim_by_pos(test1,test2,'propn')) print('s.o.d.s: ',sim_of_diffs(test1,test2,pos='propn')) print('\n _______Entities_______') print(get_ents((test1,test2))) print('ent_matchratio: ',ent_match_ratio(test1,test2)) #print('has_ents: ',both_have_ents((test1,test2))) print('\n _______Entity_Types_______') print(get_ent_types((test1,test2))) print('ent_type_match ratio: ',ent_type_match_ratio(test1,test2)) <file_sep>import time from fuzzywuzzy import fuzz from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.preprocessing import StandardScaler import xgboost as xgb from sklearn.metrics import confusion_matrix from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score from sklearn import svm #basic features df_200K['len_q1'] = df_200K['question1'].apply(lambda x: len(str(x))) df_200K['len_q2'] = df_200K['question2'].apply(lambda x: len(str(x))) df_200K['diff_len'] = abs(df_200K['len_q1'] - df_200K['len_q2']) df_200K['len_char_q1'] = df_200K['question1'].apply(lambda x: len(''.join(set(str(x).replace(' ', ''))))) df_200K['len_char_q2'] = df_200K['question2'].apply(lambda x: len(''.join(set(str(x).replace(' ', ''))))) df_200K['len_word_q1'] = df_200K['question1'].apply(lambda x: len(str(x).split())) df_200K['len_word_q2'] = df_200K['question2'].apply(lambda x: len(str(x).split())) df_200K['common_words'] = df_200K.apply(lambda x: len(set(str(x['question1']).lower().split()).intersection(set(str(x['question2']).lower().split()))), axis=1) #fuzzywuzzy ratio features df_200K['fuzz_simple_ratio'] = df_200K.apply(lambda x: fuzz.ratio(str(x['question1']), str(x['question2'])), axis=1) df_200K['fuzz_partial_ratio'] = df_200K.apply(lambda x: fuzz.partial_ratio(str(x['question1']), str(x['question2'])), axis=1) df_200K['fuzz_token_set_ratio'] = df_200K.apply(lambda x: fuzz.token_set_ratio(str(x['question1']), str(x['question2'])), axis=1) df_200K['fuzz_partial_token_set_ratio'] = df_200K.apply(lambda x: fuzz.partial_token_set_ratio(str(x['question1']), str(x['question2'])), axis=1) df_200K['fuzz_token_sort_ratio'] = df_200K.apply(lambda x: fuzz.token_sort_ratio(str(x['question1']), str(x['question2'])), axis=1) df_200K['fuzz_partial_token_sort_ratio'] = df_200K.apply(lambda x: fuzz.partial_token_sort_ratio(str(x['question1']), str(x['question2'])), axis=1) #sim_by_verb_column sim_by_verb_list = [] for i, j in zip(smart_df['q1'], smart_df['q2']): sim_by_verb_list.append(sim_by_pos(i,j,'verb')) sim_by_verb_series = pd.Series(sim_by_verb_list) sim_by_verb_series.rename("sim_by_verb", inplace=True) smart_df = pd.concat([smart_df, sim_by_verb_series], axis=1) #sim_of_diffs_by_verb_column sim_of_diffs_by_verb_list = [] for i, j in zip(smart_df['q1'], smart_df['q2']): sim_of_diffs_by_verb_list.append(sim_of_diffs_by_pos(i,j,'verb')) sim_of_diffs_by_verb_series = pd.Series(sim_of_diffs_by_verb_list) sim_of_diffs_by_verb_series.rename("sim_of_diffs_by_verb", inplace=True) smart_df = pd.concat([smart_df, sim_of_diffs_by_verb_series], axis=1) #sim_by_noun_column sim_by_noun_list = [] for i, j in zip(smart_df['q1'], smart_df['q2']): sim_by_noun_list.append(sim_by_pos(i,j,'noun')) sim_by_noun_series = pd.Series(sim_by_noun_list) sim_by_noun_series.rename("sim_by_noun", inplace=True) smart_df = pd.concat([smart_df, sim_by_noun_series], axis=1) #sim_of_diffs_by_noun_column sim_of_diffs_by_noun_list = [] for i, j in zip(smart_df['q1'], smart_df['q2']): sim_of_diffs_by_noun_list.append(sim_of_diffs_by_pos(i,j,'noun')) sim_of_diffs_by_noun_series = pd.Series(sim_of_diffs_by_noun_list) sim_of_diffs_by_noun_series.rename("sim_of_diffs_by_noun", inplace=True) smart_df = pd.concat([smart_df, sim_of_diffs_by_noun_series], axis=1) #distplots sns.distplot(smart_df['sim_by_verb']) sns.distplot(smart_df['sim_of_diffs_by_verb']) sns.distplot(smart_df['sim_by_noun']) sns.distplot(smart_df['sim_of_diffs_by_noun']) #define X and y X = df_200K.iloc[:,6:] y = df_200K.iloc[:,5:6] #transform scaler = StandardScaler() X_scaled = scaler.fit_transform(X) #split X_train, X_test, y_train, y_test = train_test_split(X_scaled, y) #logistic regression logreg = LogisticRegression(fit_intercept = False, C = 1e12) logreg_model = logreg.fit(X_train, y_train) logreg_model y_hat_train = logreg_model.predict(X_train) y_hat_test = logreg_model.predict(X_test) residuals = y_train_array - y_hat_train pd.Series(residuals).value_counts() pd.Series(residuals).value_counts(normalize=True) y_test_array = np.array(y_test['is_duplicate']) residuals = y_test_array - y_hat_test pd.Series(residuals).value_counts() pd.Series(residuals).value_counts(normalize=True) print(confusion_matrix(y_test_array, y_hat_test)) #Random Forest rf_clf = RandomForestClassifier() mean_rf_cv_score = np.mean(cross_val_score(rf_clf, X_scaled, y, cv=3)) print("Mean Cross Validation Score for Random Forest Classifier: {:.4}%".format(mean_rf_cv_score * 100)) rf_param_grid = { 'n_estimators': [10, 30, 100], 'criterion': ['gini', 'entropy'], 'max_depth': [None, 2, 6, 10], 'min_samples_split': [10, 20], 'min_samples_leaf': [1, 2, 5] } start = time.time() rf_grid_search = GridSearchCV(rf_clf, rf_param_grid, cv=3) rf_grid_search.fit(X_scaled, y) print("Testing Accuracy: {:.4}%".format(rf_grid_search.best_score_ * 100)) print("Total Runtime for Grid Search on Random Forest Classifier: {:.4} seconds".format(time.time() - start)) print("") print("Optimal Parameters: {}".format(rf_grid_search.best_params_)) #SVM import time start_time = time.time() clf = svm.SVC(probability=True) clf.fit(X_train, y_train) total = time.time() - start_time clf.predict_proba(X_test) clf.score(X_test, y_test) <file_sep># Redundant Question Classification The goal of this project is to understand what makes two questions semantically the same (according to Quora). The labeled data come from Quora via a Kaggle competition. For Quora, such a classifier would help improve user experience and reduce website maintenance costs. ## Features Because the problem has been solved best by complex deep learning models, we sought to create a model that uses interpretable features as inputs. Using Spacy's pretrained language model and processing pipeline with fuzzywuzzy match ratios, we engineered 17 features: <ul> <li>Question Similarity <li>Similarity of Different Words <li>Entity Type Match Ratio <li>Entity Match Ratio <li>Proper Noun Match Ratio <li>Noun Match Ratio <li>Noun Similarity <li>Similarity of Different Nouns <li>The previous three points, for verbs, adjectives, and adverbs </ul> **Similarity** refers to the cosine similarity of the aggregate word embeddings by document or subdocument<br> **Entity Type** refers to Spacy's named entity recognition. These are "real world objects with names", ie person, country, place, money, date <br> **Entity** refers to the entity instance, ie <NAME>, Great Britain, $12.12, October 1999<br> ## Feature Explorer ![Duplicate](/resources/dup.png) ## Models ### Logistic Regression Mean Cross Val Score: 67.17% <br> ### Random Forest Mean Cross Val Score: 73.39% <br> Feature Importance:<br> ![Feature Importance XGBoost](/resources/rf_fts.png) ### XGBoost Mean Cross Val Score: 73.64% <br> Feature Importance:<br> ![Feature Importance XGBoost](/resources/xgboost_fts.png)
8d7defac717e833e6ddf6e80066f70a29d604bd7
[ "Markdown", "Python" ]
3
Python
colemiller94/quora_question_project
bc9b6c9c3ac164d02b191e99980db97b5a74f784
6769d162e2711a5621f9be42b0f36b393894dc49
refs/heads/master
<file_sep># frozen_string_literal: true module SitePrism VERSION = '3.4.2' end
d9ac6cb49e48b33b62013cf985c41ccf7f167674
[ "Ruby" ]
1
Ruby
ineverov/site_prism-1
34a1ec938bee8c7cbd6dfba067d0747d65906c5e
8335190a704c25ebac8aba6b6442653df751abfa
refs/heads/master
<file_sep># aplicatii diverse ## aplicatii HTML ## aplicatii android # boancamaria.github.io <file_sep>document.getElementById(" id_logic_version").innerHTML= Logic="2019.11.4.2"; window.addEventListener("deviceorientation ", on_gyro_data_uab); window.addEventListener("devicemotion ", on_acc_data_uab); function on_gyro_data_uab(e) { document.getElementById("id_alpha").innerHTML = Math.round(e.alpha * 100)/100; document.getElementById("id_beta").innerHTML = Math.round(e.beta * 100)/100; document.getElementById("id_gama").innerHTML = Math.round(e.gama * 100)/100; } function on_acc_data_uab(e) { var acc = a.accelerationIncludingGravity; document.getElementById("id_acc_x").innerHTML = Math.round(acc.x * 100)/100; document.getElementById("id_acc_x").innerHTML = Math.round(acc.y * 100)/100; document.getElementById("id_acc_x").innerHTML = Math.round(acc.z * 100)/100; var rot_x = Math.atan(acc.x / acc.z) *180/Math.PI; var rot_y = Math.atan(acc.y / acc.z) *180/Math.PI; document.getElementById("id_rot_x").innerHTML =Math.round(rot_x*100)/100; document.getElementById("id_rot_y").innerHTML =Math.round(rot_y*100)/100;
6fe15e0e9fa0a40b26905e13f2e6d73a9818ce60
[ "Markdown", "JavaScript" ]
2
Markdown
boancamaria/boancamaria.github.io
a81dad49ef07d435d568c852f5268613c2ca17a4
f31b71dfdb8df201bd8dc8c32dffd138b5610c05
refs/heads/master
<file_sep>import unittest from homepage import HomePage from selenium import webdriver from webDemoPage import WebDemoPage class TestDemoApplications(unittest.TestCase): def setUp(self): self.driver = webdriver.Firefox() self.driver.maximize_window() def tearDown(self): self.driver.quit() def scenario_GAL(self, algorithm, dataset): homePage = HomePage(self.driver) webDemo = homePage.selectDemoApp('GAL') webDemo.setAlgorithm(algorithm) webDemo.setDataSet(dataset) webDemo.processData() def scenario_GALC(self, dataset): homePage = HomePage(self.driver) webDemo = homePage.selectDemoApp('GALC') webDemo.setDataSet(dataset) webDemo.processData() def checkResultsLink(self): webDemo = WebDemoPage(self.driver) resultsUrl = webDemo.getResultsUrl() webDemo.navigate(resultsUrl) webDemo.waitUntilDataIsProcessed() def checkResults(self, algType, expectedSummary, expectedLabelsCount, expectedWorkersCount): webDemo = WebDemoPage(self.driver) if algType == 'GAL': self.assertDictEqual(expectedSummary, webDemo.getResults_Summary_GAL()) self.assertEqual(expectedLabelsCount, webDemo.getResults_Labels_GAL()) self.assertEqual(expectedWorkersCount, webDemo.getResults_Workers_GAL()) else: self.assertDictEqual(expectedSummary, webDemo.getResults_Summary_GALC()) self.assertEqual(expectedLabelsCount, webDemo.getResults_Labels_GALC()) self.assertEqual(expectedWorkersCount, webDemo.getResults_Workers_GALC()) def test_GALDemo_EM_SmallDataset(self): self.scenario_GAL('EM Algorithm', 'Small: 25 assigned labels, 1 gold') expectedSummary = {'no_workers':u'5', 'no_objects':u'5','assigned_labels':u'25', 'gold_labels':u'1', 'est_data_quality':u'100%', 'est_workers_quality':u'73%', 'eval_data_quality':u'100%', 'eval_workers_quality':u'73%'} self.checkResults('GAL', expectedSummary, 5, 5) self.checkResultsLink() self.checkResults('GAL', expectedSummary, 5, 5) def test_GALDemo_MV_SmallDataset(self): self.scenario_GAL('Majority Vote', 'Small: 25 assigned labels, 1 gold') expectedSummary = {'no_workers':u'5', 'no_objects':u'5','assigned_labels':u'25', 'gold_labels':u'1', 'est_data_quality':u'52%', 'est_workers_quality':u'25%', 'eval_data_quality':u'60%', 'eval_workers_quality':u'73%'} self.checkResults('GAL', expectedSummary, 5, 5) self.checkResultsLink() self.checkResults('GAL', expectedSummary, 5, 5) def test_GALDemo_EM_LargeDataSet(self): self.scenario_GAL('EM Algorithm', 'Large: 5000 assigned labels, 30 golds') expectedSummary = {'no_workers':u'83', 'no_objects':u'1000','assigned_labels':u'5000', 'gold_labels':u'30', 'est_data_quality':u'79%', 'est_workers_quality':u'39%', 'eval_data_quality':u'48%', 'eval_workers_quality':u'42%'} self.checkResults('GAL', expectedSummary, 200, 83) self.checkResultsLink() self.checkResults('GAL', expectedSummary, 200, 83) def test_GALDemo_MV_LargeDataSet(self): self.scenario_GAL('Majority Vote', 'Large: 5000 assigned labels, 30 golds') expectedSummary = {'no_workers':u'83', 'no_objects':u'1000','assigned_labels':u'5000', 'gold_labels':u'30', 'est_data_quality':u'73%', 'est_workers_quality':u'44%', 'eval_data_quality':u'41%', 'eval_workers_quality':u'42%'} self.checkResults('GAL', expectedSummary, 200, 83) self.checkResultsLink() self.checkResults('GAL', expectedSummary, 200, 83) def test_GALCDemo(self): self.scenario_GALC('200 assigned labels, 10 golds') expectedSummary = {'no_workers':u'2', 'no_objects':u'100','assigned_labels':u'200', 'gold_labels':u'10'} self.checkResults('GALC', expectedSummary, 100, 2) self.checkResultsLink() self.checkResults('GALC', expectedSummary, 100, 2)<file_sep>Troia-UI-Tests ============== Selenium GUI test for Troia Web <file_sep>from page import Page from webDemoPage import WebDemoPage from settings import Settings class HomePage(Page): def __init__(self, driver): Page.__init__(self, driver) Page.navigate(self, Settings.url) def selectDemoApp(self, demoApp): if demoApp == 'GAL': self.clickButton('id', 'drop3') self.findElement('xpath', "id('menu3')/li[1]/a").click() else: self.clickButton('id', 'drop3') self.findElement('xpath', "id('menu3')/li[2]/a").click() return WebDemoPage(self.driver) if __name__ == '__main__': homePage = HomePage() homePage.goToGALDemo()<file_sep>selenium xvfbwrapper unittest-xml-reporting <file_sep>class Settings(): webElementTimeOut = 60 url = 'http://devel.project-troia.com'<file_sep>import unittest import xmlrunner import sys from xvfbwrapper import Xvfb import settings vdisplay = Xvfb(width=1280, height=720) vdisplay.start() if len(sys.argv) > 1: settings.Settings.url = sys.argv[1] sys.argv = sys.argv[:1] print "Started Xvfb" unittest.main(testRunner=xmlrunner.XMLTestRunner(output='selenium-demos-reports', verbosity=2), module="testDemoApp") vdisplay.stop() print "Ended Xvfb" <file_sep>import selenium.webdriver.support.ui as ui from selenium import webdriver from settings import Settings import random import string import time class Page(object): def __init__(self, driver): self.driver = driver def navigate(self, url): self.driver.get(url) def getUrl(self): return self.driver.current_url def findElements(self, idMode, idValue): try: webElements = None if (idMode == 'id'): webElements = self.driver.find_elements_by_id(idValue) elif (idMode == 'xpath'): webElements = self.driver.find_elements_by_xpath(idValue) elif (idMode == 'name'): webElements = self.driver.find_elements_by_name(idValue) elif (idMode == 'linkText'): webElements = self.driver.find_elements_by_link_text(idValue) elif (idMode == 'partialLinkText'): webElements = self.driver.find_elements_by_partial_link_text(idValue) elif (idMode == 'tagName'): webElements = self.driver.find_elements_by_tag_name(idValue) elif (idMode == 'className'): webElements = self.driver.find_elements_by_class_name(idValue) elif (idMode == 'cssSelector'): webElements = self.driver.find_elements_by_css_selector(idValue) else: webElements = None hover = webdriver.ActionChains(self.driver).move_to_element(webElements[0]) hover.perform() return webElements except: print 'Cannot find elements %s %s' %(idMode, idValue) def findElement(self, idMode, idValue): webElement = None try: if (idMode == 'id'): webElement = self.driver.find_element_by_id(idValue) elif (idMode == 'xpath'): webElement = self.driver.find_element_by_xpath(idValue) elif (idMode == 'name'): webElement = self.driver.find_element_by_name(idValue) elif (idMode == 'linkText'): webElement = self.driver.find_element_by_link_text(idValue) elif (idMode == 'partialLinkText'): webElement = self.driver.find_element_by_partial_link_text(idValue) elif (idMode == 'tagName'): webElement = self.driver.find_element_by_tag_name(idValue) elif (idMode == 'className'): webElement = self.driver.find_element_by_class_name(idValue) elif (idMode == 'cssSelector'): webElement = self.driver.find_element_by_css_selector(idValue) else: webElement = None hover = webdriver.ActionChains(self.driver).move_to_element(webElement) hover.perform() except: print 'Cannot find element %s %s' %(idMode, idValue) return webElement def setText(self, idMode, idValue, text): elem = self.findElement(idMode, idValue) elem.send_keys(text) def selectListValue(self, idMode, idValue, value): elem = self.findElement(idMode, idValue) for option in elem.find_elements_by_tag_name('option'): if option.text.upper() == value.upper(): option.click() def clickButton(self, idMode, idValue): element = self.findElement(idMode, idValue) element.click() def waitUntilElementIsPresent(self, idMode, idValue): wait = ui.WebDriverWait(self.driver, Settings.webElementTimeOut) if (idMode == 'id'): wait.until(lambda driver: self.driver.find_element_by_id(idValue)) elif (idMode == 'tagName'): wait.until(lambda driver: self.driver.find_element_by_tag_name(idValue)) elif (idMode == 'className'): wait.until(lambda driver: self.driver.find_element_by_class_name(idValue)) <file_sep>from page import Page import time class WebDemoPage(Page): def __init__(self, driver): Page.__init__(self, driver) self.waitUntilElementIsPresent('id', 'id_data_choose') def setAlgorithm(self, algorithm): self.selectListValue('id', 'id_algorithm_choose', algorithm) def setDataSet(self, dataSet): self.selectListValue('id', 'id_data_choose', dataSet) time.sleep(5) def processData(self): self.clickButton('id', 'send_data') self.waitUntilDataIsProcessed() def waitUntilDataIsProcessed(self): wait = 1 while (wait == 1): self.waitUntilElementIsPresent('xpath', "id('result')") spinningImg = self.findElement('xpath', "id('result')/img") if spinningImg != None: imgStyleAttribute = spinningImg.get_attribute('style') if imgStyleAttribute == 'display: none;': wait = 0 def getResults_Summary_GAL(self): res = {} table = self.findElement('xpath', "id('summary_list')/tbody") res['no_workers'] = table.find_element_by_xpath('tr[1]/td[2]').text res['no_objects'] = table.find_element_by_xpath('tr[2]/td[2]').text res['assigned_labels'] = table.find_element_by_xpath('tr[3]/td[2]').text res['gold_labels'] = table.find_element_by_xpath('tr[4]/td[2]').text res['est_data_quality'] = table.find_element_by_xpath('tr[5]/td[2]/a').text res['est_workers_quality'] = table.find_element_by_xpath('tr[6]/td[2]/a').text res['eval_data_quality'] = table.find_element_by_xpath('tr[7]/td[2]').text res['eval_workers_quality'] = table.find_element_by_xpath('tr[8]/td[2]').text return res def getResults_Labels_GAL(self): self.clickButton('xpath', "id('resultsTab')/li[2]/a") return len(self.findElements('xpath', "id('objects_table')/table/tbody/tr")) def getResults_Workers_GAL(self): self.clickButton('xpath', "id('resultsTab')/li[3]/a") return len(self.findElements('xpath', "id('workers_table')/table/tbody/tr")) def getResults_Summary_GALC(self): self.waitUntilDataIsProcessed() res = {} table = self.findElement('xpath', "id('summary_list')/tbody") res['no_workers'] = table.find_element_by_xpath('tr[1]/td[2]').text res['no_objects'] = table.find_element_by_xpath('tr[2]/td[2]').text res['assigned_labels'] = table.find_element_by_xpath('tr[3]/td[2]').text res['gold_labels'] = table.find_element_by_xpath('tr[4]/td[2]').text return res def getResults_Labels_GALC(self): self.clickButton('xpath', "id('resultsTab')/li[2]/a") return len(self.findElements('xpath', "id('objects_table')/tbody/tr")) def getResults_Workers_GALC(self): self.clickButton('xpath', "id('resultsTab')/li[3]/a") return len(self.findElements('xpath', "id('workers_table')/tbody/tr")) def getResultsUrl(self): self.clickButton('xpath', "id('resultsTab')/li[1]/a") url = self.findElement('xpath', "id('url')/pre").text return url def downloadResults(self): self.clickButton('id', 'download_zip_btn')
b370a672c31b87e3fc517f483fb06ea07186d5ad
[ "Markdown", "Python", "Text" ]
8
Python
dmitrea/Troia-UI-Tests
aafbf11d29c6e7a8cbbdbc4f8a454c69169bf476
2b904438fe160463f3c98e4d960e6c3b82e0ad64
refs/heads/master
<file_sep>ph2.5 ===== random pixiv hot pictures on your chrome new tab page. ###TODO 1. 目前只有top50的图片(默认拿到页面里只有50个),接下来可以加入更多,通过请求ajax接口。`http://www.pixiv.net/ranking.php?mode=daily&content=illust&p=1&format=json` 2. 可以加入国际排行榜的图片 3. 可以优先展现新上榜的图片 4. 设计更好的界面 5. pin住某一张图片作为当天的背景<file_sep>function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } var init = function(){ var ls = localStorage; var pixivHotPicUrl = "http://www.pixiv.net/ranking.php?mode=daily&content=illust" var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; if (dd < 10) { dd = '0' + dd; } if (mm<10) { mm = '0' + mm; } today = mm + '/' + dd; function getRandomImageId() { var imageIdList = ls[today].split(','); var index = getRandomInt(0, imageIdList.length); return imageIdList[index]; } function lazyReloadRandomImage() { var pixivEmbedIFrameSrcA = 'http://embed.pixiv.net/embed_mk2.php?id='; var pixivEmbedIFrameSrcZ = '&size=large&border=on&done=null'; var pixivEmbedIFrameSrc = pixivEmbedIFrameSrcA + getRandomImageId() + pixivEmbedIFrameSrcZ; $("div.pixiv-embed").find("> iframe").attr('src', pixivEmbedIFrameSrc); setTimeout(lazyReloadRandomImage, 60000); } function renderRandomImage() { var pixivEmbedJsTmplA = '<script src="js/embed.js" data-id="'; var pixivEmbedJsTmplZ = '" data-size="large" data-border="on" charset="utf-8"></script>'; var imageId = getRandomImageId(); var embedJSLink = pixivEmbedJsTmplA + imageId + pixivEmbedJsTmplZ; $("#gallery").html(embedJSLink); } if (ls[today] === undefined) { ls.clear(); $.get(pixivHotPicUrl, function(data){ var $pixivHotPageContent = $(data); var rankingImageItems = []; $pixivHotPageContent.find("section.ranking-item").each(function(){ rankingImageItems.push($(this).attr('data-id')); }); ls[today] = rankingImageItems; if (ls[today].length) { renderRandomImage(); setTimeout(lazyReloadRandomImage, 60000); } }); } else { renderRandomImage(); setTimeout(lazyReloadRandomImage, 60000); } } addEventListener('DOMContentLoaded', init); $(document).ready(function(){ $("#download-original").on("click", function(){ var imageId = $(".pixiv-embed").attr('data-id'); if (!imageId) { return; } var imagePageUrl = 'http://www.pixiv.net/member_illust.php?mode=medium&illust_id=' + imageId; $.get(imagePageUrl, function(data){ var originalElem = $(data).find('img.original-image'); if (!originalElem) { alert("原始图片未发现"); return; } var originalImageUrl = originalElem.attr("data-src"); window.location = originalImageUrl; }) return false; }); });
3c6f6b9570da71a2352d4402358d70b0e5cc3131
[ "Markdown", "JavaScript" ]
2
Markdown
de1o/ph2.5
53feeb5a9c5acb9abd3e6ecd0606c8181d1be745
30be9b5759e1d82861629e401c78b9077a304b5f
refs/heads/main
<file_sep>// // GameView.swift // TicTacToeSwiftUI // // Created by <NAME> on 5/20/21. // import SwiftUI struct GameView: View { @StateObject private var viewModel = GameViewModel() var body: some View { //geometry UI for dynamic screen sizes GeometryReader { geometry in VStack { Spacer() LazyVGrid(columns: viewModel.columns) { ForEach(0..<9) { i in ZStack { //circle first GameCircleView(proxy: geometry) //then image PlayerIndicator(systemmImageName: viewModel.moves[i]?.indicator ?? "") }.onTapGesture { viewModel.processPlayerMove(for: i) } } } Spacer() } .disabled(viewModel.isGameboardDisabled) .padding() .alert(item: $viewModel.alertItem, content: { alertItem in Alert(title: alertItem.title, message: alertItem.message, dismissButton: .default(alertItem.buttonTitle, action: { viewModel.resetGameBoard() })) }) } } } enum Player { case human, computer } struct Move { let player: Player let boardIndex: Int var indicator: String { return player == .human ? "xmark" : "circle" } } struct ContentView_Previews: PreviewProvider { static var previews: some View { GameView() } } struct GameCircleView: View { var proxy: GeometryProxy var body: some View { Circle() .foregroundColor(.red).opacity(0.8) .frame(width: proxy.size.width/3 - 15, height: proxy.size.width/3 - 15) } } struct PlayerIndicator: View { var systemmImageName: String var body: some View { Image(systemName: systemmImageName) .resizable() .frame(width: 40, height: 40, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/) } } <file_sep>// // Alerts.swift // TicTacToeSwiftUI // // Created by <NAME> on 5/23/21. // import SwiftUI struct AlertItem: Identifiable { let id = UUID() var title: Text var message: Text var buttonTitle: Text } struct AlertContext { static let humanWin = AlertItem(title: Text("You Win!"), message: Text("You are so smart. You beat the AI."), buttonTitle: Text("YASS")) static let computerWin = AlertItem(title: Text("You Lost :("), message: Text("Yoou programmed a super AI"), buttonTitle: Text("Rematch")) static let draw = AlertItem(title: Text("Draw"), message: Text("Tough battle"), buttonTitle: Text("Try Again")) } <file_sep>// // TicTacToeSwiftUIApp.swift // TicTacToeSwiftUI // // Created by <NAME> on 5/20/21. // import SwiftUI @main struct TicTacToeSwiftUIApp: App { var body: some Scene { WindowGroup { GameView() } } } <file_sep>// // GameViewModel.swift // TicTacToeSwiftUI // // Created by <NAME> on 5/23/21. // import SwiftUI final class GameViewModel: ObservableObject { let columns: [GridItem] = [GridItem(.flexible()), GridItem(.flexible()), GridItem(.flexible())] //@State private var isHumansTurn = true isHumanTurn.toggle() @Published var moves: [Move?] = Array(repeating: nil, count: 9) @Published var isGameboardDisabled = false @Published var alertItem: AlertItem? func isSquareOccupied(in moves: [Move?], forIndex index: Int) -> Bool { return moves.contains(where: { $0?.boardIndex == index }) } func determineComputerMovePosition(in moves: [Move?]) -> Int { //If AI can win, then win let winPatterns: Set<Set<Int>> = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [0,1,2], [2,5,8], [0,4,8], [2,4,6]] let computerMoves = moves.compactMap{ $0 }.filter{ $0.player == .computer} let computerPositions = Set(computerMoves.map { $0.boardIndex }) for pattern in winPatterns { let winPositions = pattern.subtracting(computerPositions) if winPositions.count == 1 { let isAvaliable = isSquareOccupied(in: moves, forIndex: winPositions.first!) if isAvaliable { return winPositions.first! } } } //If AI can't win, then block let humanMoves = moves.compactMap{ $0 }.filter{ $0.player == .human} let humanPositions = Set(humanMoves.map { $0.boardIndex }) for pattern in winPatterns { let winPositions = pattern.subtracting(humanPositions) if winPositions.count == 1 { let isAvaliable = isSquareOccupied(in: moves, forIndex: winPositions.first!) if isAvaliable { return winPositions.first! } } } //If AI cant block the take middle quare let middleSquare = 4 if !isSquareOccupied(in: moves, forIndex: middleSquare) { return middleSquare } //If AI cant take middle position, then take randdom square var movePosition = Int.random(in: 0..<9) while isSquareOccupied(in: moves, forIndex: movePosition) { movePosition = Int.random(in: 0..<9) } return movePosition } func checkForWinCondition(for player: Player, in moves: [Move?]) -> Bool { let winPatterns: Set<Set<Int>> = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [0,1,2], [2,5,8], [0,4,8], [2,4,6]] //parsing array //compactMap to remove nilS & filre by player type let playerMoves = moves.compactMap{ $0 }.filter{ $0.player == player} //map to only get board indexes let playerPositions = Set(playerMoves.map { $0.boardIndex }) for pattern in winPatterns where pattern.isSubset(of: playerPositions) { return true } return false } func checkForDraw(in moves: [Move?]) -> Bool { return moves.compactMap{ $0 }.count == 9 } func resetGameBoard() { //reset move array moves = Array(repeating: nil, count: 9) } func processPlayerMove(for position: Int) { if isSquareOccupied(in: moves, forIndex: position) { return } moves[position] = Move(player: .human, boardIndex: position) //check for win or draw if checkForWinCondition(for: .human, in: moves) { alertItem = AlertContext.humanWin return } //check for draw if checkForDraw(in: moves){ alertItem = AlertContext.draw return } isGameboardDisabled = true //computer move DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [self] in let computerPosition = determineComputerMovePosition(in: moves) moves[computerPosition] = Move(player: .computer, boardIndex: computerPosition) isGameboardDisabled = false if checkForWinCondition(for: .computer, in: moves) { alertItem = AlertContext.computerWin } if checkForDraw(in: moves){ alertItem = AlertContext.draw return } } } }
3c7dd2b864d4813b979a78ee5399f124cfdde85a
[ "Swift" ]
4
Swift
olowoshiai/MVVMTicAIGame
a658c8c6344eabd72f6655a1a34591cefe7074c4
10814efd7f59978c93a41c0551bb9884bb1d1408
refs/heads/master
<file_sep>var instance_skel = require('../../instance_skel'); var debug; var log; var relay_max = '8'; function pad(num) { var s = "00" + num; return s.substr(s.length-2); } function instance(system, id, config) { var self = this; // super-constructor instance_skel.apply(this, arguments); self.actions(); // export actions self.init_presets(); // init presets return self; } instance.prototype.updateConfig = function(config) { var self = this; self.config = config; relay_max = self.config.relay_nr; self.init_presets(); self.actions(); } instance.prototype.init = function() { var self = this; self.init_presets(); self.status(self.STATE_OK); debug = self.debug; log = self.log; } instance.prototype.CHOICES_RELAY_CH = [ { id: '4', label: '4 CH'}, { id: '8', label: '8 CH'}, { id: '16', label: '16 CH'}, ]; // Return config fields for web config instance.prototype.config_fields = function () { var self = this; return [ { type: 'textinput', id: 'host', label: 'Target IP', width: 5, regex: self.REGEX_IP }, { type: 'textinput', id: 'port', label: 'HTTP Port (Default: 30000)', width: 4, default: 30000, regex: self.REGEX_PORT }, { type: 'dropdown', id: 'relay_nr', label: 'Relay Channels', width: 3, default: '8', choices: self.CHOICES_RELAY_CH } ] } // When module gets deleted instance.prototype.destroy = function() { var self = this; debug("destroy"); } instance.prototype.CHOICES_RELAY_4_ON = [ { id: '1', label: 'Relay 1 ON'}, { id: '3', label: 'Relay 2 ON'}, { id: '5', label: 'Relay 3 ON'}, { id: '7', label: 'Relay 4 ON'}, ]; instance.prototype.CHOICES_RELAY_4_OFF = [ { id: '0', label: 'Relay 1 OFF'}, { id: '2', label: 'Relay 2 OFF'}, { id: '4', label: 'Relay 3 OFF'}, { id: '6', label: 'Relay 4 OFF'}, ]; instance.prototype.CHOICES_RELAY_8_ON = [ { id: '1', label: 'Relay 1 ON'}, { id: '3', label: 'Relay 2 ON'}, { id: '5', label: 'Relay 3 ON'}, { id: '7', label: 'Relay 4 ON'}, { id: '9', label: 'Relay 5 ON'}, { id: '11', label: 'Relay 6 ON'}, { id: '13', label: 'Relay 7 ON'}, { id: '15', label: 'Relay 8 ON'}, ]; instance.prototype.CHOICES_RELAY_8_OFF = [ { id: '0', label: 'Relay 1 OFF'}, { id: '2', label: 'Relay 2 OFF'}, { id: '4', label: 'Relay 3 OFF'}, { id: '6', label: 'Relay 4 OFF'}, { id: '8', label: 'Relay 5 OFF'}, { id: '10', label: 'Relay 6 OFF'}, { id: '12', label: 'Relay 7 OFF'}, { id: '14', label: 'Relay 8 OFF'}, ]; instance.prototype.CHOICES_RELAY_16_ON = [ { id: '1', label: 'Relay 1 ON'}, { id: '3', label: 'Relay 2 ON'}, { id: '5', label: 'Relay 3 ON'}, { id: '7', label: 'Relay 4 ON'}, { id: '9', label: 'Relay 5 ON'}, { id: '11', label: 'Relay 6 ON'}, { id: '13', label: 'Relay 7 ON'}, { id: '15', label: 'Relay 8 ON'}, { id: '17', label: 'Relay 9 ON'}, { id: '19', label: 'Relay 10 ON'}, { id: '21', label: 'Relay 11 ON'}, { id: '23', label: 'Relay 12 ON'}, { id: '25', label: 'Relay 13 ON'}, { id: '27', label: 'Relay 14 ON'}, { id: '29', label: 'Relay 15 ON'}, { id: '31', label: 'Relay 16 ON'}, ]; instance.prototype.CHOICES_RELAY_16_OFF = [ { id: '0', label: 'Relay 1 OFF'}, { id: '2', label: 'Relay 2 OFF'}, { id: '4', label: 'Relay 3 OFF'}, { id: '6', label: 'Relay 4 OFF'}, { id: '8', label: 'Relay 5 OFF'}, { id: '10', label: 'Relay 6 OFF'}, { id: '12', label: 'Relay 7 OFF'}, { id: '14', label: 'Relay 8 OFF'}, { id: '16', label: 'Relay 9 OFF'}, { id: '18', label: 'Relay 10 OFF'}, { id: '20', label: 'Relay 11 OFF'}, { id: '22', label: 'Relay 12 OFF'}, { id: '24', label: 'Relay 13 OFF'}, { id: '26', label: 'Relay 14 OFF'}, { id: '28', label: 'Relay 15 OFF'}, { id: '30', label: 'Relay 16 OFF'}, ]; instance.prototype.init_presets = function () { var self = this; var presets = []; var pstSize = '18'; relay_max = self.config.relay_nr; switch (relay_max) { case '4': for (var input in self.CHOICES_RELAY_4_ON) { presets.push({ category: 'Relay ON', label: self.CHOICES_RELAY_4_ON[input].label, bank: { style: 'text', text: self.CHOICES_RELAY_4_ON[input].label, size: pstSize, color: '16777215', bgcolor: self.rgb(0,204,0) }, actions: [{ action: 'relay_on', options: { action: self.CHOICES_RELAY_4_ON[input].id } }] }); } for (var input in self.CHOICES_RELAY_4_OFF) { presets.push({ category: 'Relay OFF', label: self.CHOICES_RELAY_4_OFF[input].label, bank: { style: 'text', text: self.CHOICES_RELAY_4_OFF[input].label, size: pstSize, color: '16777215', bgcolor: self.rgb(255,0,0) }, actions: [{ action: 'relay_off', options: { action: self.CHOICES_RELAY_4_OFF[input].id } }] }); } break; case '8': for (var input in self.CHOICES_RELAY_8_ON) { presets.push({ category: 'Relay ON', label: self.CHOICES_RELAY_8_ON[input].label, bank: { style: 'text', text: self.CHOICES_RELAY_8_ON[input].label, size: pstSize, color: '16777215', bgcolor: self.rgb(0,204,0) }, actions: [{ action: 'relay_on', options: { action: self.CHOICES_RELAY_8_ON[input].id } }] }); } for (var input in self.CHOICES_RELAY_8_OFF) { presets.push({ category: 'Relay OFF', label: self.CHOICES_RELAY_8_OFF[input].label, bank: { style: 'text', text: self.CHOICES_RELAY_8_OFF[input].label, size: pstSize, color: '16777215', bgcolor: self.rgb(255,0,0) }, actions: [{ action: 'relay_off', options: { action: self.CHOICES_RELAY_8_OFF[input].id } }] }); } break; case '16': for (var input in self.CHOICES_RELAY_16_ON) { presets.push({ category: 'Relay ON', label: self.CHOICES_RELAY_16_ON[input].label, bank: { style: 'text', text: self.CHOICES_RELAY_16_ON[input].label, size: pstSize, color: '16777215', bgcolor: self.rgb(0,204,0) }, actions: [{ action: 'relay_on', options: { action: self.CHOICES_RELAY_16_ON[input].id } }] }); } for (var input in self.CHOICES_RELAY_16_OFF) { presets.push({ category: 'Relay OFF', label: self.CHOICES_RELAY_16_OFF[input].label, bank: { style: 'text', text: self.CHOICES_RELAY_16_OFF[input].label, size: pstSize, color: '16777215', bgcolor: self.rgb(255,0,0) }, actions: [{ action: 'relay_off', options: { action: self.CHOICES_RELAY_16_OFF[input].id } }] }); } break; } /* */ self.setPresetDefinitions(presets); } instance.prototype.actions = function(system) { var self = this; var x = self.CHOICES_RELAY_8_ON; var y = self.CHOICES_RELAY_8_OFF; relay_max = self.config.relay_nr; switch (relay_max) { case '4': x = self.CHOICES_RELAY_4_ON; y = self.CHOICES_RELAY_4_OFF; break; case '8': x = self.CHOICES_RELAY_8_ON; y = self.CHOICES_RELAY_8_OFF; break; case '16': x = self.CHOICES_RELAY_16_ON; y = self.CHOICES_RELAY_16_OFF; break; } self.setActions({ 'relay_on': { label: 'Turn Relay ON', options: [ { type: 'dropdown', id: 'action', label: 'Relay', default: '1', choices: x } ] }, 'relay_off': { label: 'Turn Relay OFF', options: [ { type: 'dropdown', id: 'action', label: 'Relay:', default: '0', choices: y } ] } }); } instance.prototype.action = function(action) { var self = this; var cmd; switch(action.action) { case 'relay_on': cmd = pad(action.options.action); break; case 'relay_off': cmd = pad(action.options.action); break; } if (cmd !== undefined) { var message = 'http://' + self.config.host + '/' + self.config.port + '/' + cmd; debug('sending ',message,"to",self.config.host); console.log('HTTP Send: ' + message); self.system.emit('rest_get', message, function (err, result) { if (err !== null) { self.log('error', 'HTTP GET Request failed (' + result.error.code + ')'); self.status(self.STATUS_ERROR, result.error.code); } else { self.status(self.STATUS_OK); } }); } } instance_skel.extendedBy(instance); exports = module.exports = instance;<file_sep># companion-module-sain-smart-relay See HELP.md and LICENSE **V0.0.1** * Initial Upload * Added the ability to turn relays on and off * Added presets for 4ch, 8ch and 16ch units **V1.0.0** * Ready for release **To Do** <file_sep>## Sain Smart Relay This module will connect to a Sain Smart Relay. Example of an 8 channel unit: https://www.sainsmart.com/collections/internet-of-things/products/rj45-tcp-ip-remote-control-board-with-integrated-8-ch-relay **Available commands for Sain Smart Relay** * Turn Relay ON * Turn Relay OFF **Not Implementet** * Get Relay Status (Unreliable)
7af9fa136b31429474d6d192f256d4f2b0200ef3
[ "JavaScript", "Markdown" ]
3
JavaScript
bitfocus/companion-module-sain-smart-relay
9b7274d9bb0f9b7d8dbca91e5d046d5d676daf6d
23714d5556df6a39682f5e5b0ba0c8aec487107b
refs/heads/master
<file_sep>var randomCompany = ["Sub Prime Academy", "The Nerdlierery", "Code 402", "Target Practice", "Software For Better"]; var staff = {}; var maxFrontEndPoints = 60; var maxClientPoints = 60; var maxServerPoints = 60; var clientLogicFilled = false; var frontEndFilled = false; var serverLogicFilled = false; var positionFilled = 0; var frontEndScrum = 0; var clientsideScrum = 0; var serverScrum = 0; var sprintsArray = []; var totalSprints = 0; $(document).ready(function(){ $('.container').prepend('<button class="generate btn-info">Generate Project</button>'); $('body').on('click', '.generate' , createProject); $('.projectContainer').on('click', 'button', assignStaff); }); function createProject(){ sprintsArray = []; positionFilled = 0; clientLogicFilled = false; frontEndFilled = false; serverLogicFilled = false; frontEndScrum = randomFrontEndPoints(); clientsideScrum = randomClientPoints(); serverScrum = randomServerPoints(); $('.projectContainer').empty(); //var company = randomCompanyGenerator(); //var frontEndPoints = randomFrontEndPoints(); //var clientPoints = randomClientPoints(); //var serverPoints = randomServerPoints(); //$('.container').append('<div class="projectContainer"></div>'); $('.projectContainer').append('<h2>' + randomCompanyGenerator() + '</h2>'); $('.projectContainer').append('<ul><li>Front-End Scrum Points: ' + frontEndScrum + '</li><li>Clientside Scrum Points: ' + clientsideScrum +'</li><li>Serverside Scrum Points: '+ serverScrum +'</li></ul>'); $('.projectContainer').append('<button class=" btn-danger assignStaff">Assign Staff</button>'); } var randomCompanyGenerator = function (){ return randomCompany[randomNumber(0, randomCompany.length -1)]; }; function randomFrontEndPoints(){ return randomNumber(10, maxFrontEndPoints); } function randomClientPoints(){ return randomNumber(10, maxClientPoints); } function randomServerPoints(){ return randomNumber(10, maxServerPoints); } function randomNumber(min, max){ return Math.floor(Math.random() * (1 + max - min) + min); } function assignStaff(){ $.ajax({ type: 'GET', url: '/staff', success: function(data){ staff.name = data.name; staff.skill = data.skill; staff.sprint = data.sprint; matchSkills(staff); } }); // for (var i = 0; i < sprintsArray.length; i++) { // totalSprints += sprintsArray[i]; // } //$('.projectContainer').append('<p>Weeks until completion: ' + (totalSprints / sprintsArray.length) + '</p>'); // console.log(totalSprints); // console.log(sprintsArray); } function matchSkills(staff){ if (staff.skill == 'Clientside Logic' && clientLogicFilled === false){ $('.projectContainer').append('<div class="clientside-container"></div>'); $('.clientside-container').append('<h2>' + staff.name + '</h2>'); $('.clientside-container').append('<p>Skill: ' + staff.skill + '</p>'); $('.clientside-container').append('<p>Average Sprints: ' + staff.sprint + '</p>'); $('.clientside-container').append('<p class="clientside-completion">Sprints till completion: ' + Math.ceil(clientsideScrum / staff.sprint) + '</p>'); $('.clientside-completion').data('sprints', Math.ceil(clientsideScrum / staff.sprint)); console.log($('.clientside-completion').data()); sprintsArray.push($('.clientside-completion').data('sprints')); clientLogicFilled = true; console.log(staff.skill , "filled!"); positionFilled++; } if (staff.skill == 'Front End' && frontEndFilled === false){ $('.projectContainer').append('<div class="frontend-container"></div>'); $('.frontend-container').append('<h2>' + staff.name + '</h2>'); $('.frontend-container').append('<p>Skill: ' + staff.skill + '</p>'); $('.frontend-container').append('<p>Average Sprints: ' + staff.sprint + '</p>'); $('.frontend-container').append('<p class="frontend-completion">Sprints till completion: ' + Math.ceil(frontEndScrum / staff.sprint) + '</p>'); $('.frontend-completion').data('sprints', Math.ceil(frontEndScrum / staff.sprint)); sprintsArray.push($('.frontend-completion').data('sprints')); // $('.frontend-container').append('<p>''</p>'); frontEndFilled = true; console.log(staff.skill , "filled!"); positionFilled++; } if (staff.skill == 'Serverside Logic' && serverLogicFilled === false){ $('.projectContainer').append('<div class="serverside-container"></div>'); $('.serverside-container').append('<h2>' + staff.name + '</h2>'); $('.serverside-container').append('<p>Skill: ' + staff.skill + '</p>'); $('.serverside-container').append('<p>Average Sprints: ' + staff.sprint + '</p>'); $('.serverside-container').append('<p class="serverside-completion">Sprints till completion: ' + Math.ceil(serverScrum / staff.sprint) + '</p>'); $('.serverside-completion').data('sprints', Math.ceil(serverScrum / staff.sprint)); sprintsArray.push($('.serverside-completion').data('sprints')); serverLogicFilled = true; console.log(staff.skill , "filled!"); positionFilled++; } if(positionFilled < 3){ staff = {}; assignStaff(); } if(positionFilled == 3){ for (var i = 0; i < sprintsArray.length; i++) { totalSprints += sprintsArray[i]; } $('.projectContainer').children('.assignStaff').after('<p>Weeks until completion: ' + Math.max.apply(null, sprintsArray) + '</p>'); console.log(totalSprints); console.log(sprintsArray); } // console.log("i = " + i); // } } <file_sep>var randomFirstNameArray = ['Enrique','Hank','Biz','Brady',]; var randomLastNameArray = ['Ortega','Andre','Cook', 'The Destroyer','Peterson']; var randomName = function(){ return randomFirstNameArray[randomNumber(0,randomFirstNameArray.length - 1)] + " " + randomLastNameArray[randomNumber(0,randomLastNameArray.length - 1)]; }; function randomNumber(min, max){ return Math.floor(Math.random() * (1 + max - min) + min); } module.exports = randomName;
f7863212956ae9aaa0b31232c3507faae59641b4
[ "JavaScript" ]
2
JavaScript
enriqueortega/project_management_app
bf5842992c594c5cdb76053945e2ebcda3fbf347
1521aede6d6251c5d6282bd18e0f0cec7bf21165
refs/heads/master
<repo_name>onybot/onybot<file_sep>/libs/program.cpp #include "Arduino.h" #include "program.h" #include "command.h" #include "constants.h" Program::Program(){ _programIndex = 0; running = false; _runIndex = 0; } bool Program::addCommand(String str){ Command cmd; cmd.id = str; cmd.info = String(_programIndex + 1, DEC) + RUN_SEPARATOR + str; cmd.empty = false; _commands[_programIndex] = cmd; _programIndex++; if (_programIndex > MAX_COMMANDS){ _programIndex = 0; } return true; } Command Program::run(){ Command cmd; if (running == false){ running = true; _runIndex = 0; _currentCommand = -1; } if (_runIndex <= _programIndex && _programIndex > 0){ cmd = runCommand(_runIndex); } else { running = false; cmd.empty = true; } return cmd; } Command Program::runCommand(int index){ Command cmd; cmd = _commands[index]; if (_currentCommand != index){ // run command first time // do nothing, show command info _currentCommand = index; } else { // not first time. run command actually // run command cmd.run(); // next command; _runIndex ++; } return cmd; } int Program::getNumCommads(){ return _programIndex; } Command Program::getCommand(int index){ return _commands[index]; } void Program::clear(){ _programIndex = 0; } <file_sep>/libs/command.cpp #include "Arduino.h" #include "command.h" #include "constants.h" Command::Command(){ empty = false; } void Command::run(){ delay(COMMAND_TEST_DELAY); }<file_sep>/libs/event.cpp #include "Arduino.h" #include "event.h" #include "constants.h" Event::Event(){ _lastChange=0; _lastButton=BTN_NONE; } int Event::_readButton(){ int analog_key = analogRead(0); if (analog_key < BTN_RIGHT_THRESHOLD){ return BTN_RIGHT; } if (analog_key < BTN_UP_THRESHOLD){ return BTN_UP; } if (analog_key < BTN_DOWN_THRESHOLD){ return BTN_DOWN; } if (analog_key < BTN_LEFT_THRESHOLD){ return BTN_LEFT; } if (analog_key < BTN_SELECT_THRESHOLD){ return BTN_SELECT; } return BTN_NONE; } // read the buttons int Event::getEvent() { int return_btn; int pressed = _readButton(); int now = millis(); return_btn = pressed; if (pressed == _lastButton && pressed != BTN_NONE && now - _lastChange < PRESS_STEP) { return_btn = BTN_NONE; } else { if (pressed != _lastButton){ _lastChange = now; } } _lastButton = pressed; if (return_btn != BTN_NONE) { Serial.println("btn pressed: " + String(pressed, DEC)); } return return_btn; } int Event::getLightIntensity(){ int lightNow = millis(); int timeLasted; timeLasted = lightNow - _lastChange; if (timeLasted > LCD_LIGHT_TIME){ return LCD_LIGHT_MIN; } else { return LCD_LIGHT_MAX; } } <file_sep>/main/main.ino #include "Arduino.h" #include <LiquidCrystal.h> #include "constants.h" #include "utils.h" #include "event.h" #include "fsm.h" ////////////////////////////////// // GLOBALS ////////////////////////////////// // select the pins used on the LCD panel LiquidCrystal lcd(8, 9, 4, 5, 6, 7); Event event; Fsm fsm; void setup() { //init serial monitor Serial.begin(9600); Serial.println("Setup fun"); //init lcd lcd.begin(LCD_CHARS, LCD_LINES); pinMode(LCD_CTRL_LIGHT_PIN, OUTPUT); analogWrite(LCD_CTRL_LIGHT_PIN, DEFAULT_LCD_LIGHT); //init fsm fsm.init(); lcdPrintLine(lcd, 0, fsm.firstLine); lcdPrintLine(lcd, 1, fsm.secondLine); } void loop() { int light; if(fsm.runEvent(event.getEvent())){ lcdPrintLine(lcd, 0, fsm.firstLine); lcdPrintLine(lcd, 1, fsm.secondLine); } if (fsm.automaticLight == true && LCD_AUTOMATIC_LIGHT == true){ light = event.getLightIntensity(); analogWrite(LCD_CTRL_LIGHT_PIN, light); } delay(LOOP_WAITING); }<file_sep>/libs/fsm.h #include "Arduino.h" #include "program.h" #ifndef fsm_h #define fsm_h #define WELCOME_STATE 0 #define MAIN_STATE 1 #define PROGRAM_STATE 2 #define VIEW_STATE 3 #define DELETE_STATE 4 #define VERSION_STATE 5 #define RUN_STATE 6 #define INITIAL_STATE WELCOME_STATE class Fsm { public: //methods void init(); bool runEvent(int event); //attributes String firstLine; String secondLine; bool automaticLight; private: //Attributes int _currentState; int _menuIndex; int _menuViewIndex; bool _changedLine; int _startState; Program program; bool _wait; //methods void _welcomeState(int event); void _mainState(int event); void _setState(int event); // main void _setMain(); void _runEventMain(int event); void _selectMenu(); // welcome void _setWelcome(); void _runEventWelcome(int event); // program void _setProgram(); void _runEventProgram(int event); // view void _setView(); void _runEventView(int event); // run void _setRun(); void _runEventRun(int event); // delete void _setDelete(); void _runEventDelete(int event); // version void _setVersion(); void _runEventVersion(int event); }; #endif <file_sep>/libs/fsm.cpp #include "Arduino.h" #include "fsm.h" #include "event.h" #include "constants.h" #include "command.h" #include "menu.h" #include "program.h" void Fsm::init(){ _setState(INITIAL_STATE); _wait = false; automaticLight = true; } bool Fsm::runEvent(int event){ bool previous; previous = _currentState; switch (_currentState){ case MAIN_STATE: { _runEventMain(event); break; } case WELCOME_STATE: { _runEventWelcome(event); break; } case PROGRAM_STATE: { _runEventProgram(event); break; } case VIEW_STATE: { _runEventView(event); break; } case DELETE_STATE: { _runEventDelete(event); break; } case VERSION_STATE: { _runEventVersion(event); break; } case RUN_STATE: { _runEventRun(event); break; } } return _changedLine; } void Fsm::_setState(int state){ switch (state) { case WELCOME_STATE: { _setWelcome(); break; } case MAIN_STATE: { _setMain(); break; } } } //////////////////////////////////////////// // WELCOME //////////////////////////////////////////// void Fsm::_runEventWelcome(int event){ int timeCondition; timeCondition = millis() - _startState; _changedLine = true; if(timeCondition > WELCOME_TIME || event != BTN_NONE){ _setMain(); return; } _changedLine = false; } void Fsm::_setWelcome(){ _currentState = WELCOME_STATE; firstLine = WELCOME_STRING_1; secondLine = WELCOME_STRING_2; _changedLine = true; _startState = millis(); } //////////////////////////////////////////// // MAIN //////////////////////////////////////////// void Fsm::_setMain(){ Serial.println("set main menu"); _currentState = MAIN_STATE; firstLine = MENU_STRING_1; _menuIndex = -1; _runEventMain(BTN_NONE); _changedLine = true; } void Fsm::_runEventMain(int event){ Menu menu; int arrayLenght; int i; arrayLenght = (int) sizeof(MAIN_MENU_STRING_2)/sizeof(String); String strArray[arrayLenght]; for(i=0; i<arrayLenght; i++){ strArray[i] = MAIN_MENU_STRING_2[i]; } menu.runEvent(event, _menuIndex, strArray, arrayLenght, true); if (menu.selected == true){ // PROGRAM if (strArray[menu.index] == MAIN_MENU_PROGRAM){ return _setProgram(); // VIEW } if (strArray[menu.index] == MAIN_MENU_VIEW){ return _setView(); // DELETE } if (strArray[menu.index] == MAIN_MENU_DELETE){ return _setDelete(); // RUN } else if (strArray[menu.index] == MAIN_MENU_RUN){ return _setRun(); //VERSION } else if (strArray[menu.index] == MAIN_MENU_VERSION){ return _setVersion(); } } else { if (menu.index >= 0){ _changedLine = true; secondLine = String(menu.index + 1, DEC) + MENU_SEPARATOR + strArray[menu.index]; _menuIndex = menu.index; } else { _changedLine = false; } } } //////////////////////////////////////////// // PROGRAM //////////////////////////////////////////// void Fsm::_setProgram(){ _currentState = PROGRAM_STATE; firstLine = PROGRAM_STRING_1; _menuIndex = -1; _runEventProgram(BTN_NONE); _changedLine = true; } void Fsm::_runEventProgram(int event){ Menu menu; int arrayLenght; int i; if (_wait == true){ _wait = false; delay(PROGRAM_WAIT); _setProgram(); return; } // update strings arrayLenght = (int) sizeof(PROGRAM_MENU_STRING_2)/sizeof(String); String strArray[arrayLenght]; for(i=0; i<arrayLenght; i++){ strArray[i] = PROGRAM_MENU_STRING_2[i]; } _wait = false; // get menu selected menu.runEvent(event, _menuIndex, strArray, arrayLenght, true); if (menu.back == true){ _setMain(); } else if (menu.selected == true){ program.addCommand(strArray[menu.index]); firstLine = PROGRAM_WAIT_STRING_1; secondLine = strArray[menu.index]; _changedLine = true; _wait = true; } else { if (menu.index >= 0){ _changedLine = true; secondLine = strArray[menu.index]; _menuIndex = menu.index; } else { _changedLine = false; } } } //////////////////////////////////////////// // VIEW //////////////////////////////////////////// void Fsm::_setView(){ Serial.println("set view"); _currentState = VIEW_STATE; firstLine = VIEW_STRING_1; _menuViewIndex = -1; _runEventView(BTN_NONE); _changedLine = true; } void Fsm::_runEventView(int event){ //definitions Menu menu; Command cmd; int arrayLenght; int numCommands; int i; numCommands = program.getNumCommads(); if (numCommands == 0){ arrayLenght = 1; } else { arrayLenght = numCommands; } String strArray[arrayLenght]; // create menu string array if (numCommands == 0){ strArray[0] = VIEW_STRING_EMPTY; } else { for(i=0; i<arrayLenght; i++){ cmd = program.getCommand(i); strArray[i] = cmd.id; } } // get menu selected menu.runEvent(event, _menuViewIndex, strArray, arrayLenght, false); if (menu.back == true){ _setMain(); } else if (menu.selected == true){ //delete? } else { if (menu.index >= 0){ _changedLine = true; if (numCommands == 0){ secondLine = strArray[menu.index]; } else { secondLine = String(menu.index + 1, DEC) + MENU_SEPARATOR + strArray[menu.index]; } _menuViewIndex = menu.index; } else { _changedLine = false; } } } //////////////////////////////////////////// // DELETE //////////////////////////////////////////// void Fsm::_setDelete(){ _currentState = DELETE_STATE; firstLine = DELETE_STRING_1; secondLine = DELETE_STRING_2; _changedLine = true; _startState = millis(); program.clear(); } void Fsm::_runEventDelete(int event){ int timeCondition; timeCondition = millis() - _startState; _changedLine = true; if(timeCondition > DELETE_TIME || event != BTN_NONE){ _setMain(); return; } _changedLine = false; } //////////////////////////////////////////// // VERSION //////////////////////////////////////////// void Fsm::_setVersion(){ _currentState = VERSION_STATE; firstLine = VERSION_STRING_1; secondLine = VERSION_STRING_2; _changedLine = true; _startState = millis(); } void Fsm::_runEventVersion(int event){ int timeCondition; timeCondition = millis() - _startState; _changedLine = true; if(timeCondition > VERSION_TIME || event != BTN_NONE){ _setMain(); return; } _changedLine = false; } //////////////////////////////////////////// // RUN //////////////////////////////////////////// void Fsm::_setRun(){ Serial.println("set run"); _currentState = RUN_STATE; firstLine = RUN_STRING_1; secondLine = RUN_STRING_2; _changedLine = true; _startState = millis(); automaticLight = false; } void Fsm::_runEventRun(int event){ Command cmd; String previous; cmd = program.run(); if (cmd.empty == false){ previous = secondLine; if (secondLine != cmd.info){ secondLine = cmd.info; _changedLine = true; } else { _changedLine = false; } } else { automaticLight = true; _setMain(); return; } } <file_sep>/libs/program.h #include "Arduino.h" #include "command.h" #ifndef program_h #define program_h #define MAX_COMMANDS 100 class Program { public: //methods Program(); bool addCommand(String str); Command run(); int getNumCommads(); Command getCommand(int index); void clear(); //Attributes private: //Attributes Command _commands[MAX_COMMANDS]; int _programIndex; int _runIndex; bool running; int _currentCommand; //methods Command runCommand(int index); }; #endif <file_sep>/libs/command.h #include "Arduino.h" #ifndef command_h #define command_h class Command { public: //methods Command(); void run(); //Attributes String id; String info; bool empty; private: //Attributes //methods }; #endif <file_sep>/libs/constants.h #ifndef constants_h #define constants_h #define LOOP_WAITING 500 #define MENU_SEPARATOR " -> " //COMMON #define MAX_ANALOG_WRITE 255 //STRINGS #define WELCOME_TIME 2200 #define WELCOME_STRING_1 "ONYBOT: ROBOTICS" #define WELCOME_STRING_2 "& CONSTRUCTIVISM" #define MENU_STRING_1 "MENU" #define MAIN_MENU_PROGRAM "PROGRAMAR" #define MAIN_MENU_VIEW "VER ORDENES" #define MAIN_MENU_DELETE "BORRAR ORDENES" #define MAIN_MENU_RUN "EJECUTAR" #define MAIN_MENU_VERSION "VERSION" const String MAIN_MENU_STRING_2[] PROGMEM = { MAIN_MENU_PROGRAM, MAIN_MENU_VIEW, MAIN_MENU_RUN, MAIN_MENU_DELETE, MAIN_MENU_VERSION }; #define PROGRAM_WAIT 1000 //time storing command #define PROGRAM_WAIT_STRING_1 "ALMACENANDO..." #define PROGRAM_STRING_1 "SELEC ORDEN" #define PROGRAM_MENU_FORWARD "ADELANTE" #define PROGRAM_MENU_REAR "ATRAS" #define PROGRAM_MENU_LEFT "IZQUIERDA" #define PROGRAM_MENU_RIGHT "DERECHA" const String PROGRAM_MENU_STRING_2[] PROGMEM = { PROGRAM_MENU_FORWARD, PROGRAM_MENU_LEFT, PROGRAM_MENU_RIGHT, PROGRAM_MENU_REAR }; #define VIEW_STRING_1 "ALMACENADO" #define VIEW_STRING_EMPTY "------ " #define DELETE_STRING_1 "BORRANDO" #define DELETE_STRING_2 "ORDENES" #define DELETE_TIME 1500 #define VERSION_STRING_1 "ONYBOT 0.0.1" #define VERSION_STRING_2 "www.onytes.com" #define VERSION_TIME 5000 //time showing version info #define RUN_STRING_1 "EJECUTANDO" #define RUN_STRING_2 "ORDEN" #define RUN_SEPARATOR " - " #define COMMAND_TEST_DELAY 1000 #define COMMAND_FORWARD PROGRAM_MENU_FORWARD #define COMMAND_REAR PROGRAM_MENU_REAR #define COMMAND_LEFT PROGRAM_MENU_LEFT #define COMMAND_RIGHT PROGRAM_MENU_RIGHT //LCD #define LCD_CHARS 16 #define LCD_LINES 2 #define LCD_CTRL_LIGHT_PIN 10 #define LCD_LIGHT_MIN 0 #define LCD_LIGHT_MAX MAX_ANALOG_WRITE #define DEFAULT_LCD_LIGHT LCD_LIGHT_MAX/30 #define LCD_LIGHT_TIME 2000 #define LCD_AUTOMATIC_LIGHT false #endif<file_sep>/libs/event.h #include "Arduino.h" #ifndef event_h #define event_h // define some values used by the panel and buttons #define BTN_NONE -1 #define BTN_RIGHT 0 #define BTN_UP 1 #define BTN_DOWN 2 #define BTN_LEFT 3 #define BTN_SELECT 4 #define BTN_SLEEP 5 #define PRESS_STEP 100//millisecs #define BTN_RIGHT_THRESHOLD 50 #define BTN_UP_THRESHOLD 250 #define BTN_DOWN_THRESHOLD 450 #define BTN_LEFT_THRESHOLD 650 #define BTN_SELECT_THRESHOLD 850 class Event { public: //methods Event(); int getEvent(); int getLightIntensity(); //attributes private: //Methods int _readButton(); //Attributes int _lastChange; int _lastButton; }; #endif<file_sep>/libs/menu.cpp #include "Arduino.h" #include "event.h" #include "menu.h" #include "constants.h" Menu::Menu(){} void Menu::runEvent(int event, int menuIndex, String lineTwoArray[], int arrayLenght, bool looping){ int previous; previous = menuIndex; selected = false; back = false; // first time if (menuIndex == -1){ menuIndex = 0; } else { if (event == BTN_UP){ menuIndex = menuIndex - 1; } else if (event == BTN_DOWN){ menuIndex = menuIndex + 1; } else if (event == BTN_SELECT || event == BTN_RIGHT){ // change state selected = true; index = menuIndex; return; } else if (event == BTN_LEFT){ // change state back = true; index = menuIndex; return; } if (menuIndex < 0 ){ if (looping == true){ menuIndex = arrayLenght - 1; } else { menuIndex = 0; } } if (menuIndex > arrayLenght - 1){ if (looping == true){ menuIndex = 0; } else { menuIndex = arrayLenght - 1; } } menuIndex = menuIndex % arrayLenght; } if (menuIndex != previous){ index = menuIndex; } else { index = -1; } } <file_sep>/libs/menu.h #include "Arduino.h" #include "command.h" #ifndef menu_h #define menu_h #define MAX_COMMANDS 100 class Menu { public: //methods Menu(); void runEvent(int event, int menuIndex, String lineTwoArray[], int arrayLenght, bool looping); //Attributes int index; bool selected; bool back; private: //Attributes //methods }; #endif
4ccac52c4ee905dce32ef95833c3ef9c0da8ab1c
[ "C", "C++" ]
12
C++
onybot/onybot
54ef13b8893cdc76b131f7c86548820ef7e2e22f
fc2f8b9ccc23f4b4fe5d3b7fe63fdc224cb61fff
refs/heads/master
<repo_name>rrm-tech/pdfmake-_using_express<file_sep>/app.js const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); const pdfRoutes = require('./routes/pdfmake') const app = express(); app.use(express.static(path.join(__dirname,'public'))); app.use(bodyParser.urlencoded({extended:false})) app.use('/pdfMake',pdfRoutes) app.use('/',(req,res)=>{ res.sendFile('index.html') }) app.listen(3002,()=>{ console.log('Server is up and run') })<file_sep>/README.md # pdfmake-_using_express pdfmake _using_express git clone --branch 0.1 https://github.com/bpampuch/pdfmake.git <file_sep>/pdf.js // playground requires you to assign document definition to a variable called dd var dd = { content: [ { columns: [ { image: 'sampleImage.jpg', fit: [100, 100] }, { text: 'Scotic Design \n Inspection Report', style: 'header' }, { text: 'Report\n Date', style: 'subheader' } ] }, { style: 'tableExample', table: { widths: [100, '*', 200, '*'], body: [ ['To'], ['fixed-width cells have exactly the specified width', {text: 'nothing interesting here', italics: true, color: 'gray'}, {text: 'nothing interesting here', italics: true, color: 'gray'}, {text: 'nothing interesting here', italics: true, color: 'gray'}] ] } }, ], styles: { header: { fontSize: 18, bold: true }, subheader: { fontSize: 15, bold: true }, quote: { italics: true }, small: { fontSize: 8 } } }
cae5f24c1c668fad3a98d23b00f5abbf96e335f2
[ "JavaScript", "Markdown" ]
3
JavaScript
rrm-tech/pdfmake-_using_express
dea6578e1dcbd17514e186684e332bd679c25e27
120092e33b20b71bb32e816c135bd7b6efa35768
refs/heads/master
<repo_name>Muhammeday99/Maze_Solver<file_sep>/MazeSolver_Using_Dijkstra's_Algorithm/src/MatrixGraph.java import java.util.Iterator; public class MatrixGraph extends AbstractGraph { private double[][] edges; public MatrixGraph(int numV, boolean directed) { super(numV, directed); edges = new double[numV][numV]; for (int i = 0; i < numV; i++) { for (int j = 0; j < numV; j++) { edges[i][j] = Double.POSITIVE_INFINITY; } } } @Override public void insert(Edge edge) { if (edge.getSource()< 0 || edge.getSource() > getNumV()-1 || edge.getDest()< 0 || edge.getDest() > getNumV()-1) { return; } edges[edge.getSource()][edge.getDest()] = edge.getWeight(); if(!isDirected()) { edges[edge.getDest()][edge.getSource()] = edge.getWeight(); } } @Override public boolean isEdge(int source, int dest) { return edges[source][dest] < Double.POSITIVE_INFINITY; } @Override public Edge getEdge(int source, int dest) { if(isEdge(source, dest)) return new Edge(source, dest, edges[source][dest]); return null; } @Override public Iterator<Edge> edgeIterator(int source) { return null; } } <file_sep>/MazeSolver_Using_Dijkstra's_Algorithm/src/AbstractGraph.java import java.util.Scanner; public abstract class AbstractGraph implements Graph { // Data Fields /** The number of vertices */ private int numV; /** Flag to indicate whether this is a directed graph */ private boolean directed; public AbstractGraph(int numV, boolean directed) { this.numV = numV; this.directed = directed; } @Override public int getNumV() { return numV; } @Override public boolean isDirected() { return directed; } public void loadEdgesFromFile(Scanner scan) { // Programming Exercise 1 } /** Factory method to create a graph and load the data from an input file. The first line of the input file should contain the number of vertices. The remaining lines should contain the edge data as described under loadEdgesFromFile. @param scan The Scanner connected to the data file @param isDirected true if this is a directed graph, false otherwise @param type The string "Matrix" if an adjacency matrix is to be created, and the string "List" if an adjacency list is to be created @throws IllegalArgumentException if type is neither "Matrix" nor "List" */ public static Graph createGraph(Scanner scan, boolean isDirected, String type) { int numV = scan.nextInt(); AbstractGraph returnValue; type = type.toLowerCase(); switch (type) { case "matrix": returnValue = new MatrixGraph(numV, isDirected); break; case "list": returnValue = new ListGraph(numV, isDirected); break; default: throw new IllegalArgumentException(); } returnValue.loadEdgesFromFile(scan); return returnValue; } }
b8cc34f7c075d89816fcd4a4d939f721ad4466eb
[ "Java" ]
2
Java
Muhammeday99/Maze_Solver
3da9d0ad750ec793586c89fa3428bf247f388474
e73fad81b1096b73d01ccbb03794d005df4c3080
refs/heads/master
<file_sep># local-library-website Local Library website written in Django. <file_sep># Generated by Django 3.1.5 on 2021-01-19 04:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0001_initial'), ] operations = [ migrations.AlterField( model_name='author', name='date_of_birth', field=models.DateField(blank=True, null=True, verbose_name='Birth Date'), ), migrations.AlterField( model_name='author', name='date_of_death', field=models.DateField(blank=True, null=True, verbose_name='Death Date'), ), migrations.AlterField( model_name='bookinstance', name='status', field=models.CharField( blank=True, choices=[ ('m', 'Maintenance'), ('o', 'On loan'), ('a', 'Available'), ('r', 'Reserved') ], default='d', help_text='Book availability', max_length=1 ), ), migrations.AlterField( model_name='language', name='name', field=models.CharField(help_text="Enter the book's natural language (e.g. English (South Africa), Tswana, Zulu etc.)", max_length=200), ), ] <file_sep># Generated by Django 3.1.5 on 2021-01-24 16:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0002_auto_20210119_0657'), ] operations = [ migrations.AlterField( model_name='author', name='first_name', field=models.CharField(blank=True, max_length=100, null=True), ), migrations.AlterField( model_name='author', name='surname', field=models.CharField(blank=True, max_length=100, null=True), ), migrations.AlterField( model_name='book', name='title', field=models.CharField(help_text="Enter the book's title", max_length=200), ), migrations.AlterField( model_name='bookinstance', name='imprint', field=models.CharField(help_text='This identifies a particular publisher or registrant. May be up to 7 digits.', max_length=7), ), ] <file_sep>asgiref==3.2.10 dj-database-url==0.5.0 Django==3.1.2 gunicorn==20.0.4 psycopg2-binary==2.8.6 pytz==2020.5 sqlparse==0.4.1 whitenoise==5.2.0
494e155ea90951e500285e265885d82da05d4038
[ "Markdown", "Python", "Text" ]
4
Markdown
oflenake/local-library-website
3ed07e53c96dcec8cd5163185c73fd9d67fc948b
a882602f73ae1fc81109de4c90310e0f983465dc
refs/heads/master
<file_sep># Replaces terminal symbols in data with count less than 5 import json # Get Word Counts: countsFile = open('C:\Python2\PA2\cfg_mark.counts', 'r') cList = countsFile.readlines() wordsD = {} # Dictionary for words to be replaced for n in range(len(cList)): if cList[n].split(' ')[1] == 'UNARYRULE': if cList[n].split(' ')[3][:-1] in wordsD: wordsD[cList[n].split(' ')[3][:-1]] = str(int(wordsD[cList[n].split(' ')[3][:-1]]) + int(cList[n].split(' ')[0])) else: wordsD[cList[n].split(' ')[3][:-1]] = cList[n].split(' ')[0] for key in list(wordsD): if int(wordsD[key]) >= 5: del wordsD[key] countsFile.close() # Function that replaces tree values: def extract_list_values(li): for item in li: if len(item) == 3: extract_list_values(item) elif len(item) == 2 and isinstance(item, list): for key in wordsD: if item[1] == key: item[1] = '_RARE_' return li # Replace words in tree treeFile = open('C:\Python2\PA2\parse_train_vert.dat', 'r') new_treeFile = open('C:\Python2\PA2\parse_train_mark.counts.out', 'w') with treeFile as f: for line in f: ptree = json.loads(line) extract_list_values(ptree) new_treeFile.write(json.dumps(ptree)+'\n') treeFile.close() new_treeFile.close() print 'Mission complete' <file_sep># Replaces terminal symbols in data with count less than 5 import json # Get Word Counts: countsFile = open('C:\Python2\PA2\cfg.counts', 'r') cList = countsFile.readlines() wordsD = {} # Dictionary for words to be replaced for n in range(len(cList)): if cList[n].split(' ')[1] == 'UNARYRULE': if cList[n].split(' ')[3][:-1] in wordsD: wordsD[cList[n].split(' ')[3][:-1]] = str(int(wordsD[cList[n].split(' ')[3][:-1]]) + int(cList[n].split(' ')[0])) else: wordsD[cList[n].split(' ')[3][:-1]] = cList[n].split(' ')[0] for key in list(wordsD): if int(wordsD[key]) >= 5: del wordsD[key] countsFile.close() # Replace words in tree treeFile = open('C:\Python2\PA2\parse_train.dat', 'r') new_treeFile = open('C:\Python2\PA2\parse_train_rare.dat', 'w') '''with treeFile as f: for line in f: data.append(json.loads(line))''' # Read the lines from the initial file and replace rare words line = treeFile.readline() while line != '': lineList = line.split('"') new_str = '' for item in lineList: if item in wordsD: i = lineList.index(item) lineList[i] = '_RARE_' new_str = '"'.join(lineList) else: new_str = '"'.join(lineList) new_treeFile.write(new_str) line = treeFile.readline() print 'Mission complete' treeFile.close() new_treeFile.close() <file_sep>import json import operator # CKY algorithm parser # Extract sentences to be parsed from file sentenceFile = open('C:\Python2\PA2\parse_test.dat', 'r') sentenceList = [] sentence = sentenceFile.readline() while sentence != '': sentenceList.append(sentence.split(' ')) sentence = sentenceFile.readline() # Cut off '\n' for sentence in sentenceList: n = len(sentence) sentence[n-1] = sentence[n-1][:-1] sentenceFile.close() # Extract grammar with probabilities from files biFile = open('C:\Python2\PA2\qm.bin', 'r') unFile = open('C:\Python2\PA2\qm.uni', 'r') # Retrieve non-terminal rules into dictionary biDict = {} biLine = biFile.readline() while biLine != '': if not (biLine.split(' ')[1], biLine.split(' ')[2]) in biDict: biDict[biLine.split(' ')[1], biLine.split(' ')[2]] = [[biLine.split(' ')[0], biLine.split(' ')[3]]] biLine = biFile.readline() else: biDict[biLine.split(' ')[1], biLine.split(' ')[2]].append([biLine.split(' ')[0], biLine.split(' ')[3]]) biLine = biFile.readline() biFile.close() # Retrieve terminal rules into dictionary unDict = {} unLine = unFile.readline() while unLine != '': if not unLine.split(' ')[1] in unDict: D = {} D[unLine.split(' ')[0]] = unLine.split(' ')[2] unDict[unLine.split(' ')[1]] = (D) unLine = unFile.readline() else: D = {} D[unLine.split(' ')[0]] = unLine.split(' ')[2] unDict[unLine.split(' ')[1]].update(D) unLine = unFile.readline() unFile.close() # CKY Parsing algorithm # Probabilistic CKY: def pcky(sentence): n = len(sentence) Parse = [[i for i in range(n+1)] for j in range(n+1)] # Create Parse Matrix # Add unary rules: for w in range(n): for key in unDict: for un in unDict[key]: if sentence[w] == key: if Parse[w][w+1] == w+1: Parse[w][w+1] = [[un, key, unDict[key][un]]] else: Parse[w][w+1].append([un, key, unDict[key][un]]) if not sentence[w] in unDict: for unR in unDict['_RARE_']: if Parse[w][w+1] == w+1: Parse[w][w+1] = [[unR, sentence[w], unDict['_RARE_'][unR]]] else: Parse[w][w+1].append([unR, sentence[w], unDict['_RARE_'][unR]]) # Add binary rules: for span in range(2, n+1): for start in range(n+1-span): end = start + span for mid in range(start+1, end): if isinstance(Parse[start][mid], list) and isinstance(Parse[mid][end], list): for X in Parse[start][mid]: for Y in Parse[mid][end]: if (X[0], Y[0]) in biDict: for item in biDict[X[0], Y[0]]: Z = item[0] pX = float(X[-1]) pY = float(Y[-1]) pZ = float(item[1]) * pX * pY nl = [Z, X[:-1], Y[:-1], pZ] if isinstance(Parse[start][end], int): Parse[start][end] = [nl] elif isinstance(Parse[start][end], list): if not any(Z in li for li in Parse[start][end]): Parse[start][end].append(nl) else: for li in Parse[start][end]: if Z in li: pr = float(li[3]) p = max(pZ, pr) if p == pZ: Parse[start][end].remove(li) Parse[start][end].append(nl) return Parse # Write trees into json file: outFile = open('C:\Python2\PA2\parse_test.p3.out', 'w') # Open output file for s in sentenceList: Parse = pcky(s) if s[len(s)-1] == '?': for item in Parse[0][len(s)]: if item[0] == 'SBARQ': tree = item[:-1] # Write into file: outFile.write(json.dumps(tree)+'\n') else: for item in Parse[0][len(s)]: if item[0] == 'S': tree = item[:-1] # Write into file: outFile.write(json.dumps(tree)+'\n') outFile.close() print 'Mission complete' <file_sep>import json # Retrieve the list of trees: ptFile = open('C:\Python2\PA2\parse_train_rare_t.dat', 'r') trees = [] with ptFile as l: for line in l: trees.append(json.loads(line)) ptFile.close() # Retrieve rules with probabilities: # Binary Rules probabilities dictionary: prbFile = open('C:\Python2\PA2\q.bin', 'r') brDict = {} pstr = prbFile.readline() while pstr != '': brDict[' '.join(pstr.split(' ')[:-2])] = pstr.split(' ')[-2] pstr = prbFile.readline() prbFile.close() # Unary Rules probabilities dictionary: pruFile = open('C:\Python2\PA2\q.uni', 'r') urDict = {} pstr = pruFile.readline() while pstr != '': urDict[' '.join(pstr.split(' ')[:-2])] = pstr.split(' ')[-2] pstr = pruFile.readline() pruFile.close() # Function that retrieve rule values: def extract_list_values(li): bi = li[0] + ' ' + li[1][0] + ' ' + li[2][0] BinList.append(bi) for item in li: if len(item) == 3: extract_list_values(item) elif len(item) == 2 and isinstance(item, list): UniList.append(item) return BinList, UniList # Count probability for each tree and add value to dictionary: treepDict = {} prb = 1 for tree in trees: BinList = [] UniList = [] extract_list_values(tree) for item in BinList: for key in brDict: if item == key: prb = prb * float(brDict[key]) treepDict[str(tree)] = prb for key in treepDict: print key print treepDict[key] <file_sep># Function to compute rule parameters. # def compute_rp(): countsFile = open('C:\Python2\PA2\parse_train_mark.counts.out', 'r') countsL = countsFile.readlines() # Rule counts dictionaries nontermD = {} unaryD = {} binaryD = {} for line in countsL: if line.split(' ')[1] == 'NONTERMINAL': nontermD[line.split(' ')[2][:-1]] = line.split(' ')[0] elif line.split(' ')[1] == 'UNARYRULE': unaryD[line.split(' ')[2] + ' ' + line.split(' ')[3][:-1]] = line.split(' ')[0] elif line.split(' ')[1] == 'BINARYRULE': binaryD[line.split(' ')[2] + ' ' + line.split(' ')[3] + ' ' + line.split(' ')[4][:-1]] = line.split(' ')[0] countsFile.close() # Compute count parameters: # Non-Terminal parameters: q_bi_file = open('C:\Python2\PA2\qm.bin', 'w') qNT = {} for keyB in binaryD: for keyN in nontermD: if keyB.split(' ')[0] == keyN: qNT[keyB] = float(binaryD[keyB])/float(nontermD[keyN]) q_bi_file.write(keyB + ' ' + str(qNT[keyB]) + ' \n') q_bi_file.close() # Terminal parameters: q_un_file = open('C:\Python2\PA2\qm.uni', 'w') qT = {} for keyU in unaryD: for keyN in nontermD: if keyU.split(' ')[0] == keyN: qT[keyU] = float(unaryD[keyU])/float(nontermD[keyN]) q_un_file.write(keyU + ' ' + str(qT[keyU]) + ' \n') q_un_file.close() print 'mission complete' <file_sep># Natural Language Processing, Problem Set 2 Link to the assignment description: https://spark-public.s3.amazonaws.com/nlangp/assignments/h2-p.2.pdf
7d4ae4480e4430dc0210b6aeb840d3f842e292f3
[ "Markdown", "Python" ]
6
Python
RinSer/coursera_nlangp-001_PA2
697cda8441c9aeb671d4fe1bf8025b3c0e218917
207169690b11a6787744576ccbb96b52e03124ae
refs/heads/main
<file_sep># Rock-Fall-Game<file_sep>import random from typing import NoReturn from game import GameObject, Game import pygame #todo - convert all sets of coords to rect objects #todo - player input and collision detection #todo - score #todo - loss state class Player(GameObject): """Player object class""" def __init__(self, x: int, y: int, width: int, height: int): super().__init__(x, y) self.width = width self.height = height def draw(self, window: pygame.display, COLOUR_PALETTE) -> None: """Method to specify what to draw onto the window""" pygame.draw.rect(window, COLOUR_PALETTE["White"], (self.x, self.y, self.width, self.height)) class Rock(GameObject): """Rock object class""" def __init__(self, game: Game, x: int, y: int, width: int, height: int, velocity: float): super().__init__(x, y) self.game = game self.width = width self.height = height self.velocity = velocity print(self.velocity) def draw(self, window: pygame.display, COLOUR_PALETTE) -> None: """Method to specify what to draw onto the window""" pygame.draw.rect(window, COLOUR_PALETTE["Brown"], (self.x, self.y, self.width, self.height)) def update(self) -> None: """Method to update the rock each frame""" if self.y >= self.game.window_height: self.x = random.randint(0, self.game.window_width - self.width) self.y = - self.height - random.randint(0, 100) self.y += self.velocity class RockFallGame(Game): """Main game class""" def __init__(self, window_name: str, window_width: int, window_height: int, COLOUR_PALETTE: dict, frame_rate: int ): super().__init__( window_name, window_width, window_height, COLOUR_PALETTE, frame_rate ) self.frame_rate = frame_rate player = Player(window_width / 2, window_height * 0.9 - 40, 25, 25) self.add_object(player) for x in range(10): rock_width = random.randint(30, 60) rock_height = random.randint(30, 60) rock = Rock(self, random.randint(0, window_width - rock_width), -rock_height - random.randint(0, 150 * x), rock_width, rock_height, round(random.uniform(3, 6), 2)) self.add_object(rock) def update_objects(self) -> None: """Method to run the update method on all game objects""" for x in self.objects: x.update() # All objects inherit from pygame.sprite.Sprite # and so should have an empty update method def main_loop(self) -> None: """Method containing the main loop""" while True: self.clock.tick(self.frame_rate) self.handle_events() self.update_objects() self.draw() pygame.display.flip() def main() -> None: COLOURS = { "Black": (0, 0, 0), "White": (255, 255, 255), "Brown": (100, 50, 20) } pygame.init() game = RockFallGame("Rock Fall", 500, 500, COLOURS, 60) game.main_loop() if __name__ == "__main__": main() <file_sep>import os import sys from typing import NoReturn import pygame class GameObject(pygame.sprite.Sprite): """Base game object class""" def __init__(self, x, y): super().__init__() self.x = x self.y = y def draw(self, window: pygame.display) -> None: """Method to specify what to draw onto the window""" class Game(): """Main game class""" def __init__(self, window_name: str, window_width: int, window_height: int, COLOUR_PALETTE: dict, frame_rate: int ): self.COLOUR_PALETTE = COLOUR_PALETTE self.window_name = window_name self.clock = pygame.time.Clock() self.window_width = window_width self.window_height = window_height self.objects: list[GameObject] = [] self.setup_window() def setup_window(self) -> None: """Method to setup game window""" self.window = pygame.display.set_mode( (self.window_width, self.window_height)) pygame.display.set_caption((self.window_name)) os.environ["SDL_VIDEO_CENTERED"] = "1" def draw(self) -> None: """Method to draw all objects""" self.window.fill(self.COLOUR_PALETTE["Black"]) for obj in self.objects: obj.draw(self.window, self.COLOUR_PALETTE) def add_object(self, game_object: GameObject) -> None: """Method to add a game object to the game object list""" self.objects.append(game_object) def handle_events(self) -> None: """Method to handle pygame events""" for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() def main_loop(self) -> None: """Method containing the main loop""" while True: self.clock.tick(self.frame_rate) self.handle_events() self.draw() pygame.display.flip()
f22ae37509a5f0292d0090e67a6a7ff668af96f5
[ "Markdown", "Python" ]
3
Markdown
Anthony-de-cruz/Rock-Fall-Game
1a44c40972c3e155929c627f425938462bab3f75
2efa00015066842b15fb24169bf68dc9ffd7b1f3
refs/heads/master
<repo_name>jalvarado-guzman/ExData_Plotting1<file_sep>/Rscript/plot1.R # To load the function to read the data contained in the file source('Rscript/Load_Data.R') # Read the data, create a plot and save the plot to the figure directory data<-getLines() png('figure/plot1.png',480,480,'px') hist(data$Global_active_power,col='red',main='Global Active Power',xlab='Global Active Power (kilowatt)',ylab='Frequency') dev.off()<file_sep>/README.Rmd --- title: "Project1" author: "<NAME>" date: "Thursday, March 05, 2015" output: html_document --- ## Directories The purpose of this repository is to complete the first project of the Exploratory Data Analysis class on the <a href="https://www.coursera.org/",target="_blank">Coursera</a> platform. The directories and files contained in this repo are the following: <ol> <li><b>Instructions.md</b>: Instructions on how to complete the project</li> <li> <b>figure</b>: Directory containing the png files of the plots <ul> <li><b>plot1.png</b>: Picture of the first graph</li> <li><b>plot2.png</b>: Picture of the second graph</li> <li><b>plot3.png</b>: Picture of the third graph</li> <li><b>plot4.png</b>: Picture of the fourth graph</li> </ul> <li> <b>Rscript</b>: Directory containing the R scripts used to load the data and generate the plots <ul> <li><b>Load_Data.R</b>: Function used to load and format the data in R</li> <li><b>plot1.R</b>: R script used generate the first graph</li> <li><b>plot1.R</b>: R script used generate the second graph</li> <li><b>plot1.R</b>: R script used generate the third graph</li> <li><b>plot1.R</b>: R script used generate the fourth graph</li> </ul> ## Loading the Data The following function was used to load, subset and format the data into R: ```{r Plot1-Code,eval=FALSE} # This function will perfome the following actions # Download the zip file provided for the project and save it on the current working directory # Unzip the file to the current working directory and delete the zip file downloaded previously # Create an extra file in the current working directory containing only the records for the 02/01/2007 and 02/02/2007 # Read the file created on the previous step into a data frame and add an additional field named Date_Time formatting # the Date and Time columns into a POSIXLT Object # Finally return the dataset created on the previous step getLines<-function(){ # Load the stringr package require(stringr) # Download the zip file download.file('https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip', paste(getwd(),'household_power_consumption.zip',sep = '/'),quiet = T) # Unzip the file downloaded unzip('household_power_consumption.zip') file<-'household_power_consumption.txt' # Remove the zip file from the current working directory file.remove('household_power_consumption.zip') # Open a connection to the text file for reading con <- file(file, 'r') # Out file where the records from 02/01/2007 and 02/02/2007 are going to be writen outfile <- file(paste('subset',file,sep='_'), 'w') # Read the first line in the file for naming the fields or columns in the data frame unig the stringr package names<-str_split(readLines(file,1),';')[[1]] # Read the text file in chuncks of 1000 lines and write the lines to the outfile if Date of the line is either 2/1/2007 or 2/2/2007 while (length(lines <- readLines(con, n=1000)) > 0){ for (i in 1:length(lines)){ if(grepl('^(1/2/2007|2/2/2007)',lines[i])){ write(lines[i],outfile,append = TRUE) } } } # Close the connections to the files close(con) close(outfile) # Read in to data frame the out file containing the records of the desire dates data<-read.table('subset_household_power_consumption.txt',sep =';',header=FALSE,stringsAsFactors = FALSE,na.strings = '?', colClasses = c(rep('character',2),rep('numeric',7))) # Assign the names of the fields to the data frame names(data)<-names # Format the date and time columns into a new column in the data frame data$Date_Time<-strptime(paste(data$Date,data$Time),'%d/%m/%Y %H:%M:%S') # Return the data frame return(data) } ``` ## First Graph ![Plot1](figure/plot1.png) ## Code to generate the first graph ```{r Code-Graph1,eval=FALSE} # To load the function to read the data contained in the file source('Rscript/Load_Data.R') # Read the data, create a plot and save the plot to the figure directory data<-getLines() png('figure/plot1.png',480,480,'px') hist(data$Global_active_power,col='red',main='Global Active Power',xlab='Global Active Power (kilowatt)',ylab='Frequency') dev.off() ``` ## Second Graph ![Plot2](figure/plot2.png) ## Code to generate the second graph ```{r Code-Graph2,eval=FALSE} # To load the function to read the data contained in the file source('Rscript/Load_Data.R') # Read the data, create a plot and save the plot to the figure directory data<-getLines() png('figure/plot2.png',480,480,'px') with(data,plot(Date_Time,Global_active_power,type = 'l',ylab='Global Active Power (kilowatt)',xlab='')) dev.off() ``` ## Third Graph ![Plot3](figure/plot3.png) ## Code to generate the third graph ```{r Code-Graph3,eval=FALSE} # To load the function to read the data contained in the file source('Rscript/Load_Data.R') # Read the data, create a plot and save the plot to the figure directory data<-getLines() png('figure/plot3.png',480,480,'px') plot(data$Date_Time,data$Sub_metering_1,type = 'n',ylab='Energy sub metering',xlab='') lines(data$Date_Time,data$Sub_metering_1) lines(data$Date_Time,data$Sub_metering_2,col='red') lines(data$Date_Time,data$Sub_metering_3,col='blue') legend('topright',legend = c('Sub metering 1','Sub metering 2','Sub metering 3'),col=c('black','red','blue'),lty=1) dev.off() ``` ## Fourth Graph ![Plot3](figure/plot4.png) ## Code to generate the fourth graph ```{r Code-Graph4,eval=FALSE} # To load the function to read the data contained in the file source('Rscript/Load_Data.R') # Read the data, create a plot and save the plot to the figure directory data<-getLines() png('figure/plot4.png',480,480,'px') marOriginal<-par('mar') par(mfrow=c(2,2),mar=c(4,4,2,1)) plot(data$Date_Time,data$Global_active_power,xlab='',ylab='Global Active Power',type='l') plot(data$Date_Time,data$Voltage,ylab='Voltage',xlab='datetime',type='l') plot(data$Date_Time,data$Sub_metering_1,type = 'n',ylab='Energy sub metering',xlab='') lines(data$Date_Time,data$Sub_metering_1) lines(data$Date_Time,data$Sub_metering_2,col='red') lines(data$Date_Time,data$Sub_metering_3,col='blue') legend('topright',legend = c('Sub metering 1','Sub metering 2','Sub metering 3'),col=c('black','red','blue'),lty=1,bty = 'n') plot(data$Date_Time,data$Global_reactive_power,xlab='datetime',type='l') par(mfrow=c(1,1),mar=marOriginal) dev.off() ``` <file_sep>/Rscript/Load_Data.R # This function will perfome the following actions # Download the zip file provided for the project and save it on the current working directory # Unzip the file to the current working directory and delete the zip file downloaded previously # Create an extra file in the current working directory containing only the records for the 02/01/2007 and 02/02/2007 # Read the file created on the previous step into a data frame and add an additional field named Date_Time formatting # the Date and Time columns into a POSIXLT Object # Finally return the dataset created on the previous step getLines<-function(){ # Load the stringr package require(stringr) # Download the zip file download.file('https://d396qusza40orc.cloudfront.net/exdata%2Fdata%2Fhousehold_power_consumption.zip', paste(getwd(),'household_power_consumption.zip',sep = '/'),quiet = T) # Unzip the file downloaded unzip('household_power_consumption.zip') file<-'household_power_consumption.txt' # Remove the zip file from the current working directory file.remove('household_power_consumption.zip') # Open a connection to the text file for reading con <- file(file, 'r') # Out file where the records from 02/01/2007 and 02/02/2007 are going to be writen outfile <- file(paste('subset',file,sep='_'), 'w') # Read the first line in the file for naming the fields or columns in the data frame unig the stringr package names<-str_split(readLines(file,1),';')[[1]] # Read the text file in chuncks of 1000 lines and write the lines to the outfile if Date of the line is either 2/1/2007 or 2/2/2007 while (length(lines <- readLines(con, n=1000)) > 0){ for (i in 1:length(lines)){ if(grepl('^(1/2/2007|2/2/2007)',lines[i])){ write(lines[i],outfile,append = TRUE) } } } # Close the connections to the files close(con) close(outfile) # Read in to data frame the out file containing the records of the desire dates data<-read.table('subset_household_power_consumption.txt',sep =';',header=FALSE,stringsAsFactors = FALSE,na.strings = '?', colClasses = c(rep('character',2),rep('numeric',7))) # Assign the names of the fields to the data frame names(data)<-names # Format the date and time columns into a new column in the data frame data$Date_Time<-strptime(paste(data$Date,data$Time),'%d/%m/%Y %H:%M:%S') # Return the data frame return(data) }<file_sep>/Rscript/plot4.R # To load the function to read the data contained in the file source('Rscript/Load_Data.R') # Read the data, create a plot and save the plot to the figure directory data<-getLines() png('figure/plot4.png',480,480,'px') marOriginal<-par('mar') par(mfrow=c(2,2),mar=c(4,4,2,1)) plot(data$Date_Time,data$Global_active_power,xlab='',ylab='Global Active Power',type='l') plot(data$Date_Time,data$Voltage,ylab='Voltage',xlab='datetime',type='l') plot(data$Date_Time,data$Sub_metering_1,type = 'n',ylab='Energy sub metering',xlab='') lines(data$Date_Time,data$Sub_metering_1) lines(data$Date_Time,data$Sub_metering_2,col='red') lines(data$Date_Time,data$Sub_metering_3,col='blue') legend('topright',legend = c('Sub metering 1','Sub metering 2','Sub metering 3'),col=c('black','red','blue'),lty=1,bty = 'n') plot(data$Date_Time,data$Global_reactive_power,xlab='datetime',type='l') par(mfrow=c(1,1),mar=marOriginal) dev.off()<file_sep>/Rscript/plot2.R # To load the function to read the data contained in the file source('Rscript/Load_Data.R') # Read the data, create a plot and save the plot to the figure directory data<-getLines() png('figure/plot2.png',480,480,'px') with(data,plot(Date_Time,Global_active_power,type = 'l',ylab='Global Active Power (kilowatt)',xlab='')) dev.off()<file_sep>/Rscript/plot3.R # To load the function to read the data contained in the file source('Rscript/Load_Data.R') # Read the data, create a plot and save the plot to the figure directory data<-getLines() png('figure/plot3.png',480,480,'px') plot(data$Date_Time,data$Sub_metering_1,type = 'n',ylab='Energy sub metering',xlab='') lines(data$Date_Time,data$Sub_metering_1) lines(data$Date_Time,data$Sub_metering_2,col='red') lines(data$Date_Time,data$Sub_metering_3,col='blue') legend('topright',legend = c('Sub metering 1','Sub metering 2','Sub metering 3'),col=c('black','red','blue'),lty=1) dev.off()
7350224823619a15098a94cbc0b7f89d57945a6c
[ "R", "RMarkdown" ]
6
R
jalvarado-guzman/ExData_Plotting1
4d95ef001125ad6bdff5409b11610708ef57c93a
0f09582108924fb8482a6acf6e3bcd86cfe463b8
refs/heads/master
<file_sep>require_relative './eql/sql/parser' require_relative './eql/sql/tree' <file_sep>module Eql VERSION='0.0.1' end<file_sep>source "https://ruby.taobao.org" gem "parslet" gem 'test' <file_sep>require_relative 'test_helper' # require 'parslet' class ParserTest < MiniTest::Unit::TestCase #include Eql def setup @parser = Eql::Sql::Parser.new end def teardown end def test_simples # check syntax parser with parslet [ 'select a from b', 'select a, b from comme', 'select b from far', 'select c from d', 'select a, c, d,e,f,f from b ', 'select count(a) from d', ].each do |sql| s = @parser.parse sql assert_equal(expected = "select", actual = s[:op]) assert(! s[:select].nil?) assert(! s[:from].nil?) assert(! (Eql.build s).nil?) end end def test_bad_sql [ 'select', ' select a from b', 'select a, b from c where a = "120.0, ~!@#$%^&*+_\}{\" asdfa"sf"', ].each do |bad_sql| assert_raises Parslet::ParseFailed do @parser.parse bad_sql end end end def test_where [ 'select a from b where a > 20', 'select a,b from c where a = 20', 'select a,b from c where 20 < a and b < 234', 'select a,b from c where 20 < a or b = 234', 'select a, b from c where a = "oo"', 'select a, b from c where a = "oo" and c > 235', 'select a, b from c where a = "120.0, ~!@#$%^&*+_\}{\" asdfasf"', #'select a from b where a > 20.0', #'select a from b where a > 0.0', #'select a from b where a > -0', ].each do |where_sql| s = @parser.parse where_sql assert_equal(expected = "select", actual = s[:op]) assert(! s[:select].nil?) assert(! s[:from].nil?) assert(! s[:where].nil?) assert(! (Eql.build s).nil?) end end def test_group_by [ 'select a from b group by c', 'select a from b where a > 345 group by c', 'select a from b where a > 345 and foo = "hoge" group by c', ].each do |where_sql| s = @parser.parse where_sql assert_equal(expected = "select", actual = s[:op]) assert(! s[:select].nil?) assert(! s[:from].nil?) assert(! s[:group_by].nil?) assert(! (Eql.build s).nil?) end end def test_join [ 'select a from b where x=1 and y = "2" and z = true join c,d on e = f group by c', 'select a from b join c,d on e = f and x = 2 and y = "abc" and z = true group by c' # 'select a from b join c on e = f group by c', # 'select a from b where a > 345 group by c', # 'select a from b where a > 345 and foo = "hoge" group by c', ].each do |where_sql| begin s = @parser.parse where_sql puts s rescue Parslet::ParseFailed => failure fail failure.cause.ascii_tree end assert_equal(expected = "select", actual = s[:op]) assert(! s[:select].nil?) assert(! s[:from].nil?) assert(! s[:join].nil?) assert(! s[:group_by].nil?) assert(! (Eql.build s).nil?) end end def test_ref [ 'select a from b', 'select a from b where a.x = 2 and y = "abc" and z = true group by c' # 'select a from b join c on e = f group by c', # 'select a from b where a > 345 group by c', # 'select a from b where a > 345 and foo = "hoge" group by c', ].each do |where_sql| begin s = @parser.parse where_sql puts s rescue Parslet::ParseFailed => failure fail failure.cause.ascii_tree end assert_equal(expected = "select", actual = s[:op]) assert(! s[:select].nil?) assert(! s[:from].nil?) assert(! (Eql.build s).nil?) end end def test_alias [ 'select a as a2 from b', 'select a as a2,c as c2 from b as b2', 'select a as a2 from b as b2,c as c2', 'select a.x as x from b as b2,c as c2' #, #'select a from b where a.x = 2 and y = "abc" and z = true group by c' # 'select a from b join c on e = f group by c', # 'select a from b where a > 345 group by c', # 'select a from b where a > 345 and foo = "hoge" group by c', ].each do |where_sql| begin s = @parser.parse where_sql puts s rescue Parslet::ParseFailed => failure fail failure.cause.ascii_tree end assert_equal(expected = "select", actual = s[:op]) assert(! s[:select].nil?) assert(! s[:from].nil?) assert(! (Eql.build s).nil?) end end end
eba7b11578dd02e3e6020d902375544137a6b382
[ "Ruby" ]
4
Ruby
haoch/eql
1f5bca1fd9be93d07d3f79c41acb02800e3ee7ad
e4bed921ea0dceba9c32ee9b0b20e43095e902b5
refs/heads/master
<file_sep>from django.shortcuts import render from django.views import generic from .models import Team class IndexView(generic.ListView): template_name = 'prode/index.html' context_object_name = 'team_list' def get_queryset(self): """Return all existing teams on database""" return Team.objects.all()<file_sep>from django.db import models class Team(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name # class Match(models.Model): # start = models.DateTimeField() # end = models.DateTimeField() # team1 = models.ForeignKey(Team, on_delete=models.CASCADE) # team2 = models.ForeignKey(Team, on_delete=models.CASCADE) # team1_score = models.PositiveIntegerField() # team2_score = models.PositiveIntegerField()
53cc3d996a1883fe17dc6a9732ce197ece73f2a7
[ "Python" ]
2
Python
luis-sama/prodesama
7032a3a12fbd329f0b284b6ad65e5a9fc3517998
ecbd0101017670cf1695cd56cd88fe5838b923dd
refs/heads/master
<repo_name>wcurrie/sandwich-maker<file_sep>/candlestickmaker/src/main/resources/application.properties server.port=8083 spring.output.ansi.enabled=ALWAYS spring.sleuth.sampler.percentage=1.0<file_sep>/kitchenhand/src/main/java/com/example/kitchenhand/rxjava2/SpanPropagationConfig.java package com.example.kitchenhand.rxjava2; import io.reactivex.plugins.RxJavaPlugins; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.sleuth.Span; import org.springframework.cloud.sleuth.Tracer; import org.springframework.context.annotation.Configuration; import javax.annotation.PostConstruct; /** * Using rxjava's Schedulers.io() to make concurrent http requests means those requests happen on a different thread. * For zipkin to follow the trace we need to copy the state from between the tomcat request thread and the rxjava thread. */ @Configuration public class SpanPropagationConfig { @Autowired private Tracer tracer; @PostConstruct public void applyHack() { // seems spring cloud sleuth doesn't support rxjava2.x RxJavaPlugins.setScheduleHandler(runnable -> { // cribbed from org.springframework.cloud.sleuth.instrument.rxjava.SleuthRxJavaSchedulersHook.TraceAction.call() Span currentSpan = tracer.getCurrentSpan(); if (currentSpan != null) { return () -> { tracer.continueSpan(currentSpan); try { runnable.run(); } finally { tracer.detach(tracer.getCurrentSpan()); } }; } else { return runnable; } }); } } <file_sep>/README.md # Zipkin Experiment What is zipkin?: [one explanation](http://ryanjbaxter.com/cloud/spring%20cloud/spring/2016/07/07/spring-cloud-sleuth.html) Couple of spring boot services with silly names: butcher, baker, candlestickmaker and kitchenhand. ## How? Made a sandwich in docker using: 1. mvn clean package 2. docker-compose up 3. curl -XPOST localhost:8080/sandwiches Look at zipkin trace by visiting http://localhost:9411. Grab a trace ID from the docker logs. Eg 6fe09cac9d9b37d3 in: kitchenhand_1 | 2017-02-26 04:49:32.757 INFO [kitchenhand,6fe09cac9d9b37d3,6fe09cac9d9b37d3,true] 1 --- [readScheduler-2] c.e.k.controller.SandwichController : Collecting ham Compare with curl -XPOST localhost:8080/sandwiches?turbo=true (tip: it's not actually much faster) ## What should I see? The communication paths between the services: ![zipkin dependencies](https://github.com/wcurrie/sandwich-maker/blob/master/zipkin-dependencies.png "zipkin's dependency view") A trace of the purely sequential flow (curl -XPOST localhost:8080/sandwiches): ![sequential flow](https://github.com/wcurrie/sandwich-maker/blob/master/sequential-sandwich.png "sequential flow") A trace of with concurrent HTTP calls from RxJava (curl -XPOST localhost:8080/sandwiches?turbo=true): ![concurrent flow](https://github.com/wcurrie/sandwich-maker/blob/master/turbo-sandwich.png "concurrent flow") ## Weave Scope See how the containers are connected using weave scope: sudo curl -L git.io/scope -o /usr/local/bin/scope sudo chmod a+x /usr/local/bin/scope scope launch open http://localhost:4040 ## Resources https://spring.io/blog/2016/02/15/distributed-tracing-with-spring-cloud-sleuth-and-spring-cloud-zipkin https://github.com/spring-cloud/spring-cloud-sleuth Collecting traces Use https://github.com/openzipkin/zipkin/tree/master/zipkin-server wget -O zipkin.jar 'https://search.maven.org/remote_content?g=io.zipkin.java&a=zipkin-server&v=LATEST&c=exec' java -jar zipkin.jar https://github.com/openzipkin/docker-zipkin ### Eureka https://spring.io/blog/2015/01/20/microservice-registration-and-discovery-with-spring-cloud-and-netflix-s-eureka ### Other Directions * https://github.com/openzipkin/zipkin-aws * Converting a trace into plantuml sequence diagram * Try spring 5 and webflux * Put each service in an alpine docker container, start them all using docker compose<file_sep>/baker/src/main/resources/application-docker.properties eureka.client.serviceUrl.defaultZone=http://eureka:8761/eureka spring.zipkin.baseUrl=http://zipkin:9411<file_sep>/butcher/src/main/resources/application.properties server.port=8082 spring.output.ansi.enabled=ALWAYS spring.sleuth.sampler.percentage=1.0<file_sep>/docker-compose.yml version: '2' services: eureka: image: 'eureka' ports: - '8761:8761' candlestickmaker: image: 'candlestickmaker' butcher: image: 'butcher' baker: image: 'baker' kitchenhand: image: 'kitchenhand' ports: - '8080:8080' zipkin: image: 'openzipkin/zipkin' ports: - '9411:9411' <file_sep>/kitchenhand/src/main/java/com/example/kitchenhand/controller/SandwichController.java package com.example.kitchenhand.controller; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.reactivex.Single; import io.reactivex.schedulers.Schedulers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.Arrays; import java.util.Map; import java.util.UUID; @RestController @RequestMapping("/sandwiches") public class SandwichController { private static final Logger LOG = LoggerFactory.getLogger(SandwichController.class); private final RestTemplate restTemplate; @Autowired public SandwichController(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @PostMapping(produces = "application/json") public Map<String, Object> make() { LOG.info("Getting a candle to work by"); Map candle = restTemplate.getForObject("http://candlestickmaker/candles", Map.class); LOG.info("Lighting " + candle.get("id")); LOG.info("Collecting bread"); Map bread = restTemplate.getForObject("http://baker/loaves", Map.class); LOG.info("Collecting ham"); Map ham = restTemplate.getForObject("http://butcher/ham?slices=2", Map.class); return makeSandwich(Arrays.asList(bread, ham)); } @PostMapping(produces = "application/json", params = "turbo=true") public Map<String, Object> makeQuickly() { LOG.info("Getting a candle to work by"); Map candle = restTemplate.getForObject("http://candlestickmaker/candles", Map.class); LOG.info("Lighting " + candle.get("id")); // probably a terrible use of rx-java LOG.info("Gathering ingredients"); Single<Map> bread = Single.fromCallable(() -> { LOG.info("Collecting bread"); return restTemplate.getForObject("http://baker/loaves", Map.class); }).subscribeOn(Schedulers.io()); Single<Map> ham = Single.fromCallable(() -> { LOG.info("Collecting ham"); return restTemplate.getForObject("http://butcher/ham?slices=2", Map.class); }).subscribeOn(Schedulers.io()); Iterable<Map> ingredients = Single.merge(bread, ham).blockingIterable(); return makeSandwich(ingredients); } private Map<String, Object> makeSandwich(Iterable<Map> ingredients) { LOG.info("Making a sandwich"); return new ImmutableMap.Builder<String, Object>() .put("id", UUID.randomUUID()) .put("contents", ImmutableList.builder() .addAll(ingredients) .build()) .build(); } } <file_sep>/baker/src/main/resources/application.properties server.port=8081 spring.output.ansi.enabled=ALWAYS spring.sleuth.sampler.percentage=1.0
63650b2f8fda6d91fc278982bd6ff453f8c1a00a
[ "Markdown", "Java", "YAML", "INI" ]
8
INI
wcurrie/sandwich-maker
0ba4076d31bd648c97f9fc5784706657e550b573
0718a69f307972605938b42476bdca976dc903be
refs/heads/master
<file_sep>#ifndef MATH_HPP #define MATH_HPP //Clamp a value in range [lowValue,hightValue] void clamp( float* param, float lowValue, float hightValue ) { if( *param > hightValue ) { *param = hightValue; } if( *param < lowValue ) { *param = lowValue; } } //Clamp an angle value in range [-180,180] void clampAsAngle( float* angle ) { if( *angle > 180.f ) { *angle -= 360.0f; } if( *angle <- 180.f ) { *angle += 360.0f; } } #endif // MATH_HPP <file_sep>#ifndef ANIMATEDMESHSCENENODE_HPP #define ANIMATEDMESHSCENENODE_HPP #include <irrlicht.h> class AnimatedMeshSceneNode : public irr::scene::IAnimatedMeshSceneNode { public: //TODO: refactor character manager with this class if possible } #endif // ANIMATEDMESHSCENENODE_HPP <file_sep>cmake_minimum_required(VERSION 2.6) set( PROJECT_NAME Irrlicht-Project ) project( ${PROJECT_NAME} ) # Search for /usr/local/lib/libIrrlicht.a find_library( IRRLICHT_LIBRARY NAMES Irrlicht PATHS $ENV{IRRDIR}/lib ) # Configure Project set( CMAKE_BUILD_TYPE Debug ) set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin ) set( MEDIA_DIR "${CMAKE_SOURCE_DIR}/media/" ) configure_file( CMake/Project_Config.h.in Project_Config.h @ONLY ) # add_executable sources file(GLOB SOURCES src/*.cpp) file(GLOB HEADERS include/*.[ch]*) # Include CMake Generated files ( ProjectConfig.h ) include_directories( ${CMAKE_CURRENT_BINARY_DIR} ) # Specify g++ option add_definitions( -Wall -Wextra -std=c++11 ) add_executable( ${PROJECT_NAME} ${SOURCES} ${HEADERS} ) target_link_libraries( ${PROJECT_NAME} ${IRRLICHT_LIBRARY} -lGL -lXxf86vm -lXext -lX11 -lXcursor ) <file_sep>#ifndef EVENTRECEIVER_H #define EVENTRECEIVER_H #include <irrlicht.h> //Define controls #define KEY_UP irr::KEY_KEY_Z #define KEY_DOWN irr::KEY_KEY_S #define KEY_LEFT irr::KEY_KEY_Q #define KEY_RIGHT irr::KEY_KEY_D #define KEY_JUMP irr::KEY_KEY_K #define KEY_ATTACK irr::KEY_SPACE class EventReceiver : public irr::IEventReceiver { public: EventReceiver() { for ( irr::u32 i=0; i < irr::KEY_KEY_CODES_COUNT; ++i ) { KeyIsDown[i] = false; KeyIsPressed[i] = false; } } // This is the one method that we have to implement virtual bool OnEvent(const irr::SEvent& event) { // Remember whether each key is down or up if ( event.EventType == irr::EET_KEY_INPUT_EVENT ) { // if( event.KeyInput.PressedDown ) // { // if( !KeyIsDown[event.KeyInput.Key] ) // { // KeyIsPressed[event.KeyInput.Key] = true; // } // else // { // KeyIsPressed[event.KeyInput.Key] = false; // } // } KeyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown; } return false; } // This is used to check whether a key is being held down virtual bool IsKeyDown( irr::EKEY_CODE keyCode ) const { return KeyIsDown[keyCode]; } // This is used to check whether a key is being held down // virtual bool IsKeyPressed( irr::EKEY_CODE keyCode ) // { // if( KeyIsPressed[keyCode] && !KeyIsDown[keyCode]) // KeyIsPressed[keyCode] = false; // // Set keys to press if another key is down // // WARNING: should check any other active key than arrows if some. // // This is used because the OnEvent() method miss to set key pressed // // if we press another key just after having pressed one. // if( numberOfKeysDown() > 1 && KeyIsPressed[keyCode] ) // KeyIsPressed[keyCode] = false; // return KeyIsPressed[keyCode]; // } //Indicates if arrow keys are down bool IsArrowDown() { return( KeyIsDown[irr::KEY_KEY_Z] || KeyIsDown[irr::KEY_KEY_S] || KeyIsDown[irr::KEY_KEY_Q] || KeyIsDown[irr::KEY_KEY_D] ); } //Indicates if arrow keys are pressed int numberOfKeysDown() { int count = 0; for ( irr::u32 i=0; i < irr::KEY_KEY_CODES_COUNT; ++i ) { if( KeyIsDown[i] ) { ++count; } } return( count ); } private: // We use this array to store the current state of each key bool KeyIsDown[irr::KEY_KEY_CODES_COUNT]; // Check if keys are pressed bool KeyIsPressed[irr::KEY_KEY_CODES_COUNT]; }; #endif // EVENTRECEIVER_H <file_sep>#ifndef ANIMATIONENDCALLBACK_HPP #define ANIMATIONENDCALLBACK_HPP #include <irrlicht.h> class AnimationEndCallBack : public irr::scene::IAnimationEndCallBack { public: AnimationEndCallBack() :animationEnd(false) {} // This is used to check whether a key is being held down virtual void OnAnimationEnd( irr::scene::IAnimatedMeshSceneNode *node ) { animationEnd=true; node->setLoopMode( true ); } bool animationEnd; }; #endif // ANIMATIONENDCALLBACK_HPP <file_sep>#ifndef CHARACTERMANAGER_HPP #define CHARACTERMANAGER_HPP #include <irrlicht.h> #include "PathFinder.hpp" #include "EventReceiver.hpp" #include "AnimationEndCallBack.hpp" #include "Math.hpp" #include <iostream> class CharacterManager { public: //! Constructor CharacterManager() :y_MeshRotation( 0.0f ), animationType( irr::scene::EMAT_STAND ), animationSwitch(false) {} //Add ITerrainSceneNode to scene manager void addCharacterToScene( irr::scene::ISceneManager* sceneManager, irr::video::IVideoDriver* driver ) { //Path Finder to load texture PathFinder pathFinder; //Add mesh irr::scene::IAnimatedMesh* meshCharacter = sceneManager->getMesh( pathFinder.getFullMediaPath( "faerie.md2" ) ); characterNode = sceneManager->addAnimatedMeshSceneNode( meshCharacter ); /* To let the mesh look a little bit nicer, we change its material. We disable lighting because we do not have a dynamic light in here, and the mesh would be totally black otherwise. Then we set the frame loop, such that the predefined STAND animation is used. And last, we apply a texture to the mesh. Without it the mesh would be drawn using only a color. Mesh mouvement is set by the 3rd person camera manager */ characterNode->setMaterialFlag(irr::video::EMF_LIGHTING, false); characterNode->setMaterialTexture( 0, driver->getTexture( pathFinder.getFullMediaPath( "faerie2.bmp" ) ) ); characterNode->setMD2Animation( irr::scene::EMAT_STAND ); characterNode->setPosition( irr::core::vector3df( 5400, 570, 5200 ) ); metaTriangleSelector = sceneManager->createMetaTriangleSelector(); } //Collision Handling void addSceneNodeCollision( irr::scene::ISceneManager* sceneManager, irr::scene::ISceneNode* sceneNode ) { //WARNING: For futur development. Not Tested Yet. // Create triangle selector irr::scene::ITriangleSelector* selector = sceneNode->getTriangleSelector(); if(!selector) { return; } metaTriangleSelector->addTriangleSelector(selector); //Create collision response animator and attach it to the scene node animator = sceneManager->createCollisionResponseAnimator( metaTriangleSelector, characterNode, irr::core::vector3df( 70, 30, 70 ),//Ellipsoid Radius irr::core::vector3df( 0, -10, 0 ),//Gravity per second irr::core::vector3df( 0, 10, 0) ); //Ellipsoid Translation (Offset) selector->drop(); characterNode->addAnimator( animator ); animator->drop(); } //Update 3rd person position and orientation void updateTransform( EventReceiver* eventReceiver ) { //Mesh Speed float speed = 0.0f; //KeyBoard Mesh action if( eventReceiver->IsKeyDown( KEY_DOWN) ) { speed = -4.0f; } if( eventReceiver->IsKeyDown( KEY_UP ) ) { speed = 4.0f; } if( eventReceiver->IsKeyDown( KEY_RIGHT ) ) { y_MeshRotation += 3.0f; speed = 3.0f; } if( eventReceiver->IsKeyDown( KEY_LEFT ) ) { y_MeshRotation -= 3.0f; speed = 3.0f; } if( animationType == irr::scene::EMAT_ATTACK ) { speed = 0.0f; } clampAsAngle( &y_MeshRotation ); //Calculates mesh position irr::core::vector3df meshForward( sin( ( characterNode->getRotation().Y + 90.0f ) * irr::core::PI/180.0f ), 0, cos( ( characterNode->getRotation().Y + 90.0f ) * irr::core::PI/180.0f ) ); meshForward.normalize(); irr::core::vector3df newPos = meshForward * speed + characterNode->getPosition(); //Update Mesh characterNode->setPosition( newPos ); characterNode->setRotation( irr::core::vector3df( 0, y_MeshRotation + 180.0f, 0 ) ); } //Update 3rd person animation void updateAnimation( EventReceiver* eventReceiver ) { //Set standing or running if( animationType != irr::scene::EMAT_ATTACK && animationType != irr::scene::EMAT_JUMP ) {if( (eventReceiver->IsKeyDown( KEY_UP) || eventReceiver->IsKeyDown( KEY_DOWN) || eventReceiver->IsKeyDown( KEY_LEFT) || eventReceiver->IsKeyDown( KEY_RIGHT) )) { if( animationType != irr::scene::EMAT_RUN) { animationType = irr::scene::EMAT_RUN; animationSwitch = true; } else { animationSwitch = false; } } else { if(animationType != irr::scene::EMAT_STAND) { animationType = irr::scene::EMAT_STAND; animationSwitch = true; } else { animationSwitch = false; } } } //handle Jump if(animationType != irr::scene::EMAT_JUMP ) { if(eventReceiver->IsKeyDown( KEY_JUMP)) { characterNode->setLoopMode( false ); animationType = irr::scene::EMAT_JUMP ; animationSwitch = true;characterNode->setAnimationEndCallback( &jumpEndReceiver ); animator->jump(3.0f); } } else { if( jumpEndReceiver.animationEnd ) { animationSwitch =true; animationType = irr::scene::EMAT_STAND; jumpEndReceiver.animationEnd=false; } else { animationSwitch = false; } } //handle attack if( animationType != irr::scene::EMAT_ATTACK ) { if(eventReceiver->IsKeyDown( KEY_ATTACK)) { characterNode->setLoopMode( false ); animationType = irr::scene::EMAT_ATTACK ; animationSwitch = true;characterNode->setAnimationEndCallback( &attackEndReceiver ); } } else { if( attackEndReceiver.animationEnd ) { animationSwitch =true; animationType = irr::scene::EMAT_STAND; attackEndReceiver.animationEnd=false; } else { animationSwitch = false; } } //Switch animation if(animationSwitch) { characterNode->setMD2Animation(animationType); animationSwitch =false; } } void UpdateCharacter( EventReceiver* eventReceiver ) { updateTransform( eventReceiver ); updateAnimation( eventReceiver ); } //Animated Mesh scene node irr::scene::IAnimatedMeshSceneNode* characterNode; //Collision handling irr::scene::ISceneNodeAnimatorCollisionResponse* animator; irr::scene::IMetaTriangleSelector * metaTriangleSelector; //3rd Person parameters // Rotation parameter float y_MeshRotation; // Animation irr::scene::EMD2_ANIMATION_TYPE animationType; AnimationEndCallBack attackEndReceiver; AnimationEndCallBack jumpEndReceiver; bool animationSwitch; }; #endif // CHARACTERMANAGER_HPP <file_sep>#ifndef PATHFINDER_HPP #define PATHFINDER_HPP #include "Project_Config.h" #include "irrString.h" class PathFinder { public: PathFinder() {} // Return full path to the file stored in media file irr::core::stringc getFullMediaPath(const char* filename) { irr::core::stringc media_DIR = MEDIA_DIR; return media_DIR + filename; } private: }; #endif // PATHFINDER_HPP <file_sep>#ifndef CAMERAMANAGER_HPP #define CAMERAMANAGER_HPP #include <irrlicht.h> #include "PathFinder.hpp" #include "EventReceiver.hpp" #include "CharacterManager.hpp" #include "Math.hpp" #include <iostream> class CameraManager { public: //! Constructor CameraManager() :FarValue( 42000.0f ), setCameraToMeshOrientation( true ), moveCameraCursor( false ), d_Interpolate( 1.0f ), x_Rotation( 0.0f ), y_Rotation( 0.0f ) {} //Add 3er person camera void add3rdPersonCameraToScene( irr::scene::ISceneManager* sceneManager ) { //WARNING : Call move3rdPersonCameraControl() in the main loop to trigger. cameraNode = sceneManager->addCameraSceneNode( 0, //Parent Node irr::core::vector3df( 0.0f, 0.0f, 0.0f ), //CamDOWNera position irr::core::vector3df( 0.0f, 0.0f, 0.0f ), //Camera orientation 0, //Camera Id true ); //Set Active cameraNode->setFarValue( FarValue ); } //Add FPS camera void addFPSCameraToScene( irr::scene::ISceneManager* sceneManager ) { cameraNode = sceneManager->addCameraSceneNodeFPS( 0, 100.0f, 1.2f ); cameraNode->setPosition(irr::core::vector3df(2700*2,255*2,2600*2)); cameraNode->setTarget(irr::core::vector3df(2397*2,343*2,2700*2)); cameraNode->setFarValue( FarValue ); } //Add Static camera void addStaticCameraToScene( irr::scene::ISceneManager* sceneManager ) { cameraNode = sceneManager->addCameraSceneNode( 0, //Parent Node irr::core::vector3df( 40.0f, 10.0f, 15.0f ), //Camera position irr::core::vector3df( 0.0f, 9.0f, 15.0f ) ); //Camera orientation cameraNode->setFarValue( FarValue ); } //Timer tick void timerTick( irr::IrrlichtDevice* device ) { float deltaTime = device->getTimer()->getTime() - time; timer += deltaTime/100000.0f; } //Move 3rd person camera to its character void UpdateCamera( irr::IrrlichtDevice* device, EventReceiver* eventReceiver, CharacterManager characterManager ) { //Get cursor mouvement irr::core::position2d<irr::f32> cursorPos = device->getCursorControl()->getRelativePosition(); float cursorSensibility = 256.0f; float dx = ( cursorPos.X - 0.5 ) * cursorSensibility; float dy = ( cursorPos.Y - 0.5 ) * cursorSensibility; //Update Rotation y_Rotation += dx; x_Rotation += dy; clamp( &x_Rotation, -90, 10 ); clampAsAngle( &y_Rotation ); //Reset Cursor position device->getCursorControl()->setPosition( 0.5f, 0.5f ); //Set Camera to 3rd person orientation if( checkOrientation( device, eventReceiver->IsArrowDown(), dx, dy, characterManager.y_MeshRotation ) ) { replaceCameraToMesh(characterManager.y_MeshRotation); } //3rd person position irr::core::vector3df characterNodePosition = characterManager.characterNode->getPosition(); //Camera Zoom float Zoom = 70.0f; //Camera Position and Orientation irr::core::vector3df cameraPos = characterNodePosition + irr::core::vector3df( Zoom, Zoom, 0 ); cameraPos.rotateXYBy( x_Rotation, characterNodePosition ); cameraPos.rotateXZBy( -y_Rotation, characterNodePosition ); //Update cameraNode->setPosition( cameraPos ); cameraNode->setTarget( irr::core::vector3df( characterNodePosition.X, characterNodePosition.Y, characterNodePosition.Z ) ); } //Set camera orientation to mesh orientation void replaceCameraToMesh(float y_MeshRotation) { if( abs(y_MeshRotation-y_Rotation) >= 1.0f ) { //Determine delta rotation to perform //**WARNING: Could be improve by doing calculation only on first pass // No need to recalculate angle at every frame for interpolation** float yOmega = y_MeshRotation - y_Rotation; clampAsAngle( &yOmega ); float xOmega = -25.0f - x_Rotation; clampAsAngle( &xOmega ); //Interpolate rotation between mesh and camera irr::core::vector3df d_Rotation(xOmega,yOmega, 0); irr::core::vector3df cameraRotation(x_Rotation,y_Rotation,0); irr::core::vector3df currentRotation; currentRotation.interpolate(irr::core::vector3df(0.0f,0.0f,0.0f),d_Rotation,d_Interpolate); //Rotate camera to mesh x_Rotation += currentRotation.X; y_Rotation +=currentRotation.Y; //Update interpolation step d_Interpolate -= 0.0005f; } else { //Reset interpolation parameters d_Interpolate = 1.0f; setCameraToMeshOrientation = false; } } //Check orientation condition to replace camera to mesh orientation bool checkOrientation( irr::IrrlichtDevice* device, bool arrowDown, float dx, float dy, float y_MeshRotation ) { // Check Mesh-Camera angle when Mesh is moving and camera is not moved // with cursor if( abs(y_MeshRotation-y_Rotation) >= 50.0f && !setCameraToMeshOrientation && arrowDown && !moveCameraCursor ) { setCameraToMeshOrientation = true; } // Check if cursor has moved if( dx > 0 || dy > 0) { setCameraToMeshOrientation = false; moveCameraCursor = true; timer = 0.0f; time = device->getTimer()->getTime(); } // Reset camera orientation after a certain time if it has been moved // with cursor if( moveCameraCursor ) { timerTick( device ); if( timer > 2.0f ) { setCameraToMeshOrientation =true; moveCameraCursor = false; timer = 0.0f; } } return setCameraToMeshOrientation; } //Camera parameters irr::scene::ICameraSceneNode* cameraNode; float FarValue; //3rd Person Camera parameters // Replace camera to mesh direction parameters bool setCameraToMeshOrientation; bool moveCameraCursor; float d_Interpolate; // Rotation parameters float x_Rotation; float y_Rotation; // Time parameters float time; float timer; }; #endif // CAMERAMANAGER_HPP <file_sep>#include <irrlicht.h> #include "Project_Config.h" #include "../include/EventReceiver.hpp" #include "../include/TerrainManager.hpp" #include "../include/CameraManager.hpp" #include "../include/CharacterManager.hpp" int main(void) { //Event Receiver EventReceiver eventReceiver; // Device creation irr::IrrlichtDevice* device = irr::createDevice( irr::video::EDT_OPENGL, // API = OpenGL irr::core::dimension2d<irr::u32>( 800, 600 ), // Window Size 640x480p 32, false, false, false, &eventReceiver ); // 32 bits/pixel, FullScreen, StencilBuffer, Vsync, Receiver // Create Video Driver irr::video::IVideoDriver* driver = device->getVideoDriver(); // Set cursor position device->getCursorControl()->setPosition( 0.5f, 0.5f ); // Create SceneManager irr::scene::ISceneManager* sceneManager = device->getSceneManager(); //Set Cursor visibility device->getCursorControl()->setVisible( false ); //Add 3rd Person camera CameraManager cameraManager; cameraManager.add3rdPersonCameraToScene( sceneManager ); // Add terrain scene node TerrainManager terrainManager; terrainManager.addTerrainToScene( sceneManager, driver ); //Here, the terrain create its own triangleSelector and set the cameraNode to collide with it; //See Character manager for better approach. terrainManager.addSceneNodeCollision( sceneManager, cameraManager.cameraNode ); terrainManager.addSkyBox( sceneManager, driver ); //Add mesh CharacterManager characterManager; characterManager.addCharacterToScene( sceneManager, driver ); //Here the characterNode stores all triangleSelector for every object it collides with. characterManager.addSceneNodeCollision( sceneManager, terrainManager.terrainNode ); //Set font color ( A (transparency), R, G, B ) irr::video::SColor color( 255, 255, 255, 255); //Rendering loop while (device->run()) { //Close window if the Escape key is pressed if(eventReceiver.IsKeyDown( irr::KEY_ESCAPE)) { device->closeDevice(); } //3rd Person mouvement cameraManager.UpdateCamera( device, &eventReceiver, characterManager ); characterManager.UpdateCharacter( &eventReceiver ); // characterManager.updateAnimationType( &eventReceiver ); //Draw scene driver->beginScene( true, true, color ); sceneManager->drawAll (); driver->endScene (); } device->drop (); //Free memory return EXIT_SUCCESS; } <file_sep>#ifndef TERRAINSCENENODE_HPP #define TERRAINSCENENODE_HPP #include <irrlicht.h> #include "PathFinder.hpp" class TerrainManager { public: //! Constructor TerrainManager() {} //Add ITerrainSceneNode to scene manager void addTerrainToScene( irr::scene::ISceneManager* sceneManager, irr::video::IVideoDriver* driver ) { //Path Finder to load texture PathFinder pathFinder; //Create node terrainNode = sceneManager->addTerrainSceneNode( pathFinder.getFullMediaPath( "terrain-heightmap.bmp" ),//HeightMap 0, //Parent node -1, //Node id irr::core::vector3df( 0.f, 0.f, 0.f ), //Position irr::core::vector3df( 0.f, 0.f, 0.f ), //Rotation irr::core::vector3df( 40.f, 4.4f, 40.f ), //Scale irr::video::SColor( 255, 255, 255, 255 ), //VertexColor 5, //MaxLOD irr::scene::ETPS_17, //PatchSize 4 ); //SmoothFactor //Set Material terrainNode->setMaterialFlag( irr::video::EMF_LIGHTING, false ); terrainNode->setMaterialTexture( 0, driver->getTexture( pathFinder.getFullMediaPath( "terrain-texture.jpg" ) ) ); terrainNode->setMaterialTexture(1, driver->getTexture( pathFinder.getFullMediaPath( "detailmap3.jpg" ) ) ); terrainNode->setMaterialType( irr::video::EMT_DETAIL_MAP ); terrainNode->scaleTexture( 1.0f, 20.0f ); } //Collision Handling void addSceneNodeCollision( irr::scene::ISceneManager* sceneManager, irr::scene::ISceneNode* sceneNode ) { // Create triangle selector irr::scene::ITriangleSelector* selector = sceneManager->createTerrainTriangleSelector( terrainNode, 0 ); terrainNode->setTriangleSelector( selector ); //Disable gravity for the Camera if( sceneNode->getID() == 0 ) { y_gravity = 0.0f; } else { y_gravity = -10.0f; } //Create collision response animator and attach it to the scene node irr::scene::ISceneNodeAnimator* animator = sceneManager->createCollisionResponseAnimator( selector, sceneNode, irr::core::vector3df( 60, 100, 60 ),//Ellipsoid Radius irr::core::vector3df( 0, y_gravity, 0 ),//Gravity per second irr::core::vector3df( 0, -76, 0) ); //Ellipsoid Translation (Offset) //WARNING: The offset to set depends on the mesh origin. selector->drop(); sceneNode->addAnimator( animator ); animator->drop(); } // Add Sky Dome void addSkyDome( irr::scene::ISceneManager* sceneManager, irr::video::IVideoDriver* driver ) { //Path Finder to load texture PathFinder pathFinder; driver->setTextureCreationFlag(irr::video::ETCF_CREATE_MIP_MAPS, false); /*irr::scene::ISceneNode* skydome=*/sceneManager->addSkyDomeSceneNode( driver->getTexture( pathFinder.getFullMediaPath( "skydome.jpg" ) ),16,8,0.9f,2.0f); driver->setTextureCreationFlag(irr::video::ETCF_CREATE_MIP_MAPS, true); } // Add Sky Box void addSkyBox( irr::scene::ISceneManager* sceneManager, irr::video::IVideoDriver* driver ) { //Path Finder to load texture PathFinder pathFinder; driver->setTextureCreationFlag(irr::video::ETCF_CREATE_MIP_MAPS, false); /*irr::scene::ISceneNode* skybox=*/sceneManager->addSkyBoxSceneNode( driver->getTexture( pathFinder.getFullMediaPath( "irrlicht2_up.jpg" ) ), driver->getTexture( pathFinder.getFullMediaPath( "irrlicht2_dn.jpg" ) ), driver->getTexture( pathFinder.getFullMediaPath( "irrlicht2_lf.jpg" ) ), driver->getTexture( pathFinder.getFullMediaPath( "irrlicht2_rt.jpg" ) ), driver->getTexture( pathFinder.getFullMediaPath( "irrlicht2_ft.jpg" ) ), driver->getTexture( pathFinder.getFullMediaPath( "irrlicht2_bk.jpg" ) ) ); driver->setTextureCreationFlag(irr::video::ETCF_CREATE_MIP_MAPS, true); } //Terrain scene node irr::scene::ITerrainSceneNode* terrainNode; float y_gravity; }; #endif // TERRAINSCENENODE_HPP
ae9887b113c72569e3ba6f1fb39e2bcb0e64a744
[ "CMake", "C++" ]
10
C++
LucasGandel/Irrlicht_Project
61c33acb94dfe7613d0b4d1b17a9460305b05b50
0c421f5f5a5725b9443dc28b55c5e0d4eabd9664
refs/heads/master
<repo_name>garyHuang/dragon<file_sep>/dragon-comm/src/main/java/org/dragon/beans/GenerateSqlUtils.java package org.dragon.beans; import java.beans.PropertyDescriptor; import java.io.Serializable; import java.lang.reflect.Field; import java.util.List; import java.util.Map; import java.util.Vector; import org.apache.commons.lang3.StringUtils; import org.dragon.annotations.ID; import org.dragon.annotations.Table; import org.dragon.logs.LogManager; import org.dragon.reflect.BeanUtils; import org.dragon.reflect.FieldUtils; /** * @author Gary * */ public class GenerateSqlUtils implements Serializable{ protected static final String SQL_SEPARATOR = ","; private static final long serialVersionUID = -92006765081491278L; protected Entity entity = new Entity() ; protected List<Object>params = new Vector<Object>(); public GenerateSqlUtils(Class<? extends Object> targetClass){ entity.setTableName( getTableName(targetClass) ) ; List<PropertyDescriptor> descriptors = BeanUtils.getDescriptors( targetClass ); for(PropertyDescriptor descriptor : descriptors){ String fieldName = descriptor.getDisplayName(); Field targetField = FieldUtils.getTargetField(targetClass, fieldName ) ; ID idAnnotation = targetField.getAnnotation(ID.class); entity.addColumn( descriptor.getDisplayName() , null ); if(idAnnotation==null){ entity.addColumn(fieldName, null); }else{ entity.setPkName( fieldName ) ; entity.addColumn(fieldName, null) ; } } } public GenerateSqlUtils(Object target){ generateEntity( target ); } /** * @param target * */ private void generateEntity(Object target) { Class<? extends Object> targetClass = target.getClass(); List<PropertyDescriptor> descriptors = BeanUtils.getDescriptors( target.getClass() ); for(PropertyDescriptor descriptor : descriptors){ String fieldName = descriptor.getDisplayName() ; Field targetField = FieldUtils.getTargetField(targetClass, fieldName) ; ID idAnnotation = targetField.getAnnotation(ID.class); if(null == idAnnotation){ entity.addColumn( fieldName , FieldUtils.getValueObj(target, targetField ) ); }else{ entity.setPkName( fieldName ); entity.setPkValue( FieldUtils.getValueObj(target, targetField ) ) ; } } String tableName = getTableName(targetClass); entity.setTableName( tableName ); } private String getTableName(Class<? extends Object> targetClass) { Table tableAnnotation = targetClass.getAnnotation( Table.class ); String tableName = targetClass.getName() ; if(null != tableAnnotation){ if(!StringUtils.isBlank(tableAnnotation.name())){ tableName = tableAnnotation.name(); } } return tableName; } /** * 获取更新语句 * */ public String getUpdateSql(){ StringBuffer sqlBuffer = new StringBuffer(); sqlBuffer.append("UPDATE ").append(entity.getTableName()).append(" SET "); List<String>sets = new Vector<String>(); for(String column:entity.getColumns()){ sets.add(String.format("%s = ?", column)); params.add( entity.getNameParam().get( column ) ); } sqlBuffer.append( StringUtils.join(sets , SQL_SEPARATOR ) ); sqlBuffer.append(" WHERE ").append( entity.getPkName() ).append(" = ?"); params.add( entity.getPkValue() ); LogManager.log("sql:" + sqlBuffer); return sqlBuffer.toString() ; } public String getDeleteSql(){ StringBuffer sqlBuffer = new StringBuffer(); sqlBuffer.append("DELETE FROM ") .append(entity.getTableName()) .append(" WHERE ") .append( entity.getPkName() ) .append(" = ?") ; LogManager.log("sql:" + sqlBuffer); return sqlBuffer.toString() ; } public String getDeleteSql(Map<String,?> whereMap){ StringBuffer sqlBuffer = new StringBuffer(); sqlBuffer.append("DELETE FROM ") .append(entity.getTableName()) .append(" WHERE " ) ; List<String>where = new Vector<String>(); for(String column:whereMap.keySet() ){ where.add(String.format("%s = ?", column)); params.add( whereMap.get(column) ); } sqlBuffer.append( StringUtils.join(where , SQL_SEPARATOR ) ); LogManager.log("sql:" + sqlBuffer); return sqlBuffer.toString() ; } /** * @param setMap * @param whereMap * */ public String getUpdateSql(Map<String,?> setMap , Map<String,?> whereMap){ StringBuffer sqlBuffer = new StringBuffer(); sqlBuffer.append("UPDATE ").append(entity.getTableName()).append(" SET "); List<String>sets = new Vector<String>(); for(String column:setMap.keySet() ){ sets.add(String.format("%s = ?", column)); params.add( setMap.get(column) ); } sqlBuffer.append( StringUtils.join(sets , SQL_SEPARATOR ) ); List<String>where = new Vector<String>(); for(String column:whereMap.keySet() ){ where.add(String.format("%s = ?", column)); params.add( whereMap.get(column) ); } sqlBuffer.append(" WHERE ") ; sqlBuffer.append( StringUtils.join( where , SQL_SEPARATOR ) ); LogManager.log("sql:" + sqlBuffer); return sqlBuffer.toString() ; } public String getQueryForPk(){ StringBuffer buffer = new StringBuffer() ; buffer.append("SELECT "); buffer.append( StringUtils.join( entity.getColumns() , SQL_SEPARATOR ) ); buffer.append(" FROM ").append( entity.getTableName() ); buffer.append(" WHERE ").append( entity.getPkName() ) .append(" = ?") ; LogManager.log("sql:" + buffer); return buffer.toString() ; } public Entity getEntity() { return entity; } public List<Object> getParams() { return params; } } <file_sep>/dragon-comm/src/main/java/org/dragon/reflect/FieldUtils.java package org.dragon.reflect; import java.lang.reflect.Field; import java.util.Map; /** * @author GaryHuang * @date 2016��6��28�� 18:14:35 * @mail <EMAIL> * */ public class FieldUtils { public static Field getTargetField(Class<?> targetClass, String fieldName) { Field field = null; try { if (targetClass == null) { return field; } if (Object.class.equals(targetClass)) { return field; } field = org.apache.commons.lang3.reflect.FieldUtils .getDeclaredField(targetClass, fieldName, true); if (field == null) { field = getTargetField(targetClass.getSuperclass(), fieldName); } } catch (Exception e) { } return field; } public static Object getValueObj(Object o, String field) { if (o == null) return null; Object value = null; if (o instanceof Map<?, ?>) { Map<?, ?> map = (Map<?, ?>) o; value = map.get(field); } else { try { value = org.apache.commons.lang3.reflect.FieldUtils.readField( getTargetField(o.getClass(), field), o, true); } catch (Exception e) { } } return value; } public static Object getValueObj(Object o,Field field) { try { return org.apache.commons.lang3.reflect.FieldUtils.readField( field, o, true); } catch (Exception e) { e.printStackTrace(); } return null ; } public static void setValueObj(Object o, String fieldName,Object value) { Field field = getTargetField(o.getClass() , fieldName); try { org.apache.commons.lang3.reflect.FieldUtils.writeField(field, o, value, true ); } catch (Exception e) { } } } <file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>gary-core</groupId> <artifactId>gary-parent</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>pom</packaging> <modules> <module>gary-comm</module> <module>dragon-comm</module> <module>dragon-jdbc</module> <module>dragon-web</module> <module>dragon-service</module> <module>dragon-service-inter</module> </modules> <properties> <!-- spring版本 --> <spring-version>4.2.5.RELEASE</spring-version> <redis-version>2.5.2</redis-version> <spring-session-version>1.2.2.RELEASE</spring-session-version> <dragon-version>0.0.1-SNAPSHOT</dragon-version> <dubbo-version>2.5.3</dubbo-version> <aspectjrt-version>1.8.9</aspectjrt-version> <spring-data-redis-version>1.5.2.RELEASE</spring-data-redis-version> </properties> <dependencies> <!-- spring 上下文 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring-version}</version> </dependency> <!-- spring core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring-version}</version> </dependency> <!-- spring jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring-version}</version> </dependency> <!-- spring mvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring-version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring-version}</version> </dependency> <!-- spring session --> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> <version>${spring-session-version}</version> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session</artifactId> <version>${spring-session-version}</version> </dependency> <!-- spring redis --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>${spring-data-redis-version}</version> </dependency> <!-- 链接数据库 相关jar包--> <dependency> <groupId>org.mariadb.jdbc</groupId> <artifactId>mariadb-java-client</artifactId> <version>1.5.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- apache 小工具 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.2.1</version> </dependency> <!-- apache 小工具 --> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.9.1</version> </dependency> <!-- apache 小工具 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency> <!-- 阿里巴巴,快速Json --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.17</version> </dependency> <!-- redis - client --> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency> <!-- dubbo包,导入dubbo会自动导入一个spring的包,这里需要把这个包排除 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>dubbo</artifactId> <version>${dubbo-version}</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> </exclusion> <exclusion> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.20.0-GA</version> </dependency> <!-- zookper 客户端 --> <dependency> <groupId>com.101tec</groupId> <artifactId>zkclient</artifactId> <version>0.9</version> </dependency> <!-- spring aop 相关包 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${aspectjrt-version}</version> </dependency> <!-- spring aop 相关包 --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectjrt-version}</version> </dependency> <!-- jstl相关 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> </dependencies> </project><file_sep>/dragon-service/src/main/java/com/dragon/dao/impl/RedisDaoImpl.java package com.dragon.dao.impl; import java.util.HashMap; import java.util.Map; import org.dragon.reflect.BeanUtils; import org.dragon.utils.ConvertUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.BoundHashOperations; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.serializer.RedisSerializer; import com.dragon.dao.RedisDao; public class RedisDaoImpl implements RedisDao{ @Autowired protected StringRedisTemplate stringRedisTemplate = null ; @Autowired protected RedisTemplate<String, Object> redisTemplate; private RedisSerializer<String> getRedisSerializer() { return stringRedisTemplate.getStringSerializer() ; } public String get(final String keyId){ return stringRedisTemplate.execute(new RedisCallback<String>() { public String doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = getRedisSerializer(); byte[] key = serializer.serialize( keyId ); byte[] result = connection.get(key) ; return serializer.deserialize( result ) ; } }); } public boolean delete(String key) { stringRedisTemplate.delete(key) ; return true ; } public boolean set(final String key,final String value) { return stringRedisTemplate.execute(new RedisCallback<Boolean>() { public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = getRedisSerializer() ; if(null == get(key)){ return connection.setNX(serializer.serialize(key) , serializer.serialize(value) ) ; }else{ connection.set(serializer.serialize(key) , serializer.serialize(value) ); return true ; } } }) ; } public boolean set(String head, String key, Object value) { Map<String, String> beanToMap = BeanUtils.beanToMapString( value ); String allKey = String.format("%s_%s", head , ConvertUtils.trimString(beanToMap.get( key )) ); BoundHashOperations<String, Object, Object> boundHashOps = stringRedisTemplate.boundHashOps( allKey ) ; boundHashOps.putAll( beanToMap ) ; return true ; } public Map<String,String> get(String head,String key) { final String allKey = String.format("%s_%s", head , key ) ; return stringRedisTemplate.execute(new RedisCallback<Map<String,String>>() { public Map<String,String> doInRedis(RedisConnection connection) throws DataAccessException { Map<String,String> keyValue = new HashMap<String, String>(); byte[] key = getRedisSerializer().serialize( allKey ) ; if(connection.exists(key)){ Map<byte[], byte[]> hGetAll = connection.hGetAll( key ); for(byte[] keyBytes : hGetAll.keySet()){ keyValue.put(getRedisSerializer().deserialize(keyBytes) , getRedisSerializer().deserialize(hGetAll.get(keyBytes)) ); } } return keyValue; } }) ; } public static void main(String[] args) { ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:spring-data-redis.xml") ; RedisDaoImpl redisDao = applicationContext.getBean( RedisDaoImpl.class ) ; System.out.println( redisDao.get("user", "1") ) ; applicationContext.close(); } } <file_sep>/dragon-comm/src/main/java/org/dragon/models/EntityBase.java package org.dragon.models; import java.io.Serializable; import org.dragon.annotations.ID; public class EntityBase<PK> implements Serializable{ private static final long serialVersionUID = 7279926465474652996L; @ID protected PK id ; public PK getId() { return id; } public void setId(PK id) { this.id = id; } } <file_sep>/Dragon.java public static void main(String[]args){ System.out.println("add"); } <file_sep>/dragon-comm/src/main/java/org/dragon/dialects/MySqlDialect.java package org.dragon.dialects; public class MySqlDialect implements Dialect { @Override public String getLimitString(String sql, int offset, int rows) { return String.format("%s LIMIT %d,%d", sql, offset, rows); } }<file_sep>/dragon-comm/src/main/java/org/dragon/utils/JsonParser.java package org.dragon.utils; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; public class JsonParser { /** * 将JSON转换成为List<Map<String, Object>>格式 * @param json json字符串 * @return List<Map<String, Object>>返回数据 * */ public static List<Map<String, Object>> parseToList(String json) { JSONArray jsonArray = null; try { jsonArray = JSONArray.parseArray( json ); } catch (Exception e) { } return parseToMaps(jsonArray); } /** * 将JSON转换成为Map<String, Object>格式 * @param json json字符串 * @return Map<String, Object>返回数据 * */ public static Map<String, Object> parseToObj(String json) { JSONObject jSONObject = null; try { jSONObject = JSONObject.parseObject( json ); } catch (Exception e) { e.printStackTrace(); } return parseToMap(jSONObject); } protected static Map<String, Object> parseToMap(JSONObject obj) { Map<String, Object> map = new HashMap<String,Object>(); if(null == obj){ return map ; } try { obj.forEach((key , value) -> { if (value instanceof JSONArray) { map.put(key, parseToMaps((JSONArray) value)); } else if (value instanceof JSONObject) { map.put(key, parseToMap((JSONObject) value)); } else { map.put(key, ConvertUtils.toStr(value)); } }); } catch (Exception e) { } return map; } protected static List<Map<String, Object>> parseToMaps(JSONArray jsonArray) { List<Map<String, Object>> maps = new Vector<Map<String, Object>>(); if(null == jsonArray){ return maps ; } try { jsonArray.forEach((data) -> { if (data instanceof JSONObject) { maps.add(parseToMap((JSONObject) data)); } }); } catch (Exception e) { } return maps; } } <file_sep>/dragon-web/src/main/java/com/dragon/utils/UrlConstant.java package com.dragon.utils; public class UrlConstant { public static final String LOGIN_URL = "admin/p_login" ; public static final String LOGIN_JSP = "admin/login" ; } <file_sep>/dragon-web/src/main/java/com/dragon/admin/service/AdminMainService.java package com.dragon.admin.service; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.dragon.utils.ConvertUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.alibaba.fastjson.JSON; import com.dragon.entity.SysUser; import com.dragon.service.SysPermissionService; import com.dragon.utils.ContextUtils; @Component("admin_main") @SuppressWarnings("unchecked") public class AdminMainService { @Autowired protected SysPermissionService sysPermissionService ; public String menu(Map<String,Object> data){ SysUser sysUser = (SysUser) ContextUtils.getSession().getAttribute("sysUser"); List<Map<String, Object>> datas = sysPermissionService.queryUserPer( sysUser.getId() ) ; Map<Integer , Map<String,Object>> parents = new HashMap<Integer, Map<String,Object>>(); datas.stream().forEach((item) -> { Integer pid = ConvertUtils.toInt( item.get("pid") ) ; item.remove("createDate"); if(pid == 0){ parents.put(ConvertUtils.toInt( item.get("id") ) , item ) ; }else{ List<Map<String, Object>> subData = (List<Map<String, Object>>) parents.get(pid).get("menus"); if(null == subData){ subData = new ArrayList<Map<String, Object>>(); parents.get(pid).put( "menus" , subData); } subData.add( item ) ; } }); return JSON.toJSONString( parents.values() ) ; } } <file_sep>/dragon-dubbo/src/main/resources/config.properties jdbc.url=jdbc:mysql://local01:3310/dragon?autoReconnect=true&characterEncoding=UTF-8 jdbc.driver=org.mariadb.jdbc.Driver jdbc.username=dragon jdbc.password=<PASSWORD><file_sep>/dragon-comm/src/main/java/org/dragon/utils/DateUtils.java package org.dragon.utils; import java.util.Date; public class DateUtils { public static Date parseYYYYMMDD(String dateStr){ try { return org.apache.commons.lang3.time.DateUtils.parseDate(dateStr, "yyyy-MM-dd"); } catch (Exception e) { } return null; } public static Date parseYYYYMMDD0(String dateStr){ try { return org.apache.commons.lang3.time.DateUtils.parseDate(dateStr + " 00:00:00", "yyyy-MM-dd HH:mm:ss"); } catch (Exception e) { } return null; } public static Date parseYYYYMMDD23(String dateStr){ try { return org.apache.commons.lang3.time.DateUtils.parseDate(dateStr + " 23:59:59", "yyyy-MM-dd HH:mm:ss"); } catch (Exception e){ } return null; } } <file_sep>/dragon-service/src/main/java/com/dragon/dao/RedisDao.java package com.dragon.dao; public interface RedisDao { } <file_sep>/dragon-comm/src/main/java/org/dragon/logs/LogManager.java package org.dragon.logs; import org.apache.log4j.Logger; public class LogManager { static Logger logger = Logger.getLogger(LogManager.class); public static void info(Object msg) { logger.info(msg); } public static void log(Object msg){ logger.info(msg); } public static void err(Object msg) { logger.info(msg); if (msg == null) { return; } if (msg instanceof Throwable) { Throwable t = (Throwable) msg; logger.error("", t); } } public static void err(Object msg , Throwable throwable) { logger.error(msg, throwable); } } <file_sep>/dragon-comm/src/main/java/org/dragon/utils/RandomUtils.java package org.dragon.utils; import java.security.SecureRandom; public class RandomUtils { public static Integer getInt(){ return new SecureRandom().nextInt(); } } <file_sep>/dragon-service/src/main/java/com/dragon/dao/SysUserDao.java package com.dragon.dao; import org.dragon.dao.BaseDao; import com.dragon.entity.SysUser; public interface SysUserDao extends BaseDao<SysUser, Integer> { } <file_sep>/dragon-comm/src/main/java/org/dragon/beans/Entity.java package org.dragon.beans; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeSet; public class Entity implements Serializable { private static final long serialVersionUID = 4129470023128587348L; private String tableName; private String pkName ; public Map<String, Object> getNameParam() { return nameParam; } private Object pkValue ; public Object getPkValue() { return pkValue; } public void setPkValue(Object pkValue) { this.pkValue = pkValue; } protected Set<String> columns = new TreeSet<String>(); protected Map<String,Object> nameParam = new HashMap<String, Object>(); public void addColumn(String column , Object value){ columns.add( column ); nameParam.put(column , value); } public Set<String> getColumns() { return columns; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public String getPkName() { return pkName; } public void setPkName(String pkName) { this.pkName = pkName; } @Override public String toString() { return "Entity [tableName=" + tableName + ", pkName=" + pkName + ", pkValue=" + pkValue + ", columns=" + columns + ", nameParam=" + nameParam + "]"; } } <file_sep>/README.md # dragon项目说明 ## dragon-comm 通用的工具项目 ## dragon-dubbo 实体,dao 和service存放项目,需要在tomcat中启动 ## dragon-service 只存放 service的接口 ## dragonweb jsp 静态图片,Action存放位置 ## 使用技术 spring-jdbc,spring-core,spring-mvc,dubbo,redis,spring-redis-session <file_sep>/config/创建表.sql /* SQLyog Ultimate v11.11 (64 bit) MySQL - 5.5.5-10.1.17-MariaDB : Database - dragon ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; DROP TABLE IF EXISTS `sys_grepu_per`; CREATE TABLE `sys_grepu_per` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id', `groupId` int(11) DEFAULT '0' COMMENT '组ID', `permissionId` int(11) DEFAULT NULL COMMENT '权限id', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `sys_grepu_per` */ /*Table structure for table `sys_group` */ DROP TABLE IF EXISTS `sys_group`; CREATE TABLE `sys_group` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id', `gname` varchar(80) DEFAULT '' COMMENT '权限组名称', `remark` varchar(150) DEFAULT '' COMMENT '描述', `createdate` datetime DEFAULT NULL COMMENT '创建时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `sys_group` */ /*Table structure for table `sys_permission` */ DROP TABLE IF EXISTS `sys_permission`; CREATE TABLE `sys_permission` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id', `menuname` varchar(80) DEFAULT '' COMMENT '菜单名称', `icon` varchar(30) DEFAULT 'icon-nav' COMMENT '菜单图标', `url` varchar(120) DEFAULT '' COMMENT 'url', `pid` int(11) DEFAULT '0' COMMENT '父ID', `createDate` datetime DEFAULT NULL COMMENT '创建时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `sys_permission` */ /*Table structure for table `sys_user` */ DROP TABLE IF EXISTS `sys_user`; CREATE TABLE `sys_user` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID', `loginName` varchar(30) DEFAULT '' COMMENT '登录名称', `pwd` varchar(64) DEFAULT '' COMMENT '密码', `phone` varchar(20) DEFAULT '' COMMENT '手机号码', `email` varchar(80) DEFAULT '' COMMENT '邮箱账号', `createDate` datetime DEFAULT NULL COMMENT '系统时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; /*Data for the table `sys_user` */ insert into `sys_user`(`id`,`loginName`,`pwd`,`phone`,`email`,`createDate`) values (1,'admin','123456','12','122','2016-09-20 14:24:23'); /*Table structure for table `sys_user_group` */ DROP TABLE IF EXISTS `sys_user_group`; CREATE TABLE `sys_user_group` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id', `userid` int(11) DEFAULT NULL COMMENT '管理员id', `groupid` int(11) DEFAULT NULL COMMENT '组id', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `sys_user_group` */ /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; <file_sep>/dragon-comm/src/main/java/org/dragon/utils/Pager.java package org.dragon.utils; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import org.dragon.sqls.Condition; public class Pager implements Serializable{ private static final long serialVersionUID = 5721192875321132646L; private int pageId = 1; private int total ; private int totlePage ; private int pageSize = 15 ; private int fristRow ; private Object rows ; private boolean everyQueryCount = true ; private List<Condition> conditions = new ArrayList<Condition>(); public int getTotlePage() { return totlePage; } public void setTotlePage(int totlePage) { this.totlePage = totlePage; } public List<Condition> getConditions() { return conditions; } public void addConditions(Condition condition) { this.conditions.add( condition ) ; } public int getPageId() { return pageId; } public void setPageId(int pageId) { this.pageId = pageId; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public int getFristRow() { fristRow = (pageId-1) * pageSize ; return fristRow; } public void setFristRow(int fristRow) { this.fristRow = fristRow; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public Object getRows() { return rows; } public void setRows(Object rows) { this.rows = rows; } public boolean isEveryQueryCount() { return everyQueryCount; } public void setEveryQueryCount(boolean everyQueryCount) { this.everyQueryCount = everyQueryCount; } } <file_sep>/dragon-web/src/main/webapp/WEB-INF/static/dragon.js var dragon = { } dragon.getFullUrl=function(url){ return basePath + url ; } dragon.submitForm = function(from , url , success ){ $(from).form('submit',{ onSubmit:function(){ var flag = $( this ).form('enableValidation').form('validate') ; if(flag){ dragon.progress(true); } return flag ; }, url : dragon.getFullUrl(url) , success : function( data ){ $.messager.progress("close"); var map = $.parseJSON( data ); if( map.success ){ success( map.data ) ; }else{ dragon.warn( map.msg ); } }, onLoadError: function(e){ dragon.warn( "服务器内部错误"); } }) } /*页面跳转*/ dragon.go = function(url){ window.location = dragon.getFullUrl( url ); } /*加载进度条*/ dragon.progress = function(auto){ $.messager.progress({ title:'请稍后', msg:'正在努力加载中...' }); } /*消息框*/ dragon.info = function( msg ){ $.messager.alert("消息框" , msg , 'info' ); } dragon.warn = function( msg ){ $.messager.alert("温馨提示" , msg , 'warning' ); } dragon.show = function(code , msg){ if(code == 0){ dragon.info(msg); }else{ dragon.warn(msg); } } <file_sep>/dragon-comm/src/main/java/org/dragon/dao/impl/BaseDaoImpl.java package org.dragon.dao.impl; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import org.apache.commons.beanutils.BeanUtilsBean2; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.dragon.beans.Entity; import org.dragon.beans.GenerateSqlUtils; import org.dragon.dao.BaseDao; import org.dragon.dialects.Dialect; import org.dragon.logs.LogManager; import org.dragon.sqls.Condition; import org.dragon.utils.ConvertUtils; import org.dragon.utils.Pager; import org.dragon.utils.SqlUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; @SuppressWarnings({"unchecked" , "rawtypes"}) public abstract class BaseDaoImpl<T , PK> implements BaseDao<T, PK>{ @Autowired protected JdbcTemplate jdbc ; @Autowired protected Dialect dialect; Class<T> persistentClass ; Class<PK> pkClass ; /** * 默认构造函数 * */ public BaseDaoImpl(){ persistentClass = (Class<T>)getSuperClassGenricType(getClass(), 0); pkClass = (Class<PK>)getSuperClassGenricType(getClass(), 1); } /** * 插入方法 * @param t 当前插入的对象 * */ public PK insert(T t){ SimpleJdbcInsert insert = new SimpleJdbcInsert(jdbc.getDataSource()); GenerateSqlUtils sqlUtils = new GenerateSqlUtils( t ); Entity entity = sqlUtils.getEntity(); insert.setTableName( entity.getTableName() ); insert.setColumnNames( new ArrayList<String>(entity.getColumns()) ); insert.setGeneratedKeyName( entity.getPkName() ); Number idKey = insert.executeAndReturnKey( entity.getNameParam() ) ; PK convert = ConvertUtils.convert(idKey, pkClass); org.dragon.reflect.FieldUtils.setValueObj(t , entity.getPkName() , convert ) ; return convert ; } /** * 修改一个对象的方法 * @param t 对象 * @param whereMap 条件 * */ public Integer update(T t){ GenerateSqlUtils sqlUtils = new GenerateSqlUtils( t ); String updateSql = sqlUtils.getUpdateSql() ; return jdbc.update( updateSql , sqlUtils.getParams().toArray() ); } /** * 修改一个对象的方法 * @param sql 修改Sql * @param whereMap 条件 * */ public Integer update(String sql , Object...params){ return jdbc.update( sql , params) ; } /** * 修改一个对象的方法 * @param setMap 修改的字段 * @param whereMap 条件 * */ public Integer update(Map<String,?> setMap , Map<String,?> whereMap){ GenerateSqlUtils sqlUtils = new GenerateSqlUtils( persistentClass ); String updateSql = sqlUtils.getUpdateSql(setMap , whereMap ) ; return jdbc.update( updateSql , sqlUtils.getParams().toArray() ); } /** * 根据主键删除 * @param key 主键id * */ public Integer delete(PK key){ GenerateSqlUtils sqlUtils = new GenerateSqlUtils( persistentClass ); return jdbc.update( sqlUtils.getDeleteSql() , key ); } /** * 根据多个参数删除语句 * @param whereMap 根据where删除 * */ public Integer delete(Map<String,?> whereMap){ GenerateSqlUtils sqlUtils = new GenerateSqlUtils( persistentClass ); return jdbc.update( sqlUtils.getDeleteSql(whereMap) , sqlUtils.getParams().toArray() ); } /** * 查询语句 * */ public T get(PK pk) { GenerateSqlUtils sqlUtils = new GenerateSqlUtils( persistentClass ); List<Map<String, Object>> results = jdbc.queryForList(sqlUtils.getQueryForPk() , pk ) ; if(CollectionUtils.isEmpty(results)){ return null ; } Map<String, Object> result = results.get( 0 ) ; T t = null ; try { t = setEntityVal(result); } catch (Exception e) { LogManager.err( String.format("get %s", persistentClass.getSimpleName() ) , e ) ; } return t ; } /** * @desc 获取泛型类型 * @author Gary * @param clazz 获取泛型的类 * @param index 当前获取第几个泛型 * */ protected static Class<Object> getSuperClassGenricType(final Class clazz, final int index) { Type genType = clazz.getGenericSuperclass(); if (!(genType instanceof ParameterizedType)) { return Object.class; } Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if (index >= params.length || index < 0) { return Object.class; } if (!(params[index] instanceof Class)) { return Object.class; } return (Class) params[index]; } /** * 分页查询 * */ @Override public Pager queryPage(Pager pager) { GenerateSqlUtils sqlUtils = new GenerateSqlUtils( persistentClass ); Entity entity = sqlUtils.getEntity( ); String queryAllHead = StringUtils.join(entity.getColumns() , "," ) ; /*创建简单Sql*/ StringBuffer buffer = new StringBuffer( String.format(" from %s" ,entity.getTableName() ) ) ; /*添加where语句*/ List<Object> params = SqlUtils.appendSql(buffer, pager.getConditions()) ; /*添加分页*/ String limitSql = dialect.getLimitString("select " + queryAllHead +buffer.toString() , pager.getFristRow(), pager.getPageSize() ) ; /*jdbc查询*/ List<Map<String, Object>> results = jdbc.queryForList( limitSql , params.toArray() ) ; List<T> datas = new Vector<T>(); for(Map<String, Object> result:results){ T t = setEntityVal(result); datas.add( t ) ; } /** * 查询数量 * */ Map<String, Object> countMap = jdbc.queryForMap("select count(*) c " + buffer.toString() , params.toArray()); if(!MapUtils.isEmpty(countMap)){ pager.setTotal( ConvertUtils.toInt(countMap.get("c")) ); } pager.setRows( datas ) ; return pager ; } /** * 根据SQL语句查询返回 * @param baseSql 自定义SQL * @param pager 分页对象 * @return List<Map<String, Object>> * */ public List<Map<String, Object>> queryAll(String baseSql , Object...params) { StringBuffer sqlBuffer = new StringBuffer(baseSql); /* 返回结果 */ return jdbc.queryForList( sqlBuffer.toString() , params) ; } /** * 根据SQL语句查询返回 * @param baseSql 自定义SQL * @param pager 分页对象 * @return List<Map<String, Object>> * */ public List<Map<String, Object>> queryPage(String baseSql,Pager pager) { StringBuffer sqlBuffer = new StringBuffer(baseSql); /*添加where语句*/ List<Object> params = SqlUtils.appendSql(sqlBuffer, pager.getConditions()) ; /*添加分页*/ String limitSql = dialect.getLimitString(sqlBuffer.toString() , pager.getFristRow(), pager.getPageSize() ) ; /* 返回结果 */ return jdbc.queryForList( limitSql , params.toArray() ) ; } /** * 蒋值填入T实体中 * */ private T setEntityVal(Map<String, Object> result){ T t = null ; try { t = persistentClass.newInstance(); Iterator<String> iterator = result.keySet().iterator(); while(iterator.hasNext()){ Object v = iterator.next(); if(null == result.get(v)){ iterator.remove(); } } BeanUtilsBean2.getInstance().populate(t, result); } catch (Exception e) { LogManager.err( "BaseDao.setEntityVal" , e ); } return t; } @Override public List<T> query( Condition...conditions) { GenerateSqlUtils sqlUtils = new GenerateSqlUtils( persistentClass ); Entity entity = sqlUtils.getEntity( ); /*创建简单Sql*/ StringBuffer buffer = new StringBuffer( String.format("select %s from %s" , StringUtils.join(entity.getColumns() , "," ) ,entity.getTableName() ) ) ; /*添加where语句*/ List<Object> params = SqlUtils.appendSql(buffer, Arrays.asList(conditions)) ; List<Map<String, Object>> results = jdbc.queryForList( buffer.toString() , params.toArray() ); List<T> datas = new Vector<T>(); results.forEach((result)->{ T t = setEntityVal(result); datas.add( t ) ; }); return datas; } @Override public T queryItem(Condition...conditions) { GenerateSqlUtils sqlUtils = new GenerateSqlUtils( persistentClass ); Entity entity = sqlUtils.getEntity( ); /*创建简单Sql*/ StringBuffer buffer = new StringBuffer( String.format("select %s from %s" , StringUtils.join(entity.getColumns() , "," ) ,entity.getTableName() ) ) ; /*添加where语句*/ List<Object> params = SqlUtils.appendSql(buffer, Arrays.asList(conditions)) ; List<Map<String, Object>> results = jdbc.queryForList( buffer.toString() , params.toArray() ); T t = null ; if(!CollectionUtils.isEmpty(results)){ t = setEntityVal(results.get(0)) ; } return t ; } }
ad2bd5a3fc249a0eb63f00691c8e518e3400d8dc
[ "SQL", "Markdown", "JavaScript", "Maven POM", "INI", "Java" ]
22
Java
garyHuang/dragon
b45d9b670fc9946513bfdc81f8f2149fd1a99621
fccaf953b17c66edd81c237c6a1885c23ccd39fa
refs/heads/master
<repo_name>siusivilla/dev-training<file_sep>/Robofriends/src/components/Scroll.js import React from 'react'; const Scroll =(props) => { // wrap component return ( //{{}} codice css passato nell'oggetto <div style={{overflowY:'scroll', border: '1px solid black', height: '400px'}}> {props.children} </div> ); } export default Scroll;<file_sep>/README.md # My personal training Esercizi e progetti per i corsi Udemy - Zero to Mastery - Landing Page <file_sep>/Robofriends/src/components/SearchBox.js import React from 'react'; const SearchBox =({searchChange}) => { // devo restituire sempre e solo un unico elemento quindi creo il div return ( <div className='pa2'> <input className='pa3 ba b--green bg-lightest-blue' type='search' placeholder='Trova Robots' onChange={searchChange} //funzione richiamata al cambiamento del campo /> </div> ) } export default SearchBox;
23e8bcbc04b94f6048b36c85272d0e1c8cca84e2
[ "JavaScript", "Markdown" ]
3
JavaScript
siusivilla/dev-training
94f23d2755843a2ac6f1500e10c1d8cd4b99431e
4b22eb9125476d00888bf3e9cc16289ab104c604
refs/heads/master
<repo_name>sadminriley/megapyoriginal<file_sep>/README.md # megapy A python wrapper to make the MegaCLI tool more user friendly, and the commands easier to remember. # MegaPy Usage ``` MegaPy v.1 usage: megapy.py [-h] [--enclosure ENCL] [--physical PHYS] [--vdrive VDRIVE] [--controller CONTROL] A wrapper to make MegaCLI commands more user friendly and easier to remember optional arguments: -h, --help show this help message and exit --enclosure ENCL View the servers enclosure information --physical PHYS View the servers physical drive information --vdrive VDRIVE View the servers virtual drive information --controller CONTROL View the servers controller information ``` <file_sep>/megapy.py #!/usr/bin/python import sh import os import subprocess import argparse __version__ = 'MegaPy v.1' __author__ = 'Riley - <EMAIL>' megapath = "/opt/MegaCli/" megadir = os.path.dirname(megapath) megainstall = ['/usr/bin/yum', 'install', 'imh-megapkg', '-y'] def main(): if not os.path.exists(megadir): install = raw_input('MegaCLI does not exist on this server! Would you like ' + 'to install it now?(yes/no): ').lower() if install in ('yes', 'y'): subprocess.Popen(megainstall) if install in ('no', 'n'): print('Closing....') else: print('Please enter yes or no. Closing...') if os.path.exists(megadir): print __version__ ''' Entry point for arguments. Parsing those arguments ''' parser = argparse.ArgumentParser(description='A wrapper to make MegaCLI commands more ' + ' user friendly and easier to remember' ) parser.add_argument('--enclosure', help='View the servers enclosure information', dest='encl' ) parser.add_argument('--physical', help='View the servers physical drive information', dest='phys' ) parser.add_argument('--vdrive', help='View the servers virtual drive information', dest='vdrive' ) parser.add_argument('--controller', help='View the servers controller information', dest='control' ) args = parser.parse_args() if __name__ == '__main__': main()
c9f173859ce235362994a5a0adb1c7371fc27933
[ "Markdown", "Python" ]
2
Markdown
sadminriley/megapyoriginal
07c464697fb7cd8a3bd86f62b3fa7bf147039930
fd099710b538e8256059ddc2eb89cf0699054ffb
refs/heads/master
<repo_name>chintanpatelqa/PathFactoryAssignment<file_sep>/ReadMe.MD # LOGIN TEST #### Installation * You need to have Java8 JDK installed and update the PATH Environment Variable. * Download the latest Eclipse IDE for Java Developers and add Installed JREs. * Download latest Maven. - Add the path to Maven bin directory to the PATH environment variable. - Configure Maven - C:\Users\<Name>\.m2 folder - Install "Maven Integration for Eclipse (Luna and newer) 1.5" & configure Maven plugin(m2e) for Eclipse. #### Framework Architecture * Login_Test *src/main/java *com.ap.qa.base *TestBase.java - Java file to execute the test cases in the xml file. *com.ap.qa.config *configuration.properties- The Properties class provides methods to get data from the properties file and store data into the properties file *com.ap.qa.ExtentReportListener- The ExtentReports object is used to generate an HTML report in the specified location. The path of the report is given as an argument in the ExtentReports constructor. *com.ap.qa.pages- Page classes for UI *ForgotPwPg.java *HomePage.java *LoginPage.java *MyAccountPg.java *com.ap.qa.testdata *LoginTest.xlsx- Scenarios and data used to validate the test cases are saved in this excel file. *com.ap.qa.util *src/test/java *com.ap.qa.testcases *HomePageTest.java- contains Home webpage testcases *LoginPageTest.java- contains Login webpage testcases with negative scerios and forgot password scenario *MyAccount.java- contains My Account testcases *src/main/resources *testng.xml- It is configuration file in TestNG. It is used to define test suites and tests. It is also used to pass Parameters to the test methods. *test-output - After the execution of testcases, Extent reports are saved in this folder *pom.xml - xml file to add/update the dependencies of the project. #### Technologies used Java,TestNG, Maven, Selenium Webdriver. #### Framework used Page Object Model #### Running test - Run testng.xml in src/main/resources as java application to execute the testcases. - Update the arguments in the testng.xml file. - In testng.xml file we can specify multiple name (s) which needs to be executed.We need to run the testng.xml file. (Right click on testng.xml and select Run as ‘TestNG Suite”)<file_sep>/src/test/java/com/ap/qa/testcases/HomePageTest.java package com.ap.qa.testcases; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.ap.qa.base.TestBase; import com.ap.qa.pages.HomePage; import com.ap.qa.pages.LoginPage; /** * * @author Chintan * */ public class HomePageTest extends TestBase { HomePage homePg; LoginPage loginPg; public HomePageTest() { super(); } @BeforeMethod public void setUp() { initialization(); driver.get(prop.getProperty("url")); homePg = new HomePage(); } @Test(priority = 1) public void HomePageTitleTest() { String title = homePg.validateHomePageTitle(); Assert.assertEquals(title, "My Store"); } @Test(priority = 1) public void ClickSignIn() throws Throwable { captureScreenShot(); homePg.SignInButton().click(); } @AfterMethod public void tearDown() { driver.quit(); } }
60635ba4f23984eb92b21574dea0a059470d9700
[ "Markdown", "Java" ]
2
Markdown
chintanpatelqa/PathFactoryAssignment
937b0210483148e1802ed311fc43841d674d9c79
fafdf73300b3c9419450bd30977f71846c9082be
refs/heads/master
<repo_name>alukart32/Numeric_Method_Lab_3_Depletion_Direct_Method<file_sep>/src/DepletionMethod.java import static java.lang.Math.abs; public class DepletionMethod { TestMatrix testMatrix; double La; // собственное значение (сигма) Matrix X; // собственный вектор-столбец (ню) Matrix XSubExactX; // оценка точности собств. векторов double m; int iterations; // произведенное количество итераций double Accuracy; double lambdaSubExactLambda; // оценка точности собств. значений private double epsLa; // точность определения собств значения private double epsX; // точность опр. собств вектора private int limit; // максимально допустимое число итераций public DepletionMethod() { } public DepletionMethod(double epsLa, double epsX, int iterationsLimit) { this.epsLa = epsLa; this.epsX = epsX; this.limit = iterationsLimit; iterations = 0; Accuracy = La = 0.0; } public void solve(int N, int range, boolean DEBUG_MSG) { testMatrix = new TestMatrix(N); // инициализация объекта testMatrix.createTestData(range, N); // создаем тестовые данные // выделяем память X = new Matrix(N, 1); Matrix xn = new Matrix(N, 1); xn.fill(range); // рандомный начальный вектор double prevLa = 0.0; // предыдущее собственное значение Matrix prevX = new Matrix(N, 1); // предыдущий собственнный вектор Matrix r = new Matrix(N, 1); for (iterations = 0; iterations < limit; iterations++) { xn.normalize(); X = xn; xn = testMatrix.A.mul(X); r = X.transpose().mul(xn); La = r.getCells(0,0); r = ( X.absolute().sub(prevX.absolute()) ).absolute(); // выходим, если достигли точности m = Matrix.maximum(r); if (abs(La - prevLa) < epsLa && m < epsX) /// max|x(K+1)i - x(iterations)i| // maximum((X.absolute() - prevX.absolute()).absolute()) < epsX) break; prevLa = La; prevX = X; } /// мера точности Accuracy = max|(A*x)i - (La*x)i| - R Matrix t = new Matrix(X); t.mul(La); Accuracy = Matrix.maximum((testMatrix.A.mul(X).sub(t)).absolute()); lambdaSubExactLambda = abs(La - testMatrix.getMaxExactLa()); XSubExactX = ((X.absolute().sub(testMatrix.getMaxExactX().absolute())).absolute()); // // if (DEBUG_MSG) // { // System.out.println("Iterations = " + (iterations + 1)); // System.out.println("Accuracy = " + Accuracy + "\n"); // // System.out.println("La = \n" + La ); // System.out.println(testMatrix.getMaxExactLa()); // System.out.println("X = "); // X.show(); // System.out.println("\nExactX ="); // testMatrix.showMaxExactX(); // System.out.println(); // // System.out.println(" |Lambda - exactLambda| = " + abs(La - testMatrix.getMaxExactLa()) + "\n"); // System.out.println("|X - exactX| = \n"); // ((X.absolute().sub(testMatrix.getMaxExactX().absolute())).absolute()).show(); // } } public Matrix getXSubExactX() { return XSubExactX; } public int getIterations() { return iterations; } public double getAccuracy() { return Accuracy; } public Matrix getX() { return X; } public double getM() { return m; } public Matrix getExactX() { return testMatrix.maxExactX; } public double getLambdaSubExactLambda() { return lambdaSubExactLambda; } private void cleanMemory(){ testMatrix = null; X = null; Accuracy = La = epsLa = epsX = 0.0; iterations = limit = 0; } }
463e4b8fb1014c1ff935b0d68c91e6a6d2d1c3c8
[ "Java" ]
1
Java
alukart32/Numeric_Method_Lab_3_Depletion_Direct_Method
4d5e3a7c049aa8d78c1f77e0cc100a94bd136ba3
573450555df4a0b0e125e01b6670368cd2577429
refs/heads/main
<file_sep>/* * Student name:<NAME> * * Student number:2940836 */ import java.util.*; public class Assignment1_2018{ public static void main(String args[]){ //test print print(3,6); //======================================== //test sum System.out.println("\n\n" + sum(1,10)); //======================================== //test printBinary printBinary(55); System.out.println(""); printBinary(11); //======================================== } static void print(int a, int b){ //assume a <= b if(a < b){ System.out.print(a); print(a+1,b); } else{ System.out.print(b); } } static int sum(int a, int b){ if(a == b){ return a; } else{ return getSum(a, a+1, b); } } static int getSum(int a, int a0, int b){ if(a0 == b) return a+b; else{ return(getSum(a+a0, a0+1, b)); } } static void printBinary(int x){ if(x > 1){ printBinary(x/2); } if(x % 2 == 0){ System.out.print(0); } else{ System.out.print(1); x--; } } }
5ef1df57704166834f5690f92da4f7964f9a8708
[ "Java" ]
1
Java
CiaranWinna/DSA_Asig_01
b161768a7ba3bb8942f28acf4a63535a5f58f9ef
06b4a3c681295a9f88cdad76830eaf94e082a717
refs/heads/master
<file_sep>using System; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Domaci { public class Imenik { public string Ime { get; set; } public string Broj { get; set; } public string Datum_Dod { get; set; } public Imenik() { } public Imenik(string i, string b) { Ime = i; Broj = b; Datum_Dod = DateTime.Now.ToString("dd:MM:yy - HH:mm"); } } } <file_sep>using System; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; namespace Domaci { public class Metode { static public bool Provera(ObservableCollection<Imenik> Lista,string br, out Imenik i) { foreach (Imenik broj in Lista) { if (broj.Broj == br) { i = broj; return true; } } i = null; return false; } static public bool ProveraBroja(string br) { return Regex.IsMatch(br, @"^[0-9]+$"); } } } <file_sep>using System; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Domaci { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { ObservableCollection<Imenik> Lista = new ObservableCollection<Imenik>(); public MainWindow() { InitializeComponent(); Datagrd1.ItemsSource = Lista; Datagrd2.ItemsSource = Lista; Datagrd3.ItemsSource = Lista; } private void Izbrisi(object sender, RoutedEventArgs e) { Lista.Remove(Datagrd1.SelectedItem as Imenik); Lista.Remove(Datagrd2.SelectedItem as Imenik); } public void Dup(object sender, RoutedEventArgs e) { Imenik SelecItem = (Imenik)Datagrd2.SelectedItem; if (SelecItem == null) { MessageBox.Show("Prvo morate da odaberete kontakt da bi ste ga izmenili!"); } else { ImeII.Text = SelecItem.Ime; BrojII.Text = SelecItem.Broj; } } private void Dodaj(object sender, RoutedEventArgs e) { string tmpIme = ImeI.Text; string tmpBroj = BrojI.Text; if (Metode.Provera(Lista, tmpBroj, out Imenik I)) { MessageBox.Show($"Vec postojeci kontakt sa istim brojem ! > {I.Ime} < "); } else if (tmpIme.Length == 0 || tmpBroj.Length == 0) { MessageBox.Show("Polja ne smeju biti prazna!"); } else if (Metode.ProveraBroja(tmpBroj) == false) { MessageBox.Show("U polju za broj mozete da unesete samo numericke vrednosti!"); } else { Lista.Add(new Imenik(tmpIme, tmpBroj)); ImeI.Text = null; BrojI.Text = null; MessageBox.Show("Uspesno dodat novi kontakt!"); } } private void Izmeni(object sender, RoutedEventArgs e) { string tmpIme = ImeII.Text; string tmpBroj = BrojII.Text; if (Metode.Provera(Lista, tmpBroj, out Imenik I)) { MessageBox.Show($"Vec postojeci kontakt sa istim brojem ! > {I.Ime} < "); } else if (tmpIme.Length == 0 || tmpBroj.Length == 0) { MessageBox.Show("Polja ne smeju biti prazna!"); } else if (Metode.ProveraBroja(tmpBroj) == false) { MessageBox.Show("U polju za broj mozete da unesete samo numericke vrednosti!"); } else { Imenik SelectItem = (Imenik)Datagrd2.SelectedItem; Metode.Provera(Lista, SelectItem.Broj, out Imenik Izmena); Izmena.Ime = tmpIme; Izmena.Broj = tmpBroj; ImeII.Text = null; BrojII.Text = null; } } } }
750dcb7a9a4c348a14d81ee15d86c0980370553b
[ "C#" ]
3
C#
Ame-A/Zadaci_4
36ac2a20d42fc111b4fd72beccf95ad8cdcb9615
d0ba755d73716b26e9c7c970962f984d7ed939fe
refs/heads/master
<file_sep>var fs = require("fs"); var PImage = require("pureimage"); var winston = require("winston"); var colors = [ "#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50", "#f1c40f", "#e67e22", "#e74c3c", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d" ]; function getColor(text) { var idx = text.charCodeAt() % colors.length return colors[idx] } function genTextAvatar(text, outputFilePath, size, callback) { var img = PImage.make(size, size); var ctx = img.getContext('2d'); var font = PImage.registerFont(`${__dirname}/../public/font/SourceSansPro-Regular.ttf`, 'Source Sans Pro'); font.load(function () { ctx.fillStyle = getColor(text); ctx.fillRect(0, 0, size, size); ctx.font = `${size / 1.5}pt 'Source Sans Pro'`; ctx.fillStyle = "#FFFFFF"; ctx.fillText(text.substring(0, 2).toUpperCase(), size / 6, size / 1.4); PImage.encodePNGToStream(img, fs.createWriteStream(outputFilePath)).then(() => { winston.debug(`wrote out the png file to ${outputFilePath}`); callback(outputFilePath) }).catch((e) => { winston.error("there was an error writing", e); callback(emptyOutputFilePath) }); }); } module.exports = { genTextAvatar: genTextAvatar }
957a43c6cbc3a7cf4dc34cf89e9a82f7ca038ba9
[ "JavaScript" ]
1
JavaScript
ejithon/textavatar
27c6648cf6efd07d968931ef2f327e7cb8bdcae6
0df2db0ca583b0d25dbec8c6f51e4bc4fb5c8adc
refs/heads/master
<file_sep>package com.chipkillmar; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.io.ByteArrayOutputStream; import java.util.*; import java.util.Map.Entry; import java.util.stream.Collectors; /** * Outputs a DOT graph showing how HotSpot JVM GC command line options map to different * collector selections in the VM at runtime. * <p> * It creates combinations of GC options, and uses them to construct a command line * for starting an external JVM process that will print actual collector settings to stdout. */ public class GraphCollectors { public static void main(String[] args) { // These are the GC command line options available in the HotSpot JVM. // Generate the power set from all available collector positive and negative command line options. Set<Set<String>> powerSet = Sets.powerSet(new LinkedHashSet<>(Arrays.asList( "-XX:+UseConcMarkSweepGC", "-XX:+UseG1GC", "-XX:+UseParNewGC", "-XX:+UseParallelGC", "-XX:+UseParallelOldGC", "-XX:+UseSerialGC", "-XX:-UseConcMarkSweepGC", "-XX:-UseG1GC", "-XX:-UseParNewGC", "-XX:-UseParallelGC", "-XX:-UseParallelOldGC", "-XX:-UseSerialGC" ))); // Filter in combinations of 1 or 2 command line options. List<Set<String>> collectorOptions = powerSet.stream() .filter(s -> s.size() == 1 || s.size() == 2) .collect(Collectors.toList()); // Filter out combinations of all negative (-XX:-...) command line options. collectorOptions = collectorOptions.stream().filter(options -> { final boolean[] allNegative = {true}; options.forEach(option -> { if (!isNegativeOption(option)) { allNegative[0] = false; } }); return !allNegative[0]; }).collect(Collectors.toList()); // Filter out combinations of negating (-XX:-UseG1GC -XX:+UseG1GC) command line options. collectorOptions = collectorOptions.stream().filter(options -> { if (options.size() == 2) { Iterator<String> iterator = options.iterator(); String option1 = iterator.next(); String option2 = iterator.next(); return !option1.substring("-XX:-".length()).equals(option2.substring("-XX:+".length())); } return true; }).collect(Collectors.toList()); // Build the command to start the JVM. String javaHome = System.getProperty("java.home"); String fileSeparator = System.getProperty("file.separator"); String javaCommand = String.format("%s%sbin%sjava", javaHome, fileSeparator, fileSeparator); // The fully qualified Java main class to execute. String mainClass = PrintGCMXBeanNames.class.getName(); // Maps JVM options to java commands that will invoke a program to print the collector // names via JMX. Map<Set<String>, List<String>> commandMap = Maps.newLinkedHashMap(); collectorOptions.forEach(options -> { List<String> command = Lists.newArrayList(); command.add(javaCommand); options.forEach(command::add); command.add("-classpath"); command.add(System.getProperty("java.class.path")); command.add(mainClass); commandMap.put(options, command); }); // Maps JVM options to runtime collector names. final Map<Set<String>, List<String>> optionsMap = Maps.newLinkedHashMap(); commandMap.forEach((options, command) -> { ProcessBuilder processBuilder = new ProcessBuilder(command); try { Process process = processBuilder.start(); int returnCode = process.waitFor(); if (returnCode == 0) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b; while (-1 != (b = process.getInputStream().read())) { baos.write(b); } List<String> collectorNames = Splitter.on(',').splitToList(baos.toString("UTF-8")); optionsMap.put(options, collectorNames); } // Return code of 1 means the following: // "Conflicting collector combinations in option list; please refer to the release notes for the // combinations allowed // Error: Could not create the Java Virtual Machine. // Error: A fatal exception has occurred. Program will exit." } catch (Exception e) { System.err.println("An unexpected error occurred."); e.printStackTrace(); } }); // Removes sets with negative command line options that don't result in different collectors at runtime. // For example: "java -XX:+UseG1GC -XX:-UseSerialGC" results in the same collectors as "java -XX:+UseG1GC", // so we can remove the former options. Map<Set<String>, List<String>> filteredOptionsMap = optionsMap.entrySet().stream().filter(entry -> { Set<String> options = entry.getKey(); if (options.size() == 2) { // Modify the set, removing the negative options. Set<String> modifiedOptions = Sets.newLinkedHashSet(); modifiedOptions.addAll(options.stream() .filter(option -> !isNegativeOption(option)) .collect(Collectors.toList()) ); // Removes sets with negative options that don't affect the results. return modifiedOptions.size() == 1 && !optionsMap.get(modifiedOptions).equals(optionsMap.get(options)); } else { return true; } }).collect(Collectors.toMap(Entry::getKey, Entry::getValue)); // Prints a DOT directed graph description of JVM collector options to collector names. System.out.println("digraph {"); System.out.println("\tlabel=\"HotSpot JVM Collector Options\";"); System.out.println("\tlabelloc=top;"); System.out.println("\trankdir=LR;"); filteredOptionsMap.forEach((options, names) -> System.out.printf("\t\"%s\" -> \"%s\"\n", Joiner.on(' ').join(options), Joiner.on(", ").join(names)) ); System.out.println("}"); } private static boolean isNegativeOption(String option) { return Strings.nullToEmpty(option).startsWith("-XX:-"); } } <file_sep># HotSpot JVM Collectors # I was curious about how different JVM garbage collector command line options mapped to actual selections in the virtual machine at runtime. _Note: all of my testing was using Oracle JDK 1.8.0_60, but the update number (60 in this case) shouldn't matter._ According to Oracle's GC Tuning Guide, these are the available GC selection command line options: * `-XX:+UseConcMarkSweepGC` * `-XX:+UseG1GC` * `-XX:+UseParallelGC` * `-XX:+UseParallelOldGC` * `-XX:+UseParNewGC` and `-XX:-UseParNewGC` * `-XX:+UseSerialGC` For example, you'd use the following options with the `java` executable for selecting the CMS collector: `java -XX:+UseConcMarkSweepGC -XX:+UseParNewGC` And the JVM would select the `ParNew` young and `ConcurrentMarkSweep` old generation collectors, as named by the `GarbageCollectorMXBean`: `ParNew, ConcurrentMarkSweep` `GraphCollectors` is a short program that [outputs a directed graph](collectors.gv) using the DOT graph language. It creates combinations of GC options, and uses them to construct a command line for starting an external JVM process that prints actual collector settings to stdout. ### Running the program ### Use the following Maven Wrapper command line to run the program, which outputs a graph to stdout: `$ mvnw compile exec:exec` ### Rendering the graph ### You'll need to download and install Graphviz [here](http://www.graphviz.org/Download.php). Render the graph using the following command line: `$ dot -Tpng collectors.gv > collectors.png` ### Results ### ![HotSpot collectors graph](collectors.png "HotSpot collectors graph") There are 7 combinations of GC command line options, mapping to 6 young and old collectors at runtime. This means, for example, that it's not strictly necessary to pass `-XX:+UseConcMarkSweepGC -XX:+UseParNewGC` to select the `ParNew` collector: the JVM will do that by default! ### References ### 1. [HotSpot JVM GC Tuning Guide](https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/collectors.html#sthref28) 2. [MXBean Javadoc](http://docs.oracle.com/javase/8/docs/api/javax/management/MXBean.html) 3. [GarbageCollectorMXBean Javadoc](http://docs.oracle.com/javase/8/docs/api/java/lang/management/GarbageCollectorMXBean.html) 4. [A great blog post by <NAME>](https://blogs.oracle.com/jonthecollector/entry/our_collectors)
c54d7d04bce029a681cd020f686692e53be7cd0b
[ "Markdown", "Java" ]
2
Java
chipkillmar/collectors
5221aaf4eb627a83fd13e7f3b66b2866895d9ab8
84cfd098453d8d71629374242025dea4ba12cb8b
refs/heads/master
<repo_name>Brave-wan/Dagger<file_sep>/app/src/main/java/www/jinke/com/dagger/MainActivity.java package www.jinke.com.dagger; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import javax.inject.Inject; public class MainActivity extends AppCompatActivity { /** * @Inject:这个很简单了,通常是在需要注入的地方添加这个依赖。 * 比如:MainActivity要使用LocalManager实例,那我们就在要使用的地方定义一个成员变量 */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } } <file_sep>/README.md # Dagger Dagger 依赖注入研究,分享 compile 'com.jakewharton:butterknife:7.0.1' compile 'com.facebook.fresco:fresco:0.9.0' compile 'io.reactivex:rxjava:1.1.0' compile 'io.reactivex:rxandroid:1.1.0' compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4' compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4' compile 'com.google.code.gson:gson:2.6.2' compile 'com.squareup.okhttp3:logging-interceptor:3.4.2' compile 'com.yqritc:recyclerview-flexibledivider:1.4.0' compile 'com.jph.takephoto:takephoto_library:4.0.3' compile 'tv.danmaku.ijk.media:ijkplayer-java:0.6.0' compile 'com.dou361.ijkplayer-armv7a:jjdxm-ijkplayer-armv7a:1.0.0' <file_sep>/library/src/main/java/www/jinke/com/library/base/BaseActivity.java package www.jinke.com.library.base; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.FragmentActivity; import android.view.Window; import java.util.LinkedList; import java.util.List; import butterknife.ButterKnife; import www.jinke.com.library.utils.commont.NetWorksUtils; import www.jinke.com.library.utils.commont.ToastUtils; /** * Created by root on 16-11-13. */ public abstract class BaseActivity extends FragmentActivity { //布局文件ID protected abstract int getContentViewId(); protected abstract void initView(); public boolean isConnected = false; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); isConnected = NetWorksUtils.isConnected(this); getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS); setContentView(getContentViewId()); ButterKnife.bind(this); addActivity(this); initView(); } @Override protected void onDestroy() { super.onDestroy(); ButterKnife.unbind(this); } @Override protected void onResume() { super.onResume(); } @Override protected void onPause() { super.onPause(); } private static List<FragmentActivity> mList = new LinkedList<>(); public static void addActivity(FragmentActivity activity) { mList.add(activity); } public static void exit() { try { for (FragmentActivity activity : mList) { if (activity != null) activity.finish(); } mList = null; } catch (Exception e) { e.printStackTrace(); } finally { System.exit(0); } } public void showToast(String msg) { ToastUtils.showShort(BaseActivity.this, msg); } }
0b2d55a43b346c01174bc641d899674d6c9f2c91
[ "Markdown", "Java" ]
3
Java
Brave-wan/Dagger
15d04b44d67e27344900595c6520cd8054de3587
70f4735616548b1754db10655d7b8655b6dc2e8d
refs/heads/master
<file_sep>package mx.edu.iems.inventario.services; import java.util.List; import mx.edu.iems.inventario.dao.AreaDao; import mx.edu.iems.inventario.dao.UsuarioDao; import mx.edu.iems.inventario.model.Area; import mx.edu.iems.inventario.model.Usuario; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Projections; import org.springframework.beans.factory.annotation.Autowired; public class AreaService { @Autowired private AreaDao areaDao; public void setAreaDao(AreaDao areaDao) { this.areaDao = areaDao; } public List<Area> listar(){ return areaDao.list(); } public void insertar(Area u){ areaDao.save(u); } public void actualizar(Area u){ areaDao.update(u); } public void eliminar(Area u){ areaDao.delete(u); } public Area findById(Integer id){ return areaDao.get(id); } public Area findByDescripcion(String descripcion){ return areaDao.buscarAreaPorDescripcion(descripcion); } public List<Area> findByCriteria(DetachedCriteria dc, int from, int size) { Criteria criteria = dc.getExecutableCriteria(areaDao .getSessionFactory().getCurrentSession()); criteria.setFirstResult(from); criteria.setMaxResults(size); return criteria.list(); } public int countByCriteria(DetachedCriteria dc) { Session session = areaDao.getSessionFactory().getCurrentSession(); Transaction t = session.beginTransaction(); Criteria criteria = dc.getExecutableCriteria(session); criteria.setProjection(Projections.rowCount()); int count = ((Long) criteria.list().get(0)).intValue(); return count; } } <file_sep>package mx.edu.iems.inventario.actions.puesto; import mx.edu.iems.inventario.model.Area; import mx.edu.iems.inventario.model.Puesto; import mx.edu.iems.inventario.services.AreaService; import mx.edu.iems.inventario.services.PuestoService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.opensymphony.xwork2.ActionSupport; public class GuardaPuestoAction extends ActionSupport { private static final Logger log = LoggerFactory .getLogger(GuardaPuestoAction.class); private String oper; private String id; private String descripcion; private Area area; // Propiedad que se cargara en el contexto de spring @Autowired private PuestoService puestoService; @Autowired private AreaService areaService; public String getOper() { return oper; } public void setOper(String oper) { this.oper = oper; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public PuestoService getPuestoService() { return puestoService; } public void setPuestoService(PuestoService puestoService) { this.puestoService = puestoService; } public Area getArea() { return area; } public void setArea(Area area) { this.area = area; } public AreaService getAreaService() { return areaService; } public void setAreaService(AreaService areaService) { this.areaService = areaService; } /** * Método por que se ejecuta por default cuando se llama el action * autentificaUsuario */ public String execute() { Puesto p; if (oper.equalsIgnoreCase("add")) { p = new Puesto(); p.setDescripcion(descripcion); Area a = areaService.findById(area.getIdarea()); log.info("[* " + area.getIdarea() + " *]"); p.setArea(a); puestoService.insertar(p); log.info("!Puesto: " + descripcion + " guardado!"); } /*else if (oper.equalsIgnoreCase("edit")) { log.debug("Edit Area"); u = new Area(); u.setIdarea(Integer.parseInt(id)); u.setDescripcion(descripcion); areaService.actualizar(u); log.info("!Area: " + descripcion + " editado!"); } else if (oper.equalsIgnoreCase("del")) { log.debug("Delete Area"); u = areaService.findById(Integer.parseInt(id)); areaService.eliminar(u); log.info("!Area: " + u.getDescripcion() + " eliminado!"); }*/ return SUCCESS; } } <file_sep>package mx.edu.iems.inventario.dao; import java.util.ArrayList; import java.util.List; import mx.edu.iems.inventario.model.Puesto; import mx.edu.iems.inventario.model.Puesto; import mx.edu.iems.inventario.model.Usuario; import mx.edu.iems.inventario.util.HibernateUtil; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class PuestoDao extends GenericDao<Puesto, Integer>{ private static final Logger log = LoggerFactory.getLogger(PuestoDao.class); public List<Puesto> list() { log.info("Se está consultando la tabla Puesto..."); //se utiliza eager para que haga una solo consulta return (List<Puesto>)getHibernateTemplate().find("FROM Puesto p left join fetch p.area a left join fetch a.puestos left join fetch p.empleados"); } public Puesto buscarPuestoPorDescripcion(String descripcion) { String hql = "FROM Puesto WHERE login like '" + descripcion + "%'"; List<Puesto> Puesto = getHibernateTemplate().find(hql); if(!Puesto.isEmpty()) return Puesto.iterator().next(); else return null; } } <file_sep>package mx.edu.iems.inventario.model; // Generated 14/05/2013 11:10:50 PM by Hibernate Tools 3.4.0.CR1 import java.util.HashSet; import java.util.Set; /** * Ubicacion generated by hbm2java */ public class Ubicacion implements java.io.Serializable { private int idubicacion; private String descripcion; private Set nobreaks = new HashSet(0); private Set monitors = new HashSet(0); private Set cpus = new HashSet(0); public Ubicacion() { } public Ubicacion(int idubicacion, String descripcion) { this.idubicacion = idubicacion; this.descripcion = descripcion; } public Ubicacion(int idubicacion, String descripcion, Set nobreaks, Set monitors, Set cpus) { this.idubicacion = idubicacion; this.descripcion = descripcion; this.nobreaks = nobreaks; this.monitors = monitors; this.cpus = cpus; } public int getIdubicacion() { return this.idubicacion; } public void setIdubicacion(int idubicacion) { this.idubicacion = idubicacion; } public String getDescripcion() { return this.descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Set getNobreaks() { return this.nobreaks; } public void setNobreaks(Set nobreaks) { this.nobreaks = nobreaks; } public Set getMonitors() { return this.monitors; } public void setMonitors(Set monitors) { this.monitors = monitors; } public Set getCpus() { return this.cpus; } public void setCpus(Set cpus) { this.cpus = cpus; } } <file_sep>package mx.edu.iems.inventario.dao; import java.util.List; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Projections; import mx.edu.iems.inventario.model.Area; import mx.edu.iems.inventario.model.Usuario; public class UsuarioDao extends GenericDao<Usuario, Integer>{ public List<Usuario> list() { return (List<Usuario>)getHibernateTemplate().find("FROM Usuario a left join fetch a.computadoras left join fetch a.cpus left join fetch a.empleados left join fetch a.monitors" + " left join fetch a.nobreaks "); //return (List<Usuario>)getHibernateTemplate().find("FROM Usuario right join fetch"); } public Usuario buscarUsuarioPorLogin(String login) { String hql = "FROM Usuario WHERE login like '" + login + "%'"; List<Usuario> usuario = getHibernateTemplate().find(hql); if(!usuario.isEmpty()) return usuario.iterator().next(); else return null; } } <file_sep>jdbc.driver = org.postgresql.Driver jdbc.url = jdbc:postgresql://localhost:5432/inventario jdbc.username = kylix jdbc.password = <PASSWORD> <file_sep>package mx.edu.iems.inventario.services; import java.util.List; import mx.edu.iems.inventario.dao.UsuarioDao; import mx.edu.iems.inventario.model.Usuario; import org.hibernate.Criteria; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.DetachedCriteria; import org.hibernate.criterion.Projections; import org.springframework.beans.factory.annotation.Autowired; public class UsuarioService { @Autowired private UsuarioDao usuarioDao; public void setUsuarioDao(UsuarioDao usuarioDao) { this.usuarioDao = usuarioDao; } public List<Usuario> listar(){ return usuarioDao.list(); } public void insertar(Usuario u){ usuarioDao.save(u); } public void actualizar(Usuario u){ usuarioDao.update(u); } public void eliminar(Usuario u){ usuarioDao.delete(u); } public boolean isCorrect(String login, String password){ Usuario u = usuarioDao.buscarUsuarioPorLogin(login); //Checa que el usuario esté en la bd y que ademas coincida el password if (u != null && u.getPassword().equals(password)) return true; else return false; } public Usuario findById(Integer id){ return usuarioDao.get(id); } public Usuario findByLogin(String login){ return usuarioDao.buscarUsuarioPorLogin(login); } public List<Usuario> findByCriteria(DetachedCriteria dc, int from, int size) { Criteria criteria = dc.getExecutableCriteria(usuarioDao .getSessionFactory().getCurrentSession()); criteria.setFirstResult(from); criteria.setMaxResults(size); return criteria.list(); } public int countByCriteria(DetachedCriteria dc) { Session session = usuarioDao.getSessionFactory().getCurrentSession(); Transaction t = session.beginTransaction(); Criteria criteria = dc.getExecutableCriteria(session); criteria.setProjection(Projections.rowCount()); int count = ((Long) criteria.list().get(0)).intValue(); return count; } } <file_sep>package mx.edu.iems.inventario.model; // Generated 14/05/2013 11:10:50 PM by Hibernate Tools 3.4.0.CR1 import java.util.HashSet; import java.util.Set; /** * Estadoequipo generated by hbm2java */ public class Estadoequipo implements java.io.Serializable { private int idestadoequipo; private String descripcion; private Set nobreaks = new HashSet(0); private Set cpus = new HashSet(0); private Set monitors = new HashSet(0); public Estadoequipo() { } public Estadoequipo(int idestadoequipo, String descripcion) { this.idestadoequipo = idestadoequipo; this.descripcion = descripcion; } public Estadoequipo(int idestadoequipo, String descripcion, Set nobreaks, Set cpus, Set monitors) { this.idestadoequipo = idestadoequipo; this.descripcion = descripcion; this.nobreaks = nobreaks; this.cpus = cpus; this.monitors = monitors; } public int getIdestadoequipo() { return this.idestadoequipo; } public void setIdestadoequipo(int idestadoequipo) { this.idestadoequipo = idestadoequipo; } public String getDescripcion() { return this.descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Set getNobreaks() { return this.nobreaks; } public void setNobreaks(Set nobreaks) { this.nobreaks = nobreaks; } public Set getCpus() { return this.cpus; } public void setCpus(Set cpus) { this.cpus = cpus; } public Set getMonitors() { return this.monitors; } public void setMonitors(Set monitors) { this.monitors = monitors; } } <file_sep>package mx.edu.iems.inventario.beans; import java.util.List; import mx.edu.iems.inventario.model.Area; import mx.edu.iems.inventario.services.AreaService; public class ComboAreas{ private String areascombo; public String getAreascombo() { areascombo = "{value:'SI:SI;NO:NO;'}"; return areascombo; } public void setAreascombo(String areascombo) { this.areascombo = areascombo; } } <file_sep>package mx.edu.iems.inventario.model; // Generated 14/05/2013 11:10:50 PM by Hibernate Tools 3.4.0.CR1 import java.util.HashSet; import java.util.Set; /** * Tiponobreak generated by hbm2java */ public class Tiponobreak implements java.io.Serializable { private int idtiponobreak; private String marca; private String modelo; private String observacion; private Set nobreaks = new HashSet(0); public Tiponobreak() { } public Tiponobreak(int idtiponobreak, String marca, String modelo, String observacion) { this.idtiponobreak = idtiponobreak; this.marca = marca; this.modelo = modelo; this.observacion = observacion; } public Tiponobreak(int idtiponobreak, String marca, String modelo, String observacion, Set nobreaks) { this.idtiponobreak = idtiponobreak; this.marca = marca; this.modelo = modelo; this.observacion = observacion; this.nobreaks = nobreaks; } public int getIdtiponobreak() { return this.idtiponobreak; } public void setIdtiponobreak(int idtiponobreak) { this.idtiponobreak = idtiponobreak; } public String getMarca() { return this.marca; } public void setMarca(String marca) { this.marca = marca; } public String getModelo() { return this.modelo; } public void setModelo(String modelo) { this.modelo = modelo; } public String getObservacion() { return this.observacion; } public void setObservacion(String observacion) { this.observacion = observacion; } public Set getNobreaks() { return this.nobreaks; } public void setNobreaks(Set nobreaks) { this.nobreaks = nobreaks; } } <file_sep>package mx.edu.iems.inventario.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory; /** * Inicializa la fabrica de sesiones de hibernate */ static { sessionFactory = new Configuration().configure().buildSessionFactory(); } /** * Regresa la fabrica de sesiones. * @return Fabrica de sesiones. */ public static SessionFactory getSessionFactory() { return sessionFactory; } }<file_sep><?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>mx.edu.iems</groupId> <artifactId>inventario</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>inventario</name> <properties> <struts2.version>2.3.7</struts2.version> <struts2.jepert>3.4.0</struts2.jepert> </properties> <dependencies> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.2.4</version> </dependency> <!-- Dependencia de rich text --> <dependency> <groupId>com.jgeppert.struts2.jquery</groupId> <artifactId>struts2-jquery-richtext-plugin</artifactId> <version>${struts2.jepert}</version> </dependency> <!-- Dependencia de tree --> <dependency> <groupId>com.jgeppert.struts2.jquery</groupId> <artifactId>struts2-jquery-tree-plugin</artifactId> <version>${struts2.jepert}</version> </dependency> <!-- Dependencia para ocupar TwitterBootstrap --> <dependency> <groupId>com.jgeppert.struts2.bootstrap</groupId> <artifactId>struts2-bootstrap-plugin</artifactId> <version>1.5.2</version> </dependency> <!-- Dependencia básica para jquery --> <dependency> <groupId>com.jgeppert.struts2.jquery</groupId> <artifactId>struts2-jquery-plugin</artifactId> <version>${struts2.jepert}</version> </dependency> <!-- Depedencia para ocupar grid --> <dependency> <groupId>com.jgeppert.struts2.jquery</groupId> <artifactId>struts2-jquery-grid-plugin</artifactId> <version>${struts2.jepert}</version> </dependency> <!-- Dependencia para manejar DataSource --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- Dependencias de spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>3.0.5.RELEASE</version> </dependency> <!-- Dependencia de spring para strus --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>${struts2.version}</version> </dependency> <!-- Dependencia para manejar respuestas en JSON --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-json-plugin</artifactId> <version>${struts2.version}</version> </dependency> <!-- Dependencia para Postgres --> <dependency> <groupId>postgresql</groupId> <artifactId>postgresql</artifactId> <version>8.4-702.jdbc4</version> </dependency> <!-- Dependencias para agregar slf4j, lo ocupa y es importante para Hibernate para sus logs, es muy parecido a log4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.4</version> </dependency> <!-- Dependencias para manejar Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>3.5.1-Final</version> </dependency> <dependency> <groupId>org.hibernate.javax.persistence</groupId> <artifactId>hibernate-jpa-2.0-api</artifactId> <version>1.0.1.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.6.8.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.5.6-Final</version> </dependency> <!-- Dependencia para trabajar con anotaciones en Struts --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-convention-plugin</artifactId> <version>${struts2.version}</version> </dependency> <!-- Estas dependencias se generaron automaticamente cuando se creo el proyecto maven con el archetype struts-blank --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>${struts2.version}</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-config-browser-plugin</artifactId> <version>${struts2.version}</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-junit-plugin</artifactId> <version>${struts2.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.5</version> <scope>test</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.4</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.zeroturnaround</groupId> <artifactId>jrebel-maven-plugin</artifactId> <executions> <execution> <id>generate-rebel-xml</id> <phase>process-resources</phase> <goals> <goal>generate</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>8.1.7.v20120910</version> <configuration> <stopKey>CTRL+C</stopKey> <stopPort>8999</stopPort> <systemProperties> <systemProperty> <name>log4j.configuration</name> <value>file:${basedir}/src/main/resources/log4j.properties</value> </systemProperty> <systemProperty> <name>slf4j</name> <value>false</value> </systemProperty> </systemProperties> <scanIntervalSeconds>0</scanIntervalSeconds> <webAppSourceDirectory>${basedir}/src/main/webapp/</webAppSourceDirectory> <webAppConfig> <contextPath>/struts2-blank</contextPath> <descriptor>${basedir}/src/main/webapp/WEB-INF/web.xml</descriptor> </webAppConfig> </configuration> <dependencies> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> </plugin> </plugins> </build> </project> <file_sep>package mx.edu.iems.inventario.model; // Generated 14/05/2013 11:10:50 PM by Hibernate Tools 3.4.0.CR1 import java.util.HashSet; import java.util.Set; /** * Empleado generated by hbm2java */ public class Empleado implements java.io.Serializable { private int idempleado; private Puesto puesto; private Usuario usuario; private boolean activo; private String apaterno; private String amaterno; private String nombre; private String fechaalta; private String fechanacimiento; private Set cpus = new HashSet(0); private Set nobreaks = new HashSet(0); private Set monitors = new HashSet(0); private Set computadoras = new HashSet(0); public Empleado() { } public Empleado(int idempleado, Puesto puesto, Usuario usuario, boolean activo, String apaterno, String amaterno, String nombre, String fechaalta, String fechanacimiento) { this.idempleado = idempleado; this.puesto = puesto; this.usuario = usuario; this.activo = activo; this.apaterno = apaterno; this.amaterno = amaterno; this.nombre = nombre; this.fechaalta = fechaalta; this.fechanacimiento = fechanacimiento; } public Empleado(int idempleado, Puesto puesto, Usuario usuario, boolean activo, String apaterno, String amaterno, String nombre, String fechaalta, String fechanacimiento, Set cpus, Set nobreaks, Set monitors, Set computadoras) { this.idempleado = idempleado; this.puesto = puesto; this.usuario = usuario; this.activo = activo; this.apaterno = apaterno; this.amaterno = amaterno; this.nombre = nombre; this.fechaalta = fechaalta; this.fechanacimiento = fechanacimiento; this.cpus = cpus; this.nobreaks = nobreaks; this.monitors = monitors; this.computadoras = computadoras; } public int getIdempleado() { return this.idempleado; } public void setIdempleado(int idempleado) { this.idempleado = idempleado; } public Puesto getPuesto() { return this.puesto; } public void setPuesto(Puesto puesto) { this.puesto = puesto; } public Usuario getUsuario() { return this.usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public boolean isActivo() { return this.activo; } public void setActivo(boolean activo) { this.activo = activo; } public String getApaterno() { return this.apaterno; } public void setApaterno(String apaterno) { this.apaterno = apaterno; } public String getAmaterno() { return this.amaterno; } public void setAmaterno(String amaterno) { this.amaterno = amaterno; } public String getNombre() { return this.nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getFechaalta() { return this.fechaalta; } public void setFechaalta(String fechaalta) { this.fechaalta = fechaalta; } public String getFechanacimiento() { return this.fechanacimiento; } public void setFechanacimiento(String fechanacimiento) { this.fechanacimiento = fechanacimiento; } public Set getCpus() { return this.cpus; } public void setCpus(Set cpus) { this.cpus = cpus; } public Set getNobreaks() { return this.nobreaks; } public void setNobreaks(Set nobreaks) { this.nobreaks = nobreaks; } public Set getMonitors() { return this.monitors; } public void setMonitors(Set monitors) { this.monitors = monitors; } public Set getComputadoras() { return this.computadoras; } public void setComputadoras(Set computadoras) { this.computadoras = computadoras; } } <file_sep>$(document).ready(function() { $('#usuario').click(function() { $('#principal').html(''); $.ajax({ url : 'listarUsuarios.jsp', dataType : 'html', type : 'GET', success : function(data) { $('#principal').html(data); } }); }); $('#areas').click(function() { $('#principal').html(''); $.ajax({ url : 'listarAreas.jsp', dataType : 'html', type : 'GET', success : function(data) { $('#principal').html(data); } }); }); $('#puest').click(function() { $('#principal').html(''); $.ajax({ url : 'listarPuestos.jsp', dataType : 'html', type : 'GET', success : function(data) { $('#principal').html(data); } }); }); //Ya no se ocupa se deja como ejemplo $('#btnAltaUsuario').click(function() { $('#principal').html(''); $.ajax({ url : 'altaUsuario.jsp', dataType : 'html', type : 'GET', success : function(data) { $('#principal').html(data); } }); }); }); <file_sep>inventario ========== Sistema de Inventario. version 1.0 Tecnologías utilizadas: Jsp, Servlet, Maven 3, Struts, Hibernate, Spring 2, ajax, jquery, json, bootstrap, jetty. <file_sep>package mx.edu.iems.inventario.actions.area; import java.util.List; import mx.edu.iems.inventario.model.Area; import mx.edu.iems.inventario.services.AreaService; import org.hibernate.Criteria; import org.hibernate.criterion.DetachedCriteria; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.google.gson.Gson; import com.opensymphony.xwork2.ActionSupport; public class ListarAreasAction extends ActionSupport { private static final Logger log = LoggerFactory.getLogger(ListarAreasAction.class); private List<Area> areas; //Get how many rows we want to have into the grid - rowNum attribute in the // grid private Integer rows = 0; // Get the requested page. By default grid sets this to 1. private Integer page = 0; // sorting order - asc or desc private String sord; // get index row - i.e. user click to sort. private String sidx; // Search Field private String searchField; // The Search String private String searchString; // he Search Operation // ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc'] private String searchOper; // Your Total Pages private Integer total = 0; // All Record private Integer records = 0; // Propiedad que se cargara en el contexto de spring @Autowired private AreaService areaService; public List<Area> getAreas() { return areas; } public void setAreas(List<Area> areas) { this.areas = areas; } public Integer getRows() { return rows; } public void setRows(Integer rows) { this.rows = rows; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public String getSord() { return sord; } public void setSord(String sord) { this.sord = sord; } public String getSidx() { return sidx; } public void setSidx(String sidx) { this.sidx = sidx; } public String getSearchField() { return searchField; } public void setSearchField(String searchField) { this.searchField = searchField; } public String getSearchString() { return searchString; } public void setSearchString(String searchString) { this.searchString = searchString; } public String getSearchOper() { return searchOper; } public void setSearchOper(String searchOper) { this.searchOper = searchOper; } public Integer getTotal() { return total; } public void setTotal(Integer total) { this.total = total; } public Integer getRecords() { return records; } public void setRecords(Integer records) { this.records = records; } public AreaService getAreaService() { return areaService; } public void setAreaService(AreaService areaService) { this.areaService = areaService; } /** * Método que se ejecuta por default cuando se llama el action * listarUsuarios */ public String execute() { int to = (rows * page); int from = to - rows; DetachedCriteria criteria = DetachedCriteria.forClass(Area.class); //Count Rows (select count(*) from custumer) records = areaService.countByCriteria(criteria); // Reset count Projection criteria.setProjection(null); criteria.setResultTransformer(Criteria.ROOT_ENTITY); log.debug("Records " + records); //Your logic to search and select the required data. //areas = areaService.findByCriteria(criteria, from, rows); areas = areaService.listar(); if(to > records) to = records; //calculate the total pages for the query total = (int) Math.ceil((double) records / (double) rows); return SUCCESS; } } <file_sep>package mx.edu.iems.inventario.model; // Generated 14/05/2013 11:10:50 PM by Hibernate Tools 3.4.0.CR1 /** * Computadora generated by hbm2java */ public class Computadora implements java.io.Serializable { private String idcomputadora; private Monitor monitor; private Empleado empleado; private Usuario usuario; private Nobreak nobreak; private Cpu cpu; private String fechaalta; public Computadora() { } public Computadora(String idcomputadora, Monitor monitor, Empleado empleado, Usuario usuario, Nobreak nobreak, Cpu cpu, String fechaalta) { this.idcomputadora = idcomputadora; this.monitor = monitor; this.empleado = empleado; this.usuario = usuario; this.nobreak = nobreak; this.cpu = cpu; this.fechaalta = fechaalta; } public String getIdcomputadora() { return this.idcomputadora; } public void setIdcomputadora(String idcomputadora) { this.idcomputadora = idcomputadora; } public Monitor getMonitor() { return this.monitor; } public void setMonitor(Monitor monitor) { this.monitor = monitor; } public Empleado getEmpleado() { return this.empleado; } public void setEmpleado(Empleado empleado) { this.empleado = empleado; } public Usuario getUsuario() { return this.usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public Nobreak getNobreak() { return this.nobreak; } public void setNobreak(Nobreak nobreak) { this.nobreak = nobreak; } public Cpu getCpu() { return this.cpu; } public void setCpu(Cpu cpu) { this.cpu = cpu; } public String getFechaalta() { return this.fechaalta; } public void setFechaalta(String fechaalta) { this.fechaalta = fechaalta; } }
6e434dd1089bb4c8634fa45c29977fa0410043c2
[ "JavaScript", "Markdown", "Maven POM", "INI", "Java" ]
17
Java
alberrtor/inventario
8970461d890bb6b225f83ce3f2e452196ff03b20
ed076421d4deef3c00883f870290cd602c3d8e77